Add queued email and Firebase push delivery

This commit is contained in:
GonnaHetzMe committed 2026-11-19 14:02:02 +01:00
1 parent c96eb155ae
commit 599237dd2c
22 files changed
+497 -8

No files matched your search

+5 -1
View File
@@ -9,7 +9,7 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce
| Složka / soubor | Obsah | | 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) | | [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) | | [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) |
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` | | [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. 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 ### Vývoj bez Dockeru
Vyžaduje .NET SDK 10. Unit testy: Vyžaduje .NET SDK 10. Unit testy:
+1
View File
@@ -18,6 +18,7 @@
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" /> <PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" /> <PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageVersion Include="MailKit" Version="5.0.0" /> <PackageVersion Include="MailKit" Version="5.0.0" />
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
<PackageVersion Include="FluentValidation" Version="12.2.0" /> <PackageVersion Include="FluentValidation" Version="12.2.0" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" /> <PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<!-- testy --> <!-- testy -->
@@ -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
{
/// <summary>Přehled doručení podle stavu, výchozí stav je FAILED.</summary>
[HttpGet]
[ProducesResponseType<PagedResult<NotificationDeliveryDto>>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
public Task<PagedResult<NotificationDeliveryDto>> List(
CancellationToken ct, [FromQuery] string status = "FAILED", [FromQuery] int page = 1, [FromQuery] int pageSize = 20) =>
deliveries.ListAsync(status, page, pageSize, ct);
/// <summary>Vrátí neúspěšné doručení do fronty s novým počtem pokusů.</summary>
[HttpPost("{id:int}/retry")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Retry(int id, CancellationToken ct)
{
await deliveries.RetryAsync(id, ct);
return NoContent();
}
}
@@ -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
{
/// <summary>Zaregistruje FCM token pro právě přihlášeného uživatele.</summary>
[HttpPost]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Register(RegisterDeviceRequest request, CancellationToken ct)
{
await devices.RegisterAsync(request.Token, ct);
return NoContent();
}
/// <summary>Odregistruje token právě přihlášeného uživatele.</summary>
[HttpDelete("{token}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Unregister(string token, CancellationToken ct)
{
await devices.UnregisterAsync(token, ct);
return NoContent();
}
}
+20
View File
@@ -1,9 +1,11 @@
using System.Net;
using System.Threading.RateLimiting; using System.Threading.RateLimiting;
using Helpdesk.Api.Infrastructure; using Helpdesk.Api.Infrastructure;
using Helpdesk.Application; using Helpdesk.Application;
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth; using Helpdesk.Application.Auth;
using Helpdesk.Infrastructure; using Helpdesk.Infrastructure;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.JsonWebTokens;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -28,6 +30,21 @@ builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<AppExceptionHandler>(); builder.Services.AddExceptionHandler<AppExceptionHandler>();
builder.Services.AddHelpdeskSwagger(); 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<ForwardedHeadersOptions>(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). // Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
builder.Services.AddRateLimiter(options => builder.Services.AddRateLimiter(options =>
{ {
@@ -47,6 +64,9 @@ builder.Services.AddRateLimiter(options =>
var app = builder.Build(); var app = builder.Build();
if (!string.IsNullOrWhiteSpace(trustedProxy))
app.UseForwardedHeaders();
app.UseExceptionHandler(); app.UseExceptionHandler();
app.UseStatusCodePages(); app.UseStatusCodePages();
@@ -32,6 +32,7 @@ public interface IAppDbContext
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default); Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct); Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct); Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
} }
public interface IPasswordHasher public interface IPasswordHasher
@@ -31,8 +31,11 @@ public sealed class BadRequestException(string message) : AppException(message)
public override int StatusCode => 400; 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; public override int StatusCode => 503;
} }
@@ -24,7 +24,9 @@ public static class DependencyInjection
services.AddScoped<CatalogService>(); services.AddScoped<CatalogService>();
services.AddScoped<IssueService>(); services.AddScoped<IssueService>();
services.AddScoped<NotificationService>(); services.AddScoped<NotificationService>();
services.AddScoped<NotificationDeliveryService>();
services.AddScoped<NotificationWriter>(); services.AddScoped<NotificationWriter>();
services.AddScoped<PushDeviceService>();
services.AddScoped<ProposalService>(); services.AddScoped<ProposalService>();
services.AddScoped<StatisticsService>(); services.AddScoped<StatisticsService>();
return services; return services;
@@ -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<PagedResult<NotificationDeliveryDto>> ListAsync(string status, int page, int pageSize, CancellationToken ct)
{
if (!EnumCode.TryParse<DeliveryStatus>(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<NotificationDeliveryDto>([], 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<NotificationDeliveryDto>(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í.");
}
}
@@ -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í.");
}
}
@@ -5,7 +5,7 @@ namespace Helpdesk.Domain.Notifications;
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
public enum DeliveryChannel { Email, Push } public enum DeliveryChannel { Email, Push }
public enum DeliveryStatus { Pending, Skipped } public enum DeliveryStatus { Pending, Sent, Failed, Skipped }
public sealed class Notification : IHasCreatedAt public sealed class Notification : IHasCreatedAt
{ {
@@ -46,6 +46,9 @@ public sealed class Notification : IHasCreatedAt
public sealed class NotificationDelivery( public sealed class NotificationDelivery(
Notification notification, DeliveryChannel channel, bool enabled, DateTime now) 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) { } private NotificationDelivery() : this(null!, default, false, default) { }
public int Id { get; private set; } public int Id { get; private set; }
@@ -53,11 +56,45 @@ public sealed class NotificationDelivery(
public Notification Notification { get; private set; } = notification; public Notification Notification { get; private set; } = notification;
public DeliveryChannel Channel { get; private set; } = channel; public DeliveryChannel Channel { get; private set; } = channel;
public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped; 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 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 sealed class PushDevice
{ {
public int Id { get; private set; } public int Id { get; private set; }
public int UserId { get; private set; } public int UserId { get; private set; }
public string FcmToken { get; private set; } = null!;
} }
@@ -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<NotificationDispatcher> 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<bool> DeliverNextAsync(CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
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);
}
@@ -3,6 +3,7 @@ using Helpdesk.Application.Issues;
using Helpdesk.Infrastructure.Background; using Helpdesk.Infrastructure.Background;
using Helpdesk.Infrastructure.Email; using Helpdesk.Infrastructure.Email;
using Helpdesk.Infrastructure.Files; using Helpdesk.Infrastructure.Files;
using Helpdesk.Infrastructure.Notifications;
using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Persistence;
using Helpdesk.Infrastructure.Security; using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -37,11 +38,15 @@ public static class DependencyInjection
services.AddSingleton<ITokenService, JwtTokenService>(); services.AddSingleton<ITokenService, JwtTokenService>();
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>(); services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
AddEmailSender(services, configuration.GetSection("Smtp"), environment); AddEmailSender(services, configuration.GetSection("Smtp"), environment);
var firebaseCredentials = configuration["Firebase:ServiceAccountJson"];
if (!string.IsNullOrWhiteSpace(firebaseCredentials))
services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials));
services.AddSingleton<IAttachmentStore, FileAttachmentStore>(); services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
services.AddHostedService<RevokedTokenStoreLoader>(); services.AddHostedService<RevokedTokenStoreLoader>();
services.AddHostedService<AdminSeeder>(); services.AddHostedService<AdminSeeder>();
services.AddHostedService<AuthTokenCleanupService>(); services.AddHostedService<AuthTokenCleanupService>();
services.AddHostedService<NotificationDispatcher>();
return services; return services;
} }
@@ -25,7 +25,7 @@ internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILo
if (!MailboxAddress.TryParse(to, out var recipient)) if (!MailboxAddress.TryParse(to, out var recipient))
{ {
LogDeliveryFailure("InvalidRecipient"); LogDeliveryFailure("InvalidRecipient");
throw new EmailDeliveryException(); throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false);
} }
var settings = options.Value; var settings = options.Value;
@@ -48,7 +48,13 @@ internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILo
OperationCanceledException)) OperationCanceledException))
{ {
LogDeliveryFailure(exception.GetType().Name); 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);
} }
} }
@@ -11,6 +11,7 @@
<PackageReference Include="EFCore.NamingConventions" /> <PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="BCrypt.Net-Next" /> <PackageReference Include="BCrypt.Net-Next" />
<PackageReference Include="MailKit" /> <PackageReference Include="MailKit" />
<PackageReference Include="FirebaseAdmin" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" /> <PackageReference Include="Microsoft.Extensions.Caching.Memory" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
@@ -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<string> InvalidTokens);
internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
{
public static FirebasePushSender Create(string serviceAccountJson)
{
ServiceAccountCredential credential;
try
{
credential = CredentialFactory.FromJson<ServiceAccountCredential>(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<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
{
var data = new Dictionary<string, string>
{
["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<string>();
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();
}
@@ -86,9 +86,18 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score"); modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
modelBuilder.ApplyConfiguration(new NotificationConfiguration()); modelBuilder.ApplyConfiguration(new NotificationConfiguration());
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration()); modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
modelBuilder.Entity<PushDevice>().ToTable("push_device"); var pushDevice = modelBuilder.Entity<PushDevice>();
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) 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". // Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
@@ -73,6 +73,7 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati
b.ToTable("notification_delivery"); b.ToTable("notification_delivery");
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10); b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10); b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
b.Property(x => x.LastError).HasMaxLength(1000);
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId); b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
} }
} }
@@ -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;
+5
View File
@@ -19,6 +19,8 @@ ADMIN_PASSWORD=change-me-admin
# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli. # Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli.
PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1 PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1
API_HTTP_PORT=8080 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. # Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény.
PUBLIC_BASE_URL= #https://helpdesk.domain.local PUBLIC_BASE_URL= #https://helpdesk.domain.local
@@ -32,6 +34,9 @@ SMTP_MAILBOX=
# Jednoduché uvozovky zachovají ve skutečném hesle např. znak $. # Jednoduché uvozovky zachovají ve skutečném hesle např. znak $.
SMTP_PASSWORD='' SMTP_PASSWORD=''
# Jednořádkový JSON klíče servisního účtu Firebase v jednoduchých uvozovkách.
FIREBASE_SERVICE_ACCOUNT_JSON=''
# Development = bez proxy # Development = bez proxy
# Production = s reverse proxy # Production = s reverse proxy
ASPNETCORE_ENVIRONMENT=Development ASPNETCORE_ENVIRONMENT=Development
+2
View File
@@ -0,0 +1,2 @@
FROM mariadb:11.4
COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh
+3 -2
View File
@@ -5,7 +5,7 @@ name: helpdesk
services: services:
db: db:
image: mariadb:11.4 build: ./db-init
environment: environment:
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?} MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
MARIADB_DATABASE: helpdesk MARIADB_DATABASE: helpdesk
@@ -14,7 +14,6 @@ services:
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?} APP_DB_PASSWORD: ${APP_DB_PASSWORD:?}
volumes: volumes:
- db-data:/var/lib/mysql - db-data:/var/lib/mysql
- ./db-init:/docker-entrypoint-initdb.d:ro
healthcheck: healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 5s interval: 5s
@@ -51,6 +50,8 @@ services:
Smtp__Port: ${SMTP_PORT:-465} Smtp__Port: ${SMTP_PORT:-465}
Smtp__Mailbox: ${SMTP_MAILBOX:-} Smtp__Mailbox: ${SMTP_MAILBOX:-}
Smtp__Password: ${SMTP_PASSWORD:-} Smtp__Password: ${SMTP_PASSWORD:-}
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_EMAIL: ${ADMIN_EMAIL:-}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
volumes: volumes: