| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using Pomodoro.Web.Models; |
| | | 3 | | using Pomodoro.Web.Services; |
| | | 4 | | using Pomodoro.Web.Services.Repositories; |
| | | 5 | | |
| | | 6 | | namespace Pomodoro.Web.Services; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Service for managing the consent modal after timer completion. |
| | | 10 | | /// Uses PeriodicTimer for thread-safe async countdown handling. |
| | | 11 | | /// Dependencies are injected via constructor for explicit dependency declaration. |
| | | 12 | | /// </summary> |
| | | 13 | | public class ConsentService : IConsentService, IAsyncDisposable |
| | | 14 | | { |
| | | 15 | | private readonly ISessionOptionsService _sessionOptionsService; |
| | | 16 | | private readonly ILogger<ConsentService> _logger; |
| | | 17 | | private bool _isDisposed; |
| | | 18 | | private bool _isInitialized; |
| | 178 | 19 | | private readonly object _initLock = new(); |
| | | 20 | | |
| | | 21 | | // PeriodicTimer-based countdown for thread-safe async handling |
| | | 22 | | private PeriodicTimer? _countdownTimer; |
| | | 23 | | private CancellationTokenSource? _countdownCts; |
| | 178 | 24 | | private readonly object _timerLock = new(); |
| | | 25 | | |
| | | 26 | | private readonly ITimerService _timerService; |
| | | 27 | | private readonly ITaskService _taskService; |
| | | 28 | | private readonly INotificationService _notificationService; |
| | | 29 | | private readonly AppState _appState; |
| | | 30 | | |
| | | 31 | | public event Action? OnConsentRequired; |
| | | 32 | | public event Action? OnCountdownTick; |
| | | 33 | | public event Action? OnConsentHandled; |
| | | 34 | | |
| | 697 | 35 | | public bool IsModalVisible { get; private set; } |
| | 205 | 36 | | public SessionType CompletedSessionType { get; private set; } |
| | 1284 | 37 | | public int CountdownSeconds { get; private set; } |
| | 318 | 38 | | public List<ConsentOption> AvailableOptions { get; private set; } = new(); |
| | | 39 | | |
| | 178 | 40 | | public ConsentService( |
| | 178 | 41 | | ITimerService timerService, |
| | 178 | 42 | | ITaskService taskService, |
| | 178 | 43 | | INotificationService notificationService, |
| | 178 | 44 | | AppState appState, |
| | 178 | 45 | | ISessionOptionsService sessionOptionsService, |
| | 178 | 46 | | ILogger<ConsentService> logger) |
| | 178 | 47 | | { |
| | 178 | 48 | | _timerService = timerService; |
| | 178 | 49 | | _taskService = taskService; |
| | 178 | 50 | | _notificationService = notificationService; |
| | 178 | 51 | | _appState = appState; |
| | 178 | 52 | | _sessionOptionsService = sessionOptionsService; |
| | 178 | 53 | | _logger = logger; |
| | 178 | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Initializes the service - called after all services are created |
| | | 58 | | /// Uses lock to prevent duplicate event subscriptions from multiple Initialize calls |
| | | 59 | | /// </summary> |
| | | 60 | | public void Initialize() |
| | 61 | 61 | | { |
| | 61 | 62 | | lock (_initLock) |
| | 61 | 63 | | { |
| | 67 | 64 | | if (_isInitialized) return; |
| | 55 | 65 | | _isInitialized = true; |
| | 55 | 66 | | } |
| | | 67 | | |
| | 55 | 68 | | if (_timerService != null) |
| | 55 | 69 | | { |
| | 55 | 70 | | _timerService.OnTimerComplete += HandleTimerComplete; |
| | 55 | 71 | | } |
| | 61 | 72 | | } |
| | | 73 | | |
| | | 74 | | private void HandleTimerComplete(SessionType sessionType) |
| | 39 | 75 | | { |
| | | 76 | | // Use SafeTaskRunner for consistent fire-and-forget handling with error logging |
| | 39 | 77 | | SafeTaskRunner.RunAndForget( |
| | 39 | 78 | | () => HandleTimerCompleteSafeAsync(sessionType), |
| | 39 | 79 | | _logger, |
| | 39 | 80 | | Constants.SafeTaskOperations.ConsentTimerComplete |
| | 39 | 81 | | ); |
| | 39 | 82 | | } |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Safe async wrapper for HandleTimerComplete to avoid async void issues |
| | | 86 | | /// </summary> |
| | | 87 | | private async Task HandleTimerCompleteSafeAsync(SessionType sessionType) |
| | 39 | 88 | | { |
| | | 89 | | try |
| | 39 | 90 | | { |
| | | 91 | | // Play sound and show notification based on user preferences |
| | 39 | 92 | | await PlayCompletionSoundAndNotifyAsync(sessionType); |
| | | 93 | | |
| | | 94 | | // Get settings to check if auto-start is enabled |
| | 36 | 95 | | var settings = _appState?.Settings; |
| | | 96 | | |
| | | 97 | | // Only show consent modal if auto-start is enabled |
| | | 98 | | // When auto-start is disabled, user must manually start the next session |
| | 36 | 99 | | if (settings?.AutoStartEnabled == true) |
| | 9 | 100 | | { |
| | 9 | 101 | | ShowConsentModal(sessionType); |
| | 9 | 102 | | } |
| | 36 | 103 | | } |
| | 3 | 104 | | catch (Exception ex) |
| | 3 | 105 | | { |
| | 3 | 106 | | _logger.LogError(ex, Constants.Messages.LogConsentHandleCompleteError); |
| | 3 | 107 | | } |
| | 39 | 108 | | } |
| | | 109 | | |
| | | 110 | | /// <summary> |
| | | 111 | | /// Plays completion sound and shows notification based on settings |
| | | 112 | | /// </summary> |
| | | 113 | | private async Task PlayCompletionSoundAndNotifyAsync(SessionType sessionType) |
| | 39 | 114 | | { |
| | 45 | 115 | | if (!TryGetNotificationSettings(out var settings)) return; |
| | | 116 | | |
| | 33 | 117 | | if (settings.SoundEnabled) |
| | 15 | 118 | | { |
| | 15 | 119 | | await PlaySoundAsync(sessionType); |
| | 12 | 120 | | } |
| | | 121 | | |
| | 30 | 122 | | if (settings.NotificationsEnabled) |
| | 12 | 123 | | { |
| | 12 | 124 | | await ShowNotificationAsync(sessionType); |
| | 12 | 125 | | } |
| | 36 | 126 | | } |
| | | 127 | | |
| | | 128 | | private bool TryGetNotificationSettings(out TimerSettings? settings) |
| | 39 | 129 | | { |
| | 39 | 130 | | settings = _appState?.Settings; |
| | 39 | 131 | | return _notificationService != null && settings != null; |
| | 39 | 132 | | } |
| | | 133 | | |
| | | 134 | | private async Task PlaySoundAsync(SessionType sessionType) |
| | 15 | 135 | | { |
| | 15 | 136 | | if (sessionType == SessionType.Pomodoro) |
| | 12 | 137 | | { |
| | 12 | 138 | | await _notificationService.PlayTimerCompleteSoundAsync(); |
| | 9 | 139 | | } |
| | | 140 | | else |
| | 3 | 141 | | { |
| | 3 | 142 | | await _notificationService.PlayBreakCompleteSoundAsync(); |
| | 3 | 143 | | } |
| | 12 | 144 | | } |
| | | 145 | | |
| | | 146 | | private async Task ShowNotificationAsync(SessionType sessionType) |
| | 12 | 147 | | { |
| | 12 | 148 | | if (sessionType == SessionType.Pomodoro) |
| | 9 | 149 | | { |
| | 9 | 150 | | await _notificationService.ShowNotificationAsync( |
| | 9 | 151 | | $"{Constants.SessionTypes.PomodoroEmoji}{Constants.Formatting.EmojiTitleSeparator}{Constants.Messages.Po |
| | 9 | 152 | | Constants.Messages.PomodoroNotificationMessage, |
| | 9 | 153 | | sessionType); |
| | 9 | 154 | | } |
| | | 155 | | else |
| | 3 | 156 | | { |
| | 3 | 157 | | await _notificationService.ShowNotificationAsync( |
| | 3 | 158 | | $"{Constants.SessionTypes.TimerEmoji}{Constants.Formatting.EmojiTitleSeparator}{Constants.Messages.Break |
| | 3 | 159 | | Constants.Messages.BreakNotificationMessage, |
| | 3 | 160 | | sessionType); |
| | 3 | 161 | | } |
| | 12 | 162 | | } |
| | | 163 | | |
| | | 164 | | public void ShowConsentModal(SessionType completedSessionType) |
| | 128 | 165 | | { |
| | 128 | 166 | | CompletedSessionType = completedSessionType; |
| | | 167 | | |
| | | 168 | | // Get the countdown seconds from user settings |
| | 128 | 169 | | var settings = _appState?.Settings; |
| | 128 | 170 | | CountdownSeconds = settings?.AutoStartDelaySeconds ?? Constants.UI.DefaultConsentCountdownSeconds; |
| | | 171 | | |
| | 128 | 172 | | AvailableOptions = _sessionOptionsService.GetOptionsForSessionType(completedSessionType); |
| | 128 | 173 | | IsModalVisible = true; |
| | | 174 | | |
| | 128 | 175 | | StartCountdown(); |
| | 128 | 176 | | OnConsentRequired?.Invoke(); |
| | 128 | 177 | | } |
| | | 178 | | |
| | | 179 | | public async Task SelectOptionAsync(SessionType nextSessionType) |
| | 21 | 180 | | { |
| | 21 | 181 | | await HideModalAndStartSessionAsync(nextSessionType); |
| | 21 | 182 | | } |
| | | 183 | | |
| | | 184 | | public async Task HandleTimeoutAsync() |
| | 68 | 185 | | { |
| | | 186 | | // Get the default option based on completed session type |
| | 68 | 187 | | var defaultOption = _sessionOptionsService.GetDefaultOption(CompletedSessionType); |
| | 68 | 188 | | await HideModalAndStartSessionAsync(defaultOption); |
| | 68 | 189 | | } |
| | | 190 | | |
| | | 191 | | public void HideConsentModal() |
| | 22 | 192 | | { |
| | 22 | 193 | | StopCountdown(); |
| | 22 | 194 | | IsModalVisible = false; |
| | 22 | 195 | | OnConsentHandled?.Invoke(); |
| | 22 | 196 | | } |
| | | 197 | | |
| | | 198 | | public void RefreshOptions() |
| | 9 | 199 | | { |
| | 9 | 200 | | if (IsModalVisible) |
| | 6 | 201 | | { |
| | 6 | 202 | | AvailableOptions = _sessionOptionsService.GetOptionsForSessionType(CompletedSessionType); |
| | 6 | 203 | | OnConsentRequired?.Invoke(); |
| | 6 | 204 | | } |
| | 9 | 205 | | } |
| | | 206 | | |
| | | 207 | | private async Task HideModalAndStartSessionAsync(SessionType sessionType) |
| | 89 | 208 | | { |
| | 89 | 209 | | StopCountdown(); |
| | 89 | 210 | | IsModalVisible = false; |
| | 89 | 211 | | OnConsentHandled?.Invoke(); |
| | | 212 | | |
| | 99 | 213 | | if (_timerService == null || _taskService == null) return; |
| | | 214 | | |
| | 79 | 215 | | await StartSessionAsync(sessionType); |
| | 89 | 216 | | } |
| | | 217 | | |
| | | 218 | | private async Task StartSessionAsync(SessionType sessionType) |
| | 79 | 219 | | { |
| | 79 | 220 | | switch (sessionType) |
| | | 221 | | { |
| | | 222 | | case SessionType.Pomodoro: |
| | 51 | 223 | | if (_taskService.CurrentTaskId.HasValue) |
| | 3 | 224 | | { |
| | 3 | 225 | | await _timerService.StartPomodoroAsync(_taskService.CurrentTaskId.Value); |
| | 3 | 226 | | } |
| | | 227 | | else |
| | 48 | 228 | | { |
| | 48 | 229 | | _logger.LogWarning(Constants.Messages.LogCannotStartPomodoroNoTask); |
| | 48 | 230 | | } |
| | 51 | 231 | | break; |
| | | 232 | | case SessionType.ShortBreak: |
| | 25 | 233 | | await _timerService.StartShortBreakAsync(); |
| | 25 | 234 | | break; |
| | | 235 | | case SessionType.LongBreak: |
| | 3 | 236 | | await _timerService.StartLongBreakAsync(); |
| | 3 | 237 | | break; |
| | | 238 | | } |
| | 79 | 239 | | } |
| | | 240 | | |
| | | 241 | | #region Countdown Timer Management |
| | | 242 | | |
| | | 243 | | /// <summary> |
| | | 244 | | /// Starts the countdown timer using PeriodicTimer for thread-safe async handling |
| | | 245 | | /// </summary> |
| | | 246 | | private void StartCountdown() |
| | 128 | 247 | | { |
| | | 248 | | // Stop any existing countdown first |
| | 128 | 249 | | StopCountdown(); |
| | | 250 | | |
| | 128 | 251 | | lock (_timerLock) |
| | 128 | 252 | | { |
| | 131 | 253 | | if (_isDisposed) return; |
| | | 254 | | |
| | 125 | 255 | | _countdownCts = new CancellationTokenSource(); |
| | 125 | 256 | | _countdownTimer = new PeriodicTimer(TimeSpan.FromSeconds(Constants.Notifications.CountdownIntervalSeconds)); |
| | | 257 | | |
| | | 258 | | // Run countdown in background - fire-and-forget with proper error handling |
| | 125 | 259 | | _ = RunCountdownAsync(_countdownCts.Token); |
| | 125 | 260 | | } |
| | 128 | 261 | | } |
| | | 262 | | |
| | | 263 | | /// <summary> |
| | | 264 | | /// Stops the countdown timer and cleans up resources |
| | | 265 | | /// </summary> |
| | | 266 | | private void StopCountdown() |
| | 311 | 267 | | { |
| | 311 | 268 | | lock (_timerLock) |
| | 311 | 269 | | { |
| | 311 | 270 | | _countdownCts?.Cancel(); |
| | 311 | 271 | | _countdownCts?.Dispose(); |
| | 311 | 272 | | _countdownCts = null; |
| | | 273 | | |
| | 311 | 274 | | _countdownTimer?.Dispose(); |
| | 311 | 275 | | _countdownTimer = null; |
| | 311 | 276 | | } |
| | 311 | 277 | | } |
| | | 278 | | |
| | | 279 | | /// <summary> |
| | | 280 | | /// Async countdown loop using PeriodicTimer |
| | | 281 | | /// This runs on the synchronization context when awaited, ensuring thread-safe UI updates |
| | | 282 | | /// </summary> |
| | | 283 | | private async Task RunCountdownAsync(CancellationToken cancellationToken) |
| | 128 | 284 | | { |
| | | 285 | | try |
| | 128 | 286 | | { |
| | | 287 | | PeriodicTimer? timer; |
| | 128 | 288 | | lock (_timerLock) |
| | 128 | 289 | | { |
| | 128 | 290 | | timer = _countdownTimer; |
| | 128 | 291 | | } |
| | | 292 | | |
| | 131 | 293 | | if (timer == null) return; |
| | | 294 | | |
| | 442 | 295 | | while (await timer.WaitForNextTickAsync(cancellationToken)) |
| | 382 | 296 | | { |
| | 382 | 297 | | if (await ProcessCountdownTickAsync()) |
| | 62 | 298 | | { |
| | 62 | 299 | | break; |
| | | 300 | | } |
| | 317 | 301 | | } |
| | 62 | 302 | | } |
| | 58 | 303 | | catch (OperationCanceledException) |
| | 58 | 304 | | { |
| | 58 | 305 | | } |
| | 3 | 306 | | catch (Exception ex) |
| | 3 | 307 | | { |
| | 3 | 308 | | _logger.LogDebug(ex, Constants.Messages.LogCountdownError); |
| | 3 | 309 | | } |
| | 126 | 310 | | } |
| | | 311 | | |
| | | 312 | | private async Task<bool> ProcessCountdownTickAsync() |
| | 383 | 313 | | { |
| | 383 | 314 | | lock (_timerLock) |
| | 383 | 315 | | { |
| | 383 | 316 | | if (_countdownTimer == null) |
| | 1 | 317 | | { |
| | 1 | 318 | | return true; |
| | | 319 | | } |
| | 382 | 320 | | } |
| | | 321 | | |
| | 382 | 322 | | if (_isDisposed || !IsModalVisible) |
| | 6 | 323 | | { |
| | 6 | 324 | | return true; |
| | | 325 | | } |
| | | 326 | | |
| | 376 | 327 | | CountdownSeconds--; |
| | 376 | 328 | | OnCountdownTick?.Invoke(); |
| | | 329 | | |
| | 373 | 330 | | if (CountdownSeconds <= 0) |
| | 56 | 331 | | { |
| | 56 | 332 | | StopCountdown(); |
| | | 333 | | |
| | 56 | 334 | | if (!_isDisposed) |
| | 56 | 335 | | { |
| | 56 | 336 | | await HandleTimeoutAsync(); |
| | 56 | 337 | | } |
| | 56 | 338 | | return true; |
| | | 339 | | } |
| | | 340 | | |
| | 317 | 341 | | return false; |
| | 380 | 342 | | } |
| | | 343 | | |
| | | 344 | | #endregion |
| | | 345 | | |
| | | 346 | | #region IAsyncDisposable |
| | | 347 | | |
| | | 348 | | public async ValueTask DisposeAsync() |
| | 16 | 349 | | { |
| | 16 | 350 | | _isDisposed = true; |
| | 16 | 351 | | StopCountdown(); |
| | 16 | 352 | | IsModalVisible = false; |
| | | 353 | | |
| | 16 | 354 | | if (_timerService != null) |
| | 16 | 355 | | { |
| | 16 | 356 | | _timerService.OnTimerComplete -= HandleTimerComplete; |
| | 16 | 357 | | } |
| | | 358 | | |
| | 16 | 359 | | await ValueTask.CompletedTask; |
| | 16 | 360 | | } |
| | | 361 | | |
| | | 362 | | #endregion |
| | | 363 | | } |