2024-02-23 03:23:57 +00:00
|
|
|
using System.Text.Json;
|
2024-02-23 05:36:31 +00:00
|
|
|
using System.Text.Json.Serialization;
|
2024-02-24 00:43:14 +00:00
|
|
|
using HtmlAgilityPack;
|
2024-05-05 02:18:20 +01:00
|
|
|
using OliverBooth.Common.Data.Mastodon;
|
|
|
|
using OliverBooth.Common.Services;
|
2024-02-23 05:36:31 +00:00
|
|
|
using OliverBooth.Data.Mastodon;
|
2024-02-23 03:23:57 +00:00
|
|
|
|
|
|
|
namespace OliverBooth.Services;
|
|
|
|
|
|
|
|
internal sealed class MastodonService : IMastodonService
|
|
|
|
{
|
2024-02-23 05:36:31 +00:00
|
|
|
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
|
|
|
|
{
|
|
|
|
Converters = { new JsonStringEnumConverter() },
|
|
|
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
|
|
|
|
};
|
2024-02-24 00:43:14 +00:00
|
|
|
|
2024-05-05 21:10:23 +01:00
|
|
|
private readonly IConfiguration _configuration;
|
2024-02-23 03:23:57 +00:00
|
|
|
private readonly HttpClient _httpClient;
|
|
|
|
|
2024-05-05 21:10:23 +01:00
|
|
|
public MastodonService(IConfiguration configuration, HttpClient httpClient)
|
2024-02-23 03:23:57 +00:00
|
|
|
{
|
2024-05-05 21:10:23 +01:00
|
|
|
_configuration = configuration;
|
2024-02-23 03:23:57 +00:00
|
|
|
_httpClient = httpClient;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
2024-05-05 02:18:20 +01:00
|
|
|
public IMastodonStatus GetLatestStatus()
|
2024-02-23 03:23:57 +00:00
|
|
|
{
|
2024-07-05 00:46:40 +01:00
|
|
|
string domain = _configuration.GetSection("Mastodon:Domain").Value ?? string.Empty;
|
2024-05-05 21:10:23 +01:00
|
|
|
string token = _configuration.GetSection("Mastodon:Token").Value ?? string.Empty;
|
|
|
|
string account = _configuration.GetSection("Mastodon:Account").Value ?? string.Empty;
|
2024-07-05 00:46:40 +01:00
|
|
|
|
2024-02-23 03:23:57 +00:00
|
|
|
using var request = new HttpRequestMessage();
|
|
|
|
request.Headers.Add("Authorization", $"Bearer {token}");
|
2024-07-05 00:46:40 +01:00
|
|
|
request.RequestUri = new Uri($"https://{domain}/api/v1/accounts/{account}/statuses");
|
2024-02-23 03:23:57 +00:00
|
|
|
|
|
|
|
using HttpResponseMessage response = _httpClient.Send(request);
|
|
|
|
using var stream = response.Content.ReadAsStream();
|
2024-02-23 05:36:31 +00:00
|
|
|
var statuses = JsonSerializer.Deserialize<MastodonStatus[]>(stream, JsonSerializerOptions);
|
2024-02-24 00:43:14 +00:00
|
|
|
|
|
|
|
MastodonStatus status = statuses?[0]!;
|
|
|
|
var document = new HtmlDocument();
|
|
|
|
document.LoadHtml(status.Content);
|
|
|
|
|
2024-02-26 13:14:02 +00:00
|
|
|
HtmlNodeCollection? links = document.DocumentNode.SelectNodes("//a");
|
|
|
|
if (links is not null)
|
|
|
|
{
|
|
|
|
foreach (HtmlNode link in links)
|
|
|
|
{
|
|
|
|
link.InnerHtml = link.InnerText;
|
|
|
|
}
|
|
|
|
}
|
2024-02-24 00:43:14 +00:00
|
|
|
|
|
|
|
status.Content = document.DocumentNode.OuterHtml;
|
|
|
|
return status;
|
2024-02-23 03:23:57 +00:00
|
|
|
}
|
|
|
|
}
|