oliverbooth.dev/OliverBooth/Services/MastodonService.cs

57 lines
1.9 KiB
C#
Raw Normal View History

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;
using HtmlAgilityPack;
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
};
private readonly IConfiguration _configuration;
2024-02-23 03:23:57 +00:00
private readonly HttpClient _httpClient;
public MastodonService(IConfiguration configuration, HttpClient httpClient)
2024-02-23 03:23:57 +00:00
{
_configuration = configuration;
2024-02-23 03:23:57 +00:00
_httpClient = httpClient;
}
/// <inheritdoc />
public IMastodonStatus GetLatestStatus()
2024-02-23 03:23:57 +00:00
{
string token = _configuration.GetSection("Mastodon:Token").Value ?? string.Empty;
string account = _configuration.GetSection("Mastodon:Account").Value ?? string.Empty;
2024-02-23 03:23:57 +00:00
using var request = new HttpRequestMessage();
request.Headers.Add("Authorization", $"Bearer {token}");
request.RequestUri = new Uri($"https://mastodon.olivr.me/api/v1/accounts/{account}/statuses");
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);
MastodonStatus status = statuses?[0]!;
var document = new HtmlDocument();
document.LoadHtml(status.Content);
HtmlNodeCollection? links = document.DocumentNode.SelectNodes("//a");
if (links is not null)
{
foreach (HtmlNode link in links)
{
link.InnerHtml = link.InnerText;
}
}
status.Content = document.DocumentNode.OuterHtml;
return status;
2024-02-23 03:23:57 +00:00
}
}