feat: remplacer Gotify par ntfy — push notifications multi-utilisateur avec isolation par topic

- Nouveau NtfyService: topic isolé par user (heimdall_{userId})
- Configuration globale Ntfy:BaseUrl + Ntfy:Token (plus de token par user)
- Renommage UserNotificationConfig: Gotify* → Ntfy*
- Migration des colonnes DB: gotify_enabled/url/token → ntfy_enabled/url
- Ajout service ntfy dans docker-compose (binwiederhier/ntfy)
- Mise à jour .env.example avec NTFY__BASE_URL et NTFY__TOKEN
- Suppression GotifyService et IGotifyService
This commit is contained in:
Arnaud Dartois committed 2026-07-27 04:56:16 +00:00
1 parent 1080f26591
commit f800103239
25 files changed
+159 -117

No files matched your search

+4
View File
@@ -38,3 +38,7 @@ Agent__SiteToken=replace-with-actual-token
Agent__AgentName=agent-01
Agent__HeartbeatIntervalSeconds=30
Agent__RegistrationMaxRetries=5
# ntfy push notifications
NTFY__BASE_URL=http://ntfy:80
NTFY__TOKEN=
+15
View File
@@ -107,6 +107,19 @@ services:
networks:
- heimdall-net
ntfy:
image: binwiederhier/ntfy:latest
container_name: heimdall-ntfy
restart: unless-stopped
command:
- "serve"
environment:
- TZ=Europe/Paris
volumes:
- ntfy_data:/var/lib/ntfy
networks:
- heimdall-net
heimdall-agent:
image: eltruncho/heimdall-agent:latest
environment:
@@ -140,6 +153,8 @@ volumes:
driver: local
heimdall_data:
driver: local
ntfy_data:
driver: local
networks:
heimdall-net:
+17
View File
@@ -107,6 +107,21 @@ services:
networks:
- heimdall-net
ntfy:
image: binwiederhier/ntfy
container_name: heimdall-ntfy
restart: unless-stopped
command:
- "serve"
environment:
- TZ=Europe/Paris
volumes:
- ntfy_data:/var/lib/ntfy
ports:
- "8080:80"
networks:
- heimdall-net
heimdall-agent:
build:
context: ..
@@ -143,6 +158,8 @@ volumes:
driver: local
heimdall_data:
driver: local
ntfy_data:
driver: local
networks:
heimdall-net:
@@ -34,8 +34,8 @@ public sealed record UserNotificationConfigDto(
[property: JsonPropertyName("userId")] Guid UserId,
[property: JsonPropertyName("emailEnabled")] bool EmailEnabled,
[property: JsonPropertyName("emailAddress")] string? EmailAddress,
[property: JsonPropertyName("gotifyEnabled")] bool GotifyEnabled,
[property: JsonPropertyName("gotifyUrl")] string? GotifyUrl,
[property: JsonPropertyName("ntfyEnabled")] bool NtfyEnabled,
[property: JsonPropertyName("ntfyUrl")] string? NtfyUrl,
[property: JsonPropertyName("language")] string Language,
[property: JsonPropertyName("dailyDigest")] bool DailyDigest,
[property: JsonPropertyName("weeklyDigest")] bool WeeklyDigest,
@@ -45,9 +45,8 @@ public sealed record UserNotificationConfigDto(
public sealed record UpdateNotificationConfigRequest(
[property: JsonPropertyName("emailEnabled")] bool? EmailEnabled,
[property: JsonPropertyName("emailAddress")] string? EmailAddress,
[property: JsonPropertyName("gotifyEnabled")] bool? GotifyEnabled,
[property: JsonPropertyName("gotifyUrl")] string? GotifyUrl,
[property: JsonPropertyName("gotifyToken")] string? GotifyToken,
[property: JsonPropertyName("ntfyEnabled")] bool? NtfyEnabled,
[property: JsonPropertyName("ntfyUrl")] string? NtfyUrl,
[property: JsonPropertyName("language")] string? Language,
[property: JsonPropertyName("dailyDigest")] bool? DailyDigest,
[property: JsonPropertyName("weeklyDigest")] bool? WeeklyDigest,
@@ -8,9 +8,8 @@ public record UpdateNotificationConfigCommand(
Guid UserId,
bool? EmailEnabled,
string? EmailAddress,
bool? GotifyEnabled,
string? GotifyUrl,
string? GotifyToken,
bool? NtfyEnabled,
string? NtfyUrl,
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.GotifyEnabled.HasValue || request.GotifyUrl is not null || request.GotifyToken is not null)
config.UpdateGotify(request.GotifyUrl ?? config.GotifyUrl, request.GotifyToken ?? config.GotifyToken, request.GotifyEnabled ?? config.GotifyEnabled);
if (request.NtfyEnabled.HasValue || request.NtfyUrl is not null)
config.UpdateNtfy(request.NtfyUrl ?? config.NtfyUrl, request.NtfyEnabled ?? config.NtfyEnabled);
if (request.DailyDigest.HasValue || request.WeeklyDigest.HasValue)
config.UpdateDigests(request.DailyDigest ?? config.DailyDigest, request.WeeklyDigest ?? config.WeeklyDigest);
@@ -1,6 +0,0 @@
namespace Heimdall.Application.Services;
public interface IGotifyService
{
Task SendNotificationAsync(string url, string token, string title, string message, int priority = 5, CancellationToken ct = default);
}
@@ -7,7 +7,7 @@ namespace Heimdall.Application.Services;
/// <summary>
/// Core notification orchestration service.
/// Creates notifications, dispatches to channels (SignalR/Email/Gotify), respects rate limits.
/// Creates notifications, dispatches to channels (SignalR/Email/ntfy), respects rate limits.
/// </summary>
public interface INotificationService
{
@@ -0,0 +1,6 @@
namespace Heimdall.Application.Services;
public interface INtfyService
{
Task SendNotificationAsync(string topic, string title, string message, int priority = 3, CancellationToken ct = default);
}
@@ -12,9 +12,8 @@ public class UserNotificationConfig : Entity<Guid>, IAuditableEntity
public Guid UserId { get; private set; }
public bool EmailEnabled { get; private set; }
public string? EmailAddress { get; private set; }
public bool GotifyEnabled { get; private set; }
public string? GotifyUrl { get; private set; }
public string? GotifyToken { get; private set; }
public bool NtfyEnabled { get; private set; }
public string? NtfyUrl { get; private set; }
public string Language { get; private set; } = "fr";
public bool DailyDigest { get; private set; }
public bool WeeklyDigest { get; private set; }
@@ -36,11 +35,10 @@ public class UserNotificationConfig : Entity<Guid>, IAuditableEntity
EmailEnabled = enabled;
}
public void UpdateGotify(string? url, string? token, bool enabled)
public void UpdateNtfy(string? url, bool enabled)
{
GotifyUrl = url;
GotifyToken = token;
GotifyEnabled = enabled;
NtfyUrl = url;
NtfyEnabled = enabled;
}
public void UpdateDigests(bool daily, bool weekly)
@@ -4,5 +4,5 @@ public enum NotificationChannel
{
InApp = 0,
Email = 1,
Gotify = 2
Ntfy = 2
}
@@ -34,7 +34,7 @@ public static class DependencyInjection
services.AddHangfireServer(options =>
{
options.WorkerCount = 2;
options.Queues = ["default", "heartbeat", "email", "gotify", "digest"];
options.Queues = ["default", "heartbeat", "email", "ntfy", "digest"];
});
services.AddScoped<HeartbeatMonitorJob>();
@@ -15,10 +15,7 @@ public class UserNotificationConfigConfiguration : IEntityTypeConfiguration<User
builder.Property(c => c.EmailAddress)
.HasMaxLength(200);
builder.Property(c => c.GotifyUrl)
.HasMaxLength(500);
builder.Property(c => c.GotifyToken)
builder.Property(c => c.NtfyUrl)
.HasMaxLength(500);
builder.Property(c => c.Language)
@@ -141,8 +141,8 @@ public static class DependencyInjection
services.AddScoped<INotificationService, NotificationService>();
services.AddSingleton<INotificationRateLimiter, NotificationRateLimiter>();
services.AddScoped<IEmailService, EmailService>();
services.AddScoped<IGotifyService, GotifyService>();
services.AddHttpClient("Gotify", client =>
services.AddScoped<INtfyService, NtfyService>();
services.AddHttpClient("Ntfy", client =>
{
client.Timeout = TimeSpan.FromSeconds(10);
});
@@ -4,22 +4,22 @@ using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Hangfire job to send a notification via email or Gotify.
/// Hangfire job to send a notification via email or ntfy.
/// Fire-and-forget, with retry built into Hangfire.
/// </summary>
public class SendNotificationJob
{
private readonly IEmailService _emailService;
private readonly IGotifyService _gotifyService;
private readonly INtfyService _ntfyService;
private readonly ILogger<SendNotificationJob> _logger;
public SendNotificationJob(
IEmailService emailService,
IGotifyService gotifyService,
INtfyService ntfyService,
ILogger<SendNotificationJob> logger)
{
_emailService = emailService;
_gotifyService = gotifyService;
_ntfyService = ntfyService;
_logger = logger;
}
@@ -29,9 +29,9 @@ public class SendNotificationJob
await _emailService.SendEmailAsync(recipient, subject, bodyHtml, ct);
}
public async Task SendGotifyAsync(string url, string token, string title, string message, int priority = 5, CancellationToken ct = default)
public async Task SendNtfyAsync(string topic, string title, string message, int priority = 3, CancellationToken ct = default)
{
_logger.LogInformation("Sending Gotify notification: {Title}", title);
await _gotifyService.SendNotificationAsync(url, token, title, message, priority, ct);
_logger.LogInformation("Sending ntfy notification: {Title}", title);
await _ntfyService.SendNotificationAsync(topic, title, message, priority, ct);
}
}
@@ -1326,14 +1326,14 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<bool>("EmailEnabled")
.HasColumnType("boolean");
b.Property<bool>("GotifyEnabled")
b.Property<bool>("NtfyEnabled")
.HasColumnType("boolean");
b.Property<string>("GotifyToken")
b.Property<string>("NtfyToken")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("GotifyUrl")
b.Property<string>("NtfyUrl")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
@@ -62,9 +62,8 @@ namespace Heimdall.Infrastructure.Migrations
UserId = table.Column<Guid>(type: "uuid", nullable: false),
EmailEnabled = table.Column<bool>(type: "boolean", nullable: false),
EmailAddress = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
GotifyEnabled = table.Column<bool>(type: "boolean", nullable: false),
GotifyUrl = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
GotifyToken = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
NtfyEnabled = table.Column<bool>(type: "boolean", nullable: false),
NtfyUrl = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
Language = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"),
DailyDigest = table.Column<bool>(type: "boolean", nullable: false),
WeeklyDigest = table.Column<bool>(type: "boolean", nullable: false),
@@ -1323,14 +1323,14 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<bool>("EmailEnabled")
.HasColumnType("boolean");
b.Property<bool>("GotifyEnabled")
b.Property<bool>("NtfyEnabled")
.HasColumnType("boolean");
b.Property<string>("GotifyToken")
b.Property<string>("NtfyToken")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("GotifyUrl")
b.Property<string>("NtfyUrl")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
@@ -1,36 +0,0 @@
using System.Net.Http.Json;
using Heimdall.Application.Services;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class GotifyService : IGotifyService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<GotifyService> _logger;
public GotifyService(IHttpClientFactory httpClientFactory, ILogger<GotifyService> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
public async Task SendNotificationAsync(string url, string token, string title, string message, int priority = 5, CancellationToken ct = default)
{
try
{
var client = _httpClientFactory.CreateClient("Gotify");
var requestUrl = $"{url.TrimEnd('/')}/message?token={token}";
var payload = new { title, message, priority };
var response = await client.PostAsJsonAsync(requestUrl, payload, ct);
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Gotify returned {StatusCode} for {Url}", response.StatusCode, url);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send Gotify notification to {Url}", url);
}
}
}
@@ -16,7 +16,7 @@ public class NotificationService : INotificationService
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly IGotifyService _gotifyService;
private readonly INtfyService _ntfyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
@@ -25,7 +25,7 @@ public class NotificationService : INotificationService
IMapper mapper,
INotificationBroadcastService broadcast,
IEmailService emailService,
IGotifyService gotifyService,
INtfyService ntfyService,
INotificationRateLimiter rateLimiter,
ILogger<NotificationService> logger)
{
@@ -33,7 +33,7 @@ public class NotificationService : INotificationService
_mapper = mapper;
_broadcast = broadcast;
_emailService = emailService;
_gotifyService = gotifyService;
_ntfyService = ntfyService;
_rateLimiter = rateLimiter;
_logger = logger;
}
@@ -89,13 +89,11 @@ public class NotificationService : INotificationService
ct);
}
if (config.GotifyEnabled
&& !string.IsNullOrEmpty(config.GotifyUrl)
&& !string.IsNullOrEmpty(config.GotifyToken))
if (config.NtfyEnabled)
{
await _gotifyService.SendNotificationAsync(
config.GotifyUrl,
config.GotifyToken,
var topic = $"heimdall_{userId}";
await _ntfyService.SendNotificationAsync(
topic,
notification.Title,
notification.Message,
ct: ct);
@@ -0,0 +1,54 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Heimdall.Application.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class NtfyService : INtfyService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<NtfyService> _logger;
private readonly string _baseUrl;
private readonly string? _authToken;
public NtfyService(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<NtfyService> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_baseUrl = configuration.GetValue<string>("Ntfy:BaseUrl")
?? Environment.GetEnvironmentVariable("NTFY__BASE_URL")
?? "http://ntfy:80";
_authToken = configuration.GetValue<string>("Ntfy:Token")
?? Environment.GetEnvironmentVariable("NTFY__TOKEN");
}
public async Task SendNotificationAsync(string topic, string title, string message, int priority = 3, CancellationToken ct = default)
{
try
{
var client = _httpClientFactory.CreateClient("Ntfy");
var requestUrl = $"{_baseUrl.TrimEnd('/')}/{topic}";
var payload = new { topic, title, message, priority };
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(_authToken))
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _authToken);
var response = await client.PostAsync(requestUrl, content, ct);
if (!response.IsSuccessStatusCode)
{
var body = await response.Content.ReadAsStringAsync(ct);
_logger.LogWarning("ntfy returned {StatusCode} for topic {Topic}: {Body}", response.StatusCode, topic, body);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send ntfy notification to topic {Topic}", topic);
}
}
}
@@ -89,9 +89,8 @@ public class NotificationsController : ControllerBase
GetUserId(),
request.EmailEnabled,
request.EmailAddress,
request.GotifyEnabled,
request.GotifyUrl,
request.GotifyToken,
request.NtfyEnabled,
request.NtfyUrl,
request.Language,
request.DailyDigest,
request.WeeklyDigest,
@@ -222,7 +222,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, null), _ct);
userId, true, "user@example.com", null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -241,7 +241,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, null), _ct);
userId, true, "new@example.com", null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -255,24 +255,24 @@ public class NotificationHandlerTests
var userId = Guid.NewGuid();
var existing = new UserNotificationConfig(userId);
existing.UpdateEmail("existing@example.com", true);
existing.UpdateGotify("https://gotify.example.com", "old-token", true);
existing.UpdateNtfy("https://ntfy.example.com", true);
existing.UpdateDigests(true, false);
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor([existing]));
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
// 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, null), _ct);
userId, null, "updated@example.com", null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.EmailAddress.ShouldBe("updated@example.com");
result.Data.EmailEnabled.ShouldBeTrue(); // unchanged
result.Data.GotifyEnabled.ShouldBeTrue(); // unchanged
result.Data.NtfyEnabled.ShouldBeTrue(); // unchanged
}
[Fact]
public async Task Handle_UpdateNotificationConfig_ShouldUpdateGotifySettings()
public async Task Handle_UpdateNotificationConfig_ShouldUpdateNtfySettings()
{
var userId = Guid.NewGuid();
var existing = new UserNotificationConfig(userId);
@@ -281,12 +281,12 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, true, "https://gotify.example.com", "new-token", null, null, null, null), _ct);
userId, null, null, true, "https://ntfy.example.com", null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.GotifyEnabled.ShouldBeTrue();
result.Data.GotifyUrl.ShouldBe("https://gotify.example.com");
result.Data.NtfyEnabled.ShouldBeTrue();
result.Data.NtfyUrl.ShouldBe("https://ntfy.example.com");
}
[Fact]
@@ -297,7 +297,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, null, null, null, null, true, true, null), _ct);
userId, null, null, null, null, null, true, true, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -313,7 +313,7 @@ public class NotificationHandlerTests
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, null, null, null, "de", null, null, null), _ct);
userId, null, null, null, null, "de", null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
@@ -99,7 +99,7 @@ public class NotificationTests
{
((int)NotificationChannel.InApp).ShouldBe(0);
((int)NotificationChannel.Email).ShouldBe(1);
((int)NotificationChannel.Gotify).ShouldBe(2);
((int)NotificationChannel.Ntfy).ShouldBe(2);
}
}
@@ -159,7 +159,7 @@ public class UserNotificationConfigTests
config.Id.ShouldNotBe(Guid.Empty);
config.UserId.ShouldBe(userId);
config.EmailEnabled.ShouldBeFalse();
config.GotifyEnabled.ShouldBeFalse();
config.NtfyEnabled.ShouldBeFalse();
config.Language.ShouldBe("fr");
config.DailyDigest.ShouldBeFalse();
config.WeeklyDigest.ShouldBeFalse();
@@ -190,15 +190,14 @@ public class UserNotificationConfigTests
}
[Fact]
public void UpdateGotify_should_set_properties()
public void UpdateNtfy_should_set_properties()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.UpdateGotify("http://gotify:8080", "token123", true);
config.UpdateNtfy("http://ntfy:80", true);
config.GotifyUrl.ShouldBe("http://gotify:8080");
config.GotifyToken.ShouldBe("token123");
config.GotifyEnabled.ShouldBeTrue();
config.NtfyUrl.ShouldBe("http://ntfy:80");
config.NtfyEnabled.ShouldBeTrue();
}
[Fact]
@@ -27,7 +27,7 @@ public class NotificationServiceTests : IDisposable
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly IGotifyService _gotifyService;
private readonly INtfyService _ntfyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
private readonly NotificationService _service;
@@ -51,12 +51,12 @@ public class NotificationServiceTests : IDisposable
_broadcast = Substitute.For<INotificationBroadcastService>();
_emailService = Substitute.For<IEmailService>();
_gotifyService = Substitute.For<IGotifyService>();
_ntfyService = Substitute.For<INtfyService>();
_rateLimiter = Substitute.For<INotificationRateLimiter>();
_logger = Substitute.For<ILogger<NotificationService>>();
_service = new NotificationService(
_context, _mapper, _broadcast, _emailService, _gotifyService,
_context, _mapper, _broadcast, _emailService, _ntfyService,
_rateLimiter, _logger);
}