| | | 1 | | using System.Threading; |
| | | 2 | | using Microsoft.JSInterop; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Pomodoro.Web.Models; |
| | | 5 | | using Pomodoro.Web.Services.Repositories; |
| | | 6 | | |
| | | 7 | | namespace Pomodoro.Web.Services; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Service for managing the pomodoro timer. |
| | | 11 | | /// Uses JavaScript interop for reliable timer in Blazor WebAssembly. |
| | | 12 | | /// Uses IndexedDB for persistent storage. |
| | | 13 | | /// Implements event publisher pattern to decouple from TaskService and ActivityService. |
| | | 14 | | /// </summary> |
| | | 15 | | public class TimerService : ITimerService, ITimerEventPublisher, IAsyncDisposable |
| | | 16 | | { |
| | | 17 | | private readonly IIndexedDbService _indexedDb; |
| | | 18 | | private readonly ISettingsRepository _settingsRepository; |
| | | 19 | | private readonly AppState _appState; |
| | | 20 | | private readonly IJSRuntime _jsRuntime; |
| | | 21 | | private readonly ILogger<TimerService> _logger; |
| | | 22 | | private DotNetObjectReference<TimerService>? _dotNetRef; |
| | | 23 | | private SynchronizationContext? _syncContext; |
| | 217 | 24 | | private readonly SemaphoreSlim _timerCompleteLock = new(Constants.Threading.SemaphoreInitialCount, Constants.Threadi |
| | 217 | 25 | | private readonly object _timerTickLock = new(); |
| | | 26 | | private bool _isDisposed; |
| | | 27 | | |
| | | 28 | | // ITimerEventPublisher events |
| | | 29 | | public event Func<TimerCompletedEventArgs, Task>? OnTimerCompleted; |
| | | 30 | | public event Action? OnTimerStateChanged; |
| | | 31 | | |
| | | 32 | | // ITimerService events |
| | | 33 | | public event Action? OnTick; |
| | | 34 | | public event Action<SessionType>? OnTimerComplete; // Backward compatibility |
| | | 35 | | public event Action? OnStateChanged; |
| | | 36 | | |
| | | 37 | | // Public properties for UI binding |
| | 9 | 38 | | public int RemainingSeconds => _appState.CurrentSession?.RemainingSeconds ?? 0; |
| | 94 | 39 | | public int TickCount { get; private set; } // Used to force UI updates |
| | | 40 | | |
| | 1 | 41 | | public TimerSession? CurrentSession => _appState.CurrentSession; |
| | 7 | 42 | | public TimerSettings Settings => _appState.Settings; |
| | 20 | 43 | | public bool IsRunning => _appState.CurrentSession?.IsRunning ?? false; |
| | | 44 | | // IsPaused requires WasStarted to distinguish between "reset but not started" and "started then paused" |
| | | 45 | | // This ensures PiP toggle logic correctly calls StartPomodoroAsync instead of ResumeAsync after reset |
| | 16 | 46 | | public bool IsPaused => _appState.CurrentSession != null && !_appState.CurrentSession.IsRunning && _appState.Current |
| | 4 | 47 | | public bool IsStarted => _appState.CurrentSession?.WasStarted ?? false; |
| | 14 | 48 | | public SessionType CurrentSessionType => _appState.CurrentSession?.Type ?? SessionType.Pomodoro; |
| | 8 | 49 | | public TimeSpan RemainingTime => TimeSpan.FromSeconds(RemainingSeconds); |
| | | 50 | | |
| | 217 | 51 | | public TimerService( |
| | 217 | 52 | | IIndexedDbService indexedDb, |
| | 217 | 53 | | ISettingsRepository settingsRepository, |
| | 217 | 54 | | AppState appState, |
| | 217 | 55 | | IJSRuntime jsRuntime, |
| | 217 | 56 | | ILogger<TimerService> logger) |
| | 217 | 57 | | { |
| | 217 | 58 | | _indexedDb = indexedDb; |
| | 217 | 59 | | _settingsRepository = settingsRepository; |
| | 217 | 60 | | _appState = appState; |
| | 217 | 61 | | _jsRuntime = jsRuntime; |
| | 217 | 62 | | _logger = logger; |
| | 217 | 63 | | } |
| | | 64 | | |
| | | 65 | | public async Task InitializeAsync() |
| | 127 | 66 | | { |
| | | 67 | | // Capture the synchronization context for UI updates |
| | 127 | 68 | | _syncContext = SynchronizationContext.Current; |
| | | 69 | | |
| | | 70 | | // Load settings from repository |
| | 127 | 71 | | var settings = await _settingsRepository.GetAsync(); |
| | 127 | 72 | | if (settings != null) |
| | 24 | 73 | | { |
| | 24 | 74 | | _appState.Settings = settings; |
| | 24 | 75 | | } |
| | | 76 | | |
| | | 77 | | // Load daily stats from IndexedDB |
| | 127 | 78 | | var todayKey = AppState.GetCurrentDayKey().ToString(Constants.DateFormats.IsoFormat); |
| | 127 | 79 | | var dailyStats = await _indexedDb.GetAsync<DailyStats>(Constants.Storage.DailyStatsStore, todayKey); |
| | 127 | 80 | | if (dailyStats != null) |
| | 25 | 81 | | { |
| | | 82 | | // Check if the stats are from today (using UTC date = 6 AM Bangladesh time reset) |
| | 25 | 83 | | var currentDayKey = AppState.GetCurrentDayKey(); |
| | 25 | 84 | | if (dailyStats.Date == currentDayKey) |
| | 13 | 85 | | { |
| | | 86 | | // Stats are from today, restore them |
| | 13 | 87 | | _appState.TodayTotalFocusMinutes = dailyStats.TotalFocusMinutes; |
| | 13 | 88 | | _appState.TodayPomodoroCount = dailyStats.PomodoroCount; |
| | 13 | 89 | | _appState.TodayTaskIdsWorkedOn = dailyStats.TaskIdsWorkedOn ?? new List<Guid>(); |
| | 13 | 90 | | _appState.LastResetDate = dailyStats.Date; |
| | 13 | 91 | | } |
| | | 92 | | else |
| | 12 | 93 | | { |
| | | 94 | | // Stats are from a previous day, reset them |
| | 12 | 95 | | _appState.ResetDailyStats(); |
| | 12 | 96 | | } |
| | 25 | 97 | | } |
| | | 98 | | else |
| | 102 | 99 | | { |
| | | 100 | | // No saved stats, initialize fresh |
| | 102 | 101 | | _appState.ResetDailyStats(); |
| | 102 | 102 | | } |
| | | 103 | | |
| | | 104 | | // Initialize with a default Pomodoro session if none exists |
| | 127 | 105 | | if (_appState.CurrentSession == null) |
| | 127 | 106 | | { |
| | 127 | 107 | | var durationSeconds = _appState.Settings.PomodoroMinutes * Constants.TimeConversion.SecondsPerMinute; |
| | 127 | 108 | | _appState.CurrentSession = new TimerSession |
| | 127 | 109 | | { |
| | 127 | 110 | | Id = Guid.NewGuid(), |
| | 127 | 111 | | TaskId = null, |
| | 127 | 112 | | Type = SessionType.Pomodoro, |
| | 127 | 113 | | StartedAt = DateTime.UtcNow, |
| | 127 | 114 | | DurationSeconds = durationSeconds, |
| | 127 | 115 | | RemainingSeconds = durationSeconds, |
| | 127 | 116 | | IsRunning = false, |
| | 127 | 117 | | IsCompleted = false |
| | 127 | 118 | | }; |
| | 127 | 119 | | } |
| | | 120 | | |
| | | 121 | | // Create dotnet reference for JS callbacks |
| | 127 | 122 | | _dotNetRef = DotNetObjectReference.Create(this); |
| | | 123 | | |
| | | 124 | | // Initialize JavaScript constants with user settings for chart time calculations |
| | 127 | 125 | | await _indexedDb.InitializeJsConstantsAsync( |
| | 127 | 126 | | _appState.Settings.PomodoroMinutes, |
| | 127 | 127 | | _appState.Settings.ShortBreakMinutes, |
| | 127 | 128 | | _appState.Settings.LongBreakMinutes); |
| | | 129 | | |
| | 127 | 130 | | NotifyStateChanged(); |
| | 127 | 131 | | } |
| | | 132 | | |
| | | 133 | | // Called from JavaScript |
| | | 134 | | [JSInvokable(Constants.JsInvokableMethods.OnTimerTick)] |
| | | 135 | | public void OnTimerTickJs() |
| | 42 | 136 | | { |
| | | 137 | | // Check if day has changed and reset daily stats if needed |
| | 42 | 138 | | if (_appState.NeedsDailyReset()) |
| | 3 | 139 | | { |
| | 3 | 140 | | _appState.ResetDailyStats(); |
| | 3 | 141 | | } |
| | | 142 | | |
| | | 143 | | // Use lock to ensure thread-safe access to session state |
| | | 144 | | // This prevents race conditions if JS callback fires during other state modifications |
| | 42 | 145 | | lock (_timerTickLock) |
| | 42 | 146 | | { |
| | 42 | 147 | | if (_appState.CurrentSession == null || !_appState.CurrentSession.IsRunning) |
| | 4 | 148 | | { |
| | 4 | 149 | | return; |
| | | 150 | | } |
| | | 151 | | |
| | 38 | 152 | | _appState.CurrentSession.RemainingSeconds--; |
| | 38 | 153 | | TickCount++; // Increment to force UI update detection |
| | | 154 | | |
| | 38 | 155 | | if (_appState.CurrentSession.RemainingSeconds <= 0) |
| | 33 | 156 | | { |
| | | 157 | | // Use SafeTaskRunner for consistent fire-and-forget handling with error logging |
| | 33 | 158 | | SafeTaskRunner.RunAndForget( |
| | 33 | 159 | | HandleTimerCompleteSafeAsync, |
| | 33 | 160 | | _logger, |
| | 33 | 161 | | Constants.SafeTaskOperations.TimerComplete |
| | 33 | 162 | | ); |
| | 33 | 163 | | return; |
| | | 164 | | } |
| | 5 | 165 | | } |
| | | 166 | | |
| | | 167 | | // Use synchronization context to ensure UI update happens on main thread |
| | 5 | 168 | | if (_syncContext != null) |
| | 1 | 169 | | { |
| | 2 | 170 | | _syncContext.Post(_ => NotifyTick(), null); |
| | 1 | 171 | | } |
| | | 172 | | else |
| | 4 | 173 | | { |
| | 4 | 174 | | NotifyTick(); |
| | 4 | 175 | | } |
| | 42 | 176 | | } |
| | | 177 | | |
| | | 178 | | public async Task StartPomodoroAsync(Guid? taskId = null) |
| | 62 | 179 | | { |
| | 62 | 180 | | var durationSeconds = _appState.Settings.GetDurationSeconds(SessionType.Pomodoro); |
| | | 181 | | |
| | 62 | 182 | | _appState.CurrentSession = new TimerSession |
| | 62 | 183 | | { |
| | 62 | 184 | | Id = Guid.NewGuid(), |
| | 62 | 185 | | TaskId = taskId, |
| | 62 | 186 | | Type = SessionType.Pomodoro, |
| | 62 | 187 | | StartedAt = DateTime.UtcNow, |
| | 62 | 188 | | DurationSeconds = durationSeconds, |
| | 62 | 189 | | RemainingSeconds = durationSeconds, |
| | 62 | 190 | | IsRunning = true, |
| | 62 | 191 | | IsCompleted = false, |
| | 62 | 192 | | WasStarted = true |
| | 62 | 193 | | }; |
| | | 194 | | |
| | 62 | 195 | | NotifyStateChanged(); |
| | 62 | 196 | | await StartJsTimerAsync(); |
| | 62 | 197 | | } |
| | | 198 | | |
| | | 199 | | public async Task StartShortBreakAsync() |
| | 12 | 200 | | { |
| | 12 | 201 | | var durationSeconds = _appState.Settings.GetDurationSeconds(SessionType.ShortBreak); |
| | | 202 | | |
| | 12 | 203 | | _appState.CurrentSession = new TimerSession |
| | 12 | 204 | | { |
| | 12 | 205 | | Id = Guid.NewGuid(), |
| | 12 | 206 | | TaskId = null, |
| | 12 | 207 | | Type = SessionType.ShortBreak, |
| | 12 | 208 | | StartedAt = DateTime.UtcNow, |
| | 12 | 209 | | DurationSeconds = durationSeconds, |
| | 12 | 210 | | RemainingSeconds = durationSeconds, |
| | 12 | 211 | | IsRunning = true, |
| | 12 | 212 | | IsCompleted = false, |
| | 12 | 213 | | WasStarted = true |
| | 12 | 214 | | }; |
| | | 215 | | |
| | 12 | 216 | | NotifyStateChanged(); |
| | 12 | 217 | | await StartJsTimerAsync(); |
| | 12 | 218 | | } |
| | | 219 | | |
| | | 220 | | public async Task StartLongBreakAsync() |
| | 9 | 221 | | { |
| | 9 | 222 | | var durationSeconds = _appState.Settings.GetDurationSeconds(SessionType.LongBreak); |
| | | 223 | | |
| | 9 | 224 | | _appState.CurrentSession = new TimerSession |
| | 9 | 225 | | { |
| | 9 | 226 | | Id = Guid.NewGuid(), |
| | 9 | 227 | | TaskId = null, |
| | 9 | 228 | | Type = SessionType.LongBreak, |
| | 9 | 229 | | StartedAt = DateTime.UtcNow, |
| | 9 | 230 | | DurationSeconds = durationSeconds, |
| | 9 | 231 | | RemainingSeconds = durationSeconds, |
| | 9 | 232 | | IsRunning = true, |
| | 9 | 233 | | IsCompleted = false, |
| | 9 | 234 | | WasStarted = true |
| | 9 | 235 | | }; |
| | | 236 | | |
| | 9 | 237 | | NotifyStateChanged(); |
| | 9 | 238 | | await StartJsTimerAsync(); |
| | 9 | 239 | | } |
| | | 240 | | |
| | | 241 | | public async Task SwitchSessionTypeAsync(SessionType sessionType) |
| | 14 | 242 | | { |
| | | 243 | | // Stop current timer |
| | 14 | 244 | | await StopJsTimer(); |
| | | 245 | | |
| | | 246 | | // Get duration for the new session type using helper method |
| | 14 | 247 | | var durationSeconds = _appState.Settings.GetDurationSeconds(sessionType); |
| | | 248 | | |
| | | 249 | | // Create new session (not running, just prepared) |
| | 14 | 250 | | _appState.CurrentSession = new TimerSession |
| | 14 | 251 | | { |
| | 14 | 252 | | Id = Guid.NewGuid(), |
| | 14 | 253 | | TaskId = _appState.CurrentSession?.TaskId, |
| | 14 | 254 | | Type = sessionType, |
| | 14 | 255 | | StartedAt = DateTime.UtcNow, |
| | 14 | 256 | | DurationSeconds = durationSeconds, |
| | 14 | 257 | | RemainingSeconds = durationSeconds, |
| | 14 | 258 | | IsRunning = false, |
| | 14 | 259 | | IsCompleted = false |
| | 14 | 260 | | }; |
| | | 261 | | |
| | 14 | 262 | | NotifyStateChanged(); |
| | 14 | 263 | | } |
| | | 264 | | |
| | | 265 | | public async Task PauseAsync() |
| | 11 | 266 | | { |
| | 11 | 267 | | if (_appState.CurrentSession != null && _appState.CurrentSession.IsRunning) |
| | 9 | 268 | | { |
| | 9 | 269 | | _appState.CurrentSession.IsRunning = false; |
| | 9 | 270 | | await StopJsTimer(); |
| | 9 | 271 | | NotifyStateChanged(); |
| | 9 | 272 | | } |
| | 11 | 273 | | } |
| | | 274 | | |
| | | 275 | | public async Task ResumeAsync() |
| | 10 | 276 | | { |
| | 10 | 277 | | if (_appState.CurrentSession != null && !_appState.CurrentSession.IsRunning) |
| | 8 | 278 | | { |
| | 8 | 279 | | _appState.CurrentSession.IsRunning = true; |
| | 8 | 280 | | NotifyStateChanged(); |
| | 8 | 281 | | await StartJsTimerAsync(); |
| | 8 | 282 | | } |
| | 10 | 283 | | } |
| | | 284 | | |
| | | 285 | | public async Task ResetAsync() |
| | 16 | 286 | | { |
| | 16 | 287 | | await StopJsTimer(); |
| | | 288 | | |
| | | 289 | | // Reset tick count to prevent potential overflow |
| | 16 | 290 | | TickCount = 0; |
| | | 291 | | |
| | 16 | 292 | | if (_appState.CurrentSession != null) |
| | 15 | 293 | | { |
| | | 294 | | // Use helper method to get duration for current session type |
| | 15 | 295 | | var durationSeconds = _appState.Settings.GetDurationSeconds(_appState.CurrentSession.Type); |
| | | 296 | | |
| | 15 | 297 | | _appState.CurrentSession.DurationSeconds = durationSeconds; |
| | 15 | 298 | | _appState.CurrentSession.RemainingSeconds = durationSeconds; |
| | 15 | 299 | | _appState.CurrentSession.IsRunning = false; |
| | 15 | 300 | | _appState.CurrentSession.WasStarted = false; |
| | 15 | 301 | | } |
| | | 302 | | |
| | 16 | 303 | | NotifyStateChanged(); |
| | 16 | 304 | | } |
| | | 305 | | |
| | | 306 | | public async Task UpdateSettingsAsync(TimerSettings settings) |
| | 11 | 307 | | { |
| | 11 | 308 | | _appState.Settings = settings; |
| | 11 | 309 | | await SaveSettingsAsync(); |
| | | 310 | | |
| | | 311 | | // Update current session duration if timer hasn't started yet |
| | 11 | 312 | | if (_appState.CurrentSession != null && !_appState.CurrentSession.WasStarted) |
| | 4 | 313 | | { |
| | 4 | 314 | | var durationSeconds = settings.GetDurationSeconds(_appState.CurrentSession.Type); |
| | 4 | 315 | | _appState.CurrentSession.DurationSeconds = durationSeconds; |
| | 4 | 316 | | _appState.CurrentSession.RemainingSeconds = durationSeconds; |
| | 4 | 317 | | } |
| | | 318 | | |
| | | 319 | | // Initialize JS constants with new settings for chart time calculations |
| | 11 | 320 | | await _indexedDb.InitializeJsConstantsAsync(settings.PomodoroMinutes, settings.ShortBreakMinutes, settings.LongB |
| | | 321 | | |
| | 11 | 322 | | NotifyStateChanged(); |
| | 11 | 323 | | } |
| | | 324 | | |
| | | 325 | | public async Task SaveSettingsAsync() |
| | 11 | 326 | | { |
| | 11 | 327 | | await _settingsRepository.SaveAsync(_appState.Settings); |
| | 11 | 328 | | } |
| | | 329 | | |
| | | 330 | | private async Task StartJsTimerAsync() |
| | 91 | 331 | | { |
| | | 332 | | // Create the reference only once - it will be disposed in DisposeAsync() |
| | 91 | 333 | | _dotNetRef ??= DotNetObjectReference.Create(this); |
| | | 334 | | |
| | | 335 | | // Unlock audio context on user interaction (timer start) |
| | | 336 | | // This is required for browser autoplay policies |
| | | 337 | | try |
| | 91 | 338 | | { |
| | 91 | 339 | | await _jsRuntime.InvokeVoidAsync(Constants.NotificationJsFunctions.UnlockAudio); |
| | 90 | 340 | | } |
| | 1 | 341 | | catch (Exception ex) |
| | 1 | 342 | | { |
| | | 343 | | // Audio unlock may fail on some browsers - log for debugging but don't block timer |
| | 1 | 344 | | _logger.LogDebug(ex, Constants.Messages.AudioUnlockFailed); |
| | 1 | 345 | | } |
| | | 346 | | |
| | | 347 | | try |
| | 91 | 348 | | { |
| | 91 | 349 | | await _jsRuntime.InvokeVoidAsync(Constants.JsFunctions.TimerStart, _dotNetRef); |
| | 89 | 350 | | } |
| | 2 | 351 | | catch (Exception ex) |
| | 2 | 352 | | { |
| | | 353 | | // Log the error and retry with a delay |
| | 2 | 354 | | _logger.LogWarning(ex, Constants.Messages.TimerStartFailed); |
| | | 355 | | |
| | | 356 | | try |
| | 2 | 357 | | { |
| | | 358 | | // Add a small delay before retry to allow JS runtime to stabilize |
| | 2 | 359 | | await Task.Delay(100); |
| | 2 | 360 | | await _jsRuntime.InvokeVoidAsync(Constants.JsFunctions.TimerStart, _dotNetRef); |
| | 1 | 361 | | } |
| | 1 | 362 | | catch (Exception retryEx) |
| | 1 | 363 | | { |
| | 1 | 364 | | _logger.LogError(retryEx, Constants.Messages.TimerStartFailedAfterRetry); |
| | | 365 | | // Don't rethrow - the timer not starting is not critical, user can try again |
| | 1 | 366 | | } |
| | 2 | 367 | | } |
| | 91 | 368 | | } |
| | | 369 | | |
| | | 370 | | private async Task StopJsTimer() |
| | 82 | 371 | | { |
| | | 372 | | try |
| | 82 | 373 | | { |
| | 82 | 374 | | await _jsRuntime.InvokeVoidAsync(Constants.JsFunctions.TimerStop); |
| | 81 | 375 | | } |
| | 1 | 376 | | catch (Exception ex) |
| | 1 | 377 | | { |
| | 1 | 378 | | _logger.LogWarning(ex, Constants.Messages.TimerStopFailed); |
| | 1 | 379 | | } |
| | 82 | 380 | | } |
| | | 381 | | |
| | | 382 | | private async Task HandleTimerCompleteAsync() |
| | 30 | 383 | | { |
| | 30 | 384 | | await StopJsTimer(); |
| | | 385 | | |
| | 30 | 386 | | var session = _appState.CurrentSession; |
| | 31 | 387 | | if (session == null) return; |
| | | 388 | | |
| | 29 | 389 | | session.IsRunning = false; |
| | 29 | 390 | | session.IsCompleted = true; |
| | | 391 | | |
| | | 392 | | // Reset remaining seconds back to full duration for display |
| | 29 | 393 | | session.RemainingSeconds = session.DurationSeconds; |
| | | 394 | | |
| | | 395 | | // Get task name for event args (thread-safe) |
| | 29 | 396 | | string? taskName = null; |
| | 29 | 397 | | if (session.TaskId.HasValue) |
| | 24 | 398 | | { |
| | 34 | 399 | | var task = _appState.Tasks.FirstOrDefault(t => t.Id == session.TaskId.Value); |
| | 24 | 400 | | taskName = task?.Name; |
| | 24 | 401 | | } |
| | | 402 | | |
| | | 403 | | // Calculate duration using helper method |
| | 29 | 404 | | var durationMinutes = _appState.Settings.GetDurationMinutes(session.Type); |
| | | 405 | | |
| | | 406 | | // If pomodoro completed, update today's stats |
| | 29 | 407 | | if (session.Type == SessionType.Pomodoro && session.TaskId.HasValue) |
| | 24 | 408 | | { |
| | | 409 | | // Update today's stats |
| | 24 | 410 | | _appState.TodayTotalFocusMinutes += durationMinutes; |
| | 24 | 411 | | _appState.TodayPomodoroCount++; |
| | | 412 | | |
| | | 413 | | // Track unique task worked on today (thread-safe, avoids duplicates) |
| | 24 | 414 | | _appState.AddTodayTaskId(session.TaskId.Value); |
| | | 415 | | |
| | | 416 | | // Persist daily stats to storage |
| | 24 | 417 | | await SaveDailyStatsAsync(); |
| | 22 | 418 | | } |
| | | 419 | | |
| | | 420 | | // Create event args |
| | 27 | 421 | | var eventArgs = new TimerCompletedEventArgs( |
| | 27 | 422 | | session.Type, |
| | 27 | 423 | | session.TaskId, |
| | 27 | 424 | | taskName, |
| | 27 | 425 | | durationMinutes, |
| | 27 | 426 | | WasCompleted: true, |
| | 27 | 427 | | CompletedAt: DateTime.UtcNow |
| | 27 | 428 | | ); |
| | | 429 | | |
| | | 430 | | // Raise event for subscribers (TaskService, ActivityService) |
| | 27 | 431 | | await NotifyTimerCompletedAsync(eventArgs); |
| | | 432 | | |
| | | 433 | | // Backward compatibility - also raise old event |
| | 27 | 434 | | OnTimerComplete?.Invoke(session.Type); |
| | | 435 | | |
| | 27 | 436 | | NotifyStateChanged(); |
| | | 437 | | |
| | | 438 | | // Note: Auto-start is handled by ConsentService which shows a consent modal |
| | | 439 | | // When auto-start is enabled, the modal appears with a countdown |
| | | 440 | | // When auto-start is disabled, no modal appears and user manually starts next session |
| | 28 | 441 | | } |
| | | 442 | | |
| | | 443 | | /// <summary> |
| | | 444 | | /// Safe async wrapper for HandleTimerCompleteAsync to avoid fire-and-forget issues |
| | | 445 | | /// Uses semaphore to prevent concurrent timer completion handling |
| | | 446 | | /// </summary> |
| | | 447 | | private async Task HandleTimerCompleteSafeAsync() |
| | 35 | 448 | | { |
| | 40 | 449 | | if (_isDisposed) return; |
| | | 450 | | |
| | | 451 | | // Try to acquire lock - if another completion is in progress, skip this one |
| | 30 | 452 | | if (!await _timerCompleteLock.WaitAsync(0)) |
| | 1 | 453 | | { |
| | 1 | 454 | | return; |
| | | 455 | | } |
| | | 456 | | |
| | | 457 | | try |
| | 29 | 458 | | { |
| | 29 | 459 | | await HandleTimerCompleteAsync(); |
| | 27 | 460 | | } |
| | 2 | 461 | | catch (Exception ex) |
| | 2 | 462 | | { |
| | 2 | 463 | | _logger.LogError(ex, Constants.Messages.TimerHandleCompleteError); |
| | 2 | 464 | | } |
| | | 465 | | finally |
| | 29 | 466 | | { |
| | 87 | 467 | | try { _timerCompleteLock.Release(); } catch (ObjectDisposedException) { } |
| | 29 | 468 | | } |
| | 35 | 469 | | } |
| | | 470 | | |
| | | 471 | | private async Task SaveDailyStatsAsync() |
| | 24 | 472 | | { |
| | 24 | 473 | | var stats = new DailyStats |
| | 24 | 474 | | { |
| | 24 | 475 | | Date = AppState.GetCurrentDayKey(), |
| | 24 | 476 | | TotalFocusMinutes = _appState.TodayTotalFocusMinutes, |
| | 24 | 477 | | PomodoroCount = _appState.TodayPomodoroCount, |
| | 24 | 478 | | TaskIdsWorkedOn = _appState.TodayTaskIdsWorkedOn |
| | 24 | 479 | | }; |
| | 24 | 480 | | await _indexedDb.PutAsync(Constants.Storage.DailyStatsStore, stats); |
| | 22 | 481 | | } |
| | | 482 | | |
| | | 483 | | private void NotifyTick() |
| | 5 | 484 | | { |
| | 5 | 485 | | OnTick?.Invoke(); |
| | 5 | 486 | | } |
| | | 487 | | |
| | | 488 | | private async Task NotifyTimerCompletedAsync(TimerCompletedEventArgs args) |
| | 27 | 489 | | { |
| | 27 | 490 | | if (OnTimerCompleted != null) |
| | 3 | 491 | | { |
| | | 492 | | // Get all handlers and invoke them |
| | 3 | 493 | | var handlers = OnTimerCompleted.GetInvocationList(); |
| | 21 | 494 | | foreach (var handler in handlers) |
| | 6 | 495 | | { |
| | | 496 | | try |
| | 6 | 497 | | { |
| | 6 | 498 | | await ((Func<TimerCompletedEventArgs, Task>)handler)(args); |
| | 5 | 499 | | } |
| | 1 | 500 | | catch (Exception ex) |
| | 1 | 501 | | { |
| | 1 | 502 | | _logger.LogError(ex, Constants.Messages.TimerCompletionHandlerError); |
| | 1 | 503 | | } |
| | 6 | 504 | | } |
| | 3 | 505 | | } |
| | 27 | 506 | | } |
| | | 507 | | |
| | | 508 | | private void NotifyStateChanged() |
| | 295 | 509 | | { |
| | 295 | 510 | | OnStateChanged?.Invoke(); |
| | 295 | 511 | | } |
| | | 512 | | |
| | | 513 | | public async ValueTask DisposeAsync() |
| | 13 | 514 | | { |
| | 13 | 515 | | _isDisposed = true; |
| | 13 | 516 | | await StopJsTimer(); |
| | 13 | 517 | | _dotNetRef?.Dispose(); |
| | 13 | 518 | | _timerCompleteLock.Dispose(); |
| | 13 | 519 | | } |
| | | 520 | | } |