Files

33 lines
1.1 KiB
C#
Raw Permalink Normal View History

2026-10-28 14:24:41 +02:00
using Microsoft.AspNetCore.WebUtilities;
namespace StatiKosev.Services;
//posts to the ntfy topic URL from appsettings.json ("NtfyUrl", e.g. https://ntfy.sh/my-topic); empty = off
public class NtfyNotifier(HttpClient http, IConfiguration config, ILogger<NtfyNotifier> logger)
{
//fire-and-forget: a slow or unreachable ntfy server never delays the page
public void Notify(string title, string message, string? tags = null)
{
var url = config["NtfyUrl"];
if (string.IsNullOrWhiteSpace(url)) return;
var query = new Dictionary<string, string?> { ["title"] = title };
if (tags is not null) query["tags"] = tags;
_ = SendAsync(QueryHelpers.AddQueryString(url, query), message);
}
async Task SendAsync(string url, string message)
{
try
{
using var res = await http.PostAsync(url, new StringContent(message));
if (!res.IsSuccessStatusCode)
logger.LogWarning("ntfy returned {Status}", (int)res.StatusCode);
}
catch (Exception e)
{
logger.LogWarning("ntfy notification failed: {Error}", e.Message);
}
}
}