Files
Heimdall/src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs
T
Arnaud Dartois 23571da9c3
Heimdall Gitea / Build and tests (pull_request) Failing after 2m10s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
feat(i18n): localize remaining UI and server messages
2026-10-25 05:59:18 +01:00

90 lines
3.6 KiB
C#

using Heimdall.Application.Services;
using Heimdall.Application.Localization;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Hangfire recurring job that sends a weekly digest email to users who have it enabled.
/// Scheduled Monday at 8:00.
/// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads.
/// </summary>
public class WeeklyDigestJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IEmailService _emailService;
private readonly ICameraAccessService _cameraAccess;
private readonly ILogger<WeeklyDigestJob> _logger;
public WeeklyDigestJob(
IDbContextFactory<AppDbContext> dbFactory,
IEmailService emailService,
ICameraAccessService cameraAccess,
ILogger<WeeklyDigestJob> 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 = $"""
<h2>{ServerText.Get("Digest.Weekly.Title", language)}</h2>
<p>{ServerText.Get("Digest.Greeting", language)}</p>
<ul>
<li>{ServerText.Get("Digest.Weekly.Events", language)} <strong>{eventCount}</strong></li>
<li>{ServerText.Get("Digest.UnreadNotifications", language)} <strong>{unreadNotifications}</strong></li>
</ul>
<p>{ServerText.Get("Digest.Signoff", language)}</p>
""";
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);
}
}