diff --git a/Controllers/PrivateMessageController.cs b/Controllers/PrivateMessageController.cs index 1383e82..7cfe6d7 100644 --- a/Controllers/PrivateMessageController.cs +++ b/Controllers/PrivateMessageController.cs @@ -14,6 +14,7 @@ namespace StatiKosev.Controllers; [Route("messages")] public class PrivateMessageController( MessageService messagesService, + NtfyNotifier ntfy, IStringLocalizer strings, IConfiguration config, ILogger logger) : Controller @@ -39,10 +40,15 @@ public class PrivateMessageController( logger.LogInformation("Received private message from {UserId}", userId ?? "anonymous"); - if (userId is null || senderUsername is null || req.Anonymous) + var anonymous = userId is null || senderUsername is null || req.Anonymous; + if (anonymous) await messagesService.SendAnonymousAsync(req.Body, userAgent); else - await messagesService.SendAsUserAsync(req.Body, userId, senderUsername, userAgent); + await messagesService.SendAsUserAsync(req.Body, userId!, senderUsername!, userAgent); + + ntfy.Notify("New message", + $"{(anonymous ? "Anonymous" : senderUsername)}: {req.Body[..Math.Min(req.Body.Length, 200)]}", + "envelope"); TempData["Status"] = strings["MessageSent"].Value; TempData["StatusType"] = "success"; diff --git a/Pages/Index.cshtml.cs b/Pages/Index.cshtml.cs index ab360bf..1cfa68d 100644 --- a/Pages/Index.cshtml.cs +++ b/Pages/Index.cshtml.cs @@ -1,13 +1,19 @@ using Microsoft.AspNetCore.Mvc.RazorPages; +using StatiKosev.Services; namespace StatiKosev.Pages; -public class IndexModel : PageModel +public class IndexModel(NtfyNotifier ntfy) : PageModel { public string VisitorName { get; private set; } = ""; public void OnGet() { VisitorName = User.Identity?.IsAuthenticated == true ? User.Identity.Name! : ""; + + var userAgent = Request.Headers.UserAgent.ToString(); + ntfy.Notify("Home page visit", + $"{(VisitorName == "" ? "Guest" : VisitorName)}\n{userAgent[..Math.Min(userAgent.Length, 160)]}", + "eyes"); } } diff --git a/Program.cs b/Program.cs index dc9bb07..c99660f 100644 --- a/Program.cs +++ b/Program.cs @@ -27,6 +27,7 @@ public class Program builder.Services.AddRazorPages(); builder.Services.AddControllers(); builder.Services.AddScoped(); + builder.Services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(10)); builder.Services.AddNpgsqlDataSource(databaseConnectionString); builder.Services.AddDbContext((sp, o) => o.UseNpgsql(sp.GetRequiredService())); // EF shares the same connection pool diff --git a/Services/NtfyNotifier.cs b/Services/NtfyNotifier.cs new file mode 100644 index 0000000..880eab4 --- /dev/null +++ b/Services/NtfyNotifier.cs @@ -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 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 { ["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); + } + } +} diff --git a/appsettings.json b/appsettings.json index 01b3884..c176e91 100644 --- a/appsettings.json +++ b/appsettings.json @@ -4,5 +4,6 @@ }, "Logging": { "LogLevel": { "Default": "Information" } }, "MessageRateLimitSeconds": 30, - "AdminPassword": "GFiMdUgkpJJGlZlUxayDY842Yml89G6s" + "AdminPassword": "GFiMdUgkpJJGlZlUxayDY842Yml89G6s", + "NtfyUrl": "http://10.8.0.1/aspnet_demo" } \ No newline at end of file