feat: add multi-channel notification delivery
This commit is contained in:
1 parent
22ae66fe2d
commit
0552b3e424
21 files changed
+13567
-7
No files matched your search
@@ -1,15 +1,19 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Data;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Jiaowu.Api.Contracts;
|
||||
using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
using Jiaowu.Api.Infrastructure.Notifications;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Jiaowu.Api.Controllers;
|
||||
|
||||
@@ -19,7 +23,8 @@ namespace Jiaowu.Api.Controllers;
|
||||
public sealed class NotificationsController(
|
||||
AppDbContext db,
|
||||
ICurrentUserDataScope currentUserDataScope,
|
||||
ILogger<NotificationsController>? logger = null) : ControllerBase
|
||||
ILogger<NotificationsController>? logger = null,
|
||||
IOptions<NotificationDeliveryOptions>? deliveryOptions = null) : ControllerBase
|
||||
{
|
||||
private const int MaximumSelectedRecipients = 500;
|
||||
private const int NotificationBatchSize = 300;
|
||||
@@ -29,6 +34,8 @@ public sealed class NotificationsController(
|
||||
SystemRoles.CollegeAdmin + "," +
|
||||
SystemRoles.Counselor + "," +
|
||||
SystemRoles.Teacher;
|
||||
private readonly NotificationDeliveryOptions deliverySettings =
|
||||
deliveryOptions?.Value ?? new NotificationDeliveryOptions();
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> GetNotifications(
|
||||
@@ -121,6 +128,222 @@ public sealed class NotificationsController(
|
||||
return Ok(new { Count = count });
|
||||
}
|
||||
|
||||
[HttpGet("preferences")]
|
||||
public async Task<ActionResult> GetPreferences(CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = currentUserDataScope.Current.UserId;
|
||||
var preference = await db.NotificationPreferences.AsNoTracking()
|
||||
.SingleOrDefaultAsync(x => x.UserId == userId, cancellationToken);
|
||||
var user = await db.Users.AsNoTracking()
|
||||
.Where(x => x.Id == userId)
|
||||
.Select(x => new { x.Email, x.EmailConfirmed })
|
||||
.SingleAsync(cancellationToken);
|
||||
var subscriptions = await db.WebPushSubscriptions.AsNoTracking()
|
||||
.Where(x => x.UserId == userId)
|
||||
.OrderByDescending(x => x.LastSeenAt)
|
||||
.Select(x => new { x.Id, x.UserAgent, x.LastSeenAt, x.ExpiresAt })
|
||||
.ToListAsync(cancellationToken);
|
||||
return Ok(new
|
||||
{
|
||||
EmailEnabled = preference?.EmailEnabled ?? false,
|
||||
WebPushEnabled = preference?.WebPushEnabled ?? false,
|
||||
QuietHoursEnabled = preference?.QuietHoursEnabled ?? false,
|
||||
QuietStartMinute = preference?.QuietStartMinute ?? 22 * 60,
|
||||
QuietEndMinute = preference?.QuietEndMinute ?? 7 * 60,
|
||||
TimeZoneId = preference?.TimeZoneId ?? "Asia/Shanghai",
|
||||
user.Email,
|
||||
user.EmailConfirmed,
|
||||
EmailProviderEnabled = deliverySettings.Email.Enabled,
|
||||
WebPushProviderEnabled = deliverySettings.WebPush.Enabled,
|
||||
WebPushPublicKey = deliverySettings.WebPush.Enabled
|
||||
? deliverySettings.WebPush.PublicKey
|
||||
: null,
|
||||
Subscriptions = subscriptions
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPut("preferences")]
|
||||
public async Task<ActionResult> SavePreferences(
|
||||
SaveNotificationPreferenceRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.QuietStartMinute is < 0 or >= 24 * 60 ||
|
||||
request.QuietEndMinute is < 0 or >= 24 * 60 ||
|
||||
request.QuietStartMinute == request.QuietEndMinute)
|
||||
return ValidationProblem("静默时段必须是一天内两个不同的有效时间点。");
|
||||
try
|
||||
{
|
||||
_ = TimeZoneInfo.FindSystemTimeZoneById(request.TimeZoneId);
|
||||
}
|
||||
catch (Exception exception) when (
|
||||
exception is TimeZoneNotFoundException or InvalidTimeZoneException)
|
||||
{
|
||||
return ValidationProblem("所选时区无效。");
|
||||
}
|
||||
|
||||
var userId = currentUserDataScope.Current.UserId;
|
||||
var preference = await db.NotificationPreferences
|
||||
.SingleOrDefaultAsync(x => x.UserId == userId, cancellationToken);
|
||||
if (preference is null)
|
||||
{
|
||||
preference = new NotificationPreference { UserId = userId };
|
||||
db.NotificationPreferences.Add(preference);
|
||||
}
|
||||
preference.EmailEnabled = request.EmailEnabled;
|
||||
preference.WebPushEnabled = request.WebPushEnabled;
|
||||
preference.QuietHoursEnabled = request.QuietHoursEnabled;
|
||||
preference.QuietStartMinute = request.QuietStartMinute;
|
||||
preference.QuietEndMinute = request.QuietEndMinute;
|
||||
preference.TimeZoneId = request.TimeZoneId;
|
||||
preference.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("push-subscriptions")]
|
||||
public async Task<ActionResult> SavePushSubscription(
|
||||
SaveWebPushSubscriptionRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!deliverySettings.WebPush.Enabled)
|
||||
return ConflictProblem("Web Push 服务尚未配置,暂时不能订阅。");
|
||||
if (!TryValidatePushEndpoint(request.Endpoint, out var endpoint, out var error))
|
||||
return ValidationProblem(error!);
|
||||
if (request.P256dh.Length is < 20 or > 200 || request.Auth.Length is < 8 or > 100)
|
||||
return ValidationProblem("浏览器推送密钥格式无效。");
|
||||
if (request.ExpiresAt.HasValue && request.ExpiresAt <= DateTime.UtcNow)
|
||||
return ValidationProblem("浏览器推送订阅已经过期。");
|
||||
|
||||
var userId = currentUserDataScope.Current.UserId;
|
||||
var endpointHash = Hash(endpoint!.AbsoluteUri);
|
||||
var subscription = await db.WebPushSubscriptions
|
||||
.SingleOrDefaultAsync(x => x.EndpointHash == endpointHash, cancellationToken);
|
||||
if (subscription is not null && subscription.UserId != userId)
|
||||
{
|
||||
await db.NotificationDeliveries
|
||||
.Where(x => x.WebPushSubscriptionId == subscription.Id &&
|
||||
(x.State == NotificationDeliveryState.Pending ||
|
||||
x.State == NotificationDeliveryState.Processing))
|
||||
.ExecuteUpdateAsync(updates => updates
|
||||
.SetProperty(x => x.State, NotificationDeliveryState.Suppressed)
|
||||
.SetProperty(x => x.LastError,
|
||||
"浏览器推送订阅已绑定到其他账号。"), cancellationToken);
|
||||
db.WebPushSubscriptions.Remove(subscription);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
subscription = null;
|
||||
}
|
||||
if (subscription is null)
|
||||
{
|
||||
subscription = new WebPushSubscription
|
||||
{
|
||||
UserId = userId,
|
||||
Endpoint = endpoint.AbsoluteUri,
|
||||
EndpointHash = endpointHash,
|
||||
P256dh = request.P256dh,
|
||||
Auth = request.Auth
|
||||
};
|
||||
db.WebPushSubscriptions.Add(subscription);
|
||||
}
|
||||
else
|
||||
{
|
||||
subscription.P256dh = request.P256dh;
|
||||
subscription.Auth = request.Auth;
|
||||
}
|
||||
var userAgent = Request.Headers.UserAgent.ToString();
|
||||
subscription.UserAgent = userAgent[..Math.Min(userAgent.Length, 500)];
|
||||
subscription.ExpiresAt = request.ExpiresAt;
|
||||
subscription.LastSeenAt = DateTime.UtcNow;
|
||||
subscription.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Ok(new { subscription.Id, subscription.LastSeenAt });
|
||||
}
|
||||
|
||||
[HttpDelete("push-subscriptions/{id:guid}")]
|
||||
public async Task<ActionResult> DeletePushSubscription(
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = currentUserDataScope.Current.UserId;
|
||||
var subscription = await db.WebPushSubscriptions.SingleOrDefaultAsync(
|
||||
x => x.Id == id && x.UserId == userId, cancellationToken);
|
||||
if (subscription is null) return NotFound();
|
||||
db.WebPushSubscriptions.Remove(subscription);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("deliveries")]
|
||||
public async Task<ActionResult> GetDeliveries(
|
||||
int page = 1,
|
||||
int pageSize = 20,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (page < 1 || pageSize is < 1 or > 100)
|
||||
return ValidationProblem("page 必须大于 0,pageSize 必须在 1 到 100 之间。");
|
||||
var userId = currentUserDataScope.Current.UserId;
|
||||
var source = db.NotificationDeliveries.AsNoTracking()
|
||||
.Where(x => x.UserId == userId);
|
||||
var total = await source.CountAsync(cancellationToken);
|
||||
var items = await source
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id,
|
||||
x.NotificationId,
|
||||
Title = x.Notification!.Title,
|
||||
x.Channel,
|
||||
x.State,
|
||||
x.AttemptCount,
|
||||
x.NextAttemptAt,
|
||||
x.LastAttemptAt,
|
||||
x.DeliveredAt,
|
||||
x.LastError,
|
||||
x.CreatedAt
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
return Ok(new { Items = items, Total = total, Page = page, PageSize = pageSize });
|
||||
}
|
||||
|
||||
private bool TryValidatePushEndpoint(
|
||||
string value,
|
||||
out Uri? endpoint,
|
||||
out string? error)
|
||||
{
|
||||
endpoint = null;
|
||||
error = null;
|
||||
if (!Uri.TryCreate(value, UriKind.Absolute, out endpoint) ||
|
||||
endpoint.Scheme != Uri.UriSchemeHttps ||
|
||||
(!endpoint.IsDefaultPort && endpoint.Port != 443))
|
||||
{
|
||||
error = "推送端点必须使用标准 HTTPS 地址。";
|
||||
return false;
|
||||
}
|
||||
if (IPAddress.TryParse(endpoint.Host, out _) ||
|
||||
endpoint.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
|
||||
endpoint.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
error = "推送端点不能指向本机或 IP 地址。";
|
||||
return false;
|
||||
}
|
||||
var endpointHost = endpoint.Host;
|
||||
var allowed = deliverySettings.WebPush.AllowedEndpointHostSuffixes.Any(suffix =>
|
||||
endpointHost.Equals(suffix, StringComparison.OrdinalIgnoreCase) ||
|
||||
endpointHost.EndsWith($".{suffix}", StringComparison.OrdinalIgnoreCase));
|
||||
if (!allowed)
|
||||
{
|
||||
error = "该浏览器推送服务域名未被服务器允许。";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string Hash(string value) =>
|
||||
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)))
|
||||
.ToLowerInvariant();
|
||||
|
||||
[HttpGet("composer")]
|
||||
[Authorize(Roles = Senders)]
|
||||
public async Task<ActionResult> GetComposer(CancellationToken cancellationToken)
|
||||
@@ -966,6 +1189,20 @@ public enum MessageRecipientMode
|
||||
|
||||
public sealed record RoleOption(string Value, string Label);
|
||||
|
||||
public sealed record SaveNotificationPreferenceRequest(
|
||||
bool EmailEnabled,
|
||||
bool WebPushEnabled,
|
||||
bool QuietHoursEnabled,
|
||||
int QuietStartMinute,
|
||||
int QuietEndMinute,
|
||||
[Required, StringLength(100)] string TimeZoneId);
|
||||
|
||||
public sealed record SaveWebPushSubscriptionRequest(
|
||||
[Required, StringLength(2000)] string Endpoint,
|
||||
[Required, StringLength(200)] string P256dh,
|
||||
[Required, StringLength(100)] string Auth,
|
||||
DateTime? ExpiresAt);
|
||||
|
||||
internal sealed record RecipientResolution(
|
||||
MessageAudienceType AudienceType,
|
||||
string? AudienceName,
|
||||
|
||||
@@ -12,6 +12,66 @@ public sealed class Notification : EntityBase
|
||||
public string? LinkUrl { get; set; }
|
||||
public Guid? MessageDispatchId { get; set; }
|
||||
public MessageDispatch? MessageDispatch { get; set; }
|
||||
public DateTime? ExternalDeliveryPlannedAt { get; set; }
|
||||
public ICollection<NotificationDelivery> Deliveries { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class NotificationPreference : EntityBase
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public bool EmailEnabled { get; set; }
|
||||
public bool WebPushEnabled { get; set; }
|
||||
public bool QuietHoursEnabled { get; set; }
|
||||
public int QuietStartMinute { get; set; } = 22 * 60;
|
||||
public int QuietEndMinute { get; set; } = 7 * 60;
|
||||
public string TimeZoneId { get; set; } = "Asia/Shanghai";
|
||||
}
|
||||
|
||||
public sealed class WebPushSubscription : EntityBase
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public required string Endpoint { get; set; }
|
||||
public required string EndpointHash { get; set; }
|
||||
public required string P256dh { get; set; }
|
||||
public required string Auth { get; set; }
|
||||
public string? UserAgent { get; set; }
|
||||
public DateTime? ExpiresAt { get; set; }
|
||||
public DateTime LastSeenAt { get; set; } = DateTime.UtcNow;
|
||||
public ICollection<NotificationDelivery> Deliveries { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class NotificationDelivery : EntityBase
|
||||
{
|
||||
public Guid NotificationId { get; set; }
|
||||
public Notification? Notification { get; set; }
|
||||
public Guid UserId { get; set; }
|
||||
public NotificationChannel Channel { get; set; }
|
||||
public Guid? WebPushSubscriptionId { get; set; }
|
||||
public WebPushSubscription? WebPushSubscription { get; set; }
|
||||
public required string TargetKey { get; set; }
|
||||
public NotificationDeliveryState State { get; set; } =
|
||||
NotificationDeliveryState.Pending;
|
||||
public int AttemptCount { get; set; }
|
||||
public DateTime NextAttemptAt { get; set; } = DateTime.UtcNow;
|
||||
public DateTime? LastAttemptAt { get; set; }
|
||||
public DateTime? DeliveredAt { get; set; }
|
||||
public string? ProviderMessageId { get; set; }
|
||||
public string? LastError { get; set; }
|
||||
}
|
||||
|
||||
public enum NotificationChannel
|
||||
{
|
||||
Email = 1,
|
||||
WebPush = 2
|
||||
}
|
||||
|
||||
public enum NotificationDeliveryState
|
||||
{
|
||||
Pending = 1,
|
||||
Processing = 2,
|
||||
Delivered = 3,
|
||||
Failed = 4,
|
||||
Suppressed = 5
|
||||
}
|
||||
|
||||
public sealed class MessageDispatch : EntityBase
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
using System.Net;
|
||||
using System.Net.Mail;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using WebPush;
|
||||
|
||||
namespace Jiaowu.Api.Infrastructure.Notifications;
|
||||
|
||||
public sealed class NotificationDeliveryOptions
|
||||
{
|
||||
public const string SectionName = "NotificationDelivery";
|
||||
public int PollSeconds { get; set; } = 10;
|
||||
public int BatchSize { get; set; } = 100;
|
||||
public int MaxAttempts { get; set; } = 5;
|
||||
public EmailDeliveryOptions Email { get; set; } = new();
|
||||
public WebPushDeliveryOptions WebPush { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class EmailDeliveryOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
public string Host { get; set; } = string.Empty;
|
||||
public int Port { get; set; } = 587;
|
||||
public bool UseSsl { get; set; } = true;
|
||||
public string? UserName { get; set; }
|
||||
public string? Password { get; set; }
|
||||
public string FromAddress { get; set; } = string.Empty;
|
||||
public string FromName { get; set; } = "教务系统";
|
||||
}
|
||||
|
||||
public sealed class WebPushDeliveryOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
public string PublicKey { get; set; } = string.Empty;
|
||||
public string PrivateKey { get; set; } = string.Empty;
|
||||
public string[] AllowedEndpointHostSuffixes { get; set; } =
|
||||
[
|
||||
"fcm.googleapis.com",
|
||||
"push.services.mozilla.com",
|
||||
"updates.push.services.mozilla.com",
|
||||
"push.apple.com",
|
||||
"notify.windows.com"
|
||||
];
|
||||
}
|
||||
|
||||
public sealed class NotificationDeliveryWorker(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IOptions<NotificationDeliveryOptions> options,
|
||||
ILogger<NotificationDeliveryWorker> logger) : BackgroundService
|
||||
{
|
||||
private readonly NotificationDeliveryOptions settings = options.Value;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(settings.PollSeconds));
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunOnceAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Notification delivery scan failed.");
|
||||
}
|
||||
} while (await timer.WaitForNextTickAsync(stoppingToken));
|
||||
}
|
||||
|
||||
internal async Task RunOnceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
await RecoverInterruptedDeliveriesAsync(db, cancellationToken);
|
||||
await PlanAsync(db, cancellationToken);
|
||||
|
||||
for (var index = 0; index < settings.BatchSize; index++)
|
||||
{
|
||||
var deliveryId = await ClaimNextAsync(db, cancellationToken);
|
||||
if (!deliveryId.HasValue) break;
|
||||
await DeliverAsync(db, deliveryId.Value, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PlanAsync(AppDbContext db, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var notifications = await db.Notifications
|
||||
.Where(x => x.ExternalDeliveryPlannedAt == null)
|
||||
.OrderBy(x => x.CreatedAt)
|
||||
.Take(settings.BatchSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
if (notifications.Count == 0) return;
|
||||
|
||||
var userIds = notifications.Select(x => x.UserId).Distinct().ToArray();
|
||||
var users = await db.Users.AsNoTracking()
|
||||
.WhereIn(userIds, x => x.Id)
|
||||
.Select(x => new { x.Id, x.Email, x.EmailConfirmed })
|
||||
.ToDictionaryAsync(x => x.Id, cancellationToken);
|
||||
var preferences = await db.NotificationPreferences.AsNoTracking()
|
||||
.WhereIn(userIds, x => x.UserId)
|
||||
.ToDictionaryAsync(x => x.UserId, cancellationToken);
|
||||
var subscriptions = (await db.WebPushSubscriptions.AsNoTracking()
|
||||
.Where(x => x.ExpiresAt == null || x.ExpiresAt > now)
|
||||
.WhereIn(userIds, x => x.UserId)
|
||||
.ToListAsync(cancellationToken))
|
||||
.GroupBy(x => x.UserId)
|
||||
.ToDictionary(x => x.Key, x => x.ToArray());
|
||||
|
||||
foreach (var notification in notifications)
|
||||
{
|
||||
preferences.TryGetValue(notification.UserId, out var preference);
|
||||
var nextAttemptAt = QuietHours.NextAllowedAt(now, preference);
|
||||
|
||||
if (preference?.EmailEnabled == true)
|
||||
{
|
||||
users.TryGetValue(notification.UserId, out var user);
|
||||
if (!settings.Email.Enabled)
|
||||
AddSuppressed(db, notification, NotificationChannel.Email,
|
||||
"email-provider", "邮件投递服务尚未配置。", now);
|
||||
else if (user is null || !user.EmailConfirmed ||
|
||||
string.IsNullOrWhiteSpace(user.Email))
|
||||
AddSuppressed(db, notification, NotificationChannel.Email,
|
||||
"email-missing", "账号没有已验证的邮箱。", now);
|
||||
else
|
||||
AddPending(db, notification, NotificationChannel.Email,
|
||||
Hash(user.Email.Trim().ToLowerInvariant()), null, nextAttemptAt);
|
||||
}
|
||||
|
||||
if (preference?.WebPushEnabled == true)
|
||||
{
|
||||
if (!settings.WebPush.Enabled)
|
||||
AddSuppressed(db, notification, NotificationChannel.WebPush,
|
||||
"webpush-provider", "Web Push 服务尚未配置。", now);
|
||||
else if (!subscriptions.TryGetValue(notification.UserId, out var userSubscriptions) ||
|
||||
userSubscriptions.Length == 0)
|
||||
AddSuppressed(db, notification, NotificationChannel.WebPush,
|
||||
"webpush-missing", "账号尚未订阅浏览器推送。", now);
|
||||
else
|
||||
foreach (var subscription in userSubscriptions)
|
||||
AddPending(db, notification, NotificationChannel.WebPush,
|
||||
subscription.EndpointHash, subscription.Id, nextAttemptAt);
|
||||
}
|
||||
|
||||
notification.ExternalDeliveryPlannedAt = now;
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
db.ChangeTracker.Clear();
|
||||
}
|
||||
|
||||
private static async Task RecoverInterruptedDeliveriesAsync(
|
||||
AppDbContext db,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var staleBefore = now.AddMinutes(-10);
|
||||
await db.NotificationDeliveries
|
||||
.Where(x => x.State == NotificationDeliveryState.Processing &&
|
||||
x.LastAttemptAt < staleBefore)
|
||||
.ExecuteUpdateAsync(updates => updates
|
||||
.SetProperty(x => x.State, NotificationDeliveryState.Pending)
|
||||
.SetProperty(x => x.NextAttemptAt, now)
|
||||
.SetProperty(x => x.LastError, "上次投递进程中断,已自动恢复。"),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private static void AddPending(
|
||||
AppDbContext db,
|
||||
Notification notification,
|
||||
NotificationChannel channel,
|
||||
string targetKey,
|
||||
Guid? subscriptionId,
|
||||
DateTime nextAttemptAt) =>
|
||||
db.NotificationDeliveries.Add(new NotificationDelivery
|
||||
{
|
||||
NotificationId = notification.Id,
|
||||
UserId = notification.UserId,
|
||||
Channel = channel,
|
||||
TargetKey = targetKey,
|
||||
WebPushSubscriptionId = subscriptionId,
|
||||
NextAttemptAt = nextAttemptAt
|
||||
});
|
||||
|
||||
private static void AddSuppressed(
|
||||
AppDbContext db,
|
||||
Notification notification,
|
||||
NotificationChannel channel,
|
||||
string targetKey,
|
||||
string reason,
|
||||
DateTime now) =>
|
||||
db.NotificationDeliveries.Add(new NotificationDelivery
|
||||
{
|
||||
NotificationId = notification.Id,
|
||||
UserId = notification.UserId,
|
||||
Channel = channel,
|
||||
TargetKey = targetKey,
|
||||
State = NotificationDeliveryState.Suppressed,
|
||||
NextAttemptAt = now,
|
||||
LastError = reason
|
||||
});
|
||||
|
||||
private static async Task<Guid?> ClaimNextAsync(
|
||||
AppDbContext db,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var id = await db.NotificationDeliveries.AsNoTracking()
|
||||
.Where(x => x.State == NotificationDeliveryState.Pending &&
|
||||
x.NextAttemptAt <= now)
|
||||
.OrderBy(x => x.NextAttemptAt)
|
||||
.ThenBy(x => x.CreatedAt)
|
||||
.Select(x => (Guid?)x.Id)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
if (!id.HasValue) return null;
|
||||
|
||||
var claimed = await db.NotificationDeliveries
|
||||
.Where(x => x.Id == id && x.State == NotificationDeliveryState.Pending)
|
||||
.ExecuteUpdateAsync(updates => updates
|
||||
.SetProperty(x => x.State, NotificationDeliveryState.Processing)
|
||||
.SetProperty(x => x.LastAttemptAt, now)
|
||||
.SetProperty(x => x.AttemptCount, x => x.AttemptCount + 1),
|
||||
cancellationToken);
|
||||
return claimed == 1 ? id : null;
|
||||
}
|
||||
|
||||
private async Task DeliverAsync(
|
||||
AppDbContext db,
|
||||
Guid deliveryId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var delivery = await db.NotificationDeliveries
|
||||
.Include(x => x.Notification)
|
||||
.Include(x => x.WebPushSubscription)
|
||||
.SingleAsync(x => x.Id == deliveryId, cancellationToken);
|
||||
try
|
||||
{
|
||||
if (delivery.Channel == NotificationChannel.Email)
|
||||
await SendEmailAsync(db, delivery, cancellationToken);
|
||||
else
|
||||
await SendWebPushAsync(delivery, cancellationToken);
|
||||
|
||||
delivery.State = NotificationDeliveryState.Delivered;
|
||||
delivery.DeliveredAt = DateTime.UtcNow;
|
||||
delivery.LastError = null;
|
||||
}
|
||||
catch (WebPushException exception) when (
|
||||
exception.StatusCode is HttpStatusCode.Gone or HttpStatusCode.NotFound)
|
||||
{
|
||||
delivery.State = NotificationDeliveryState.Suppressed;
|
||||
delivery.LastError = "浏览器推送订阅已由推送服务注销。";
|
||||
if (delivery.WebPushSubscription is not null)
|
||||
{
|
||||
var subscriptionId = delivery.WebPushSubscription.Id;
|
||||
await db.NotificationDeliveries
|
||||
.Where(x => x.Id != delivery.Id &&
|
||||
x.WebPushSubscriptionId == subscriptionId &&
|
||||
(x.State == NotificationDeliveryState.Pending ||
|
||||
x.State == NotificationDeliveryState.Processing))
|
||||
.ExecuteUpdateAsync(updates => updates
|
||||
.SetProperty(x => x.State, NotificationDeliveryState.Suppressed)
|
||||
.SetProperty(x => x.LastError, "浏览器推送订阅已由推送服务注销。"),
|
||||
cancellationToken);
|
||||
db.WebPushSubscriptions.Remove(delivery.WebPushSubscription);
|
||||
}
|
||||
logger.LogInformation(
|
||||
"Removed expired Web Push subscription after provider response {StatusCode}.",
|
||||
exception.StatusCode);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
delivery.LastError = SafeError(exception.Message);
|
||||
if (delivery.AttemptCount >= settings.MaxAttempts)
|
||||
delivery.State = NotificationDeliveryState.Failed;
|
||||
else
|
||||
{
|
||||
delivery.State = NotificationDeliveryState.Pending;
|
||||
delivery.NextAttemptAt = DateTime.UtcNow.Add(
|
||||
RetryDelay(delivery.AttemptCount));
|
||||
}
|
||||
logger.LogWarning(exception,
|
||||
"Notification delivery {DeliveryId} attempt {AttemptCount} failed.",
|
||||
delivery.Id, delivery.AttemptCount);
|
||||
}
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
db.ChangeTracker.Clear();
|
||||
}
|
||||
|
||||
private async Task SendEmailAsync(
|
||||
AppDbContext db,
|
||||
NotificationDelivery delivery,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var email = await db.Users.AsNoTracking()
|
||||
.Where(x => x.Id == delivery.UserId && x.EmailConfirmed)
|
||||
.Select(x => x.Email)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
if (string.IsNullOrWhiteSpace(email))
|
||||
throw new InvalidOperationException("账号没有已验证的邮箱。");
|
||||
|
||||
using var message = new MailMessage
|
||||
{
|
||||
From = new MailAddress(settings.Email.FromAddress, settings.Email.FromName),
|
||||
Subject = HeaderValue(delivery.Notification!.Title),
|
||||
Body = delivery.Notification.Content,
|
||||
IsBodyHtml = true
|
||||
};
|
||||
message.To.Add(email);
|
||||
using var client = new SmtpClient(settings.Email.Host, settings.Email.Port)
|
||||
{
|
||||
EnableSsl = settings.Email.UseSsl
|
||||
};
|
||||
if (!string.IsNullOrWhiteSpace(settings.Email.UserName))
|
||||
client.Credentials = new NetworkCredential(
|
||||
settings.Email.UserName, settings.Email.Password);
|
||||
await client.SendMailAsync(message, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task SendWebPushAsync(
|
||||
NotificationDelivery delivery,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var subscription = delivery.WebPushSubscription ??
|
||||
throw new InvalidOperationException("浏览器推送订阅已经失效。");
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
{
|
||||
title = delivery.Notification!.Title,
|
||||
body = PlainText(delivery.Notification.Content),
|
||||
url = delivery.Notification.LinkUrl ?? "/notifications",
|
||||
category = delivery.Notification.Category.ToString(),
|
||||
notificationId = delivery.Notification.Id
|
||||
});
|
||||
using var client = new WebPushClient();
|
||||
await client.SendNotificationAsync(
|
||||
new PushSubscription(subscription.Endpoint, subscription.P256dh, subscription.Auth),
|
||||
payload,
|
||||
new VapidDetails(
|
||||
settings.WebPush.Subject,
|
||||
settings.WebPush.PublicKey,
|
||||
settings.WebPush.PrivateKey),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private static string Hash(string value) =>
|
||||
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)))
|
||||
.ToLowerInvariant();
|
||||
|
||||
private static string HeaderValue(string value) =>
|
||||
value.Replace('\r', ' ').Replace('\n', ' ').Trim();
|
||||
|
||||
private static string PlainText(string value) =>
|
||||
WebUtility.HtmlDecode(Regex.Replace(value, "<[^>]+>", " "))
|
||||
.Replace("\u00a0", " ")
|
||||
.Trim();
|
||||
|
||||
private static string SafeError(string value) =>
|
||||
value.Length <= 2000 ? value : value[..2000];
|
||||
|
||||
private static TimeSpan RetryDelay(int attemptCount) => attemptCount switch
|
||||
{
|
||||
<= 1 => TimeSpan.FromMinutes(1),
|
||||
2 => TimeSpan.FromMinutes(5),
|
||||
3 => TimeSpan.FromMinutes(15),
|
||||
_ => TimeSpan.FromHours(1)
|
||||
};
|
||||
}
|
||||
|
||||
internal static class QuietHours
|
||||
{
|
||||
public static DateTime NextAllowedAt(
|
||||
DateTime utcNow,
|
||||
NotificationPreference? preference)
|
||||
{
|
||||
if (preference?.QuietHoursEnabled != true) return utcNow;
|
||||
TimeZoneInfo timeZone;
|
||||
try
|
||||
{
|
||||
timeZone = TimeZoneInfo.FindSystemTimeZoneById(preference.TimeZoneId);
|
||||
}
|
||||
catch (TimeZoneNotFoundException)
|
||||
{
|
||||
timeZone = TimeZoneInfo.Utc;
|
||||
}
|
||||
catch (InvalidTimeZoneException)
|
||||
{
|
||||
timeZone = TimeZoneInfo.Utc;
|
||||
}
|
||||
|
||||
var localNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, timeZone);
|
||||
var minute = localNow.Hour * 60 + localNow.Minute;
|
||||
var start = preference.QuietStartMinute;
|
||||
var end = preference.QuietEndMinute;
|
||||
var inQuietHours = start < end
|
||||
? minute >= start && minute < end
|
||||
: minute >= start || minute < end;
|
||||
if (!inQuietHours) return utcNow;
|
||||
|
||||
var endDate = start < end || minute < end
|
||||
? localNow.Date
|
||||
: localNow.Date.AddDays(1);
|
||||
var localEnd = DateTime.SpecifyKind(
|
||||
endDate.AddMinutes(end), DateTimeKind.Unspecified);
|
||||
return TimeZoneInfo.ConvertTimeToUtc(localEnd, timeZone);
|
||||
}
|
||||
}
|
||||
Loaded 3 of 21 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user