using API.Schema.NotificationsContext; using API.Schema.NotificationsContext.NotificationConnectors; using Microsoft.EntityFrameworkCore; namespace API.Workers; /// /// Send notifications to NotificationConnectors /// /// /// public class SendNotificationsWorker(TimeSpan? interval = null, IEnumerable? dependsOn = null) : BaseWorkerWithContext(dependsOn), IPeriodic { public DateTime LastExecution { get; set; } = DateTime.UnixEpoch; public TimeSpan Interval { get; set; } = interval??TimeSpan.FromMinutes(1); protected override async Task DoWorkInternal() { Log.Debug("Sending notifications..."); List connectors = await DbContext.NotificationConnectors.ToListAsync(CancellationToken); List unsentNotifications = await DbContext.Notifications.Where(n => n.IsSent == false).ToListAsync(CancellationToken); Log.Debug($"Sending {unsentNotifications.Count} notifications to {connectors.Count} connectors..."); unsentNotifications.ForEach(notification => { connectors.ForEach(connector => { connector.SendNotification(notification.Title, notification.Message); DbContext.Entry(notification).Property(n => n.IsSent).CurrentValue = true; }); }); Log.Debug("Notifications sent."); if(await DbContext.Sync(CancellationToken) is { success: false } e) Log.Error($"Failed to save database changes: {e.exceptionMessage}"); return []; } }