using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using WindowsGotify.Models;
namespace WindowsGotify.Services;
public sealed class GotifyApiService
{
private readonly GotifyConfig _config;
private readonly Logger _logger;
private readonly HttpClient _httpClient;
public GotifyApiService(AppConfig config, Logger logger)
{
_config = config.Gotify;
_logger = logger;
_httpClient = new HttpClient
{
BaseAddress = new Uri(_config.Url.TrimEnd('/') + "/"),
Timeout = TimeSpan.FromSeconds(15)
};
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _config.ClientToken);
}
///
/// 拉取 lastId 之后的增量消息(去重补齐用)。
///
public async Task> GetMessagesSinceAsync(long sinceId, int limit, CancellationToken ct)
{
var path = $"message?limit={Math.Clamp(limit, 1, 100)}&since={Math.Max(0, sinceId)}";
using var response = await _httpClient.GetAsync(path, ct);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(ct);
var page = await JsonSerializer.DeserializeAsync(stream, cancellationToken: ct);
return page?.Messages ?? new List();
}
///
/// 拉取最近 N 条消息(历史查看用)。since=0 让服务器从最新往旧返回。
///
public async Task> GetRecentMessagesAsync(int limit, CancellationToken ct)
{
var path = $"message?limit={Math.Clamp(limit, 1, 100)}&since=0";
using var response = await _httpClient.GetAsync(path, ct);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(ct);
var page = await JsonSerializer.DeserializeAsync(stream, cancellationToken: ct);
var list = page?.Messages ?? new List();
// Gotify 的 since=0 行为:返回数据库里所有消息中的 limit 条;按 id 降序再取一次保证正确
return list.OrderByDescending(m => m.Id).Take(Math.Clamp(limit, 1, 100)).ToList();
}
}