From d78da50c9335e297d028811582766704264bf65a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 22 Oct 2026 19:43:18 +0200 Subject: [PATCH] feat(notifications): fan out camera events to authorized users --- .../CreateEvent/CreateEventHandler.cs | 10 ++- .../EventCreatedNotificationHandler.cs | 47 ++++++++++- .../Services/ICameraAccessService.cs | 3 + .../Services/INotificationRateLimiter.cs | 4 +- .../Services/INotificationService.cs | 2 +- src/Heimdall.Domain/Entities/Notification.cs | 14 +++- .../Jobs/SendNotificationJob.cs | 3 + .../Services/CameraAccessService.cs | 26 ++++++ .../Services/NotificationRateLimiter.cs | 4 +- .../Services/NotificationService.cs | 82 ++++++++++++++----- 10 files changed, 163 insertions(+), 32 deletions(-) diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs index 5dceca4..35a092f 100644 --- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs +++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs @@ -35,7 +35,11 @@ public class CreateEventHandler : IRequestHandler e.Id == eventId && e.OccurredAt == occurredAt, ct) .ConfigureAwait(false); if (existing is not null) - return ServiceResult.Success(MapResponse(existing)); + { + var existingResponse = MapResponse(existing); + await _publisher.Publish(new EventCreatedNotification(existingResponse), ct).ConfigureAwait(false); + return ServiceResult.Success(existingResponse); + } } var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, occurredAt, eventId); @@ -53,7 +57,9 @@ public class CreateEventHandler : IRequestHandler e.Id == eventId && e.OccurredAt == occurredAt, ct) .ConfigureAwait(false); if (duplicate is null) throw; - return ServiceResult.Success(MapResponse(duplicate)); + var duplicateResponse = MapResponse(duplicate); + await _publisher.Publish(new EventCreatedNotification(duplicateResponse), ct).ConfigureAwait(false); + return ServiceResult.Success(duplicateResponse); } var response = MapResponse(ev); diff --git a/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs b/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs index 3a76657..6c9bb09 100644 --- a/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs +++ b/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Services; +using Heimdall.Domain.Enums; using MediatR; namespace Heimdall.Application.Events.Notifications; @@ -6,11 +7,55 @@ namespace Heimdall.Application.Events.Notifications; public class EventCreatedNotificationHandler : INotificationHandler { private readonly IEventBroadcastService _broadcast; + private readonly ICameraAccessService _cameraAccess; + private readonly INotificationService _notifications; - public EventCreatedNotificationHandler(IEventBroadcastService broadcast) => _broadcast = broadcast; + public EventCreatedNotificationHandler( + IEventBroadcastService broadcast, + ICameraAccessService cameraAccess, + INotificationService notifications) + { + _broadcast = broadcast; + _cameraAccess = cameraAccess; + _notifications = notifications; + } public async Task Handle(EventCreatedNotification notification, CancellationToken ct) { await _broadcast.NotifyEventCreated(notification.Event, ct).ConfigureAwait(false); + + var cameraEvent = notification.Event; + var recipients = await _cameraAccess.GetUserIdsWithCameraAccessAsync(cameraEvent.CameraId, ct) + .ConfigureAwait(false); + var title = cameraEvent.Type switch + { + EventType.PersonDetected => "Personne détectée", + EventType.VehicleDetected => "Véhicule détecté", + EventType.UnknownPerson => "Personne inconnue détectée", + EventType.FaceRecognized => "Visage reconnu", + EventType.LicensePlateDetected => "Plaque détectée", + EventType.CameraOffline => "Caméra hors ligne", + EventType.CameraOnline => "Caméra en ligne", + _ => "Mouvement détecté" + }; + var message = string.IsNullOrWhiteSpace(cameraEvent.Label) + ? $"{title} sur la caméra {cameraEvent.CameraId}." + : $"{title} sur la caméra {cameraEvent.CameraId} : {cameraEvent.Label}."; + var type = cameraEvent.Type is EventType.UnknownPerson or EventType.CameraOffline + ? NotificationType.Alert + : cameraEvent.Type == EventType.CameraOnline + ? NotificationType.Info + : NotificationType.Warning; + + foreach (var userId in recipients) + { + var result = await _notifications.CreateNotificationAsync( + userId, title, message, type, cameraEvent.Type, cameraEvent.CameraId, + cameraEvent.SiteId, cameraEvent.SnapshotUrl, + $"/events?cameraId={cameraEvent.CameraId}&eventId={cameraEvent.Id}", + sourceEventId: cameraEvent.Id, ct: ct).ConfigureAwait(false); + if (!result.IsSuccess) + throw new InvalidOperationException($"Could not persist event notification for user {userId}: {result.Error}"); + } } } diff --git a/src/Heimdall.Application/Services/ICameraAccessService.cs b/src/Heimdall.Application/Services/ICameraAccessService.cs index 6dac84d..0c54c61 100644 --- a/src/Heimdall.Application/Services/ICameraAccessService.cs +++ b/src/Heimdall.Application/Services/ICameraAccessService.cs @@ -23,6 +23,9 @@ public interface ICameraAccessService /// Task> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default); + /// Returns users with current access to a camera, including direct, site, group, and admin grants. + Task> GetUserIdsWithCameraAccessAsync(Guid cameraId, CancellationToken ct = default); + /// /// Returns camera IDs the user can access within a specific site. /// Admins get all camera IDs for the site. Non-admins get cameras from diff --git a/src/Heimdall.Application/Services/INotificationRateLimiter.cs b/src/Heimdall.Application/Services/INotificationRateLimiter.cs index d5b83b9..63a1bea 100644 --- a/src/Heimdall.Application/Services/INotificationRateLimiter.cs +++ b/src/Heimdall.Application/Services/INotificationRateLimiter.cs @@ -3,10 +3,10 @@ using Heimdall.Domain.Enums; namespace Heimdall.Application.Services; /// -/// Rate-limits notifications per camera/type to prevent spam. +/// Rate-limits notifications per recipient/camera/type to prevent spam without starving other recipients. /// public interface INotificationRateLimiter { /// Returns true if the notification should be sent. - bool ShouldSend(Guid cameraId, EventType type, Guid? trackId); + bool ShouldSend(Guid cameraId, EventType type, Guid? recipientId); } diff --git a/src/Heimdall.Application/Services/INotificationService.cs b/src/Heimdall.Application/Services/INotificationService.cs index 322c089..a51cb3a 100644 --- a/src/Heimdall.Application/Services/INotificationService.cs +++ b/src/Heimdall.Application/Services/INotificationService.cs @@ -16,7 +16,7 @@ public interface INotificationService Guid userId, string title, string message, NotificationType type, EventType? eventType = null, Guid? cameraId = null, Guid? siteId = null, string? snapshotUrl = null, string? link = null, - CancellationToken ct = default); + Guid? sourceEventId = null, CancellationToken ct = default); /// Get unread notification count for a user. Task GetUnreadCountAsync(Guid userId, CancellationToken ct = default); diff --git a/src/Heimdall.Domain/Entities/Notification.cs b/src/Heimdall.Domain/Entities/Notification.cs index 53fa51f..ad533be 100644 --- a/src/Heimdall.Domain/Entities/Notification.cs +++ b/src/Heimdall.Domain/Entities/Notification.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Heimdall.Domain.Enums; using Heimdall.Domain.Primitives; @@ -27,8 +28,8 @@ public class Notification : Entity, IAuditableEntity public Notification(Guid userId, string title, string message, NotificationType type, EventType? eventType = null, Guid? cameraId = null, Guid? siteId = null, - string? snapshotUrl = null, string? link = null) - : base(Guid.NewGuid()) + string? snapshotUrl = null, string? link = null, Guid? id = null) + : base(id ?? Guid.NewGuid()) { UserId = userId; Title = title; @@ -41,6 +42,15 @@ public class Notification : Entity, IAuditableEntity Link = link; } + /// Creates a stable notification key so event delivery retries do not duplicate inbox rows. + public static Guid GetEventNotificationId(Guid userId, Guid eventId) + { + Span input = stackalloc byte[32]; + userId.TryWriteBytes(input[..16]); + eventId.TryWriteBytes(input[16..]); + return new Guid(SHA256.HashData(input)[..16]); + } + public void MarkAsRead() { IsRead = true; diff --git a/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs b/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs index 1302eb9..4b8a826 100644 --- a/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Services; +using Hangfire; using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Jobs; @@ -23,12 +24,14 @@ public class SendNotificationJob _logger = logger; } + [AutomaticRetry(Attempts = 10, OnAttemptsExceeded = AttemptsExceededAction.Fail)] public async Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default) { _logger.LogInformation("Sending email notification to {Recipient}: {Subject}", recipient, subject); await _emailService.SendEmailAsync(recipient, subject, bodyHtml, ct).ConfigureAwait(false); } + [AutomaticRetry(Attempts = 10, OnAttemptsExceeded = AttemptsExceededAction.Fail)] public async Task SendNtfyAsync(string topic, string title, string message, int priority = 3, string? baseUrl = null, CancellationToken ct = default) { _logger.LogInformation("Sending ntfy notification: {Title}", title); diff --git a/src/Heimdall.Infrastructure/Services/CameraAccessService.cs b/src/Heimdall.Infrastructure/Services/CameraAccessService.cs index a1b1701..e0e5f27 100644 --- a/src/Heimdall.Infrastructure/Services/CameraAccessService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraAccessService.cs @@ -15,6 +15,32 @@ public class CameraAccessService(IApplicationDbContext context) : ICameraAccessS public Task> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default) => ApplyCameraFilter(context.Cameras, userId).Select(c => c.Id).ToListAsync(ct); + public async Task> GetUserIdsWithCameraAccessAsync(Guid cameraId, CancellationToken ct = default) + { + var siteId = await context.Cameras.AsNoTracking() + .Where(c => c.Id == cameraId) + .Select(c => (Guid?)c.SiteId) + .FirstOrDefaultAsync(ct) + .ConfigureAwait(false); + if (!siteId.HasValue) return []; + + return await context.Users.AsNoTracking() + .Where(user => + context.UserRoles.Any(ur => ur.UserId == user.Id && + context.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin)) || + context.UserCameraAccesses.Any(grant => grant.UserId == user.Id && grant.SiteId == siteId.Value && + (grant.CameraId == null || grant.CameraId == cameraId)) || + context.UserCameras.Any(grant => grant.UserId == user.Id && grant.CameraId == cameraId) || + context.UserSites.Any(grant => grant.UserId == user.Id && grant.SiteId == siteId.Value) || + context.GroupCameraAccesses.Any(grant => grant.CameraId == cameraId && + context.Groups.Any(group => group.Id == grant.GroupId && !group.IsDeleted) && + context.UserGroups.Any(member => member.UserId == user.Id && member.GroupId == grant.GroupId))) + .Select(user => user.Id) + .Distinct() + .ToListAsync(ct) + .ConfigureAwait(false); + } + public Task> GetAccessibleCameraIdsAsync(Guid userId, Guid siteId, CancellationToken ct = default) => ApplyCameraFilter(context.Cameras, userId).Where(c => c.SiteId == siteId).Select(c => c.Id).ToListAsync(ct); diff --git a/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs b/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs index 8dcefea..3b89b31 100644 --- a/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs +++ b/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs @@ -10,9 +10,9 @@ public class NotificationRateLimiter : INotificationRateLimiter public NotificationRateLimiter(IMemoryCache cache) => _cache = cache; - public bool ShouldSend(Guid cameraId, EventType type, Guid? trackId) + public bool ShouldSend(Guid cameraId, EventType type, Guid? recipientId) { - var key = $"notif-rate:{cameraId}:{type}:{trackId ?? Guid.Empty}"; + var key = $"notif-rate:{cameraId}:{type}:{recipientId ?? Guid.Empty}"; var counter = _cache.GetOrCreate(key, entry => { diff --git a/src/Heimdall.Infrastructure/Services/NotificationService.cs b/src/Heimdall.Infrastructure/Services/NotificationService.cs index 4d7d597..bbb7230 100644 --- a/src/Heimdall.Infrastructure/Services/NotificationService.cs +++ b/src/Heimdall.Infrastructure/Services/NotificationService.cs @@ -1,5 +1,9 @@ +using System.Text.Encodings.Web; using AutoMapper; using AutoMapper.QueryableExtensions; +using Hangfire; +using Hangfire.Common; +using Hangfire.States; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; @@ -20,6 +24,7 @@ public class NotificationService : INotificationService private readonly INtfyService _ntfyService; private readonly INotificationRateLimiter _rateLimiter; private readonly ILogger _logger; + private readonly IBackgroundJobClient? _backgroundJobs; public NotificationService( IApplicationDbContext context, @@ -28,7 +33,8 @@ public class NotificationService : INotificationService IEmailService emailService, INtfyService ntfyService, INotificationRateLimiter rateLimiter, - ILogger logger) + ILogger logger, + IBackgroundJobClient? backgroundJobs = null) { _context = context; _mapper = mapper; @@ -37,20 +43,27 @@ public class NotificationService : INotificationService _ntfyService = ntfyService; _rateLimiter = rateLimiter; _logger = logger; + _backgroundJobs = backgroundJobs; } public async Task> CreateNotificationAsync( Guid userId, string title, string message, NotificationType type, EventType? eventType = null, Guid? cameraId = null, Guid? siteId = null, string? snapshotUrl = null, string? link = null, - CancellationToken ct = default) + Guid? sourceEventId = null, CancellationToken ct = default) { - // Rate limiting check - if (cameraId.HasValue && eventType.HasValue) + var notificationId = sourceEventId.HasValue + ? Notification.GetEventNotificationId(userId, sourceEventId.Value) + : (Guid?)null; + var notification = notificationId.HasValue + ? await _context.Notifications.FirstOrDefaultAsync(n => n.Id == notificationId.Value, ct).ConfigureAwait(false) + : null; + + if (notification is null && cameraId.HasValue && eventType.HasValue) { - if (!_rateLimiter.ShouldSend(cameraId.Value, eventType.Value, null)) + if (!_rateLimiter.ShouldSend(cameraId.Value, eventType.Value, userId)) { - _logger.LogDebug("Rate limited notification for camera {CameraId} type {EventType}", cameraId, eventType); + _logger.LogDebug("Rate limited notification for user {UserId}, camera {CameraId}, type {EventType}", userId, cameraId, eventType); return ServiceResult.Success(null!); // Silently skip } } @@ -75,11 +88,23 @@ public class NotificationService : INotificationService } } - var notification = new Notification( - userId, title, message, type, eventType, cameraId, siteId, snapshotUrl, link); + if (notification is null) + { + notification = new Notification( + userId, title, message, type, eventType, cameraId, siteId, snapshotUrl, link, notificationId); - _context.Notifications.Add(notification); - await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + _context.Notifications.Add(notification); + try + { + await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + } + catch (DbUpdateException) when (notificationId.HasValue) + { + notification = await _context.Notifications.AsNoTracking() + .FirstOrDefaultAsync(n => n.Id == notificationId.Value, ct).ConfigureAwait(false); + if (notification is null) throw; + } + } var dto = _mapper.Map(notification); @@ -114,28 +139,41 @@ public class NotificationService : INotificationService if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress)) { - await _emailService.SendEmailAsync( - config.EmailAddress, - notification.Title, - $"

{notification.Title}

{notification.Message}

", - ct); + var htmlBody = $"

{HtmlEncoder.Default.Encode(notification.Title)}

{HtmlEncoder.Default.Encode(notification.Message)}

"; + if (_backgroundJobs is null) + { + await _emailService.SendEmailAsync(config.EmailAddress, notification.Title, htmlBody, ct).ConfigureAwait(false); + } + else + { + var job = Job.FromExpression(service => + service.SendEmailAsync(config.EmailAddress, notification.Title, htmlBody, CancellationToken.None)); + _backgroundJobs.Create(job, new EnqueuedState("email")); + } } if (config.NtfyEnabled) { var topic = await ResolveNtfyTopicAsync(notification, userId, ct); - await _ntfyService.SendNotificationAsync( - topic, - notification.Title, - notification.Message, - priority, - config.NtfyUrl, - ct); + if (_backgroundJobs is null) + { + await _ntfyService.SendNotificationAsync( + topic, notification.Title, notification.Message, priority, config.NtfyUrl, ct).ConfigureAwait(false); + } + else + { + var ntfyUrl = config.NtfyUrl; + var job = Job.FromExpression(service => + service.SendNtfyAsync(topic, notification.Title, notification.Message, priority, ntfyUrl, CancellationToken.None)); + _backgroundJobs.Create(job, new EnqueuedState("ntfy")); + } } } catch (Exception ex) { _logger.LogError(ex, "Failed to dispatch external notification for user {UserId}", userId); + if (_backgroundJobs is not null) + throw; } } -- 2.54.1