Skip to content

Commit d88af3f

Browse files
committed
feat: add download file before play
1 parent 3b11b98 commit d88af3f

13 files changed

Lines changed: 170 additions & 180 deletions

File tree

TelegramDownloader/Controllers/FileController.cs

Lines changed: 30 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,36 @@ public async Task<IActionResult> GetFile(string id, string? idChannel, string? i
267267
};
268268
}
269269

270+
[Route("GetFileByTfmId/{id}")]
271+
public async Task<IActionResult> GetFileByTfmId(string id, [FromQuery] string idChannel, [FromQuery] string idFile)
272+
{
273+
var fileName = id;
274+
var mimeType = FileService.getMimeType(id.Split(".").Last());
275+
var dbFile = await _fs.getItemById(idChannel, idFile);
276+
if (dbFile == null)
277+
{
278+
return new ObjectResult("") { StatusCode = (int)HttpStatusCode.NotFound };
279+
}
280+
var file = _fs.ExistFileIntempFolder($"{idChannel}-{dbFile.MessageId}-{id}");
281+
if (file == null)
282+
{
283+
TL.Message idM = await _ts.getMessageFile(idChannel, Convert.ToInt32(dbFile.MessageId));
284+
ChatMessages cm = new ChatMessages();
285+
cm.message = idM;
286+
file = new FileStream(System.IO.Path.Combine(FileService.TEMPDIR, "_temp", $"{idChannel}-{idFile}-{id}"), FileMode.Create, FileAccess.ReadWrite);
287+
DownloadModel dm = new DownloadModel();
288+
dm.tis = _tis;
289+
dm.channelName = _ts.getChatName(Convert.ToInt64(idChannel));
290+
_tis.addToDownloadList(dm);
291+
await _ts.DownloadFileAndReturn(cm, file, model: dm);
292+
file.Position = 0;
293+
}
294+
295+
Response.Headers["Content-Disposition"] = $"inline; filename=\"{HttpUtility.UrlEncode(fileName)}\"";
296+
297+
return new FileStreamResult(file, mimeType);
298+
}
299+
270300
[Route("strm")]
271301
public async Task<IActionResult> GetStrm([FromQuery] string idChannel, [FromQuery] string path, [FromQuery] string host)
272302
{
@@ -424,109 +454,6 @@ public async Task<IActionResult> GetFileStream(string idChannel, string idFile,
424454

425455
}
426456

427-
[Route("GetFileStream2/{idChannel}/{idFile}/{name}")]
428-
public async Task<IActionResult> GetFileStream2(string idChannel, string idFile, string name)
429-
{
430-
var fileName = name;
431-
var mimeType = FileService.getMimeType(name.Split(".").Last());
432-
433-
var request = HttpContext.Request;
434-
var rangeHeader = request.Headers["Range"].ToString();
435-
436-
var file = await _fs.getItemById(idChannel, idFile);
437-
438-
// HttpResponseMessage fullResponse = new HttpResponseMessage(HttpStatusCode.OK); // Request.CreateResponse(HttpStatusCode.OK);
439-
TL.Message idM = await _ts.getMessageFile(idChannel, file.MessageId ?? file.ListMessageId.FirstOrDefault());
440-
//byte[] data = await _ts.DownloadFileStream(idM, 0, 512);
441-
//var stream = new MemoryStream(data);
442-
443-
// Supón que puedes obtener el tamaño total del archivo remoto
444-
long totalLength = (await _fs.getItemById(idChannel, idFile)).Size;
445-
446-
long from = 0;
447-
long initialFrom = 0;
448-
long to = 0;
449-
450-
451-
452-
if (!string.IsNullOrEmpty(rangeHeader) && rangeHeader.StartsWith("bytes="))
453-
{
454-
var range = rangeHeader.Replace("bytes=", "").Split('-');
455-
from = long.Parse(range[0]);
456-
initialFrom = from;
457-
if (range.Length > 1 && !string.IsNullOrEmpty(range[1]))
458-
to = long.Parse(range[1]);
459-
}
460-
461-
if (from > 0)
462-
{
463-
from = (from / 524288) * 524288;
464-
}
465-
466-
if (to == 0)
467-
to = (25 * 524288) + from;
468-
else
469-
to = ((to + 524288) / 524288) * 524288;
470-
471-
if (to > totalLength)
472-
{
473-
to = totalLength - 1;
474-
}
475-
476-
long length = to - from;
477-
478-
byte[] data = await _ts.DownloadFileStream(idM, from, (int)length);
479-
480-
long skipedBytes = initialFrom - from; // (data.Length + initialFrom) >= totalLength ? data.Length - (totalLength - initialFrom) : initialFrom - from;
481-
482-
if (skipedBytes < 0) skipedBytes = 0;
483-
484-
if (skipedBytes >= data.Length)
485-
return StatusCode(500, "No hay suficientes bytes en el bloque descargado");
486-
487-
long dataLength = data.Length - skipedBytes;
488-
Response.ContentLength = (dataLength + initialFrom) >= totalLength ? totalLength - initialFrom : dataLength;
489-
// Response.StatusCode = (int)HttpStatusCode.PartialContent; // 206
490-
Response.StatusCode = StatusCodes.Status206PartialContent;
491-
Response.ContentType = mimeType;
492-
Response.Headers.Add("Content-Range", $"bytes {initialFrom}-{(initialFrom + Response.ContentLength - 1)}/{totalLength}");
493-
Response.Headers.Add("Accept-Ranges", "bytes");
494-
495-
if (Request.Headers.ContainsKey("Range"))
496-
{
497-
Console.WriteLine("Range header recibido:");
498-
Console.WriteLine(Request.Headers["Range"]);
499-
}
500-
501-
foreach (var header in Response.Headers)
502-
{
503-
Console.WriteLine($"{header.Key}: {header.Value}");
504-
}
505-
506-
507-
508-
509-
var stream = new MemoryStream(data, (int)skipedBytes, (int)Response.ContentLength);
510-
511-
Console.WriteLine("Real Data length: " + stream.Length);
512-
513-
Console.WriteLine("---------------------------------------------------");
514-
515-
//return new FileStreamResult(stream, mimeType);
516-
var cancellationToken = HttpContext.RequestAborted;
517-
518-
await stream.CopyToAsync(Response.Body, 64 * 1024, cancellationToken);
519-
await Response.Body.FlushAsync(cancellationToken);
520-
521-
return new EmptyResult();
522-
// return File(stream, mimeType, enableRangeProcessing: false);
523-
//return new FileStreamResult(stream, mimeType)
524-
//{
525-
// EnableRangeProcessing = false
526-
//};
527-
528-
}
529-
530457
[Route("export/{id}")]
531458
public async Task<IActionResult> ExportDatabase(string id)
532459
{

TelegramDownloader/Controllers/TempController.cs

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,14 @@
11
using Microsoft.AspNetCore.Http.Features;
22
using Microsoft.AspNetCore.Mvc;
3-
using Microsoft.Extensions.Options;
4-
using Microsoft.Net.Http.Headers;
5-
using MongoDB.Bson;
63
using MongoDB.Driver;
74
using Newtonsoft.Json;
85
using Newtonsoft.Json.Serialization;
96
using Syncfusion.Blazor.FileManager;
107
using Syncfusion.EJ2.FileManager.Base;
11-
//File Manager's operations are available in the below namespace.
128
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;
13-
using System.Collections;
14-
using System.IO;
159
using TelegramDownloader.Data;
1610
using TelegramDownloader.Data.db;
1711
using TelegramDownloader.Models;
18-
using TL;
1912

2013
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
2114

@@ -256,42 +249,5 @@ public string ToCamelCase(FileManagerResponse<BsonFileManagerModel> userData)
256249
}
257250
});
258251
}
259-
260-
// GET: api/<FileController>
261-
[HttpGet]
262-
public IEnumerable<string> Get()
263-
{
264-
return new string[] { "value1", "value2" };
265-
}
266-
267-
// GET api/<FileController>/5
268-
[HttpGet("{id}")]
269-
public string Get(int id)
270-
{
271-
return "value";
272-
}
273-
274-
// POST api/<FileController>
275-
[HttpPost]
276-
public void Post([FromBody] string value)
277-
{
278-
}
279-
280-
// PUT api/<FileController>/5
281-
[HttpPut("{id}")]
282-
public void Put(int id, [FromBody] string value)
283-
{
284-
}
285-
286-
// DELETE api/<FileController>/5
287-
[HttpDelete("{id}")]
288-
public void Delete(int id)
289-
{
290-
}
291252
}
292-
293-
//public class uploadFile
294-
//{
295-
// public IFormFile uploadFiles
296-
//}
297253
}

TelegramDownloader/Data/FileService.cs

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,18 @@
11
using BlazorBootstrap;
22
using Microsoft.AspNetCore.Components.Forms;
33
using Microsoft.AspNetCore.StaticFiles;
4-
using Microsoft.Extensions.Logging;
54
using MongoDB.Driver;
65
using Newtonsoft.Json;
7-
using SharpCompress.Archives;
8-
using SharpCompress.Common;
96
using Syncfusion.Blazor.FileManager;
107
using Syncfusion.Blazor.Inputs;
118

129
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;
1310
using Syncfusion.EJ2.Linq;
14-
using Syncfusion.EJ2.Notifications;
1511
using System.Dynamic;
16-
using System.IO;
1712
using System.IO.Compression;
1813
using System.IO.Hashing;
1914
using System.Security.Cryptography;
20-
using System.Text.Json;
2115
using System.Text.RegularExpressions;
22-
using System.Threading.Channels;
23-
using System.Xml.Linq;
2416
using TelegramDownloader.Data.db;
2517
using TelegramDownloader.Models;
2618
using TelegramDownloader.Services;
@@ -281,6 +273,11 @@ public async Task<BsonFileManagerModel> getItemById(string dbName, string id)
281273
return await _db.getFileById(dbName, id);
282274
}
283275

276+
public async Task<BsonFileManagerModel> getSharedItemById(string id, string collection)
277+
{
278+
return await _db.getFileById(DbService.SHARED_DB_NAME, id, collection);
279+
}
280+
284281
public async Task<BsonSharedInfoModel> GetSharedInfoById(string id)
285282
{
286283
return await _db.getSingleFile(id);
@@ -1191,6 +1188,10 @@ public async Task<String> CreateStrmFiles(string path, string dbName, string hos
11911188
if (FileExtensionTypeTest.isVideoExtension(file.Type) || FileExtensionTypeTest.isAudioExtension(file.Type))
11921189
{
11931190
string contenido = Path.Combine(host, "api/file/GetFileStream", dbName, file.Id, "file" + file.Type).Replace("\\", "/");
1191+
if (HelperService.bytesToMegaBytes(file.Size) < GeneralConfigStatic.config.MaxPreloadFileSizeInMb)
1192+
{
1193+
contenido = Path.Combine(host, "api/file/GetFile", file.Name).Replace("\\", "/") + $"?idChannel={dbName}&idFile={file.Id}";
1194+
}
11941195
string pattern = $@"\.({file.Type.Replace(".", "")})$";
11951196
File.WriteAllText(Regex.Replace(filePath, pattern, ".strm"), contenido);
11961197
}
@@ -1487,17 +1488,24 @@ private string GetMimeType(string fileName)
14871488
return contentType;
14881489
}
14891490

1490-
public async Task refreshChannelFIles(string channelId)
1491+
public async Task refreshChannelFIles(string channelId, bool force = false)
14911492
{
14921493
refreshMutex.WaitOne();
14931494
refreshChannelList.Add(channelId);
14941495
refreshMutex.ReleaseMutex();
14951496
DateTime init = DateTime.Now;
1497+
List<int> presentIds = await _db.getAllIdsFromChannel(channelId);
14961498
_logger.LogInformation($"Refresh channel with id: {channelId}");
1497-
List<TelegramChatDocuments> telegramChatDocuments = (await _ts.searchAllChannelFiles(Convert.ToInt64(channelId))).Where(x => x.name != null).ToList();
1499+
List<TelegramChatDocuments> telegramChatDocuments = (await _ts.searchAllChannelFiles(Convert.ToInt64(channelId), (presentIds.Count > 0 && !force) ? presentIds.Max() : 0)).Where(x => x.name != null).ToList();
14981500
_logger.LogInformation($"Get the telegram files in: {(DateTime.Now - init).TotalSeconds} seconds for channel id:{channelId}");
1501+
List<string> fileNames = await _db.getAllFileNamesFromChannel(channelId);
14991502
var nameCount = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
15001503

1504+
foreach (string name in fileNames)
1505+
{
1506+
nameCount[name] = 1;
1507+
}
1508+
15011509
foreach (var doc in telegramChatDocuments)
15021510
{
15031511
var baseName = doc.name;
@@ -1515,7 +1523,7 @@ public async Task refreshChannelFIles(string channelId)
15151523
if (count == 0)
15161524
nameCount[baseName] = 1;
15171525
}
1518-
List<int> presentIds = await _db.getAllIdsFromChannel(channelId);
1526+
15191527
var rootFolder = await _db.getRootFolder(channelId);
15201528
foreach (TelegramChatDocuments tcd in telegramChatDocuments)
15211529
{
@@ -1543,6 +1551,17 @@ public async Task refreshChannelFIles(string channelId)
15431551
refreshChannelList.Remove(channelId);
15441552
refreshMutex.ReleaseMutex();
15451553
_logger.LogInformation($"Finish Refresh channel with id: {channelId}");
1554+
1555+
// Fix for CS1739: Removed the invalid 'autoHide' parameter and replaced it with the correct property assignment.
1556+
ToastMessage tm = new ToastMessage
1557+
{
1558+
Type = ToastType.Success,
1559+
IconName = IconName.CheckCircle,
1560+
Title = "Refresh channel files",
1561+
Message = "Files channel has been refreshed",
1562+
AutoHide = true
1563+
};
1564+
_toastService.Notify(tm);
15461565
}
15471566

15481567
public bool isChannelRefreshing(string channelId)

TelegramDownloader/Data/IFileService.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public interface IFileService
1212
Task<List<FileManagerDirectoryContent>> createFolder(string dbName, FolderCreateEventArgs<FileManagerDirectoryContent> args);
1313
void cleanTempFolder();
1414
Task<BsonSharedInfoModel> GetSharedInfoById(string id);
15+
Task<BsonFileManagerModel> getSharedItemById(string id, string collection);
1516
Task DeleteShared(string id, string collectionId);
1617
Task downloadFile(string dbName, List<FileManagerDirectoryContent> files, string targetPath, string? collectionId = null, string? channelId = null);
1718
Task downloadFile(string dbName, string path, List<string> files, string targetPath, string? collectionId = null, string? channelId = null);
@@ -35,7 +36,7 @@ public interface IFileService
3536
Task UploadFile(string dbName, string currentPath, UploadFiles file);
3637
Task UploadFileFromServer(string dbName, string currentPath, List<FileManagerDirectoryContent> files, InfoDownloadTaksModel dm = null);
3738
Task AddUploadFileFromServer(string dbName, string currentPath, List<FileManagerDirectoryContent> files, InfoDownloadTaksModel idt = null);
38-
Task refreshChannelFIles(string channelId);
39+
Task refreshChannelFIles(string channelId, bool force = false);
3940
bool isChannelRefreshing(string channelId);
4041
}
4142
}

TelegramDownloader/Data/ITelegramService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public interface ITelegramService
3535
Task logOff();
3636
Task sendVerificationCode(string vc);
3737
Task<Message> uploadFile(string chatId, Stream file, string fileName, string mimeType = null, UploadModel um = null, string caption = null);
38-
Task<List<TelegramChatDocuments>> searchAllChannelFiles(long id);
38+
Task<List<TelegramChatDocuments>> searchAllChannelFiles(long id, int lastId);
3939
bool isMyChat(long id);
4040

4141
}

TelegramDownloader/Data/TelegramService.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ public async Task<GridDataProviderResult<ChatMessages>> getPaginatedMessages(lon
520520
return await Task.FromResult(new GridDataProviderResult<ChatMessages> { Data = cm, TotalCount = messages.Count });
521521
}
522522

523-
public async Task<List<ChatMessages>> getAllFileMessages(long id)
523+
public async Task<List<ChatMessages>> getAllFileMessages(long id, int lastId = 0)
524524
{
525525
List<ChatMessages> cm = new List<ChatMessages>();
526526
InputPeer peer = chats.chats[id];
@@ -543,7 +543,8 @@ public async Task<List<ChatMessages>> getAllFileMessages(long id)
543543
{
544544
cm2.isDocument = true;
545545
}
546-
546+
if (lastId != 0 && lastId == cm2.message.id)
547+
return cm;
547548
cm.Add(cm2);
548549
}
549550
}
@@ -820,10 +821,10 @@ public async Task<string> DownloadFile(ChatMessages message, string fileName = n
820821
return null;
821822
}
822823

823-
public async Task<List<TelegramChatDocuments>> searchAllChannelFiles(long id)
824+
public async Task<List<TelegramChatDocuments>> searchAllChannelFiles(long id, int lastId = 0)
824825
{
825826
List<TelegramChatDocuments> telegramChatDocuments = new List<TelegramChatDocuments>();
826-
List<ChatMessages> result = await getAllFileMessages(id);
827+
List<ChatMessages> result = await getAllFileMessages(id, lastId);
827828

828829
foreach (var msg in result)
829830
if (msg.message is Message msgBase)

0 commit comments

Comments
 (0)