Skip to content

Commit 2c36de8

Browse files
committed
feat: add preload data channels at startup
1 parent 63420bb commit 2c36de8

5 files changed

Lines changed: 105 additions & 12 deletions

File tree

TelegramDownloader/Data/ITelegramService.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public interface ITelegramService
2929
Task<List<ChatViewBase>> getAllChats();
3030
Task<List<ChatViewBase>> getAllSavedChats();
3131
Task<ChatsWithFolders> getChatsWithFolders();
32+
Task PreloadChannelsAsync();
3233
Task<List<ChatMessages>> getAllMessages(long id, Boolean onlyFiles = false);
3334
Task<GridDataProviderResult<ChatMessages>> getPaginatedMessages(long id, int page, int size, Boolean onlyFiles = false);
3435
Task<List<ChatMessages>> getAllMediaMessages(long id, Boolean onlyFiles = false);

TelegramDownloader/Data/TelegramService.cs

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,24 @@ public TelegramService(TransactionInfoService tis, IDbService db, ILogger<IFileS
5050
{
5151
if (client == null && HasValidCredentials())
5252
{
53-
newClient();
53+
try
54+
{
55+
newClient();
56+
}
57+
catch (WTelegram.WTException ex) when (ex.Message.Contains("session file"))
58+
{
59+
// Session file is corrupted - delete it and create a new one
60+
_logger.LogWarning("Session file corrupted during startup, deleting: {Message}", ex.Message);
61+
var sessionPath = UserService.USERDATAFOLDER + "/WTelegram.session";
62+
if (File.Exists(sessionPath))
63+
{
64+
File.Delete(sessionPath);
65+
_logger.LogInformation("Deleted corrupted session file: {Path}", sessionPath);
66+
}
67+
// Create new client with fresh session
68+
newClient();
69+
_logger.LogInformation("Telegram client initialized with new session");
70+
}
5471
}
5572
else if (!HasValidCredentials())
5673
{
@@ -100,8 +117,25 @@ public void InitializeClient()
100117
if (client == null) // Double-check after acquiring lock
101118
{
102119
_logger.LogInformation("Initializing Telegram client after setup");
103-
newClient();
104-
_logger.LogInformation("Telegram client initialized successfully");
120+
try
121+
{
122+
newClient();
123+
_logger.LogInformation("Telegram client initialized successfully");
124+
}
125+
catch (WTelegram.WTException ex) when (ex.Message.Contains("session file"))
126+
{
127+
// Session file is corrupted - delete it and create a new one
128+
_logger.LogWarning("Session file corrupted, deleting and creating new session: {Message}", ex.Message);
129+
var sessionPath = UserService.USERDATAFOLDER + "/WTelegram.session";
130+
if (File.Exists(sessionPath))
131+
{
132+
File.Delete(sessionPath);
133+
_logger.LogInformation("Deleted corrupted session file: {Path}", sessionPath);
134+
}
135+
// Create new client with fresh session
136+
newClient();
137+
_logger.LogInformation("Telegram client initialized with new session");
138+
}
105139
}
106140
}
107141
catch (Exception ex)
@@ -599,6 +633,43 @@ public async Task<ChatsWithFolders> getChatsWithFolders()
599633
return result;
600634
}
601635

636+
/// <summary>
637+
/// Preloads channels and configuration at startup if user is logged in.
638+
/// This ensures channels are available for API calls without requiring UI access first.
639+
/// </summary>
640+
public async Task PreloadChannelsAsync()
641+
{
642+
if (!checkUserLogin())
643+
{
644+
_logger.LogInformation("PreloadChannelsAsync: User not logged in, skipping preload");
645+
return;
646+
}
647+
648+
try
649+
{
650+
_logger.LogInformation("PreloadChannelsAsync: Starting channel preload...");
651+
652+
// Load all channels into cache
653+
var channels = await getAllChats();
654+
_logger.LogInformation("PreloadChannelsAsync: Loaded {Count} channels", channels.Count);
655+
656+
// Also preload folders
657+
var folders = await getChatsWithFolders();
658+
_logger.LogInformation("PreloadChannelsAsync: Loaded {FolderCount} folders with {UngroupedCount} ungrouped chats",
659+
folders.Folders.Count, folders.UngroupedChats.Count);
660+
661+
// Preload favourites
662+
var favourites = await GetFouriteChannels(true);
663+
_logger.LogInformation("PreloadChannelsAsync: Loaded {Count} favourite channels", favourites.Count);
664+
665+
_logger.LogInformation("PreloadChannelsAsync: Channel preload completed successfully");
666+
}
667+
catch (Exception ex)
668+
{
669+
_logger.LogError(ex, "PreloadChannelsAsync: Error preloading channels");
670+
}
671+
}
672+
602673
public async Task<Message> uploadFile(string chatId, Stream file, string fileName, string mimeType = null, UploadModel um = null, string caption = null)
603674
{
604675
_logger.LogInformation("Starting file upload - FileName: {FileName}, Size: {SizeMB:F2}MB, ChatId: {ChatId}",

TelegramDownloader/Pages/Setup.razor

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,7 @@
475475
@code {
476476
private int currentStep = 1;
477477
private bool isLoading = false;
478+
private bool _shouldRedirectHome = false;
478479

479480
private string mongoConnectionString = "";
480481
private string mongoError = "";
@@ -483,6 +484,14 @@
483484
private string apiHash = "";
484485
private string telegramError = "";
485486

487+
protected override void OnAfterRender(bool firstRender)
488+
{
489+
if (firstRender && _shouldRedirectHome)
490+
{
491+
NavigationManager.NavigateTo("/", forceLoad: true);
492+
}
493+
}
494+
486495
protected override void OnInitialized()
487496
{
488497
// Check current setup status using cached/sync method
@@ -515,8 +524,8 @@
515524
currentStep = 2;
516525
break;
517526
case SetupStep.Complete:
518-
// Redirect to home if setup is already complete
519-
NavigationManager.NavigateTo("/", forceLoad: true);
527+
// Redirect to home if setup is already complete (done in OnAfterRender)
528+
_shouldRedirectHome = true;
520529
break;
521530
}
522531
}

TelegramDownloader/Services/TaskResumeService.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,21 @@ private async Task TryResumeTasksAsync()
110110
return;
111111
}
112112

113-
_logger.LogInformation("Telegram session is ready - proceeding to resume tasks");
113+
_logger.LogInformation("Telegram session is ready - proceeding with startup tasks");
114114
_hasResumedTasks = true;
115115

116+
// Preload channels first - this ensures they're available for API calls
117+
_logger.LogInformation("========== Preloading channels ==========");
118+
try
119+
{
120+
await telegramService.PreloadChannelsAsync();
121+
}
122+
catch (Exception ex)
123+
{
124+
_logger.LogError(ex, "Error preloading channels: {Message}", ex.Message);
125+
}
126+
127+
// Then resume pending tasks
116128
await ResumeTasksAsync(_cancellationToken);
117129
}
118130

TelegramDownloader/TelegramDownloader.csproj

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,17 @@
2424
<ItemGroup>
2525
<PackageReference Include="Blazor.Bootstrap" Version="3.5.0" />
2626
<PackageReference Include="MongoDB.Driver" Version="3.5.2" />
27-
<PackageReference Include="Serilog" Version="4.2.0" />
28-
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
29-
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
30-
<PackageReference Include="Serilog.Sinks.MongoDB" Version="7.0.0" />
27+
<PackageReference Include="Serilog" Version="4.3.0" />
28+
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
29+
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
30+
<PackageReference Include="Serilog.Sinks.MongoDB" Version="7.2.0" />
3131
<PackageReference Include="QRCoder" Version="1.7.0" />
32-
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.3.2" />
32+
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.9.0" />
3333
<PackageReference Include="Syncfusion.Blazor" Version="29.2.11" />
3434
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
3535
<PackageReference Include="Syncfusion.EJ2.AspNet.Core" Version="29.2.11" />
3636
<PackageReference Include="System.IO.Hashing" Version="10.0.1" />
37-
<PackageReference Include="WTelegramClient" Version="4.3.14" />
37+
<PackageReference Include="WTelegramClient" Version="4.4.0" />
3838
</ItemGroup>
3939

4040
<ItemGroup>

0 commit comments

Comments
 (0)