feat(notifications): fan out camera events to authorized users
Heimdall Gitea / Build and tests (pull_request) Failing after 0s
Heimdall Gitea / Publish versioned release (pull_request) Skipped

This commit is contained in:
Arnaud Dartois committed 2026-10-22 19:43:18 +02:00
1 parent 573e6c37cc
commit d78da50c93
10 files changed
+163 -32

No files matched your search

@@ -35,7 +35,11 @@ public class CreateEventHandler : IRequestHandler<CreateEventCommand, ServiceRes
.FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct)
.ConfigureAwait(false);
if (existing is not null)
return ServiceResult<CameraEventResponse>.Success(MapResponse(existing));
{
var existingResponse = MapResponse(existing);
await _publisher.Publish(new EventCreatedNotification(existingResponse), ct).ConfigureAwait(false);
return ServiceResult<CameraEventResponse>.Success(existingResponse);
}
}
var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, occurredAt, eventId);
@@ -53,7 +57,9 @@ public class CreateEventHandler : IRequestHandler<CreateEventCommand, ServiceRes
.FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct)
.ConfigureAwait(false);
if (duplicate is null) throw;
return ServiceResult<CameraEventResponse>.Success(MapResponse(duplicate));
var duplicateResponse = MapResponse(duplicate);
await _publisher.Publish(new EventCreatedNotification(duplicateResponse), ct).ConfigureAwait(false);
return ServiceResult<CameraEventResponse>.Success(duplicateResponse);
}
var response = MapResponse(ev);
@@ -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<EventCreatedNotification>
{
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}");
}
}
}
@@ -23,6 +23,9 @@ public interface ICameraAccessService
/// </summary>
Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default);
/// <summary>Returns users with current access to a camera, including direct, site, group, and admin grants.</summary>
Task<List<Guid>> GetUserIdsWithCameraAccessAsync(Guid cameraId, CancellationToken ct = default);
/// <summary>
/// Returns camera IDs the user can access within a specific site.
/// Admins get all camera IDs for the site. Non-admins get cameras from
@@ -3,10 +3,10 @@ using Heimdall.Domain.Enums;
namespace Heimdall.Application.Services;
/// <summary>
/// Rate-limits notifications per camera/type to prevent spam.
/// Rate-limits notifications per recipient/camera/type to prevent spam without starving other recipients.
/// </summary>
public interface INotificationRateLimiter
{
/// <summary>Returns true if the notification should be sent.</summary>
bool ShouldSend(Guid cameraId, EventType type, Guid? trackId);
bool ShouldSend(Guid cameraId, EventType type, Guid? recipientId);
}
@@ -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);
/// <summary>Get unread notification count for a user.</summary>
Task<int> GetUnreadCountAsync(Guid userId, CancellationToken ct = default);
+12 -2
View File
@@ -1,3 +1,4 @@
using System.Security.Cryptography;
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
@@ -27,8 +28,8 @@ public class Notification : Entity<Guid>, 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<Guid>, IAuditableEntity
Link = link;
}
/// <summary>Creates a stable notification key so event delivery retries do not duplicate inbox rows.</summary>
public static Guid GetEventNotificationId(Guid userId, Guid eventId)
{
Span<byte> input = stackalloc byte[32];
userId.TryWriteBytes(input[..16]);
eventId.TryWriteBytes(input[16..]);
return new Guid(SHA256.HashData(input)[..16]);
}
public void MarkAsRead()
{
IsRead = true;
@@ -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);
@@ -15,6 +15,32 @@ public class CameraAccessService(IApplicationDbContext context) : ICameraAccessS
public Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
=> ApplyCameraFilter(context.Cameras, userId).Select(c => c.Id).ToListAsync(ct);
public async Task<List<Guid>> 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<List<Guid>> GetAccessibleCameraIdsAsync(Guid userId, Guid siteId, CancellationToken ct = default)
=> ApplyCameraFilter(context.Cameras, userId).Where(c => c.SiteId == siteId).Select(c => c.Id).ToListAsync(ct);
@@ -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 =>
{
@@ -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<NotificationService> _logger;
private readonly IBackgroundJobClient? _backgroundJobs;
public NotificationService(
IApplicationDbContext context,
@@ -28,7 +33,8 @@ public class NotificationService : INotificationService
IEmailService emailService,
INtfyService ntfyService,
INotificationRateLimiter rateLimiter,
ILogger<NotificationService> logger)
ILogger<NotificationService> 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<ServiceResult<NotificationDto>> 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<NotificationDto>.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<NotificationDto>(notification);
@@ -114,28 +139,41 @@ public class NotificationService : INotificationService
if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress))
{
await _emailService.SendEmailAsync(
config.EmailAddress,
notification.Title,
$"<h2>{notification.Title}</h2><p>{notification.Message}</p>",
ct);
var htmlBody = $"<h2>{HtmlEncoder.Default.Encode(notification.Title)}</h2><p>{HtmlEncoder.Default.Encode(notification.Message)}</p>";
if (_backgroundJobs is null)
{
await _emailService.SendEmailAsync(config.EmailAddress, notification.Title, htmlBody, ct).ConfigureAwait(false);
}
else
{
var job = Job.FromExpression<SendNotificationJob>(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<SendNotificationJob>(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;
}
}