@@ -18,8 +18,13 @@ public TaskResumeService(IServiceProvider serviceProvider, ILogger<TaskResumeSer
1818 _logger = logger ;
1919 }
2020
21+ private CancellationToken _cancellationToken ;
22+ private bool _hasResumedTasks = false ;
23+
2124 public async Task StartAsync ( CancellationToken cancellationToken )
2225 {
26+ _cancellationToken = cancellationToken ;
27+
2328 _logger . LogInformation ( "========== TaskResumeService STARTING ==========" ) ;
2429 _logger . LogInformation ( "AutoResumeOnStartup config value: {Value}" , GeneralConfigStatic . config ? . AutoResumeOnStartup ) ;
2530 _logger . LogInformation ( "EnableTaskPersistence config value: {Value}" , GeneralConfigStatic . config ? . EnableTaskPersistence ) ;
@@ -31,68 +36,83 @@ public async Task StartAsync(CancellationToken cancellationToken)
3136 return ;
3237 }
3338
34- _logger . LogInformation ( "Auto-resume is ENABLED - will resume tasks in background" ) ;
39+ _logger . LogInformation ( "Auto-resume is ENABLED - subscribing to OnUserLoggedIn event" ) ;
40+
41+ // Subscribe to the login event
42+ TelegramService . OnUserLoggedIn += OnUserLoggedIn ;
3543
36- // Run in background to not block application startup
44+ // Also try to resume immediately in case user is already logged in
3745 _ = Task . Run ( async ( ) =>
3846 {
3947 try
4048 {
41- await ResumeTasksAsync ( cancellationToken ) ;
49+ // Wait a bit for services to initialize
50+ await Task . Delay ( 3000 , cancellationToken ) ;
51+ await TryResumeTasksAsync ( ) ;
4252 }
4353 catch ( Exception ex )
4454 {
45- _logger . LogError ( ex , "CRITICAL ERROR during task resume: {Message}" , ex . Message ) ;
55+ _logger . LogError ( ex , "Error during initial task resume attempt : {Message}" , ex . Message ) ;
4656 }
4757 } , cancellationToken ) ;
4858 }
4959
50- private async Task ResumeTasksAsync ( CancellationToken cancellationToken )
60+ private async void OnUserLoggedIn ( object sender , EventArgs e )
5161 {
52- _logger . LogInformation ( "ResumeTasksAsync - Starting, waiting 5 seconds for services... " ) ;
62+ _logger . LogInformation ( "========== OnUserLoggedIn event received ========== " ) ;
5363
54- // Wait a bit for services to be fully initialized
55- await Task . Delay ( 5000 , cancellationToken ) ;
64+ if ( _hasResumedTasks )
65+ {
66+ _logger . LogInformation ( "Tasks already resumed - skipping" ) ;
67+ return ;
68+ }
5669
57- _logger . LogInformation ( "ResumeTasksAsync - Creating service scope..." ) ;
70+ try
71+ {
72+ await TryResumeTasksAsync ( ) ;
73+ }
74+ catch ( Exception ex )
75+ {
76+ _logger . LogError ( ex , "Error resuming tasks after login: {Message}" , ex . Message ) ;
77+ }
78+ }
79+
80+ private async Task TryResumeTasksAsync ( )
81+ {
82+ if ( _hasResumedTasks )
83+ {
84+ _logger . LogInformation ( "Tasks already resumed - skipping" ) ;
85+ return ;
86+ }
5887
5988 using var scope = _serviceProvider . CreateScope ( ) ;
6089 var telegramService = scope . ServiceProvider . GetRequiredService < ITelegramService > ( ) ;
61- var persistence = scope . ServiceProvider . GetRequiredService < ITaskPersistenceService > ( ) ;
62- var fileService = scope . ServiceProvider . GetRequiredService < IFileService > ( ) ;
63- var transactionInfo = scope . ServiceProvider . GetRequiredService < TransactionInfoService > ( ) ;
6490
65- _logger . LogInformation ( "ResumeTasksAsync - Services resolved. Persistence enabled: {Enabled}, FileService type: {Type}" ,
66- persistence . IsEnabled , fileService . GetType ( ) . Name ) ;
91+ if ( ! telegramService . checkUserLogin ( ) )
92+ {
93+ _logger . LogInformation ( "Telegram session not ready yet - waiting for user login" ) ;
94+ return ;
95+ }
6796
68- // Wait for Telegram session to be ready
69- var maxWaitTime = TimeSpan . FromSeconds ( 60 ) ;
70- var waited = TimeSpan . Zero ;
71- var checkInterval = TimeSpan . FromSeconds ( 3 ) ;
97+ _logger . LogInformation ( "Telegram session is ready - proceeding to resume tasks" ) ;
98+ _hasResumedTasks = true ;
7299
73- _logger . LogInformation ( "Waiting for Telegram session to be ready (max {MaxWait}s)..." , maxWaitTime . TotalSeconds ) ;
100+ await ResumeTasksAsync ( _cancellationToken ) ;
101+ }
74102
75- while ( ! telegramService . checkUserLogin ( ) && waited < maxWaitTime )
76- {
77- if ( cancellationToken . IsCancellationRequested )
78- {
79- _logger . LogWarning ( "Cancellation requested while waiting for Telegram session" ) ;
80- return ;
81- }
103+ private async Task ResumeTasksAsync ( CancellationToken cancellationToken )
104+ {
105+ _logger . LogInformation ( "========== ResumeTasksAsync - Starting ==========" ) ;
82106
83- _logger . LogInformation ( "Waiting for Telegram session... {Waited}s elapsed" , waited . TotalSeconds ) ;
84- await Task . Delay ( checkInterval , cancellationToken ) ;
85- waited += checkInterval ;
86- }
107+ using var scope = _serviceProvider . CreateScope ( ) ;
108+ var persistence = scope . ServiceProvider . GetRequiredService < ITaskPersistenceService > ( ) ;
109+ var fileService = scope . ServiceProvider . GetRequiredService < IFileService > ( ) ;
110+ var transactionInfo = scope . ServiceProvider . GetRequiredService < TransactionInfoService > ( ) ;
87111
88- if ( ! telegramService . checkUserLogin ( ) )
89- {
90- _logger . LogWarning ( "Telegram session NOT ready after {MaxWait}s - tasks will NOT be resumed automatically. " +
91- "They will resume when user logs in." , maxWaitTime . TotalSeconds ) ;
92- return ;
93- }
112+ _logger . LogInformation ( "ResumeTasksAsync - Services resolved. Persistence enabled: {Enabled}, FileService type: {Type}" ,
113+ persistence . IsEnabled , fileService . GetType ( ) . Name ) ;
94114
95- _logger . LogInformation ( "========== Telegram session READY - Loading pending tasks from MongoDB ==========" ) ;
115+ _logger . LogInformation ( "========== Loading pending tasks from MongoDB ==========" ) ;
96116
97117 // Cleanup stale tasks first
98118 await persistence . CleanupStaleTasks ( ) ;
@@ -331,7 +351,8 @@ private async Task ResumeBatchTask(
331351
332352 public Task StopAsync ( CancellationToken cancellationToken )
333353 {
334- _logger . LogInformation ( "TaskResumeService stopping" ) ;
354+ _logger . LogInformation ( "TaskResumeService stopping - unsubscribing from events" ) ;
355+ TelegramService . OnUserLoggedIn -= OnUserLoggedIn ;
335356 return Task . CompletedTask ;
336357 }
337358 }
0 commit comments