Initial commit

This commit is contained in:
2024-09-14 19:38:04 +03:30
commit 481e8e9af8
9 changed files with 365 additions and 0 deletions

34
Services/PostResolver.cs Normal file
View File

@@ -0,0 +1,34 @@
using System.Text.Json;
using Microsoft.Extensions.Logging;
using mstdnCats.Models;
namespace mstdnCats.Services
{
public sealed class PostResolver
{
public static async Task<List<Post>?> GetPostsAsync(string tag, ILogger<MastodonBot>? logger, string instance = "https://haminoa.net")
{
// Get posts
HttpClient _httpClient = new HttpClient();
// Get posts from mastodon api (40 latest posts)
var response = await _httpClient.GetAsync($"{instance}/api/v1/timelines/tag/{tag}?limit=40");
// Print out ratelimit info
logger?.LogInformation("Remaining requests: " + response.Headers.GetValues("X-RateLimit-Remaining").First() + "time to reset: " + response.Headers.GetValues("X-RateLimit-Reset").First());
// Check if response is ok
if (
response.StatusCode == System.Net.HttpStatusCode.OK ||
response.Content.Headers.ContentType.MediaType.Contains("application/json") ||
response.Headers.TryGetValues("X-RateLimit-Remaining", out var remaining) && int.Parse(remaining.First()) != 0
)
{
// Deserialize response based on 'Post' model
return JsonSerializer.Deserialize<List<Post>>(await response.Content.ReadAsStringAsync());
}
else return null;
}
}
}