This commit is contained in:
2026-10-28 14:24:41 +02:00
parent bd22fa86b7
commit 2bc968a92c
5 changed files with 50 additions and 4 deletions
+8 -2
View File
@@ -14,6 +14,7 @@ namespace StatiKosev.Controllers;
[Route("messages")]
public class PrivateMessageController(
MessageService messagesService,
NtfyNotifier ntfy,
IStringLocalizer<StringValues> strings,
IConfiguration config,
ILogger<PrivateMessageController> 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";
+7 -1
View File
@@ -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");
}
}
+1
View File
@@ -27,6 +27,7 @@ public class Program
builder.Services.AddRazorPages();
builder.Services.AddControllers();
builder.Services.AddScoped<StatiKosev.Services.MessageService>();
builder.Services.AddHttpClient<StatiKosev.Services.NtfyNotifier>(c => c.Timeout = TimeSpan.FromSeconds(10));
builder.Services.AddNpgsqlDataSource(databaseConnectionString);
builder.Services.AddDbContext<AppDbContext>((sp, o) =>
o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>())); // EF shares the same connection pool
+32
View File
@@ -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);
}
}
}
+2 -1
View File
@@ -4,5 +4,6 @@
},
"Logging": { "LogLevel": { "Default": "Information" } },
"MessageRateLimitSeconds": 30,
"AdminPassword": "GFiMdUgkpJJGlZlUxayDY842Yml89G6s"
"AdminPassword": "GFiMdUgkpJJGlZlUxayDY842Yml89G6s",
"NtfyUrl": "http://10.8.0.1/aspnet_demo"
}