feat(notifications): add user-configurable ntfy to

This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-20 18:14:46 +02:00
1 parent 2ac2789728
commit 7a89a97bf3
15 files changed
+2310 -22

No files matched your search

@@ -36,6 +36,7 @@ public sealed record UserNotificationConfigDto(
[property: JsonPropertyName("emailAddress")] string? EmailAddress,
[property: JsonPropertyName("ntfyEnabled")] bool NtfyEnabled,
[property: JsonPropertyName("ntfyUrl")] string? NtfyUrl,
[property: JsonPropertyName("ntfyTopic")] string? NtfyTopic,
[property: JsonPropertyName("language")] string Language,
[property: JsonPropertyName("dailyDigest")] bool DailyDigest,
[property: JsonPropertyName("weeklyDigest")] bool WeeklyDigest,
@@ -47,6 +48,7 @@ public sealed record UpdateNotificationConfigRequest(
[property: JsonPropertyName("emailAddress")] string? EmailAddress,
[property: JsonPropertyName("ntfyEnabled")] bool? NtfyEnabled,
[property: JsonPropertyName("ntfyUrl")] string? NtfyUrl,
[property: JsonPropertyName("ntfyTopic")] string? NtfyTopic,
[property: JsonPropertyName("language")] string? Language,
[property: JsonPropertyName("dailyDigest")] bool? DailyDigest,
[property: JsonPropertyName("weeklyDigest")] bool? WeeklyDigest,
@@ -10,6 +10,7 @@ public record UpdateNotificationConfigCommand(
string? EmailAddress,
bool? NtfyEnabled,
string? NtfyUrl,
string? NtfyTopic,
string? Language,
bool? DailyDigest,
bool? WeeklyDigest,
@@ -32,8 +32,8 @@ public class UpdateNotificationConfigHandler : IRequestHandler<UpdateNotificatio
if (request.EmailEnabled.HasValue || request.EmailAddress is not null)
config.UpdateEmail(request.EmailAddress ?? config.EmailAddress, request.EmailEnabled ?? config.EmailEnabled);
if (request.NtfyEnabled.HasValue || request.NtfyUrl is not null)
config.UpdateNtfy(request.NtfyUrl ?? config.NtfyUrl, request.NtfyEnabled ?? config.NtfyEnabled);
if (request.NtfyEnabled.HasValue || request.NtfyUrl is not null || request.NtfyTopic is not null)
config.UpdateNtfy(request.NtfyUrl ?? config.NtfyUrl, request.NtfyEnabled ?? config.NtfyEnabled, request.NtfyTopic);
if (request.DailyDigest.HasValue || request.WeeklyDigest.HasValue)
config.UpdateDigests(request.DailyDigest ?? config.DailyDigest, request.WeeklyDigest ?? config.WeeklyDigest);
@@ -33,6 +33,7 @@ public class GetNotificationConfigHandler : IRequestHandler<GetNotificationConfi
null, // EmailAddress
false, // NtfyEnabled
null, // NtfyUrl
null, // NtfyTopic
"fr", // Language
false, // DailyDigest
false, // WeeklyDigest
@@ -14,6 +14,7 @@ public class UserNotificationConfig : Entity<Guid>, IAuditableEntity
public string? EmailAddress { get; private set; }
public bool NtfyEnabled { get; private set; }
public string? NtfyUrl { get; private set; }
public string? NtfyTopic { get; private set; }
public string Language { get; private set; } = "fr";
public bool DailyDigest { get; private set; }
public bool WeeklyDigest { get; private set; }
@@ -35,10 +36,12 @@ public class UserNotificationConfig : Entity<Guid>, IAuditableEntity
EmailEnabled = enabled;
}
public void UpdateNtfy(string? url, bool enabled)
public void UpdateNtfy(string? url, bool enabled, string? topic = null)
{
NtfyUrl = url;
NtfyEnabled = enabled;
if (topic is not null)
NtfyTopic = topic;
}
public void UpdateDigests(bool daily, bool weekly)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddUserNtfyTopic : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "NtfyTopic",
table: "user_notification_configs",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "NtfyTopic",
table: "user_notification_configs");
}
}
}
@@ -1686,6 +1686,9 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<bool>("NtfyEnabled")
.HasColumnType("boolean");
b.Property<string>("NtfyTopic")
.HasColumnType("text");
b.Property<string>("NtfyUrl")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
@@ -141,10 +141,20 @@ public class NotificationService : INotificationService
/// <summary>
/// Résout le topic ntfy cible d'une notification (ticket #105) :
/// topic du site si défini, sinon topic personnel <c>heimdall_{userId}</c>.
/// topic configuré par l'utilisateur (NtfyTopic) > topic du site > défaut heimdall_{userId}.
/// </summary>
private async Task<string> ResolveNtfyTopicAsync(Notification notification, Guid userId, CancellationToken ct)
{
// 1. User-configured topic (from profile settings)
var userConfig = await _context.UserNotificationConfigs
.AsNoTracking()
.Where(c => c.UserId == userId)
.Select(c => c.NtfyTopic)
.FirstOrDefaultAsync(ct);
if (!string.IsNullOrWhiteSpace(userConfig))
return userConfig;
// 2. Site-level topic
if (notification.SiteId is { } siteId)
{
var siteTopic = await _context.Sites
@@ -156,6 +166,7 @@ public class NotificationService : INotificationService
return siteTopic;
}
// 3. Default
return $"heimdall_{userId}";
}
@@ -183,10 +183,10 @@ else if (_profile is not null)
Installez l'app ntfy et abonnez-vous au topic ci-dessous pour recevoir les notifications.
</MudText>
<MudText Typo="Typo.body2" Class="mb-1">
<strong>Votre topic :</strong> <code>@($"heimdall_{_profile?.Id}")</code>
<strong>Votre topic :</strong> <code>@(!string.IsNullOrWhiteSpace(_ntfyTopic) ? _ntfyTopic : $"heimdall_{_profile?.Id}")</code>
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">
Ce topic est unique par utilisateur. Vous pouvez aussi utiliser un topic de site si configuré.
Personnalisez le champ "Topic ntfy" ci-dessous pour utiliser un topic différent.
</MudText>
</MudAlert>
@@ -202,6 +202,10 @@ else if (_profile is not null)
<MudTextField @bind-Value="_ntfyUrl" Label="URL du serveur ntfy (optionnel)"
Variant="Variant.Outlined" Class="mb-4" Disabled="@(!_ntfyEnabled)"
Placeholder="http://ntfy:80 (défaut)" HelperText="Laisser vide pour utiliser le serveur global" />
<MudTextField @bind-Value="_ntfyTopic" Label="Topic ntfy (optionnel)"
Variant="Variant.Outlined" Class="mb-4" Disabled="@(!_ntfyEnabled)"
Placeholder="@($"heimdall_{_profile?.Id}")"
HelperText="Personnalisez le topic de réception. Défaut : heimdall_{votre-id}" />
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-4">Résumés</MudText>
<MudSwitch @bind-Value="_dailyDigest" Label="Résumé quotidien (8h)" Color="Color.Tertiary" Class="mb-2" />
@@ -503,6 +507,7 @@ else if (_profile is not null)
private string? _emailAddress;
private bool _ntfyEnabled;
private string? _ntfyUrl;
private string? _ntfyTopic;
private bool _dailyDigest;
private bool _weeklyDigest;
private bool _savingNotif;
@@ -545,6 +550,7 @@ else if (_profile is not null)
_emailAddress = _notifConfig.EmailAddress;
_ntfyEnabled = _notifConfig.NtfyEnabled;
_ntfyUrl = _notifConfig.NtfyUrl;
_ntfyTopic = _notifConfig.NtfyTopic;
_dailyDigest = _notifConfig.DailyDigest;
_weeklyDigest = _notifConfig.WeeklyDigest;
_subscribedEvents = _notifConfig.SubscribedEvents is not null
@@ -569,6 +575,7 @@ else if (_profile is not null)
string.IsNullOrWhiteSpace(_emailAddress) ? null : _emailAddress.Trim(),
_ntfyEnabled,
string.IsNullOrWhiteSpace(_ntfyUrl) ? null : _ntfyUrl.Trim(),
string.IsNullOrWhiteSpace(_ntfyTopic) ? null : _ntfyTopic.Trim(),
_dailyDigest,
_weeklyDigest,
_subscribedEvents.Count > 0 ? _subscribedEvents.ToList() : null
@@ -589,14 +596,22 @@ else if (_profile is not null)
finally { _savingNotif = false; }
}
private string? ResolveNtfyTopic()
{
if (!string.IsNullOrWhiteSpace(_ntfyTopic))
return _ntfyTopic.Trim();
return _profile is not null ? $"heimdall_{_profile.Id}" : null;
}
private async Task TestNtfyForUserAsync()
{
_testingNtfy = true;
_ntfyTestResult = null;
try
{
var topic = _profile is not null ? $"heimdall_{_profile.Id}" : null;
_ntfyTestResult = await Api.TestNtfyAsync(topic)
var topic = ResolveNtfyTopic();
var baseUrl = string.IsNullOrWhiteSpace(_ntfyUrl) ? null : _ntfyUrl.Trim();
_ntfyTestResult = await Api.TestNtfyAsync(topic, baseUrl)
?? new TestActionResult(false, "Test impossible (API indisponible).");
}
catch (Exception ex)
@@ -91,6 +91,7 @@ public class NotificationsController : ControllerBase
request.EmailAddress,
request.NtfyEnabled,
request.NtfyUrl,
request.NtfyTopic,
request.Language,
request.DailyDigest,
request.WeeklyDigest,
@@ -293,12 +293,13 @@ public class SettingsController : ControllerBase
{
var topic = string.IsNullOrWhiteSpace(request?.Topic) ? "heimdall-test" : request.Topic;
var ok = await ntfyService.SendTestAsync(topic, "Heimdall — test de configuration",
"✅ Notification ntfy reçue : le serveur est joignable et le token est accepté.", ct: ct);
"✅ Notification ntfy reçue : le serveur est joignable et le token est accepté.",
baseUrl: request?.BaseUrl, ct: ct);
return Ok(new
{
success = ok,
message = ok
? $"Notification test envoyée sur le topic « {topic} »"
? $"Notification test envoyée sur « {topic} » ({request?.BaseUrl ?? "serveur global"})"
: "Échec de l'envoi ntfy (serveur injoignable ou rejet — voir les logs)."
});
}
@@ -322,7 +323,7 @@ public class SettingsController : ControllerBase
});
}
public sealed record TestNtfyRequest(string? Topic);
public sealed record TestNtfyRequest(string? Topic, string? BaseUrl);
/// <summary>
/// Broadcast a "ConfigReload" signal to all connected agents so they
@@ -609,10 +609,10 @@ public class HeimdallApiClient
}
/// <summary>Send a test ntfy notification (POST /api/settings/ntfy/test).</summary>
public async Task<TestActionResult?> TestNtfyAsync(string? topic = null)
public async Task<TestActionResult?> TestNtfyAsync(string? topic = null, string? baseUrl = null)
{
var client = CreateClient();
var payload = new { topic };
var payload = new { topic, baseUrl };
var response = await client.PostAsJsonAsync("api/settings/ntfy/test", payload, Json);
if (!response.IsSuccessStatusCode)
return null;
@@ -1014,6 +1014,7 @@ public class NotificationConfigItem
public string? EmailAddress { get; set; }
public bool NtfyEnabled { get; set; }
public string? NtfyUrl { get; set; }
public string? NtfyTopic { get; set; }
public string Language { get; set; } = "fr";
public bool DailyDigest { get; set; }
public bool WeeklyDigest { get; set; }
@@ -1025,6 +1026,7 @@ public record UpdateNotificationConfigRequest(
string? EmailAddress,
bool? NtfyEnabled,
string? NtfyUrl,
string? NtfyTopic,
bool? DailyDigest,
bool? WeeklyDigest,
List<string>? SubscribedEvents
@@ -223,7 +223,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, true, "user@example.com", null, null, null, null, null, null), _ct);
userId, true, "user@example.com", null, null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -242,7 +242,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, true, "new@example.com", null, null, null, null, null, null), _ct);
userId, true, "new@example.com", null, null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -263,7 +263,7 @@ public class NotificationHandlerTests
// Only update email address, leave everything else unchanged
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, "updated@example.com", null, null, null, null, null, null), _ct);
userId, null, "updated@example.com", null, null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -282,7 +282,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, true, "https://ntfy.example.com", null, null, null, null), _ct);
userId, null, null, true, "https://ntfy.example.com", null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -298,7 +298,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, null, null, null, true, true, null), _ct);
userId, null, null, null, null, null, null, true, true, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -314,7 +314,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, null, null, "de", null, null, null), _ct);
userId, null, null, null, null, null, "de", null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -117,7 +117,7 @@ public class NotificationsControllerTests
{
// Arrange
var userId = Guid.NewGuid();
var dto = new UserNotificationConfigDto(Guid.Empty, userId, false, null, false, null, "fr", false, false, null);
var dto = new UserNotificationConfigDto(Guid.Empty, userId, false, null, false, null, null, "fr", false, false, null);
_mediator.Send(Arg.Any<GetNotificationConfigQuery>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<UserNotificationConfigDto>.Success(dto));
@@ -133,10 +133,10 @@ public class NotificationsControllerTests
{
// Arrange
var request = new UpdateNotificationConfigRequest(
true, "test@test.com", true, "http://ntfy:80", "fr", true, false, null);
true, "test@test.com", true, "http://ntfy:80", null, "fr", true, false, null);
var dto = new UserNotificationConfigDto(
Guid.NewGuid(), Guid.NewGuid(), true, "test@test.com",
true, "http://ntfy:80", "fr", true, false, null);
true, "http://ntfy:80", null, "fr", true, false, null);
_mediator.Send(Arg.Any<UpdateNotificationConfigCommand>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<UserNotificationConfigDto>.Success(dto));