Skip to content

Commit ebe67ce

Browse files
committed
chore: improve events
1 parent 8a8adfe commit ebe67ce

9 files changed

Lines changed: 168 additions & 38 deletions

File tree

TelegramDownloader/Data/FileService.cs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1280,6 +1280,7 @@ public async Task UploadFileFromServer(string dbName, string currentPath, List<S
12801280
int waitForNextAttempt = 1000;
12811281
UploadModel um = new UploadModel();
12821282
um.tis = _tis;
1283+
um.startDate = DateTime.Now;
12831284
um.path = currentFilePath;
12841285
um.chatName = _ts.getChatName(Convert.ToInt64(dbName));
12851286
// add upload to task list
@@ -1335,6 +1336,7 @@ public async Task UploadFileFromServer(string dbName, string currentPath, List<S
13351336
um.chatName = _ts.getChatName(Convert.ToInt64(dbName));
13361337
// add upload to task list
13371338
idt.addUpload(um);
1339+
um.startDate = DateTime.Now;
13381340
while (attempts != 0 || um.state == StateTask.Canceled)
13391341
try
13401342
{
@@ -1586,43 +1588,65 @@ public bool isChannelRefreshing(string channelId)
15861588

15871589
public async Task UploadFile(string dbName, string currentPath, UploadFiles file) // ItemsUploadedEventArgs<FileManagerDirectoryContent> args)
15881590
{
1591+
_logger.LogInformation("UploadFile started - DbName: {DbName}, CurrentPath: {CurrentPath}, FileName: {FileName}, FileSize: {FileSize} bytes ({FileSizeMB:F2} MB)",
1592+
dbName, currentPath, file.File.Name, file.File.Size, file.File.Size / 1024.0 / 1024.0);
1593+
15891594
try
15901595
{
15911596
string currentFilePath = System.IO.Path.Combine(TEMPDIR, dbName + currentPath);
1592-
await SaveToFile(file.File, currentFilePath);
1597+
_logger.LogDebug("Saving file to temp path: {TempPath}", currentFilePath);
15931598

1599+
await SaveToFile(file.File, currentFilePath);
1600+
_logger.LogDebug("File saved to temp successfully");
15941601

15951602
BsonFileManagerModel model = new BsonFileManagerModel();
15961603
model.Size = file.File.Size;
15971604
TL.Message m = null;
1605+
15981606
if (file.File.Size > MaxSize)
15991607
{
1608+
_logger.LogInformation("File exceeds MaxSize ({MaxSizeMB:F2} MB), splitting file into chunks", MaxSize / 1024.0 / 1024.0);
16001609

16011610
List<string> files = await splitFileStreamAsync(currentFilePath, file.File.Name, MaxSize);
1611+
_logger.LogDebug("File split into {ChunkCount} chunks", files.Count);
1612+
16021613
File.Delete(System.IO.Path.Combine(currentFilePath, file.File.Name));
16031614
int i = 1;
16041615
model.ListMessageId = new List<int>();
16051616
model.isSplit = true;
1617+
16061618
foreach (string s in files)
16071619
{
1620+
_logger.LogDebug("Uploading chunk {ChunkNumber} of {TotalChunks}: {ChunkPath}", i, files.Count, s);
1621+
16081622
using (FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.Read))
16091623
m = await _ts.uploadFile(dbName, fs, $"({i} of {files.Count}) - " + file.File.Name, caption: getCaption(currentPath));
1624+
16101625
model.ListMessageId.Add(m.ID);
1626+
_logger.LogDebug("Chunk {ChunkNumber} uploaded successfully, MessageId: {MessageId}", i, m.ID);
1627+
16111628
File.Delete(s);
16121629
i++;
16131630
}
16141631

1632+
_logger.LogInformation("All {ChunkCount} chunks uploaded successfully", files.Count);
16151633
}
16161634
else
16171635
{
1636+
_logger.LogDebug("Uploading single file to Telegram");
1637+
16181638
using (FileStream ms = new FileStream(System.IO.Path.Combine(currentFilePath, file.File.Name), FileMode.Open))
16191639
{
16201640
m = await _ts.uploadFile(dbName, ms, file.File.Name, caption: getCaption(currentPath));
16211641
}
16221642
model.MessageId = m.ID;
1643+
1644+
_logger.LogDebug("File uploaded to Telegram, MessageId: {MessageId}", m.ID);
16231645
}
16241646

16251647
BsonFileManagerModel parent = await _db.getParentDirectoryByPath(dbName, currentPath);
1648+
_logger.LogDebug("Parent directory found - ParentId: {ParentId}, ParentName: {ParentName}", parent?.Id, parent?.Name);
1649+
16261650
model.Name = file.File.Name;
16271651
model.IsFile = true;
16281652
model.HasChild = false;
@@ -1635,13 +1659,20 @@ public async Task UploadFile(string dbName, string currentPath, UploadFiles file
16351659
model.Type = file.File.Name.Split(".").LastOrDefault() != null ? "." + file.File.Name.Split(".").LastOrDefault() : file.File.ContentType;
16361660

16371661
await _db.createEntry(dbName, model);
1662+
_logger.LogDebug("Database entry created for file");
1663+
16381664
await _db.addBytesToFolder(dbName, model.ParentId, model.Size);
1665+
_logger.LogDebug("Folder size updated");
16391666

16401667
GC.Collect();
1668+
1669+
_logger.LogInformation("UploadFile completed successfully - FileName: {FileName}, IsSplit: {IsSplit}, MessageId: {MessageId}",
1670+
file.File.Name, model.isSplit, model.isSplit ? string.Join(",", model.ListMessageId) : model.MessageId.ToString());
16411671
}
16421672
catch (Exception ex)
16431673
{
1644-
_logger.LogError(ex, "Error on uploadFile - FileName: {FileName}, Message: {Message}", file.File.Name, ex.Message);
1674+
_logger.LogError(ex, "Error on uploadFile - FileName: {FileName}, CurrentPath: {CurrentPath}, DbName: {DbName}, Message: {Message}",
1675+
file.File.Name, currentPath, dbName, ex.Message);
16451676
NotificationModel nm = new NotificationModel();
16461677
nm.sendEvent(new Notification($"Error on UploadFile: {file.File.Name}", "Error", NotificationTypes.Error));
16471678
throw ex;

TelegramDownloader/Data/TelegramService.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ public async Task<Message> uploadFile(string chatId, Stream file, string fileNam
338338
InputPeer peer = chats.chats[Convert.ToInt64(chatId)];
339339
um.name = fileName;
340340
um._size = file.Length;
341+
um.startDate = DateTime.Now;
341342
um._transmitted = 0;
342343
_tis.addToUploadList(um);
343344
try

TelegramDownloader/Pages/Partials/DownloadsTable.razor

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
@using TelegramDownloader.Models
33
@using TelegramDownloader.Services
44
@using TelegramDownloader.Pages.Modals.InfoModals
5+
@implements IDisposable
56

67
@inject TransactionInfoService tis
78

@@ -151,4 +152,13 @@ ItemsPropertyName="_internalId">
151152
checkNewEventsHandler();
152153
grid.RefreshDataAsync();
153154
}
155+
156+
public void Dispose()
157+
{
158+
tis.EventChanged -= eventChangedNew;
159+
foreach (DownloadModel dm in ldm)
160+
{
161+
dm.EventChanged -= eventChanged;
162+
}
163+
}
154164
}

TelegramDownloader/Pages/Partials/SpeedChart.razor

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616

1717
protected override async Task OnInitializedAsync()
1818
{
19-
tis.HistorykEventChanged += OnHistoryChanged;
19+
// Subscribe to the new incremental event
20+
tis.NewSpeedHistoryPoint += OnNewSpeedHistoryPoint;
2021
}
2122

2223
protected override async Task OnAfterRenderAsync(bool firstRender)
@@ -25,15 +26,15 @@
2526
{
2627
await InitializeChart();
2728
chartInitialized = true;
28-
await UpdateChartData(isInitial: true);
29+
await LoadInitialData();
2930
}
3031
}
3132

32-
private async void OnHistoryChanged(object? sender, System.EventArgs e)
33+
private async void OnNewSpeedHistoryPoint(object? sender, SpeedHistoryEventArgs e)
3334
{
3435
if (chartInitialized)
3536
{
36-
await InvokeAsync(async () => await UpdateChartData());
37+
await InvokeAsync(async () => await AddSinglePoint(e.DownloadPoint, e.UploadPoint));
3738
}
3839
}
3940

@@ -44,7 +45,7 @@
4445
await JS.InvokeVoidAsync("initSpeedChart", maxPoints, intervalSeconds);
4546
}
4647

47-
private async Task UpdateChartData(bool isInitial = false)
48+
private async Task LoadInitialData()
4849
{
4950
var downloadHistory = tis.GetDownloadSpeedsHistoryCopy();
5051
var uploadHistory = tis.GetUploadSpeedsHistoryCopy();
@@ -67,11 +68,30 @@
6768
})
6869
.ToList();
6970

70-
await JS.InvokeVoidAsync("updateSpeedChart", downloadData, uploadData, isInitial);
71+
await JS.InvokeVoidAsync("loadSpeedChartHistory", downloadData, uploadData);
72+
}
73+
74+
private async Task AddSinglePoint(SpeedHistory downloadPoint, SpeedHistory uploadPoint)
75+
{
76+
var download = new {
77+
time = downloadPoint.time.ToString("HH:mm:ss"),
78+
datetime = downloadPoint.time.ToString("dd/MM/yyyy HH:mm:ss"),
79+
speed = downloadPoint.speed / 1024.0 / 1024.0,
80+
files = downloadPoint.activeFiles
81+
};
82+
83+
var upload = new {
84+
time = uploadPoint.time.ToString("HH:mm:ss"),
85+
datetime = uploadPoint.time.ToString("dd/MM/yyyy HH:mm:ss"),
86+
speed = uploadPoint.speed / 1024.0 / 1024.0,
87+
files = uploadPoint.activeFiles
88+
};
89+
90+
await JS.InvokeVoidAsync("addSpeedChartPoint", download, upload);
7191
}
7292

7393
public void Dispose()
7494
{
75-
tis.HistorykEventChanged -= OnHistoryChanged;
95+
tis.NewSpeedHistoryPoint -= OnNewSpeedHistoryPoint;
7696
}
7797
}

TelegramDownloader/Pages/Partials/TasksTable.razor

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
@using TelegramDownloader.Models
33
@using TelegramDownloader.Services
44
@using TelegramDownloader.Pages.Modals.InfoModals
5+
@implements IDisposable
56

67
@inject TransactionInfoService tis
78

@@ -143,4 +144,12 @@
143144
await InvokeAsync(StateHasChanged);
144145
}
145146

147+
public void Dispose()
148+
{
149+
tis.EventChanged -= eventChangedNew;
150+
foreach (InfoDownloadTaksModel pt in lpt)
151+
{
152+
pt.EventChanged -= eventChangedPendingTask;
153+
}
154+
}
146155
}

TelegramDownloader/Pages/Partials/UploadsTable.razor

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
@using TelegramDownloader.Models
33
@using TelegramDownloader.Pages.Modals.InfoModals
44
@using TelegramDownloader.Services
5+
@implements IDisposable
56

67
@inject TransactionInfoService tis
78

@@ -143,4 +144,16 @@ ItemsPropertyName="_internalId">
143144
checkNewEventsHandler();
144145
grid.RefreshDataAsync();
145146
}
147+
148+
public void Dispose()
149+
{
150+
tis.EventChanged -= eventChangedNew;
151+
if (lum != null)
152+
{
153+
foreach (UploadModel um in lum)
154+
{
155+
um.EventChanged -= eventChangedUpload;
156+
}
157+
}
158+
}
146159
}

TelegramDownloader/Services/TransactionInfoService.cs

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public class TransactionInfoService
1515
public event EventHandler<EventArgs> EventChanged;
1616
public event EventHandler TaskEventChanged;
1717
public event EventHandler HistorykEventChanged;
18+
public event EventHandler<SpeedHistoryEventArgs> NewSpeedHistoryPoint;
1819
public List<DownloadModel> downloadModels = new List<DownloadModel>();
1920
public List<DownloadModel> pendingDownloadModels = new List<DownloadModel>();
2021
public List<UploadModel> uploadModels = new List<UploadModel>();
@@ -23,8 +24,8 @@ public class TransactionInfoService
2324
public String uploadSpeed = "0 KB/s";
2425
public long bytesUploaded = 0;
2526
public long bytesDownloaded = 0;
26-
public List<SpeedHistory> downloadSpeedsHistory = new List<SpeedHistory>();
27-
public List<SpeedHistory> uploadSpeedsHistory = new List<SpeedHistory>();
27+
public List<SpeedHistory> downloadSpeedsHistory { get; set; } = new List<SpeedHistory>();
28+
public List<SpeedHistory> uploadSpeedsHistory { get; set; } = new List<SpeedHistory>();
2829
private readonly object _speedHistoryLock = new object();
2930
private int speedHistoryCount = 0;
3031

@@ -135,15 +136,23 @@ private void setHistorySpeed()
135136
DateTime now = DateTime.Now;
136137
var activeDownloads = downloadModels.Where(x => x.state == StateTask.Working).Select(x => x.name).ToList();
137138
var activeUploads = uploadModels.Where(x => x.state == StateTask.Working).Select(x => x.name).ToList();
139+
140+
var newDownloadPoint = new SpeedHistory() { time = now, speed = bytesDownloaded, speedString = downloadSpeed, activeFiles = activeDownloads };
141+
var newUploadPoint = new SpeedHistory() { time = now, speed = bytesUploaded, speedString = uploadSpeed, activeFiles = activeUploads };
142+
138143
lock (_speedHistoryLock)
139144
{
140-
downloadSpeedsHistory.Add(new SpeedHistory() { time = now, speed = bytesDownloaded, speedString = downloadSpeed, activeFiles = activeDownloads });
141-
uploadSpeedsHistory.Add(new SpeedHistory() { time = now, speed = bytesUploaded, speedString = uploadSpeed, activeFiles = activeUploads });
145+
downloadSpeedsHistory.Add(newDownloadPoint);
146+
uploadSpeedsHistory.Add(newUploadPoint);
142147
downloadSpeedsHistory.RemoveAll(x => (now - x.time).TotalSeconds > MAX_SPEED_HISTORY_SECONDS);
143148
uploadSpeedsHistory.RemoveAll(x => (now - x.time).TotalSeconds > MAX_SPEED_HISTORY_SECONDS);
144149
}
145-
if (HistorykEventChanged != null)
146-
HistorykEventChanged.Invoke(this, EventArgs.Empty);
150+
151+
// Invoke new event with individual points
152+
NewSpeedHistoryPoint?.Invoke(this, new SpeedHistoryEventArgs(newDownloadPoint, newUploadPoint));
153+
154+
// Keep legacy event for backwards compatibility
155+
HistorykEventChanged?.Invoke(this, EventArgs.Empty);
147156
}
148157

149158
public List<SpeedHistory> GetDownloadSpeedsHistoryCopy()
@@ -429,4 +438,16 @@ public class SpeedHistory
429438
public String speedString { get; set; }
430439
public List<string> activeFiles { get; set; } = new List<string>();
431440
}
441+
442+
public class SpeedHistoryEventArgs : EventArgs
443+
{
444+
public SpeedHistory DownloadPoint { get; }
445+
public SpeedHistory UploadPoint { get; }
446+
447+
public SpeedHistoryEventArgs(SpeedHistory downloadPoint, SpeedHistory uploadPoint)
448+
{
449+
DownloadPoint = downloadPoint;
450+
UploadPoint = uploadPoint;
451+
}
452+
}
432453
}

TelegramDownloader/Shared/MainLayout.razor

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
@inherits LayoutComponentBase
2+
@implements IDisposable
23
@using TelegramDownloader.Data
34
@using TelegramDownloader.Models
45
@using TelegramDownloader.Models.GitHub
@@ -189,4 +190,9 @@
189190
{
190191
checkWorkingTasks();
191192
}
193+
194+
public void Dispose()
195+
{
196+
tis.TaskEventChanged -= eventChangedWorkingTasks;
197+
}
192198
}

0 commit comments

Comments
 (0)