Files
Heimdall/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs
T
Arnaud Dartois d78da50c93
Heimdall Gitea / Build and tests (pull_request) Failing after 0s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
feat(notifications): fan out camera events to authorized users
2026-10-22 19:43:18 +02:00

62 lines
2.7 KiB
C#

using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using MediatR;
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,
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}");
}
}
}