Skip to content

Commit 2c294a1

Browse files
committed
feat: download files v2
1 parent 8e5323b commit 2c294a1

4 files changed

Lines changed: 183 additions & 22 deletions

File tree

TelegramDownloader/Controllers/FileController.cs

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,11 @@
66
using Newtonsoft.Json.Serialization;
77

88
using Syncfusion.Blazor.FileManager;
9-
using Syncfusion.Blazor.Inputs;
109
using Syncfusion.EJ2.FileManager.Base;
1110
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;
12-
using Syncfusion.EJ2.Notifications;
13-
using System;
14-
using System.Collections.Generic;
15-
using System.IO;
1611
using System.IO.Compression;
17-
using System.Linq;
1812
using System.Net;
19-
using System.Net.Http.Headers;
20-
using System.Runtime.CompilerServices;
21-
using System.Runtime.Serialization.Formatters.Binary;
2213
using System.Web;
23-
using System.Xml.Linq;
2414
using TelegramDownloader.Data;
2515
using TelegramDownloader.Data.db;
2616
using TelegramDownloader.Models;
@@ -39,7 +29,6 @@ public class FileController : ControllerBase
3929
public string basePath;
4030
string root = FileService.RELATIVELOCALDIR;
4131

42-
private static Mutex downloadMutex = new Mutex();
4332
private static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);
4433
IDbService _db { get; set; }
4534
ITelegramService _ts { get; set; }
@@ -288,7 +277,6 @@ public async Task<IActionResult> GetFileByTfmId(string id, [FromQuery] string id
288277
String path = Path.Combine(FileService.TEMPDIR, "_temp");
289278
String filePath = Path.Combine(path, dbFile.Name);
290279
var mutexState = semaphoreSlim.Wait(10000);
291-
// var mutexState = downloadMutex.WaitOne();
292280
FileStream? file = null;
293281
if (!mutexState)
294282
{

TelegramDownloader/Data/FileService.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -226,12 +226,12 @@ public class FileService : IFileService
226226
};
227227
public static List<string> refreshChannelList = new List<string>();
228228

229-
private PhysicalFileProvider operation = new PhysicalFileProvider();
230-
private ITelegramService _ts { get; set; }
231-
private IDbService _db { get; set; }
232-
private ILogger<IFileService> _logger { get; set; }
233-
private TransactionInfoService _tis { get; set; }
234-
private ToastService _toastService { get; set; }
229+
protected PhysicalFileProvider operation = new PhysicalFileProvider();
230+
protected ITelegramService _ts { get; set; }
231+
protected IDbService _db { get; set; }
232+
protected ILogger<IFileService> _logger { get; set; }
233+
protected TransactionInfoService _tis { get; set; }
234+
protected ToastService _toastService { get; set; }
235235
private static Mutex refreshMutex = new Mutex();
236236

237237
const int MaxSize = 1024 * 1024 * 1000; // 1GB
@@ -699,7 +699,7 @@ public async Task downloadFile(string dbName, string path, List<string> files, s
699699

700700
}
701701

702-
public async Task downloadFile(string dbName, List<FileManagerDirectoryContent> files, string targetPath, string? collectionId = null, string? channelId = null)
702+
public virtual async Task downloadFile(string dbName, List<FileManagerDirectoryContent> files, string targetPath, string? collectionId = null, string? channelId = null)
703703
{
704704
NotificationModel nm = new NotificationModel();
705705
try
@@ -761,7 +761,7 @@ public async Task downloadFile(string dbName, List<FileManagerDirectoryContent>
761761

762762
}
763763

764-
private async Task downloadSplitFiles(FileManagerDirectoryContent itemFile, BsonFileManagerModel file, string currentFilePath, string dbName)
764+
public virtual async Task downloadSplitFiles(FileManagerDirectoryContent itemFile, BsonFileManagerModel file, string currentFilePath, string dbName)
765765
{
766766
int i = 1;
767767
List<string> splitPaths = new List<string>();
@@ -804,7 +804,7 @@ public static void functionCalll(string dbName, int messageId, string destPath)
804804
{
805805

806806
}
807-
private async Task downloadFromTelegram(string dbName, int messageId, string destPath, BsonFileManagerModel file = null, bool shouldWait = false, string path = null)
807+
public virtual async Task downloadFromTelegram(string dbName, int messageId, string destPath, BsonFileManagerModel file = null, bool shouldWait = false, string path = null)
808808
{
809809
DownloadModel model = new DownloadModel();
810810
model.path = path ?? destPath;
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
using BlazorBootstrap;
2+
using Microsoft.AspNetCore.Components.Forms;
3+
using Microsoft.AspNetCore.StaticFiles;
4+
using MongoDB.Driver;
5+
using Newtonsoft.Json;
6+
using Syncfusion.Blazor.FileManager;
7+
using Syncfusion.Blazor.Inputs;
8+
9+
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;
10+
using Syncfusion.EJ2.Linq;
11+
using System.Dynamic;
12+
using System.IO.Compression;
13+
using System.IO.Hashing;
14+
using System.Security.Cryptography;
15+
using System.Text.RegularExpressions;
16+
using TelegramDownloader.Data.db;
17+
using TelegramDownloader.Models;
18+
using TelegramDownloader.Services;
19+
using TL;
20+
21+
namespace TelegramDownloader.Data
22+
{
23+
public class FileServiceV2 : FileService
24+
{
25+
public FileServiceV2(
26+
ITelegramService ts,
27+
IDbService db,
28+
ILogger<IFileService> logger,
29+
TransactionInfoService tis,
30+
ToastService toastService
31+
) : base(ts, db, logger, tis, toastService)
32+
{
33+
34+
}
35+
36+
public override async Task downloadFile(string dbName, List<FileManagerDirectoryContent> files, string targetPath, string? collectionId = null, string? channelId = null)
37+
{
38+
NotificationModel nm = new NotificationModel();
39+
try
40+
{
41+
foreach (FileManagerDirectoryContent file in files)
42+
{
43+
_logger.LogInformation($"Download files to {targetPath} :: {file.Name}");
44+
}
45+
46+
nm.sendEvent(new Notification("Download Start", "Download", NotificationTypes.Info));
47+
string currentTargetPath = targetPath == null ? "/" : targetPath;
48+
// if (targetPath == null) targetPath = "/"; //path.Replace("\\", "/");
49+
foreach (var itemFile in files)
50+
{
51+
var filterPath = itemFile.FilterPath == "Files/" ? "/" : itemFile.FilterPath;
52+
BsonFileManagerModel file = null;
53+
if (itemFile.Id != null)
54+
file = collectionId == null ? await _db.getFileById(dbName, itemFile.Id) : await _db.getFileById(dbName, itemFile.Id, collectionId);
55+
else
56+
file = collectionId == null ? _db.getFileByPathSync(dbName, filterPath.Replace("\\", "/") + itemFile.Name) : _db.getFileByPathSync(dbName, filterPath.Replace("\\", "/") + itemFile.Name, collectionId);
57+
string currentFilePath = currentTargetPath;
58+
if (!itemFile.IsFile)
59+
{
60+
Directory.CreateDirectory(System.IO.Path.Combine(currentFilePath, itemFile.Name));
61+
var filesInDir = collectionId == null ? await _db.getAllFilesInDirectoryPath(dbName, itemFile.FilterPath == "" ? "/" : itemFile.FilterPath + itemFile.Name + "/") : await _db.getAllFilesInDirectoryPath(dbName, itemFile.FilterPath == "" ? "/" : itemFile.FilterPath + itemFile.Name + "/", collectionId);
62+
if (filesInDir.Count() > 0)
63+
{
64+
await downloadFile(dbName, filesInDir.Select(x => x.toFileManagerContent()).ToList(), System.IO.Path.Combine(currentTargetPath, itemFile.Name).Replace("\\", "/"), collectionId, channelId);
65+
}
66+
67+
}
68+
else
69+
{
70+
Directory.CreateDirectory(currentFilePath);
71+
if (file == null)
72+
throw new Exception($"{currentTargetPath} does not exist");
73+
if (file.isSplit)
74+
{
75+
downloadSplitFilesV2(itemFile, file, currentFilePath, channelId == null ? dbName : channelId);
76+
}
77+
else
78+
{
79+
await downloadFromTelegramV2(channelId == null ? dbName : channelId, (int)file.MessageId, System.IO.Path.Combine(currentFilePath, itemFile.Name), file);
80+
}
81+
}
82+
83+
84+
}
85+
86+
nm.sendEvent(new Notification("downloads have been completed", "Download completed", NotificationTypes.Success));
87+
88+
}
89+
catch (Exception ex)
90+
{
91+
_logger.LogError(ex, "Error on downloadFile");
92+
nm.sendEvent(new Notification("Error at download.", "Download Error", NotificationTypes.Error));
93+
throw ex;
94+
}
95+
96+
}
97+
98+
public async Task downloadSplitFilesV2(FileManagerDirectoryContent itemFile, BsonFileManagerModel file, string currentFilePath, string dbName)
99+
{
100+
int i = 1;
101+
string filePathPart = Path.Combine(currentFilePath, itemFile.Name);
102+
if (File.Exists(filePathPart))
103+
{
104+
File.Delete(filePathPart);
105+
}
106+
foreach (int messageId in file.ListMessageId)
107+
{
108+
await downloadFromTelegramV2(dbName, messageId, filePathPart, file, true, Path.Combine(currentFilePath, itemFile.Name), i);
109+
i++;
110+
}
111+
}
112+
113+
public async Task downloadFromTelegramV2(string dbName, int messageId, string destPath, BsonFileManagerModel file = null, bool shouldWait = false, string path = null, Int32 part = 0)
114+
{
115+
DownloadModel model = new DownloadModel();
116+
model.path = path ?? destPath;
117+
model.tis = _tis;
118+
if (file != null)
119+
{
120+
model.name = (part == 0 ? "" : $"({part.ToString()}) - ") + file.Name;
121+
model._size = file.Size;
122+
}
123+
model._transmitted = 0;
124+
model.callbacks = new Callbacks();
125+
try
126+
{
127+
model.channelName = _ts.getChatName(Convert.ToInt64(dbName));
128+
}
129+
catch (Exception ex)
130+
{
131+
model.channelName = "Public or Shared";
132+
}
133+
var tcs = new TaskCompletionSource<bool>();
134+
135+
EventHandler handler = null;
136+
handler = (sender, args) =>
137+
{
138+
if (model.state == StateTask.Completed)
139+
{
140+
model.EventStatechanged -= handler;
141+
tcs.SetResult(true);
142+
}
143+
};
144+
145+
model.EventStatechanged += handler;
146+
model.callbacks.callback = async () => await DownloadFileNowV2(dbName, messageId, destPath, model);
147+
_tis.addToPendingDownloadList(model, atFirst: shouldWait);
148+
// Espera hasta que el estado sea "Completed"
149+
if (shouldWait)
150+
await tcs.Task;
151+
}
152+
153+
public async Task DownloadFileNowV2(string dbName, int messageId, string destPath, DownloadModel model)
154+
{
155+
TL.Message m = await _ts.getMessageFile(dbName, messageId);
156+
ChatMessages cm = new ChatMessages();
157+
cm.message = m;
158+
159+
cm.user = null;
160+
cm.isDocument = false;
161+
if (m.media is MessageMediaDocument { document: Document document })
162+
{
163+
cm.isDocument = true;
164+
}
165+
using (FileStream fs = new FileStream(destPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
166+
{
167+
await _ts.DownloadFileAndReturn(cm, ms: fs, model: model);
168+
}
169+
170+
}
171+
172+
}
173+
}

TelegramDownloader/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@
5959
builder.Services.AddServerSideBlazor();
6060
builder.Services.AddSingleton<ITelegramService, TelegramService>();
6161
builder.Services.AddSingleton<IDbService, DbService>();
62-
builder.Services.AddTransient<IFileService, FileService>();
62+
builder.Services.AddTransient<IFileService, FileServiceV2>();
6363
builder.Services.AddSingleton<TransactionInfoService>();
6464
builder.Services.AddSingleton<FileManagerService>();
6565
builder.Services.AddSingleton<GHService>();

0 commit comments

Comments
 (0)