Skip to content

Commit b1f3d88

Browse files
committed
fix: solve some errors
1 parent 3757d6a commit b1f3d88

2 files changed

Lines changed: 77 additions & 41 deletions

File tree

TelegramDownloader/Data/TelegramService.cs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ public class TelegramService : ITelegramService
3333
private static Mutex mut = new Mutex();
3434
private ILogger<IFileService> _logger { get; set; }
3535

36+
// Event that fires when user successfully logs in
37+
public static event EventHandler OnUserLoggedIn;
38+
3639

3740
public TelegramService(TransactionInfoService tis, IDbService db, ILogger<IFileService> logger, ITaskPersistenceService persistence)
3841
{
@@ -126,6 +129,18 @@ async Task<string> DoLogin(string loginInfo) // (add this method to your code)
126129
// splitSizeGB = 4;
127130
}
128131
_logger.LogInformation("Login successful - User: {UserId}, Premium: {IsPremium}", client.User.id, isPremium);
132+
133+
// Fire the login event to notify subscribers (like TaskResumeService)
134+
try
135+
{
136+
OnUserLoggedIn?.Invoke(this, EventArgs.Empty);
137+
_logger.LogInformation("OnUserLoggedIn event fired");
138+
}
139+
catch (Exception ex)
140+
{
141+
_logger.LogError(ex, "Error firing OnUserLoggedIn event");
142+
}
143+
129144
return "ok";
130145
}
131146
/// <summary>
@@ -803,7 +818,7 @@ public async Task<Stream> DownloadFileAndReturn(ChatMessages message, Stream ms
803818
// using var fileStream = File.Create(filename);
804819
MemoryStream dest = new MemoryStream();
805820
// using var dest = new FileStream($"{Path.Combine(folder != null ? folder : Path.Combine(Environment.CurrentDirectory, "download"), filename)}", FileMode.Create, FileAccess.Write);
806-
await client.DownloadFileAsync(document, ms ?? dest, null, model.ProgressCallback);
821+
await client.DownloadFileAsync(document, ms ?? dest, (PhotoSizeBase)null, model.ProgressCallback);
807822
_logger.LogInformation("Document download completed - FileName: {FileName}", filename);
808823
return ms ?? dest;
809824
}
@@ -855,7 +870,7 @@ public async Task<Stream> DownloadFileAndReturnWithOffset(ChatMessages message,
855870
{
856871
// No offset - use standard download
857872
MemoryStream dest = new MemoryStream();
858-
await client.DownloadFileAsync(document, ms ?? dest, null, model.ProgressCallback);
873+
await client.DownloadFileAsync(document, ms ?? dest, (PhotoSizeBase)null, model.ProgressCallback);
859874
_logger.LogInformation("Document download completed - FileName: {FileName}", filename);
860875
return ms ?? dest;
861876
}
@@ -976,7 +991,7 @@ public async Task<string> DownloadFile(ChatMessages message, string fileName = n
976991
_logger.LogInformation("Starting file download to disk - FileName: {FileName}, Size: {SizeMB:F2}MB", filename, document.size / (1024.0 * 1024.0));
977992
// using var fileStream = File.Create(filename);
978993
using var dest = new FileStream($"{Path.Combine(folder != null ? folder : Path.Combine(Environment.CurrentDirectory, "local", "temp"), filename)}", FileMode.Create, FileAccess.Write);
979-
await client.DownloadFileAsync(document, dest, null, model.ProgressCallback);
994+
await client.DownloadFileAsync(document, dest, (PhotoSizeBase)null, model.ProgressCallback);
980995

981996
_logger.LogInformation("File download to disk completed - FileName: {FileName}", filename);
982997
}

TelegramDownloader/Services/TaskResumeService.cs

Lines changed: 59 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)