Files
Heimdall/src/Heimdall.Infrastructure/Services/NtfyService.cs
T
Arnaud Dartois d774d28f2a
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 7m33s
Heimdall Gitea / CI policy (pull_request) Failing after 2s
refactor(settings): manage integrations through Central UI
2026-10-26 06:26:00 +01:00

93 lines
3.6 KiB
C#

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class NtfyService : INtfyService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IServiceProvider _services;
private readonly ILogger<NtfyService> _logger;
public NtfyService(IHttpClientFactory httpClientFactory, IServiceProvider services,
ILogger<NtfyService> logger)
{
_httpClientFactory = httpClientFactory;
_services = services;
_logger = logger;
}
public async Task SendNotificationAsync(string topic, string title, string message, int priority = 3, string? baseUrl = null, CancellationToken ct = default)
{
using var response = await SendCoreAsync(topic, title, message, priority, baseUrl, ct)
.ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
throw new HttpRequestException(
$"ntfy returned HTTP {(int)response.StatusCode}", null, response.StatusCode);
}
public async Task<bool> SendTestAsync(string topic, string title, string message, string? baseUrl = null, CancellationToken ct = default)
{
try
{
using var response = await SendCoreAsync(topic, title, message, 4, baseUrl, ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("ntfy test returned HTTP {StatusCode} for topic {Topic}", response.StatusCode, topic);
}
return response.IsSuccessStatusCode;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "ntfy test failed for topic {Topic}", topic);
return false;
}
}
private async Task<HttpResponseMessage> SendCoreAsync(string topic, string title, string message, int priority, string? overrideBaseUrl, CancellationToken ct)
{
var (baseUrl, authToken) = await ResolveConfigAsync(ct).ConfigureAwait(false);
if (!string.IsNullOrEmpty(overrideBaseUrl))
baseUrl = overrideBaseUrl;
var client = _httpClientFactory.CreateClient("Ntfy");
var requestUrl = $"{baseUrl.TrimEnd('/')}/{topic}";
var payload = new { topic, title, message, priority };
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(authToken))
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authToken);
return await client.PostAsync(requestUrl, content, ct).ConfigureAwait(false);
}
/// <summary>
/// Source de vérité : AppSettings globaux en base (ntfy.*), relus à
/// chaque envoi pour prendre en compte les modifications de l'IHM.
/// </summary>
private async Task<(string BaseUrl, string? Token)> ResolveConfigAsync(CancellationToken ct)
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var baseUrl = await AppSettingReader.GetAsync(db, "ntfy.baseurl", ct).ConfigureAwait(false)
?? string.Empty;
var token = await AppSettingReader.GetAsync(db, "ntfy.token", ct).ConfigureAwait(false);
return (baseUrl, token);
}
}