Files
Heimdall/src/Heimdall.Infrastructure/Services/NotificationService.cs
T

260 lines
10 KiB
C#
Raw Normal View History

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;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Domain.Helpers;
2026-10-22 20:03:48 +02:00
using Heimdall.Infrastructure.Jobs;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class NotificationService : INotificationService
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly INtfyService _ntfyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
private readonly IBackgroundJobClient? _backgroundJobs;
public NotificationService(
IApplicationDbContext context,
IMapper mapper,
INotificationBroadcastService broadcast,
IEmailService emailService,
INtfyService ntfyService,
INotificationRateLimiter rateLimiter,
ILogger<NotificationService> logger,
IBackgroundJobClient? backgroundJobs = null)
{
_context = context;
_mapper = mapper;
_broadcast = broadcast;
_emailService = emailService;
_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,
Guid? sourceEventId = null, CancellationToken ct = default)
{
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, userId))
{
_logger.LogDebug("Rate limited notification for user {UserId}, camera {CameraId}, type {EventType}", userId, cameraId, eventType);
return ServiceResult<NotificationDto>.Success(null!); // Silently skip
}
}
2026-07-27 09:09:14 +00:00
// Validate snapshot URL — prevent SSRF and internal URL exposure
if (!string.IsNullOrEmpty(snapshotUrl))
{
if (!Uri.TryCreate(snapshotUrl, UriKind.Absolute, out var uri))
{
_logger.LogWarning("Invalid snapshot URL format: {Url}", snapshotUrl);
snapshotUrl = null;
}
else if (uri.Scheme is not ("http" or "https"))
{
_logger.LogWarning("Blocked snapshot URL with disallowed scheme: {Scheme}", uri.Scheme);
snapshotUrl = null;
}
else if (uri.IsLoopback)
{
_logger.LogWarning("Blocked snapshot URL pointing to loopback: {Url}", snapshotUrl);
snapshotUrl = null;
}
}
if (notification is null)
{
notification = new Notification(
userId, title, message, type, eventType, cameraId, siteId, snapshotUrl, link, notificationId);
_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);
// Broadcast in-app
await _broadcast.NotifyNewNotification(dto, ct).ConfigureAwait(false);
// Send via email/ntfy if user has config
await DispatchToExternalChannelsAsync(notification, userId, ct).ConfigureAwait(false);
return ServiceResult<NotificationDto>.Success(dto);
}
private async Task DispatchToExternalChannelsAsync(Notification notification, Guid userId, CancellationToken ct)
{
try
{
var config = await _context.UserNotificationConfigs
.FirstOrDefaultAsync(c => c.UserId == userId, ct);
if (config is null) return;
// Filter by subscribed event types — if configured, only send matching events
if (!config.IsEventTypeSubscribed(notification.EventType))
{
_logger.LogDebug(
"Skipping external dispatch for user {UserId}: EventType {EventType} not subscribed",
userId, notification.EventType);
return;
}
var priority = EventTypePriorityMap.GetPriority(notification.EventType);
if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress))
{
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);
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;
}
}
/// <summary>
/// Résout le topic ntfy cible d'une notification (ticket #105) :
/// topic configuré par l'utilisateur (NtfyTopic) > topic du site > défaut heimdall_{userId}.
/// </summary>
private async Task<string> ResolveNtfyTopicAsync(Notification notification, Guid userId, CancellationToken ct)
{
// 1. User-configured topic (from profile settings)
var userConfig = await _context.UserNotificationConfigs
.AsNoTracking()
.Where(c => c.UserId == userId)
.Select(c => c.NtfyTopic)
.FirstOrDefaultAsync(ct);
if (!string.IsNullOrWhiteSpace(userConfig))
return userConfig;
// 2. Site-level topic
if (notification.SiteId is { } siteId)
{
var siteTopic = await _context.Sites
.AsNoTracking()
.Where(s => s.Id == siteId)
.Select(s => s.NtfyTopic)
.FirstOrDefaultAsync(ct);
if (!string.IsNullOrWhiteSpace(siteTopic))
return siteTopic;
}
// 3. Default
return $"heimdall_{userId}";
}
public async Task<int> GetUnreadCountAsync(Guid userId, CancellationToken ct = default)
{
return await _context.Notifications
.CountAsync(n => n.UserId == userId && !n.IsRead, ct);
}
public async Task<PagedResult<NotificationDto>> GetNotificationsAsync(
Guid userId, bool? isRead, int page, int pageSize, CancellationToken ct = default)
{
var query = _context.Notifications.Where(n => n.UserId == userId);
if (isRead.HasValue)
query = query.Where(n => n.IsRead == isRead.Value);
var totalCount = await query.CountAsync(ct).ConfigureAwait(false);
var items = await query
.OrderByDescending(n => n.CreatedAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ProjectTo<NotificationDto>(_mapper.ConfigurationProvider)
.ToListAsync(ct);
return new PagedResult<NotificationDto>(items, totalCount, page, pageSize);
}
public async Task MarkAsReadAsync(Guid notificationId, Guid userId, CancellationToken ct = default)
{
var notification = await _context.Notifications
.FirstOrDefaultAsync(n => n.Id == notificationId && n.UserId == userId, ct);
if (notification is not null)
{
notification.MarkAsRead();
await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
}
}
public async Task MarkAllAsReadAsync(Guid userId, CancellationToken ct = default)
{
var unread = await _context.Notifications
.Where(n => n.UserId == userId && !n.IsRead)
.ToListAsync(ct);
foreach (var notification in unread)
notification.MarkAsRead();
await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
}
}