## What Complète le paramétrage des notifications ntfy (serveur + utilisateur, UI + backend). ## Why L'issue #60 demandait un paramétrage complet. Le code existant avait des bugs et des manques : - Le lookup DB de l'URL ntfy ratait à cause d'un mismatch de casing (`ntfy.baseUrl` vs `ntfy.baseurl`) - L'override URL par utilisateur (`UserNotificationConfig.NtfyUrl`) n'était jamais utilisé lors de l'envoi - La page profil n'affichait pas le topic ntfy à s'abonner - Le test ntfy n'envoyait pas le topic de l'utilisateur ## Changes - **Fix casing** : `NtfyService.ResolveConfigAsync` lit maintenant `ntfy.baseurl` (lowercase) pour correspondre à ce que l'UI écrit - **Per-user URL override** : `INtfyService` accepte un `baseUrl` optionnel ; `NotificationService` passe `config.NtfyUrl` lors de l'envoi - **Profile.razor** : affiche le topic ntfy personnalisé (`heimdall_{userId}`) + bouton "Tester ntfy" qui envoie vers le topic de l'utilisateur - **HeimdallApiClient** : `TestNtfyAsync` accepte et envoie le topic dans le body - **SendNotificationJob** : transmet le paramètre `baseUrl` ## Testing - `dotnet build` : 0 erreurs, 0 warnings - 963 tests unitaires passent (Domain 142, Application 391, Infrastructure 177, Agent 197, Web 243, Api 2) Closes #60 Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/152
198 lines
7.1 KiB
C#
198 lines
7.1 KiB
C#
using AutoMapper;
|
|
using AutoMapper.QueryableExtensions;
|
|
using Heimdall.Application.Common;
|
|
using Heimdall.Application.DTOs;
|
|
using Heimdall.Application.Services;
|
|
using Heimdall.Domain.Entities;
|
|
using Heimdall.Domain.Enums;
|
|
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;
|
|
|
|
public NotificationService(
|
|
IApplicationDbContext context,
|
|
IMapper mapper,
|
|
INotificationBroadcastService broadcast,
|
|
IEmailService emailService,
|
|
INtfyService ntfyService,
|
|
INotificationRateLimiter rateLimiter,
|
|
ILogger<NotificationService> logger)
|
|
{
|
|
_context = context;
|
|
_mapper = mapper;
|
|
_broadcast = broadcast;
|
|
_emailService = emailService;
|
|
_ntfyService = ntfyService;
|
|
_rateLimiter = rateLimiter;
|
|
_logger = logger;
|
|
}
|
|
|
|
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)
|
|
{
|
|
// Rate limiting check
|
|
if (cameraId.HasValue && eventType.HasValue)
|
|
{
|
|
if (!_rateLimiter.ShouldSend(cameraId.Value, eventType.Value, null))
|
|
{
|
|
_logger.LogDebug("Rate limited notification for camera {CameraId} type {EventType}", cameraId, eventType);
|
|
return ServiceResult<NotificationDto>.Success(null!); // Silently skip
|
|
}
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
}
|
|
|
|
var notification = new Notification(
|
|
userId, title, message, type, eventType, cameraId, siteId, snapshotUrl, link);
|
|
|
|
_context.Notifications.Add(notification);
|
|
await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
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;
|
|
|
|
if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress))
|
|
{
|
|
await _emailService.SendEmailAsync(
|
|
config.EmailAddress,
|
|
notification.Title,
|
|
$"<h2>{notification.Title}</h2><p>{notification.Message}</p>",
|
|
ct);
|
|
}
|
|
|
|
if (config.NtfyEnabled)
|
|
{
|
|
var topic = await ResolveNtfyTopicAsync(notification, userId, ct);
|
|
await _ntfyService.SendNotificationAsync(
|
|
topic,
|
|
notification.Title,
|
|
notification.Message,
|
|
ct: ct,
|
|
baseUrl: config.NtfyUrl);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Failed to dispatch external notification for user {UserId}", userId);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Résout le topic ntfy cible d'une notification (ticket #105) :
|
|
/// topic du site si défini, sinon topic personnel <c>heimdall_{userId}</c>.
|
|
/// </summary>
|
|
private async Task<string> ResolveNtfyTopicAsync(Notification notification, Guid userId, CancellationToken ct)
|
|
{
|
|
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;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|