oliverbooth.dev/OliverBooth/Services/MastodonService.cs

53 lines
1.7 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;
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-23 03:23:57 +00:00
private readonly HttpClient _httpClient;
public MastodonService(HttpClient httpClient)
{
_httpClient = httpClient;
}
/// <inheritdoc />
2024-02-23 05:36:31 +00:00
public MastodonStatus GetLatestStatus()
2024-02-23 03:23:57 +00:00
{
string token = Environment.GetEnvironmentVariable("MASTODON_TOKEN") ?? string.Empty;
string account = Environment.GetEnvironmentVariable("MASTODON_ACCOUNT") ?? string.Empty;
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
}
}