From 599237dd2c010fb05321bb3f2e8a44ba6873b5a0 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Thu, 19 Nov 2026 14:02:02 +0100 Subject: [PATCH] Add queued email and Firebase push delivery --- README.md | 6 +- backend/Directory.Packages.props | 1 + .../AdminNotificationDeliveriesController.cs | 32 +++++ .../Controllers/DevicesController.cs | 33 +++++ backend/src/Helpdesk.Api/Program.cs | 20 +++ .../Abstractions/Abstractions.cs | 1 + .../src/Helpdesk.Application/Common/Errors.cs | 5 +- .../DependencyInjection.cs | 2 + .../NotificationDeliveryService.cs | 53 ++++++++ .../Notifications/PushDeviceService.cs | 27 ++++ .../Notifications/Notification.cs | 39 +++++- .../Background/NotificationDispatcher.cs | 121 +++++++++++++++++ .../DependencyInjection.cs | 5 + .../Email/SmtpEmailSender.cs | 10 +- .../Helpdesk.Infrastructure.csproj | 1 + .../Notifications/FirebasePushSender.cs | 122 ++++++++++++++++++ .../Persistence/HelpdeskDbContext.cs | 11 +- .../Persistence/IssueConfigurations.cs | 1 + .../V003__push_device_token_collation.sql | 3 + deploy/.env.example | 5 + deploy/db-init/Dockerfile | 2 + deploy/docker-compose.yml | 5 +- 22 files changed, 497 insertions(+), 8 deletions(-) create mode 100644 backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs create mode 100644 backend/src/Helpdesk.Api/Controllers/DevicesController.cs create mode 100644 backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs create mode 100644 backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs create mode 100644 db/migrations/V003__push_device_token_collation.sql create mode 100644 deploy/db-init/Dockerfile diff --git a/README.md b/README.md index eae53f4..5cc6ed0 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce | Složka / soubor | Obsah | |---|---| | [docs/navrh-aplikace.md](docs/navrh-aplikace.md) | Návrhový dokument (v1.1 – včetně zapracovaných připomínek z obhajoby) | -| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – `V001` schéma, `V002` číselníky | +| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – schéma, číselníky a porovnávání FCM tokenů | | [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) | | [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` | @@ -37,6 +37,10 @@ Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adre Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli. +Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. + +S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase. + ### Vývoj bez Dockeru Vyžaduje .NET SDK 10. Unit testy: diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index ee2454d..f0f39c6 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -18,6 +18,7 @@ + diff --git a/backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs b/backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs new file mode 100644 index 0000000..bdacc59 --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs @@ -0,0 +1,32 @@ +using Helpdesk.Api.Infrastructure; +using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize(Roles = Roles.Admin)] +[Route("api/admin/notification-deliveries")] +public sealed class AdminNotificationDeliveriesController(NotificationDeliveryService deliveries) : ControllerBase +{ + /// Přehled doručení podle stavu, výchozí stav je FAILED. + [HttpGet] + [ProducesResponseType>(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public Task> List( + CancellationToken ct, [FromQuery] string status = "FAILED", [FromQuery] int page = 1, [FromQuery] int pageSize = 20) => + deliveries.ListAsync(status, page, pageSize, ct); + + /// Vrátí neúspěšné doručení do fronty s novým počtem pokusů. + [HttpPost("{id:int}/retry")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task Retry(int id, CancellationToken ct) + { + await deliveries.RetryAsync(id, ct); + return NoContent(); + } +} diff --git a/backend/src/Helpdesk.Api/Controllers/DevicesController.cs b/backend/src/Helpdesk.Api/Controllers/DevicesController.cs new file mode 100644 index 0000000..56fc6b7 --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/DevicesController.cs @@ -0,0 +1,33 @@ +using Helpdesk.Application.Notifications; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +public sealed record RegisterDeviceRequest(string Token); + +[ApiController] +[Authorize] +[Route("api/devices")] +public sealed class DevicesController(PushDeviceService devices) : ControllerBase +{ + /// Zaregistruje FCM token pro právě přihlášeného uživatele. + [HttpPost] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Register(RegisterDeviceRequest request, CancellationToken ct) + { + await devices.RegisterAsync(request.Token, ct); + return NoContent(); + } + + /// Odregistruje token právě přihlášeného uživatele. + [HttpDelete("{token}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Unregister(string token, CancellationToken ct) + { + await devices.UnregisterAsync(token, ct); + return NoContent(); + } +} diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index 88dd819..ef09b00 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -1,9 +1,11 @@ +using System.Net; using System.Threading.RateLimiting; using Helpdesk.Api.Infrastructure; using Helpdesk.Application; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Infrastructure; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.IdentityModel.JsonWebTokens; var builder = WebApplication.CreateBuilder(args); @@ -28,6 +30,21 @@ builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler(); builder.Services.AddHelpdeskSwagger(); +var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"]; +if (!string.IsNullOrWhiteSpace(trustedProxy)) +{ + if (!IPAddress.TryParse(trustedProxy, out var proxyAddress)) + throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy."); + + builder.Services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + options.KnownIPNetworks.Clear(); + options.KnownProxies.Clear(); + options.KnownProxies.Add(proxyAddress); + }); +} + // Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10). builder.Services.AddRateLimiter(options => { @@ -47,6 +64,9 @@ builder.Services.AddRateLimiter(options => var app = builder.Build(); +if (!string.IsNullOrWhiteSpace(trustedProxy)) + app.UseForwardedHeaders(); + app.UseExceptionHandler(); app.UseStatusCodePages(); diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index abcdb58..aa3f044 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -32,6 +32,7 @@ public interface IAppDbContext Task SaveChangesAsync(CancellationToken cancellationToken = default); Task BeginProposalWriteAsync(CancellationToken ct); Task LockProposalAsync(int id, CancellationToken ct); + Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct); } public interface IPasswordHasher diff --git a/backend/src/Helpdesk.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index bf94d77..56eaafb 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -31,8 +31,11 @@ public sealed class BadRequestException(string message) : AppException(message) public override int StatusCode => 400; } -public sealed class EmailDeliveryException() : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") +public sealed class EmailDeliveryException(string reason, bool retryable) + : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") { + public string Reason { get; } = reason; + public bool Retryable { get; } = retryable; public override int StatusCode => 503; } diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index 290ea91..f58039f 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -24,7 +24,9 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); return services; diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs new file mode 100644 index 0000000..028ef12 --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs @@ -0,0 +1,53 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Domain; +using Helpdesk.Domain.Notifications; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +public sealed record NotificationDeliveryDto( + int Id, int NotificationId, string Channel, string Status, int AttemptCount, + string? LastError, DateTime? NextAttemptAt, DateTime? SentAt); + +public sealed class NotificationDeliveryService(IAppDbContext db, TimeProvider clock) +{ + public async Task> ListAsync(string status, int page, int pageSize, CancellationToken ct) + { + if (!EnumCode.TryParse(status, out var deliveryStatus)) + throw new BadRequestException("Neplatný stav doručení."); + + page = Math.Max(1, page); + pageSize = Math.Clamp(pageSize, 1, 100); + var query = db.NotificationDeliveries.AsNoTracking().Where(d => d.Status == deliveryStatus); + var count = await query.CountAsync(ct); + var offset = (long)(page - 1) * pageSize; + if (offset >= count) + return new PagedResult([], count, page, pageSize); + + var rows = await query.OrderByDescending(d => d.Id).Skip((int)offset).Take(pageSize).ToListAsync(ct); + var items = rows.Select(d => new NotificationDeliveryDto(d.Id, d.NotificationId, d.Channel.ToCode(), + d.Status.ToCode(), d.AttemptCount, d.LastError, d.NextAttemptAt, d.SentAt)).ToArray(); + return new PagedResult(items, count, page, pageSize); + } + + public async Task RetryAsync(int id, CancellationToken ct) + { + var now = clock.GetUtcNow().UtcDateTime; + var delivery = db.NotificationDeliveries.Where(d => d.Id == id); + var updated = await delivery.Where(d => d.Status == DeliveryStatus.Failed) + .ExecuteUpdateAsync(setters => setters + .SetProperty(d => d.Status, DeliveryStatus.Pending) + .SetProperty(d => d.AttemptCount, 0) + .SetProperty(d => d.NextAttemptAt, now) + .SetProperty(d => d.LastError, (string?)null) + .SetProperty(d => d.SentAt, (DateTime?)null), ct); + if (updated == 1) + return; + + if (!await delivery.AnyAsync(ct)) + throw new NotFoundException("Doručení neexistuje."); + + throw new ConflictException("Zopakovat lze pouze neúspěšné doručení."); + } +} diff --git a/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs b/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs new file mode 100644 index 0000000..ef804c8 --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs @@ -0,0 +1,27 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser) +{ + public Task RegisterAsync(string token, CancellationToken ct) + { + ValidateToken(token); + return db.RegisterPushDeviceAsync(currentUser.Id, token, ct); + } + + public async Task UnregisterAsync(string token, CancellationToken ct) + { + ValidateToken(token); + var userId = currentUser.Id; + await db.PushDevices.Where(d => d.UserId == userId && d.FcmToken == token).ExecuteDeleteAsync(ct); + } + + private static void ValidateToken(string? token) + { + if (string.IsNullOrEmpty(token) || token.Length > 512 || token.Any(c => char.IsWhiteSpace(c) || char.IsControl(c))) + throw new BadRequestException("Neplatný registrační token zařízení."); + } +} diff --git a/backend/src/Helpdesk.Domain/Notifications/Notification.cs b/backend/src/Helpdesk.Domain/Notifications/Notification.cs index 53b1b46..45963cf 100644 --- a/backend/src/Helpdesk.Domain/Notifications/Notification.cs +++ b/backend/src/Helpdesk.Domain/Notifications/Notification.cs @@ -5,7 +5,7 @@ namespace Helpdesk.Domain.Notifications; public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } public enum DeliveryChannel { Email, Push } -public enum DeliveryStatus { Pending, Skipped } +public enum DeliveryStatus { Pending, Sent, Failed, Skipped } public sealed class Notification : IHasCreatedAt { @@ -46,6 +46,9 @@ public sealed class Notification : IHasCreatedAt public sealed class NotificationDelivery( Notification notification, DeliveryChannel channel, bool enabled, DateTime now) { + private static readonly TimeSpan[] RetryDelays = + [TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2)]; + private NotificationDelivery() : this(null!, default, false, default) { } public int Id { get; private set; } @@ -53,11 +56,45 @@ public sealed class NotificationDelivery( public Notification Notification { get; private set; } = notification; public DeliveryChannel Channel { get; private set; } = channel; public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped; + public int AttemptCount { get; private set; } public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null; + public string? LastError { get; private set; } + public DateTime? SentAt { get; private set; } + + public void RecordSent(DateTime now) + { + AttemptCount++; + Status = DeliveryStatus.Sent; + SentAt = now; + NextAttemptAt = null; + LastError = null; + } + + public void RecordFailure(DateTime now, string reason, bool retryable) + { + AttemptCount++; + LastError = reason; + if (retryable && AttemptCount <= RetryDelays.Length) + { + NextAttemptAt = now + RetryDelays[AttemptCount - 1]; + return; + } + + Status = DeliveryStatus.Failed; + NextAttemptAt = null; + } + + public void Skip() + { + Status = DeliveryStatus.Skipped; + NextAttemptAt = null; + LastError = null; + } } public sealed class PushDevice { public int Id { get; private set; } public int UserId { get; private set; } + public string FcmToken { get; private set; } = null!; } diff --git a/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs b/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs new file mode 100644 index 0000000..e2d072f --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs @@ -0,0 +1,121 @@ +using System.Data; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Domain.Notifications; +using Helpdesk.Infrastructure.Email; +using Helpdesk.Infrastructure.Notifications; +using Helpdesk.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Helpdesk.Infrastructure.Background; + +internal sealed partial class NotificationDispatcher( + IServiceScopeFactory scopes, IEmailSender email, TimeProvider clock, ILogger logger, + FirebasePushSender? push = null) : BackgroundService +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2); + private readonly bool emailEnabled = email is not LoggingEmailSender; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!emailEnabled && push is null) + return; + + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (await DeliverNextAsync(stoppingToken)) + continue; + } + catch (Exception failure) when (!stoppingToken.IsCancellationRequested) + { + LogDispatchFailure(failure.GetType().Name); + } + + await Task.Delay(PollInterval, clock, stoppingToken); + } + } + + private async Task DeliverNextAsync(CancellationToken ct) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); + var now = clock.GetUtcNow().UtcDateTime; + var rows = await db.NotificationDeliveries.FromSql($""" + SELECT * FROM notification_delivery + WHERE status = 'PENDING' AND next_attempt_at <= {now} + AND (({emailEnabled} AND channel = 'EMAIL') OR ({push is not null} AND channel = 'PUSH')) + ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED + """).ToListAsync(ct); + if (rows.SingleOrDefault() is not { } delivery) + return false; + + var recipient = await ( + from notification in db.Notifications.AsNoTracking() + join user in db.Users on notification.UserId equals user.Id + where notification.Id == delivery.NotificationId + select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled } + ).SingleAsync(ct); + + if (!recipient.IsActive) + delivery.Skip(); + else if (delivery.Channel == DeliveryChannel.Email) + { + if (recipient.EmailConfirmed && recipient.EmailNotificationsEnabled) + await SendEmailAsync(delivery, recipient.Notification, recipient.Email, ct); + else + delivery.Skip(); + } + else + { + await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct); + } + + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + return true; + } + + private async Task SendEmailAsync(NotificationDelivery delivery, Notification notification, string address, CancellationToken ct) + { + try + { + await email.SendAsync(address, notification.Title, notification.Message, ct); + delivery.RecordSent(clock.GetUtcNow().UtcDateTime); + } + catch (EmailDeliveryException failure) + { + delivery.RecordFailure(clock.GetUtcNow().UtcDateTime, failure.Reason, failure.Retryable); + } + } + + private async Task SendPushAsync( + HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct) + { + var devices = db.PushDevices.Where(d => d.UserId == userId); + var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct); + if (tokens.Length == 0) + { + delivery.Skip(); + return; + } + + var result = await push!.SendAsync(notification, tokens, ct); + foreach (var invalidToken in result.InvalidTokens) + await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct); + + var now = clock.GetUtcNow().UtcDateTime; + if (result.Sent) + delivery.RecordSent(now); + else + delivery.RecordFailure(now, result.FailureReason, result.Retryable); + } + + [LoggerMessage(Level = LogLevel.Error, Message = "Zpracování notifikační fronty selhalo ({FailureType}).")] + private partial void LogDispatchFailure(string failureType); +} diff --git a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs index 748944e..a9004d0 100644 --- a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs +++ b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs @@ -3,6 +3,7 @@ using Helpdesk.Application.Issues; using Helpdesk.Infrastructure.Background; using Helpdesk.Infrastructure.Email; using Helpdesk.Infrastructure.Files; +using Helpdesk.Infrastructure.Notifications; using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; @@ -37,11 +38,15 @@ public static class DependencyInjection services.AddSingleton(); services.AddSingleton(); AddEmailSender(services, configuration.GetSection("Smtp"), environment); + var firebaseCredentials = configuration["Firebase:ServiceAccountJson"]; + if (!string.IsNullOrWhiteSpace(firebaseCredentials)) + services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials)); services.AddSingleton(); services.AddHostedService(); services.AddHostedService(); services.AddHostedService(); + services.AddHostedService(); return services; } diff --git a/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs index 28ced30..f97b48d 100644 --- a/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs @@ -25,7 +25,7 @@ internal sealed partial class SmtpEmailSender(IOptions options, ILo if (!MailboxAddress.TryParse(to, out var recipient)) { LogDeliveryFailure("InvalidRecipient"); - throw new EmailDeliveryException(); + throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false); } var settings = options.Value; @@ -48,7 +48,13 @@ internal sealed partial class SmtpEmailSender(IOptions options, ILo OperationCanceledException)) { LogDeliveryFailure(exception.GetType().Name); - throw new EmailDeliveryException(); + if (exception is SmtpCommandException command) + { + var status = (int)command.StatusCode; + throw new EmailDeliveryException($"SMTP_{status}", retryable: status is < 500 or >= 600); + } + + throw new EmailDeliveryException($"SMTP_{exception.GetType().Name}", retryable: true); } } diff --git a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj index 593292c..caa7357 100644 --- a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj +++ b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj @@ -11,6 +11,7 @@ + diff --git a/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs b/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs new file mode 100644 index 0000000..0821254 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Security.Cryptography; +using FirebaseAdmin; +using FirebaseAdmin.Messaging; +using Google.Apis.Auth.OAuth2; +using Google.Apis.Auth.OAuth2.Responses; +using Helpdesk.Domain; +using Notification = Helpdesk.Domain.Notifications.Notification; + +namespace Helpdesk.Infrastructure.Notifications; + +internal sealed record PushDeliveryResult(bool Sent, bool Retryable, string FailureReason, IReadOnlyList InvalidTokens); + +internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable +{ + public static FirebasePushSender Create(string serviceAccountJson) + { + ServiceAccountCredential credential; + try + { + credential = CredentialFactory.FromJson(serviceAccountJson); + } + catch (Exception exception) when ( + exception is ArgumentException or InvalidOperationException or CryptographicException or Newtonsoft.Json.JsonException) + { + throw new InvalidOperationException("Nastavte platný JSON klíče servisního účtu Firebase."); + } + + if (string.IsNullOrWhiteSpace(credential.ProjectId)) + throw new InvalidOperationException("Klíč servisního účtu Firebase musí obsahovat project_id."); + + var app = FirebaseApp.Create(new AppOptions + { + Credential = credential.ToGoogleCredential(), + ProjectId = credential.ProjectId, + }); + return new FirebasePushSender(app); + } + + public async Task SendAsync(Notification notification, string[] tokens, CancellationToken ct) + { + var data = new Dictionary + { + ["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture), + }; + if (notification.IssueId is int issueId) + data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture); + if (notification.ProposalId is int proposalId) + data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture); + + var messaging = FirebaseMessaging.GetMessaging(app); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + var invalidTokens = new List(); + var sent = false; + var retryable = false; + var reason = "FCM_NO_ACCEPTED_DEVICE"; + + foreach (var batch in tokens.Chunk(500)) + { + try + { + var result = await messaging.SendEachForMulticastAsync(new MulticastMessage + { +#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM. + Tokens = batch, +#pragma warning restore CS0618 + Notification = new FirebaseAdmin.Messaging.Notification + { + Title = notification.Title, + Body = notification.Message, + }, + Data = data, + }, timeout.Token); + + sent |= result.SuccessCount > 0; + for (var i = 0; i < result.Responses.Count; i++) + { + if (result.Responses[i].Exception is not { } failure) + continue; + if (IsInvalidToken(failure)) + invalidTokens.Add(batch[i]); + + if (!retryable) + reason = FailureReason(failure); + retryable |= IsRetryable(failure); + } + } + catch (FirebaseMessagingException failure) + { + if (!retryable) + reason = FailureReason(failure); + retryable |= IsRetryable(failure); + } + catch (TokenResponseException) + { + return new PushDeliveryResult(sent, true, "FCM_AUTHENTICATION_FAILED", invalidTokens); + } + catch (Exception failure) when (!ct.IsCancellationRequested && + failure is HttpRequestException or IOException or OperationCanceledException) + { + return new PushDeliveryResult(sent, true, $"FCM_{failure.GetType().Name}", invalidTokens); + } + } + + return new PushDeliveryResult(sent, retryable, reason, invalidTokens); + } + + private static bool IsInvalidToken(FirebaseMessagingException failure) => + failure.MessagingErrorCode == MessagingErrorCode.Unregistered || + (failure.MessagingErrorCode == MessagingErrorCode.InvalidArgument && + failure.Message.Contains("registration token", StringComparison.OrdinalIgnoreCase)); + + private static bool IsRetryable(FirebaseMessagingException failure) => + failure.MessagingErrorCode is MessagingErrorCode.Unavailable or MessagingErrorCode.Internal or MessagingErrorCode.QuotaExceeded || + failure.ErrorCode is ErrorCode.Unavailable or ErrorCode.Internal or ErrorCode.ResourceExhausted or ErrorCode.DeadlineExceeded; + + private static string FailureReason(FirebaseMessagingException failure) => + $"FCM_{failure.MessagingErrorCode?.ToCode() ?? failure.ErrorCode.ToCode()}"; + + public void Dispose() => app.Delete(); +} diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index 0d8f000..4edcdbd 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -86,9 +86,18 @@ public sealed class HelpdeskDbContext(DbContextOptions option modelBuilder.Entity().HasNoKey().ToView("v_proposal_score"); modelBuilder.ApplyConfiguration(new NotificationConfiguration()); modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration()); - modelBuilder.Entity().ToTable("push_device"); + var pushDevice = modelBuilder.Entity(); + pushDevice.ToTable("push_device"); + pushDevice.Property(x => x.FcmToken).HasMaxLength(512); + pushDevice.HasIndex(x => x.FcmToken).IsUnique(); } + public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) => + Database.ExecuteSqlInterpolatedAsync($""" + INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token}) + ON DUPLICATE KEY UPDATE user_id = VALUES(user_id) + """, ct); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { // Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z". diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs index 6186dcd..6eb07aa 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs @@ -73,6 +73,7 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati b.ToTable("notification_delivery"); b.Property(x => x.Channel).HasConversion>().HasMaxLength(10); b.Property(x => x.Status).HasConversion>().HasMaxLength(10); + b.Property(x => x.LastError).HasMaxLength(1000); b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId); } } diff --git a/db/migrations/V003__push_device_token_collation.sql b/db/migrations/V003__push_device_token_collation.sql new file mode 100644 index 0000000..1847e40 --- /dev/null +++ b/db/migrations/V003__push_device_token_collation.sql @@ -0,0 +1,3 @@ +-- Registrační token FCM rozlišuje velikost písmen. +ALTER TABLE push_device + MODIFY fcm_token VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL; diff --git a/deploy/.env.example b/deploy/.env.example index cf5178d..2b3a300 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -19,6 +19,8 @@ ADMIN_PASSWORD=change-me-admin # Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli. PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1 API_HTTP_PORT=8080 +# Adresa reverse proxy tak, jak ji API vidí jako bezprostředního klienta. +TRUSTED_REVERSE_PROXY_IP= # Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény. PUBLIC_BASE_URL= #https://helpdesk.domain.local @@ -32,6 +34,9 @@ SMTP_MAILBOX= # Jednoduché uvozovky zachovají ve skutečném hesle např. znak $. SMTP_PASSWORD='' +# Jednořádkový JSON klíče servisního účtu Firebase v jednoduchých uvozovkách. +FIREBASE_SERVICE_ACCOUNT_JSON='' + # Development = bez proxy # Production = s reverse proxy ASPNETCORE_ENVIRONMENT=Development diff --git a/deploy/db-init/Dockerfile b/deploy/db-init/Dockerfile new file mode 100644 index 0000000..20e7473 --- /dev/null +++ b/deploy/db-init/Dockerfile @@ -0,0 +1,2 @@ +FROM mariadb:11.4 +COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index d977619..24d829d 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -5,7 +5,7 @@ name: helpdesk services: db: - image: mariadb:11.4 + build: ./db-init environment: MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?} MARIADB_DATABASE: helpdesk @@ -14,7 +14,6 @@ services: APP_DB_PASSWORD: ${APP_DB_PASSWORD:?} volumes: - db-data:/var/lib/mysql - - ./db-init:/docker-entrypoint-initdb.d:ro healthcheck: test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] interval: 5s @@ -51,6 +50,8 @@ services: Smtp__Port: ${SMTP_PORT:-465} Smtp__Mailbox: ${SMTP_MAILBOX:-} Smtp__Password: ${SMTP_PASSWORD:-} + Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-} + ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-} ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} volumes: