using Microsoft.AspNetCore.SignalR; using PlotLine.Hubs; namespace PlotLine.Services; public sealed class WordCompanionPresenceMonitor( IWordCompanionPresenceService presence, IManuscriptScanPreviewStore scanStore, IHubContext hub, ContextWorkspaceNotifications? contextNotifications = null) : BackgroundService { private static readonly TimeSpan ActiveScanHeartbeatGrace = TimeSpan.FromMinutes(30); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10)); try { while (await timer.WaitForNextTickAsync(stoppingToken)) { var offlineStatuses = await presence.MarkStaleOfflineAsync(userId => scanStore.HasRecentRunningScanForUserAsync(userId, ActiveScanHeartbeatGrace)); foreach (var status in offlineStatuses) { await hub.Clients.Group(WordCompanionFollowHub.PresenceGroup(status.UserID)) .SendAsync("WordCompanionPresenceChanged", status, stoppingToken); if (contextNotifications != null) await contextNotifications.Position(status.UserID); var failedScans = await scanStore.FailRunningForUserAsync(status.UserID, "The Word Companion disconnected before the scan finished. Reopen Word and try again."); foreach (var failedScan in failedScans) await hub.Clients.Group(WordCompanionFollowHub.PresenceGroup(status.UserID)) .SendAsync("OnboardingScanFailed", failedScan, stoppingToken); } } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } } }