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

@@ -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;
}
}