Skip to content

Commit 8e5323b

Browse files
committed
feat: improve streaming
1 parent 95ee3c1 commit 8e5323b

3 files changed

Lines changed: 44 additions & 19 deletions

File tree

TelegramDownloader/Controllers/FileController.cs

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,16 @@ public class FileController : ControllerBase
3838
public PhysicalFileProvider operation;
3939
public string basePath;
4040
string root = FileService.RELATIVELOCALDIR;
41+
42+
private static Mutex downloadMutex = new Mutex();
43+
private static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);
4144
IDbService _db { get; set; }
4245
ITelegramService _ts { get; set; }
4346
IFileService _fs { get; set; }
4447
TransactionInfoService _tis { get; set; }
48+
private ILogger<IFileService> _logger { get; set; }
4549

46-
public FileController(IDbService db, ITelegramService ts, IFileService fs, TransactionInfoService tis)
50+
public FileController(IDbService db, ITelegramService ts, IFileService fs, TransactionInfoService tis, ILogger<IFileService> logger)
4751
{
4852
this.basePath = Environment.CurrentDirectory;
4953
if (!System.IO.Directory.Exists(Path.Combine(basePath, root)))
@@ -54,6 +58,7 @@ public FileController(IDbService db, ITelegramService ts, IFileService fs, Trans
5458
_ts = ts;
5559
_db = db;
5660
_tis = tis;
61+
_logger = logger;
5762

5863
this.operation = new PhysicalFileProvider();
5964
this.operation.RootFolder(Path.Combine(basePath, root));
@@ -278,34 +283,54 @@ public async Task<IActionResult> GetFileByTfmId(string id, [FromQuery] string id
278283
{
279284
return new ObjectResult("") { StatusCode = (int)HttpStatusCode.NotFound };
280285
}
281-
var file = _fs.ExistFileIntempFolder($"{idChannel}-{(dbFile.MessageId != null ? dbFile.MessageId.ToString() : dbFile.Id)}-{id}");
286+
282287
dbFile.Name = $"{idChannel}-{(dbFile.MessageId != null ? dbFile.MessageId.ToString() : dbFile.Id)}-{id}";
283288
String path = Path.Combine(FileService.TEMPDIR, "_temp");
284289
String filePath = Path.Combine(path, dbFile.Name);
285-
if (file == null && !_tis.isFileDownloaded(path))
290+
var mutexState = semaphoreSlim.Wait(10000);
291+
// var mutexState = downloadMutex.WaitOne();
292+
FileStream? file = null;
293+
if (!mutexState)
286294
{
287-
288-
await _fs.downloadFile(idChannel, new List<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> { dbFile.toFileManagerContent() }, path);
289-
//TL.Message idM = await _ts.getMessageFile(idChannel, Convert.ToInt32(dbFile.MessageId));
290-
//ChatMessages cm = new ChatMessages();
291-
//cm.message = idM;
292-
//file = new FileStream(System.IO.Path.Combine(FileService.TEMPDIR, "_temp", $"{idChannel}-{idFile}-{id}"), FileMode.Create, FileAccess.ReadWrite);
293-
//DownloadModel dm = new DownloadModel();
294-
//dm.tis = _tis;
295-
//dm.channelName = _ts.getChatName(Convert.ToInt64(idChannel));
296-
//_tis.addToDownloadList(dm);
297-
//await _ts.DownloadFileAndReturn(cm, file, model: dm);
298-
//file.Position = 0;
295+
_logger.LogWarning("Could not acquire download mutex in 10 seconds for file {fileName}", dbFile.Name);
296+
return StatusCode(500, "Could not acquire download mutex in 10 seconds");
299297
}
300298

299+
file = _fs.ExistFileIntempFolder(dbFile.Name);
300+
var isFileDownloaded = _tis.isFileDownloaded(filePath);
301+
if (!isFileDownloaded)
302+
if ((file == null) || (file != null && file.Length < dbFile.Size))
303+
{
304+
_logger.LogWarning("Stream Downloading file {fileName}", dbFile.Name);
305+
await _fs.downloadFile(idChannel, new List<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> { dbFile.toFileManagerContent() }, path);
306+
Thread.Sleep(4000);
307+
file = _fs.ExistFileIntempFolder(dbFile.Name);
308+
}
309+
310+
if (mutexState)
311+
semaphoreSlim.Release();
312+
301313
if (file == null)
302314
{
303315
return NotFound();
304316
}
305317

306318
Response.Headers["Content-Disposition"] = $"inline; filename=\"{HttpUtility.UrlEncode(fileName)}\"";
307-
308-
return new FileStreamResult(file, mimeType);
319+
320+
try
321+
{
322+
return new FileStreamResult(file, mimeType)
323+
{
324+
FileDownloadName = fileName,
325+
EnableRangeProcessing = true
326+
327+
};
328+
}
329+
catch (OperationCanceledException)
330+
{
331+
_logger.LogInformation("❌ El cliente cerró la conexión al descargar el archivo {fileName}.", fileName);
332+
return StatusCode(StatusCodes.Status499ClientClosedRequest);
333+
}
309334
}
310335

311336
[Route("strm")]

TelegramDownloader/Data/FileService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ public async Task<List<BsonFileManagerModel>> ShareFile(string dbName, string bs
314314
String filePath = System.IO.Path.Combine(TEMPDIR, "_temp", id);
315315
if (File.Exists(filePath))
316316
{
317-
return new FileStream(filePath, FileMode.Open, FileAccess.Read);
317+
return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
318318
}
319319
return null;
320320
}

TelegramDownloader/Services/TransactionInfoService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public bool isWorking()
4949

5050
public bool isFileDownloaded(String path)
5151
{
52-
return downloadModels.Any(x => x.path == path);
52+
return downloadModels.Any(x => x.path == path && x.state == StateTask.Working || x.state == StateTask.Pending || x.state == StateTask.Paused);
5353
}
5454

5555
public bool isUploading()

0 commit comments

Comments
 (0)