logger)
{
_dbFactory = dbFactory;
_emailService = emailService;
_cameraAccess = cameraAccess;
_logger = logger;
}
public async Task ExecuteAsync(CancellationToken ct = default)
{
_logger.LogInformation("Starting weekly digest job");
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var configs = await db.UserNotificationConfigs
.Where(c => c.WeeklyDigest && c.EmailEnabled && c.EmailAddress != null)
.ToListAsync(ct);
var userIds = configs.Select(config => config.UserId).Distinct().ToArray();
var languages = await db.Users.AsNoTracking()
.Where(user => userIds.Contains(user.Id))
.ToDictionaryAsync(user => user.Id, user => user.Language, ct);
var to = DateTime.UtcNow;
var from = to.AddDays(-7);
foreach (var config in configs)
{
try
{
var cameraIds = await _cameraAccess
.GetUserAccessibleCameraIdsAsync(config.UserId, ct)
.ConfigureAwait(false);
var eventCount = cameraIds.Count > 0
? await db.CameraEvents
.CountAsync(e => e.OccurredAt >= from && e.OccurredAt < to && cameraIds.Contains(e.CameraId), ct)
: 0;
var unreadNotifications = await db.Notifications
.CountAsync(n => n.UserId == config.UserId && !n.IsRead, ct);
var language = languages.GetValueOrDefault(config.UserId, config.Language);
var subject = ServerText.Get("Digest.Weekly.Subject", language);
var body = $"""
{ServerText.Get("Digest.Weekly.Title", language)}
{ServerText.Get("Digest.Greeting", language)}
- {ServerText.Get("Digest.Weekly.Events", language)} {eventCount}
- {ServerText.Get("Digest.UnreadNotifications", language)} {unreadNotifications}
{ServerText.Get("Digest.Signoff", language)}
""";
await _emailService.SendEmailAsync(config.EmailAddress!, subject, body, ct).ConfigureAwait(false);
_logger.LogDebug("Weekly digest sent to {Email}", config.EmailAddress);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send weekly digest to {Email}", config.EmailAddress);
}
}
_logger.LogInformation("Weekly digest completed: {Count} emails sent", configs.Count);
}
}