ntfy
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user