From 1685e2e3967336e09039168fd9eb549c801744a2 Mon Sep 17 00:00:00 2001 From: Mateo Date: Fri, 4 Dec 2026 19:10:13 +0100 Subject: [PATCH 1/2] feat(api): extract and compress local archives, and extract downloads when they finish - /api/v1/local/archives: info, entries, extract and compress (zip, rar, 7z, tar, gz, bz2, xz, zst and multi-volume sets), run in the background one at a time, with progress on /api/v1/archive-operations and ArchiveProgress. - Extraction never writes outside the destination, never creates links and stops before the disk is full; password, missing volume, damaged and unsupported archives fail with a code. - extractArchives / deleteArchivesAfterExtract / archivePassword on the download endpoints: archives are extracted when their download (every volume of a set) finishes; the flag survives a restart, the password does not. - POST /api/v1/transfers/downloads now puts the files under the local root (the target path was used as is, outside it). - Capabilities local.archives and transfers.autoExtract; 7-Zip in the Docker image (INCLUDE_7ZIP) to create .7z. --- .../Controllers/Api/V1/ArchivesController.cs | 239 +++++++ .../Controllers/Api/V1/TransfersController.cs | 54 +- .../Mobile/MobileInfoController.cs | 4 + TelegramDownloader/Data/FileServiceV2.cs | 16 +- TelegramDownloader/Dockerfile | 8 + TelegramDownloader/Hubs/EventsHub.cs | 9 +- TelegramDownloader/Models/Api/ArchiveDtos.cs | 222 +++++++ TelegramDownloader/Models/Api/TransferDtos.cs | 28 + TelegramDownloader/Models/DownloadModel.cs | 2 + .../Models/Persistence/PersistedTaskModel.cs | 23 +- TelegramDownloader/Program.cs | 5 + .../Services/Api/EventsBroadcastService.cs | 21 + .../Services/Archives/ArchiveCompressor.cs | 256 ++++++++ .../Services/Archives/ArchiveExtractor.cs | 547 ++++++++++++++++ .../Services/Archives/ArchiveNames.cs | 140 +++++ .../Services/Archives/ArchiveOperation.cs | 196 ++++++ .../Archives/ArchiveOperationRegistry.cs | 136 ++++ .../Archives/ArchiveOperationService.cs | 222 +++++++ .../Services/Archives/AutoExtract.cs | 206 ++++++ .../Services/Archives/AutoExtractService.cs | 73 +++ .../Services/Archives/SevenZipTool.cs | 110 ++++ TelegramDownloader/TelegramDownloader.csproj | 1 + Test/ArchivesTest.cs | 593 ++++++++++++++++++ Test/Fixtures/Archives/multi.7z.001 | Bin 0 -> 16384 bytes Test/Fixtures/Archives/multi.7z.002 | Bin 0 -> 16384 bytes Test/Fixtures/Archives/multi.7z.003 | Bin 0 -> 7477 bytes Test/Fixtures/Archives/plain.7z | Bin 0 -> 229 bytes Test/Fixtures/Archives/secret.7z | Bin 0 -> 302 bytes Test/Fixtures/Archives/secret.zip | Bin 0 -> 705 bytes Test/MobileBulkAndSearchTest.cs | 2 +- Test/Test.csproj | 5 + 31 files changed, 3107 insertions(+), 11 deletions(-) create mode 100644 TelegramDownloader/Controllers/Api/V1/ArchivesController.cs create mode 100644 TelegramDownloader/Models/Api/ArchiveDtos.cs create mode 100644 TelegramDownloader/Services/Archives/ArchiveCompressor.cs create mode 100644 TelegramDownloader/Services/Archives/ArchiveExtractor.cs create mode 100644 TelegramDownloader/Services/Archives/ArchiveNames.cs create mode 100644 TelegramDownloader/Services/Archives/ArchiveOperation.cs create mode 100644 TelegramDownloader/Services/Archives/ArchiveOperationRegistry.cs create mode 100644 TelegramDownloader/Services/Archives/ArchiveOperationService.cs create mode 100644 TelegramDownloader/Services/Archives/AutoExtract.cs create mode 100644 TelegramDownloader/Services/Archives/AutoExtractService.cs create mode 100644 TelegramDownloader/Services/Archives/SevenZipTool.cs create mode 100644 Test/ArchivesTest.cs create mode 100644 Test/Fixtures/Archives/multi.7z.001 create mode 100644 Test/Fixtures/Archives/multi.7z.002 create mode 100644 Test/Fixtures/Archives/multi.7z.003 create mode 100644 Test/Fixtures/Archives/plain.7z create mode 100644 Test/Fixtures/Archives/secret.7z create mode 100644 Test/Fixtures/Archives/secret.zip diff --git a/TelegramDownloader/Controllers/Api/V1/ArchivesController.cs b/TelegramDownloader/Controllers/Api/V1/ArchivesController.cs new file mode 100644 index 0000000..1602abe --- /dev/null +++ b/TelegramDownloader/Controllers/Api/V1/ArchivesController.cs @@ -0,0 +1,239 @@ +using Microsoft.AspNetCore.Mvc; +using TelegramDownloader.Data; +using TelegramDownloader.Models.Api; +using TelegramDownloader.Services.Archives; + +namespace TelegramDownloader.Controllers.Api.V1 +{ + /// + /// Archives of the server's local files: list what one contains, extract + /// it (zip, rar, 7z, tar, gz, bz2, xz, zst and multi-volume sets such as + /// .part1.rar or .7z.001) and compress files into zip, 7z or + /// tar.gz. Extractions and compressions run in the background one at a + /// time; follow them on /api/v1/archive-operations or the + /// ArchiveProgress message of /hubs/events. + /// Capability local.archives. + /// + [Route("api/v1/local/archives")] + [Tags("Local files")] + public class ArchivesController : ApiV1ControllerBase + { + private readonly ArchiveOperationService _archives; + private readonly ILogger _logger; + + public ArchivesController(ArchiveOperationService archives, ILogger logger) + { + _archives = archives; + _logger = logger; + } + + private static string Root => FileService.LOCALDIR; + + /// Formats this server can extract and create. + [HttpGet("info")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status200OK)] + public IActionResult Info() => OkResult(ApiArchiveInfoDto.Current()); + + /// Lists what an archive contains, without extracting it. + /// + /// Works with any volume of a multi-volume set. 400 with code + /// password_required / wrong_password when the names are + /// encrypted too, missing_volume, unsupported or corrupt. + /// A POST so the password does not end up in URLs and logs. + /// + [HttpPost("entries")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status404NotFound)] + public IActionResult Entries([FromBody] ArchiveEntriesRequest request) + { + if (request == null || string.IsNullOrWhiteSpace(request.Path)) + return BadRequestResult("The archive path is required"); + if (!ArchiveOperationService.TryResolveFolder(Root, request.Path, out var absolute, out var error)) + return BadRequestResult(error ?? "Invalid path"); + if (!System.IO.File.Exists(absolute)) + return NotFoundResult("The archive does not exist", ApiErrorCodes.FileNotFound); + var set = ArchiveNames.SetOf(absolute); + if (set == null) + return BadRequestResult("Not an archive, or a format that is not supported", ArchiveErrorCodes.Unsupported); + + var volumes = ArchiveNames.VolumesIn(Path.GetDirectoryName(absolute)!, set); + try + { + var listing = ArchiveExtractor.List(volumes, request.Password, Math.Clamp(request.MaxEntries ?? 2000, 1, 10000)); + return OkResult(ApiArchiveListingDto.From(listing)); + } + catch (ArchiveOperationException ex) + { + return BadRequestResult(ex.Message, ex.Code); + } + catch (Exception ex) + { + _logger.LogError(ex, "Could not list the archive {Path}", request.Path); + return ErrorResult("Could not read the archive", ex); + } + } + + /// Extracts an archive in the background. + /// + /// Give any volume of a multi-volume set: the first one is found in the + /// same folder. By default it extracts into a new folder named after the + /// archive, next to it, and keeps both copies of files that already + /// exist (overwrite: rename, skip, overwrite). + /// deleteArchive removes every volume, only when nothing failed. + /// + /// Entries that would leave the destination (absolute paths, + /// ..) and links are not extracted; they are listed as failed + /// items. The extraction stops before the disk is full + /// (not_enough_space). 202 with the operation id. + /// + [HttpPost("extract")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status202Accepted)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status404NotFound)] + public IActionResult Extract([FromBody] ExtractArchiveRequest request) + { + if (request == null || string.IsNullOrWhiteSpace(request.Path)) + return BadRequestResult("The archive path is required"); + if (!ArchiveOperationService.TryResolveFolder(Root, request.Path, out var absolute, out var error)) + return BadRequestResult(error ?? "Invalid path"); + if (!System.IO.File.Exists(absolute)) + return NotFoundResult("The archive does not exist", ApiErrorCodes.FileNotFound); + if (!ArchiveNames.IsArchive(absolute)) + return BadRequestResult("Not an archive, or a format that is not supported", ArchiveErrorCodes.Unsupported); + if (request.Destination != null && !ArchiveOperationService.TryResolveFolder(Root, request.Destination, out _, out error)) + return BadRequestResult(error ?? "Invalid destination"); + if (!TryOverwrite(request.Overwrite, out var overwrite)) + return BadRequestResult("overwrite must be rename, skip or overwrite"); + + var operation = _archives.StartExtract(Root, request.Path, new ExtractRequestOptions + { + Destination = request.Destination, + IntoFolder = request.IntoFolder, + Overwrite = overwrite, + Password = request.Password, + DeleteArchive = request.DeleteArchive + }); + return Accepted(ApiResult.Ok(new ArchiveOperationStartedDto { OperationId = operation.Id }, "Extraction started")); + } + + /// Compresses files and folders into one archive in the background. + /// + /// The items must be in the same folder. The archive is written there + /// (or in destination) as name.zip, name.7z or + /// name.tar.gz, with " (1)" when the name is taken. 7z + /// needs 7-Zip on the server (sevenZipAvailable of info). + /// Links are not added. 202 with the operation id. + /// + [HttpPost("compress")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status202Accepted)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status400BadRequest)] + public IActionResult Compress([FromBody] CompressRequest request) + { + if (request == null || request.Paths == null || request.Paths.Count == 0) + return BadRequestResult("At least one path is required"); + if (!CompressFormats.IsKnown(request.Format)) + return BadRequestResult("format must be zip, 7z or tar.gz"); + if (request.Format == CompressFormats.SevenZip && !SevenZipTool.Available) + return BadRequestResult("7-Zip is not installed on the server", ArchiveErrorCodes.ToolMissing); + if (!CompressLevels.IsKnown(request.Level)) + return BadRequestResult("level must be fastest, normal or maximum"); + + string? parent = null; + foreach (var path in request.Paths) + { + if (!ArchiveOperationService.TryResolveFolder(Root, path, out var absolute, out var error)) + return BadRequestResult(error ?? "Invalid path"); + if (string.Equals(Path.TrimEndingDirectorySeparator(absolute), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)), StringComparison.OrdinalIgnoreCase)) + return BadRequestResult("The local root cannot be compressed"); + if (!System.IO.File.Exists(absolute) && !Directory.Exists(absolute)) + return NotFoundResult($"{path} does not exist", ApiErrorCodes.FileNotFound); + var folder = Path.GetDirectoryName(absolute); + if (parent != null && !string.Equals(parent, folder, StringComparison.OrdinalIgnoreCase)) + return BadRequestResult("The items must be in the same folder"); + parent = folder; + } + if (request.Destination != null && !ArchiveOperationService.TryResolveFolder(Root, request.Destination, out _, out var destError)) + return BadRequestResult(destError ?? "Invalid destination"); + + var operation = _archives.StartCompress(Root, request.Paths, new CompressRequestOptions + { + Destination = request.Destination, + Name = request.Name, + Format = request.Format, + Level = request.Level + }); + return Accepted(ApiResult.Ok(new ArchiveOperationStartedDto { OperationId = operation.Id }, "Compression started")); + } + + private static bool TryOverwrite(string? value, out OverwriteMode mode) + { + switch ((value ?? "rename").Trim().ToLowerInvariant()) + { + case "rename": mode = OverwriteMode.Rename; return true; + case "skip": mode = OverwriteMode.Skip; return true; + case "overwrite": mode = OverwriteMode.Overwrite; return true; + default: mode = OverwriteMode.Rename; return false; + } + } + } + + /// + /// Running and recent extractions and compressions (started by + /// /api/v1/local/archives/extract|compress or by "extract when the + /// download finishes"). Also pushed as ArchiveProgress on + /// /hubs/events (at most 4 per second per operation, plus one when + /// it ends). Finished operations stay readable for 30 minutes. + /// + [Route("api/v1/archive-operations")] + [Tags("Local files")] + public class ArchiveOperationsController : ApiV1ControllerBase + { + private readonly ArchiveOperationRegistry _registry; + + public ArchiveOperationsController(ArchiveOperationRegistry registry) + { + _registry = registry; + } + + /// Queued and running operations first, then the recent ones. + [HttpGet] + [ProducesResponseType(typeof(ApiResult>), StatusCodes.Status200OK)] + public IActionResult List() => OkResult(_registry.Snapshots().Select(ApiArchiveOperationDto.From).ToList()); + + /// One operation. + [HttpGet("{id}")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status404NotFound)] + public IActionResult Get(string id) + { + var operation = _registry.Get(id); + return operation == null ? NotFoundResult("Archive operation not found") : OkResult(ApiArchiveOperationDto.From(operation.Snapshot())); + } + + /// Cancels a queued or running operation. + /// + /// Files already extracted stay; a cancelled compression leaves no + /// archive. 202 with the current state, 404 when unknown, 409 when it + /// already finished. + /// + [HttpPost("{id}/cancel")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status202Accepted)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status409Conflict)] + public IActionResult Cancel(string id) + { + switch (_registry.TryCancel(id)) + { + case ArchiveCancelResult.NotFound: + return NotFoundResult("Archive operation not found"); + case ArchiveCancelResult.AlreadyFinished: + return ConflictResult("The archive operation already finished"); + default: + var operation = _registry.Get(id); + return Accepted(ApiResult.Ok( + operation == null ? null : ApiArchiveOperationDto.From(operation.Snapshot()), "Cancellation requested")); + } + } + } +} diff --git a/TelegramDownloader/Controllers/Api/V1/TransfersController.cs b/TelegramDownloader/Controllers/Api/V1/TransfersController.cs index 1aa5006..83d12a0 100644 --- a/TelegramDownloader/Controllers/Api/V1/TransfersController.cs +++ b/TelegramDownloader/Controllers/Api/V1/TransfersController.cs @@ -5,6 +5,7 @@ using TelegramDownloader.Models.Api; using TelegramDownloader.Services; using TelegramDownloader.Services.Api; +using TelegramDownloader.Services.Archives; using TelegramDownloader.Services.Upload; using TelegramDownloader.Models.FileSystem; @@ -138,6 +139,9 @@ public IActionResult Get(string id) /// /// targetPath is relative to the server local root. When omitted, /// the channel folder structure is reproduced under it. + /// + /// extractArchives extracts the archives when their download + /// finishes (see /api/v1/archive-operations for the progress). /// [HttpPost("downloads")] [RequireTelegramSession] @@ -172,7 +176,25 @@ public async Task StartDownload([FromBody] StartDownloadRequest r if (contents.Count == 0) return BadRequestResult("None of the supplied ids could be resolved", ApiErrorCodes.FileNotFound); - var targetPath = string.IsNullOrWhiteSpace(request.TargetPath) ? null : request.TargetPath; + // Absolute folders under the local root: the chosen one, or the + // channel folder of each entry ("keep the folders of the channel") + var batches = new List<(string Folder, List Entries)>(); + if (!string.IsNullOrWhiteSpace(request.TargetPath)) + { + if (!LocalPathGuard.TryResolve(FileService.LOCALDIR, request.TargetPath, out var folder, out _, out var pathError)) + return BadRequestResult(pathError ?? "Invalid target path"); + batches.Add((folder, contents)); + } + else + { + foreach (var group in contents.GroupBy(c => ChannelFolderOf(c.FilterPath))) + { + if (!LocalPathGuard.TryResolve(FileService.LOCALDIR, group.Key, out var folder, out _, out _)) + folder = FileService.LOCALDIR; + batches.Add((folder, group.ToList())); + } + } + var autoExtract = request.ExtractArchives ? AutoExtractTag.New(request.DeleteArchivesAfterExtract, request.ArchivePassword) : null; // The download pipeline is long running; hand it off so the // client is not blocked while files stream in. @@ -180,12 +202,17 @@ public async Task StartDownload([FromBody] StartDownloadRequest r { try { - await _files.downloadFile( - dbName, - contents, - targetPath, - request.SharedCollectionId, - string.IsNullOrEmpty(request.SharedCollectionId) ? null : request.ChannelId); + using var scope = AutoExtractScope.Begin(autoExtract); + foreach (var (folder, entries) in batches) + { + Directory.CreateDirectory(folder); + await _files.downloadFile( + dbName, + entries, + folder, + request.SharedCollectionId, + string.IsNullOrEmpty(request.SharedCollectionId) ? null : request.ChannelId); + } } catch (Exception ex) { @@ -337,6 +364,7 @@ public async Task DownloadMessages([FromBody] DownloadMessagesReq var accepted = 0; var skipped = new List(); var names = new HashSet(StringComparer.OrdinalIgnoreCase); + var autoExtract = request.ExtractArchives ? AutoExtractTag.New(request.DeleteArchivesAfterExtract, request.ArchivePassword) : null; foreach (var messageId in request.MessageIds.Distinct()) { var attachment = messages.TryGetValue(messageId, out var message) ? MessageAttachment.From(message) : null; @@ -349,6 +377,7 @@ public async Task DownloadMessages([FromBody] DownloadMessagesReq { var name = MessageDownloads.UniqueName(attachment.Name, names, n => System.IO.File.Exists(Path.Combine(folder, n))); var model = new DownloadModel { tis = _tis, channelName = chatName }; + AutoExtractDownloads.Attach(model, Path.Combine(folder, name), autoExtract); // Only queues it: the download runs when a slot is free. await _files.DownloadFileFromChat(new ChatMessages { message = message, isDocument = !attachment.IsPhoto }, name, folder, model); accepted++; @@ -731,6 +760,17 @@ private static (List Contents, List Missing) BuildLocalContents return (contents, missing); } + /// + /// Local folder (relative to the root) of a channel entry's folder: + /// /music/rock/ → music/rock; the channel root → "". + /// + public static string ChannelFolderOf(string? filterPath) + { + var path = (filterPath ?? string.Empty).Replace('\\', '/'); + if (path == "Files/") path = "/"; + return path.Trim('/'); + } + private static FsEntry? BuildLocalContent(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) return null; diff --git a/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs b/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs index abd42f5..c6b9965 100644 --- a/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs +++ b/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs @@ -48,6 +48,8 @@ public class MobileInfoController : ControllerBase "library.fileFilters", // kind and rule in GET /api/v1/library/files, GET /api/v1/library/files/facets "files.cue", // GET /api/v1/channels/{id}/files/{fileId}/cue, GET /api/v1/local/cue "files.audioInfo", // POST /api/v1/channels/{id}/files/audio-info (Telegram title, performer, duration, cover) + "local.archives", // /api/v1/local/archives/info|entries|extract|compress, /api/v1/archive-operations + ArchiveProgress on /hubs/events + "transfers.autoExtract", // extractArchives, deleteArchivesAfterExtract, archivePassword in POST /api/v1/transfers/downloads and /messages }; private static readonly string ServerVersion = ResolveServerVersion(); @@ -82,6 +84,8 @@ public class MobileInfoController : ControllerBase /// - `audio.transcode`: transcodificación de audio en v1: GET /api/v1/audio/transcode/info, /api/v1/channels/{id}/files/{fileId}/transcoded y /api/v1/local/transcoded /// - `files.cue`: hojas CUE (un álbum en un único fichero, partido en pistas): GET /api/v1/channels/{id}/files/{fileId}/cue y GET /api/v1/local/cue /// - `files.audioInfo`: POST /api/v1/channels/{id}/files/audio-info (título, intérprete, duración y carátula que guarda Telegram, sin descargar el fichero) + /// - `local.archives`: comprimidos de los ficheros locales: GET /api/v1/local/archives/info, POST .../entries, .../extract y .../compress; progreso en /api/v1/archive-operations y `ArchiveProgress` en /hubs/events + /// - `transfers.autoExtract`: `extractArchives`, `deleteArchivesAfterExtract` y `archivePassword` en POST /api/v1/transfers/downloads y /messages (descomprimir al terminar la descarga) /// /// Los servidores antiguos no tienen este endpoint: un **404** debe interpretarse /// como "sin funcionalidades opcionales". No accede a base de datos. diff --git a/TelegramDownloader/Data/FileServiceV2.cs b/TelegramDownloader/Data/FileServiceV2.cs index b00a411..7fe31fc 100644 --- a/TelegramDownloader/Data/FileServiceV2.cs +++ b/TelegramDownloader/Data/FileServiceV2.cs @@ -1,3 +1,4 @@ +using TelegramDownloader.Services.Archives; #nullable disable using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.StaticFiles; @@ -124,7 +125,8 @@ private async Task DownloadSplitFileAsync(string dbName, BsonFileMana TotalSize = file.Size, CreationDate = DateTime.Now, StartDate = DateTime.Now, - LastUpdated = DateTime.Now + LastUpdated = DateTime.Now, + AutoExtract = PersistedAutoExtract.From(AutoExtractScope.Current) }; await _persistence.PersistTask(task); StateTask result = await RunSplitDownloadAsync(task, startPart: 0, completedBytes: 0, transmittedInPart: 0, restart: true); @@ -146,6 +148,11 @@ public async Task RunSplitDownloadAsync(PersistedTaskModel task, int _logger.LogWarning("Split download {Name} is already running - not started twice", task.Name); return StateTask.Working; } + // The request's tag (with its password) when it is still in flight, else the persisted one + var autoExtract = task.AutoExtract == null ? null + : AutoExtractScope.Current?.GroupId == task.AutoExtract.GroupId ? AutoExtractScope.Current : task.AutoExtract.ToTag(); + AutoExtractSignals.RaiseExpected(task.DestinationPath, autoExtract); + StateTask outcome = StateTask.Error; try { if (restart) @@ -175,6 +182,7 @@ public async Task RunSplitDownloadAsync(PersistedTaskModel task, int part.callbacks.callback = () => DownloadFileNowV2(task.ChannelId, messageId, task.DestinationPath, part); StateTask result = await QueueAndWaitAsync(part, atFirst: true); + outcome = result; if (result != StateTask.Completed) { if (result == StateTask.Canceled) @@ -189,11 +197,14 @@ public async Task RunSplitDownloadAsync(PersistedTaskModel task, int await _persistence.UpdateSplitProgress(task.InternalId, i + 1, completed, completedBytes); } await _persistence.MarkCompleted(task.InternalId); + outcome = StateTask.Completed; return StateTask.Completed; } finally { _tis.UnregisterJob(task.InternalId); + if (outcome == StateTask.Completed) AutoExtractSignals.RaiseReady(task.DestinationPath, autoExtract); + else AutoExtractSignals.RaiseAbandoned(task.DestinationPath, autoExtract); } } @@ -281,6 +292,8 @@ public async Task downloadFromTelegramV2(string dbName, int messageId, string de _logger.LogDebug("Queueing download V2 - DbName: {DbName}, MessageId: {MessageId}, Part: {Part}", dbName, messageId, part); string name = file == null ? null : (part == 0 ? "" : $"({part.ToString()}) - ") + file.Name; DownloadModel model = NewDownloadModel(dbName, name, file?.Size ?? 0, path ?? destPath); + // Split parts (part > 0) are tracked by their split task, not one by one + if (part == 0) AutoExtractDownloads.Attach(model, destPath, AutoExtractScope.Current); // Setup persistence AttachPersistence(model); @@ -316,6 +329,7 @@ public DownloadModel QueueResumedDownload(PersistedTaskModel task, bool atFirst) model.progress = Percent(task.TransmittedBytes, task.TotalSize); model.state = StateTask.Pending; AttachPersistence(model); + AutoExtractDownloads.Attach(model, task.DestinationPath, task.AutoExtract?.ToTag()); model.callbacks.callback = () => DownloadFileNowV2(task.ChannelId, messageId, task.DestinationPath, model); _tis.addToPendingDownloadList(model, atFirst: atFirst); return model; diff --git a/TelegramDownloader/Dockerfile b/TelegramDownloader/Dockerfile index 718239e..3207c71 100644 --- a/TelegramDownloader/Dockerfile +++ b/TelegramDownloader/Dockerfile @@ -10,11 +10,19 @@ EXPOSE 443 # Set to "false" to create a lighter image without video transcoding support ARG INCLUDE_FFMPEG=true +# Set to "false" to leave out 7-Zip (about 3 MB): without it the server +# still extracts every format and creates zip / tar.gz, but not .7z +ARG INCLUDE_7ZIP=true + # Install ICU libraries for globalization support (required by BlazorBootstrap NumberInput) # Optionally install FFmpeg for video transcoding support (MKV, AVI, WMV, etc.) +# and 7-Zip to create .7z archives RUN apk add --no-cache icu-libs && \ if [ "$INCLUDE_FFMPEG" = "true" ]; then \ apk add --no-cache ffmpeg; \ + fi && \ + if [ "$INCLUDE_7ZIP" = "true" ]; then \ + apk add --no-cache 7zip; \ fi ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false diff --git a/TelegramDownloader/Hubs/EventsHub.cs b/TelegramDownloader/Hubs/EventsHub.cs index c4d69e8..f462394 100644 --- a/TelegramDownloader/Hubs/EventsHub.cs +++ b/TelegramDownloader/Hubs/EventsHub.cs @@ -36,6 +36,7 @@ public class EventsHub : Hub public const string LibraryScanMessage = "LibraryScan"; public const string DeleteProgressMessage = "DeleteProgress"; public const string PlayerDataChangedMessage = "PlayerDataChanged"; + public const string ArchiveProgressMessage = "ArchiveProgress"; /// Group of the connections that asked for Metrics. public const string MetricsGroup = "events.metrics"; @@ -44,9 +45,12 @@ public class EventsHub : Hub private readonly ISystemMetricsService _metrics; private readonly LibraryScanService _scan; private readonly DeleteOperationRegistry _deletes; + private readonly TelegramDownloader.Services.Archives.ArchiveOperationRegistry _archives; - public EventsHub(EventsHubState state, ISystemMetricsService metrics, LibraryScanService scan, DeleteOperationRegistry deletes) + public EventsHub(EventsHubState state, ISystemMetricsService metrics, LibraryScanService scan, DeleteOperationRegistry deletes, + TelegramDownloader.Services.Archives.ArchiveOperationRegistry archives) { + _archives = archives; _state = state; _metrics = metrics; _scan = scan; @@ -83,6 +87,9 @@ public override async Task OnConnectedAsync() foreach (var operation in _deletes.Running()) await Clients.Caller.SendAsync(DeleteProgressMessage, ApiDeleteOperationDto.From(operation.Snapshot())); + foreach (var operation in _archives.Running()) + await Clients.Caller.SendAsync(ArchiveProgressMessage, ApiArchiveOperationDto.From(operation.Snapshot())); + await base.OnConnectedAsync(); } diff --git a/TelegramDownloader/Models/Api/ArchiveDtos.cs b/TelegramDownloader/Models/Api/ArchiveDtos.cs new file mode 100644 index 0000000..4c82ab4 --- /dev/null +++ b/TelegramDownloader/Models/Api/ArchiveDtos.cs @@ -0,0 +1,222 @@ +using TelegramDownloader.Services.Archives; + +namespace TelegramDownloader.Models.Api +{ + /// What this server can do with archives (GET /api/v1/local/archives/info). + public class ApiArchiveInfoDto + { + /// Formats that can be extracted (multi-volume sets included). + public List ExtractFormats { get; set; } = new(); + + /// Formats that can be created: zip, tar.gz, and 7z when 7-Zip is installed. + public List CreateFormats { get; set; } = new(); + + /// 7-Zip is installed (creates .7z). + public bool SevenZipAvailable { get; set; } + + /// Compression levels accepted by compress. + public List Levels { get; set; } = new() { CompressLevels.Fastest, CompressLevels.Normal, CompressLevels.Maximum }; + + public static ApiArchiveInfoDto Current() => new() + { + ExtractFormats = ArchiveNames.ExtractFormats.ToList(), + CreateFormats = CompressFormats.Available.ToList(), + SevenZipAvailable = SevenZipTool.Available + }; + } + + /// Body of POST /api/v1/local/archives/entries. + public class ArchiveEntriesRequest + { + /// Archive (any volume of a set), relative to the local root. + public string Path { get; set; } = string.Empty; + + /// Password, for archives whose names are encrypted too. + public string? Password { get; set; } + + /// Maximum entries returned (default 2000, max 10000); the totals count them all. + public int? MaxEntries { get; set; } + } + + /// An entry of an archive. + public class ApiArchiveEntryDto + { + public string Path { get; set; } = string.Empty; + public bool IsDirectory { get; set; } + public long Size { get; set; } + public long CompressedSize { get; set; } + public DateTime? Modified { get; set; } + public bool IsEncrypted { get; set; } + } + + /// What an archive contains, without extracting it. + public class ApiArchiveListingDto + { + /// zip, rar, 7z, tar.gz... + public string Format { get; set; } = string.Empty; + public int VolumeCount { get; set; } + public bool IsEncrypted { get; set; } + public bool IsSolid { get; set; } + public int FileCount { get; set; } + public int FolderCount { get; set; } + + /// Size once extracted. + public long TotalSize { get; set; } + public List Entries { get; set; } = new(); + + /// More entries than returned. + public bool Truncated { get; set; } + + public static ApiArchiveListingDto From(ArchiveListing listing) => new() + { + Format = listing.Format, + VolumeCount = listing.VolumeCount, + IsEncrypted = listing.IsEncrypted, + IsSolid = listing.IsSolid, + FileCount = listing.FileCount, + FolderCount = listing.FolderCount, + TotalSize = listing.TotalSize, + Truncated = listing.Truncated, + Entries = listing.Entries.Select(e => new ApiArchiveEntryDto + { + Path = e.Path, + IsDirectory = e.IsDirectory, + Size = e.Size, + CompressedSize = e.CompressedSize, + Modified = e.Modified, + IsEncrypted = e.IsEncrypted + }).ToList() + }; + } + + /// Body of POST /api/v1/local/archives/extract. + public class ExtractArchiveRequest + { + /// Archive (any volume of a multi-volume set), relative to the local root. + public string Path { get; set; } = string.Empty; + + /// Folder to extract into, relative to the local root. Default: the folder of the archive. + public string? Destination { get; set; } + + /// Extract into a new folder named after the archive (default true). + public bool IntoFolder { get; set; } = true; + + /// Existing files: rename (default, keeps both), skip or overwrite. + public string Overwrite { get; set; } = "rename"; + + public string? Password { get; set; } + + /// Delete the archive (every volume) after a complete extraction. + public bool DeleteArchive { get; set; } + } + + /// Body of POST /api/v1/local/archives/compress. + public class CompressRequest + { + /// Files and folders of one folder, relative to the local root. + public List Paths { get; set; } = new(); + + /// Folder the archive is written to. Default: the folder of the selection. + public string? Destination { get; set; } + + /// Archive name without extension. Default: the item's name, or the folder's for several items. + public string? Name { get; set; } + + /// zip (default), 7z or tar.gz (see createFormats). + public string Format { get; set; } = CompressFormats.Zip; + + /// fastest, normal (default) or maximum. + public string Level { get; set; } = CompressLevels.Normal; + } + + /// Answer of the endpoints that start an extraction or a compression. + public class ArchiveOperationStartedDto + { + /// Read it with GET /api/v1/archive-operations/{operationId}; correlates the ArchiveProgress messages. + public string OperationId { get; set; } = string.Empty; + } + + /// An entry an archive operation could not process. + public class ApiArchiveFailureDto + { + public string Path { get; set; } = string.Empty; + public string Reason { get; set; } = string.Empty; + } + + /// + /// An extraction or compression (GET /api/v1/archive-operations/{id} + /// and the ArchiveProgress message of /hubs/events). + /// + public class ApiArchiveOperationDto + { + public string Id { get; set; } = string.Empty; + + /// extract or compress. + public string Kind { get; set; } = ArchiveKinds.Extract; + + /// Archive (extract) or selection (compress), relative to the local root. + public string Source { get; set; } = string.Empty; + + /// Folder extracted into, or archive created, relative to the local root (once known). + public string? Destination { get; set; } + + /// Started by "extract when the download finishes". + public bool Automatic { get; set; } + + /// queued → preparing → working → done, failed or cancelled. + public string Phase { get; set; } = ArchivePhases.Queued; + + public int TotalFiles { get; set; } + public long TotalBytes { get; set; } + public int ProcessedFiles { get; set; } + public long ProcessedBytes { get; set; } + + /// 0-100 by bytes (files when there are no bytes). + public int Progress { get; set; } + public string? CurrentItem { get; set; } + + /// Entries that could not be processed (a done operation may have some). + public int FailedCount { get; set; } + public List Failed { get; set; } = new(); + + /// The archive was deleted after the extraction. + public bool ArchivesDeleted { get; set; } + public bool CancelRequested { get; set; } + public string? Error { get; set; } + + /// + /// Why it failed: password_required, wrong_password, + /// not_enough_space, missing_volume, unsupported, + /// corrupt, not_found, tool_missing. + /// + public string? ErrorCode { get; set; } + public DateTime StartedAt { get; set; } + public DateTime? FinishedAt { get; set; } + + public static ApiArchiveOperationDto From(ArchiveOperationSnapshot s) => new() + { + Id = s.Id, + Kind = s.Kind, + Source = s.Source, + Destination = s.Destination, + Automatic = s.Automatic, + Phase = s.Phase, + TotalFiles = s.TotalFiles, + TotalBytes = s.TotalBytes, + ProcessedFiles = s.ProcessedFiles, + ProcessedBytes = s.ProcessedBytes, + Progress = s.Phase == ArchivePhases.Done ? 100 + : s.TotalBytes > 0 ? (int)Math.Min(100, s.ProcessedBytes * 100 / s.TotalBytes) + : s.TotalFiles > 0 ? Math.Min(100, s.ProcessedFiles * 100 / s.TotalFiles) : 0, + CurrentItem = s.CurrentItem, + FailedCount = s.FailedCount, + Failed = s.Failed.Select(f => new ApiArchiveFailureDto { Path = f.Path, Reason = f.Reason }).ToList(), + ArchivesDeleted = s.ArchivesDeleted, + CancelRequested = s.CancelRequested, + Error = s.Error, + ErrorCode = s.ErrorCode, + StartedAt = s.StartedAt, + FinishedAt = s.FinishedAt + }; + } +} diff --git a/TelegramDownloader/Models/Api/TransferDtos.cs b/TelegramDownloader/Models/Api/TransferDtos.cs index 84d076a..dafcfa9 100644 --- a/TelegramDownloader/Models/Api/TransferDtos.cs +++ b/TelegramDownloader/Models/Api/TransferDtos.cs @@ -240,6 +240,20 @@ public class StartDownloadRequest /// Set when downloading from a shared collection instead of an owned channel. public string? SharedCollectionId { get; set; } + + /// + /// Extract the archives (zip, rar, 7z, tar...) when their download + /// finishes, into a folder named after each one, next to it. The + /// volumes of a multi-volume archive are extracted together once all + /// of them are downloaded. Needs the transfers.autoExtract capability. + /// + public bool ExtractArchives { get; set; } + + /// With : delete each archive (every volume) after a complete extraction. + public bool DeleteArchivesAfterExtract { get; set; } + + /// With : password of protected archives. Kept in memory only. + public string? ArchivePassword { get; set; } } /// Body of POST /api/v1/transfers/uploads. @@ -284,6 +298,20 @@ public class DownloadMessagesRequest /// Destination folder relative to the server local root. public string? TargetPath { get; set; } + + /// + /// Extract the archives (zip, rar, 7z, tar...) when their download + /// finishes, into a folder named after each one, next to it. The + /// volumes of a multi-volume archive are extracted together once all + /// of them are downloaded. Needs the transfers.autoExtract capability. + /// + public bool ExtractArchives { get; set; } + + /// With : delete each archive (every volume) after a complete extraction. + public bool DeleteArchivesAfterExtract { get; set; } + + /// With : password of protected archives. Kept in memory only. + public string? ArchivePassword { get; set; } } /// Result returned when a transfer batch has been queued. diff --git a/TelegramDownloader/Models/DownloadModel.cs b/TelegramDownloader/Models/DownloadModel.cs index bef1976..1f33a15 100644 --- a/TelegramDownloader/Models/DownloadModel.cs +++ b/TelegramDownloader/Models/DownloadModel.cs @@ -317,6 +317,8 @@ public class DownloadModel /// its file stream is closed (completed, failed, canceled or paused). /// public event EventHandler RunFinished; + /// "Extract when the download finishes" of the request that queued it (null: off). + public TelegramDownloader.Services.Archives.AutoExtractTag AutoExtract { get; set; } public string _internalId { get; set; } = Guid.NewGuid().ToString(); public string id = Guid.NewGuid().ToString(); public string action { get; set; } = "Download"; diff --git a/TelegramDownloader/Models/Persistence/PersistedTaskModel.cs b/TelegramDownloader/Models/Persistence/PersistedTaskModel.cs index 5c2ac40..ccdf328 100644 --- a/TelegramDownloader/Models/Persistence/PersistedTaskModel.cs +++ b/TelegramDownloader/Models/Persistence/PersistedTaskModel.cs @@ -78,6 +78,26 @@ public class PersistedTaskModel // Error tracking public int RetryCount { get; set; } public string LastError { get; set; } + + /// + /// Downloads: extract the file when it finishes (it is an archive or a + /// volume of one). The password is not stored. + /// + public PersistedAutoExtract AutoExtract { get; set; } + } + + /// "Extract when the download finishes" of a persisted download. + public class PersistedAutoExtract + { + /// Shared by the files of one download request (volumes of a set belong together). + public string GroupId { get; set; } + public bool DeleteArchives { get; set; } + + public static PersistedAutoExtract From(TelegramDownloader.Services.Archives.AutoExtractTag tag) => + tag == null ? null : new PersistedAutoExtract { GroupId = tag.GroupId, DeleteArchives = tag.DeleteArchives }; + + public TelegramDownloader.Services.Archives.AutoExtractTag ToTag() => + string.IsNullOrEmpty(GroupId) ? null : new TelegramDownloader.Services.Archives.AutoExtractTag(GroupId, DeleteArchives); } /// @@ -187,7 +207,8 @@ public static PersistedTaskModel ToPersistedTask( Progress = dm.progress, CreationDate = dm.creationDate, StartDate = dm.startDate != default ? dm.startDate : null, - LastUpdated = DateTime.Now + LastUpdated = DateTime.Now, + AutoExtract = PersistedAutoExtract.From(dm.AutoExtract) }; } diff --git a/TelegramDownloader/Program.cs b/TelegramDownloader/Program.cs index cd071a7..c2302e8 100644 --- a/TelegramDownloader/Program.cs +++ b/TelegramDownloader/Program.cs @@ -223,6 +223,11 @@ builder.Services.AddSingleton(sp => new TelegramDownloader.Services.Deletes.DeleteOperationRegistry( sp.GetRequiredService>())); builder.Services.AddSingleton(); +// Archives of the local files: extract / compress one at a time, and extract downloads when they finish +builder.Services.AddSingleton(sp => new TelegramDownloader.Services.Archives.ArchiveOperationRegistry( + sp.GetRequiredService>())); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); builder.Services.AddHostedService(); // Media library: identification through metadata providers, cached images, watch state diff --git a/TelegramDownloader/Services/Api/EventsBroadcastService.cs b/TelegramDownloader/Services/Api/EventsBroadcastService.cs index bd914ef..014a83b 100644 --- a/TelegramDownloader/Services/Api/EventsBroadcastService.cs +++ b/TelegramDownloader/Services/Api/EventsBroadcastService.cs @@ -47,6 +47,9 @@ public sealed class EventsBroadcastService : IHostedService, IDisposable private readonly KeyedThrottle _deleteThrottle = new KeyedThrottle(DeleteThrottle); private readonly DeleteProgressSendState _deleteSent = new DeleteProgressSendState(); private readonly DeleteOperationRegistry _deletes; + private readonly KeyedThrottle _archiveThrottle = new KeyedThrottle(DeleteThrottle); + private readonly DeleteProgressSendState _archiveSent = new DeleteProgressSendState(); + private readonly TelegramDownloader.Services.Archives.ArchiveOperationRegistry _archives; private readonly PlayerDataService _player; private readonly ChangeDetector _authState = new ChangeDetector(); private bool _scanWasRunning; @@ -61,8 +64,10 @@ public EventsBroadcastService( LibraryScanService scan, DeleteOperationRegistry deletes, PlayerDataService player, + TelegramDownloader.Services.Archives.ArchiveOperationRegistry archives, ILogger logger) { + _archives = archives; _player = player; _deletes = deletes; _hub = hub; @@ -81,6 +86,7 @@ public Task StartAsync(CancellationToken cancellationToken) _imports.Progress += OnImportProgress; _metrics.OnMetricsUpdated += OnMetricsUpdated; _deletes.Changed += OnDeleteChanged; + _archives.Changed += SendArchiveProgress; _player.Changed += OnPlayerDataChanged; _timer = new Timer(_ => Tick(), null, TickInterval, TickInterval); _logger.LogInformation("EventsBroadcastService started - streaming application events on {Path}", "/hubs/events"); @@ -95,6 +101,7 @@ public Task StopAsync(CancellationToken cancellationToken) _imports.Progress -= OnImportProgress; _metrics.OnMetricsUpdated -= OnMetricsUpdated; _deletes.Changed -= OnDeleteChanged; + _archives.Changed -= SendArchiveProgress; _player.Changed -= OnPlayerDataChanged; _timer?.Change(Timeout.Infinite, Timeout.Infinite); return Task.CompletedTask; @@ -146,6 +153,18 @@ private void SendDeleteProgress(DeleteOperation operation) _ = SafeSend(() => _hub.Clients.All.SendAsync(EventsHub.DeleteProgressMessage, dto)); } + /// Same throttling as DeleteProgress: at most 4 per second, the final state always. + private void SendArchiveProgress(TelegramDownloader.Services.Archives.ArchiveOperation operation) + { + var snapshot = operation.Snapshot(); + var final = TelegramDownloader.Services.Archives.ArchivePhases.IsFinal(snapshot.Phase); + if (!_archiveSent.IsNewer(snapshot.Id, snapshot.Version)) return; + if (!_archiveThrottle.ShouldSend(snapshot.Id, final)) return; + _archiveSent.MarkSent(snapshot.Id, snapshot.Version, final); + var dto = ApiArchiveOperationDto.From(snapshot); + _ = SafeSend(() => _hub.Clients.All.SendAsync(EventsHub.ArchiveProgressMessage, dto)); + } + private void OnMetricsUpdated(object? sender, SystemMetrics metrics) { if (_state.MetricsSubscribers.Count == 0) return; @@ -176,6 +195,8 @@ private void Tick() // Changes the throttle held back (e.g. the start of a FLOOD_WAIT). foreach (var operation in _deletes.Running()) SendDeleteProgress(operation); + foreach (var operation in _archives.Running()) + SendArchiveProgress(operation); var scan = _scan.Current; var running = scan?.Running == true; diff --git a/TelegramDownloader/Services/Archives/ArchiveCompressor.cs b/TelegramDownloader/Services/Archives/ArchiveCompressor.cs new file mode 100644 index 0000000..c4e759a --- /dev/null +++ b/TelegramDownloader/Services/Archives/ArchiveCompressor.cs @@ -0,0 +1,256 @@ +using System.Formats.Tar; +using System.IO.Compression; + +namespace TelegramDownloader.Services.Archives +{ + /// Archive formats the server can create. + public static class CompressFormats + { + public const string Zip = "zip"; + public const string TarGz = "tar.gz"; + public const string SevenZip = "7z"; + + /// The formats this server can create (7z only with 7-Zip installed). + public static IReadOnlyList Available => SevenZipTool.Available ? new[] { Zip, SevenZip, TarGz } : new[] { Zip, TarGz }; + + public static bool IsKnown(string? format) => format is Zip or TarGz or SevenZip; + + public static string Extension(string format) => format switch + { + TarGz => ".tar.gz", + SevenZip => ".7z", + _ => ".zip" + }; + } + + /// Compression levels of . + public static class CompressLevels + { + public const string Fastest = "fastest"; + public const string Normal = "normal"; + public const string Maximum = "maximum"; + + public static bool IsKnown(string? level) => level is Fastest or Normal or Maximum; + } + + /// A file to add: its absolute path and its name inside the archive. + public sealed record CompressItem(string AbsolutePath, string EntryName, long Size, DateTime Modified); + + /// + /// Creates zip (System.IO.Compression), tar.gz (System.Formats.Tar) and 7z + /// (7-Zip command line) archives. The archive is written next to its final + /// name as .partial and renamed when complete, so a failed or + /// cancelled run never leaves a half archive with the real name. + /// + public static class ArchiveCompressor + { + /// + /// The files under (absolute files or folders, + /// all inside ), named relative to it. + /// Links are skipped (reported in ), never followed. + /// Empty folders are returned in . + /// + public static List Collect(string baseFolder, IEnumerable sources, List skipped, List emptyFolders, CancellationToken ct) + { + var items = new List(); + string Name(string path) => System.IO.Path.GetRelativePath(baseFolder, path).Replace('\\', '/'); + + void Walk(DirectoryInfo dir) + { + ct.ThrowIfCancellationRequested(); + var any = false; + foreach (var info in dir.EnumerateFileSystemInfos()) + { + any = true; + if (IsLink(info)) + { + skipped.Add(Name(info.FullName)); + continue; + } + if (info is DirectoryInfo sub) Walk(sub); + else if (info is FileInfo f) items.Add(new CompressItem(f.FullName, Name(f.FullName), f.Length, f.LastWriteTime)); + } + if (!any) emptyFolders.Add(Name(dir.FullName)); + } + + foreach (var source in sources) + { + if (Directory.Exists(source)) + { + var dir = new DirectoryInfo(source); + if (IsLink(dir)) skipped.Add(Name(source)); + else Walk(dir); + } + else if (File.Exists(source)) + { + var file = new FileInfo(source); + if (IsLink(file)) skipped.Add(Name(source)); + else items.Add(new CompressItem(file.FullName, Name(file.FullName), file.Length, file.LastWriteTime)); + } + } + return items; + } + + private static bool IsLink(FileSystemInfo info) => info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.LinkTarget != null; + + /// Writes the archive to (which must not exist yet). + public static async Task CreateAsync(string format, string level, string baseFolder, IReadOnlyList items, + IReadOnlyList emptyFolders, string output, ArchiveOperation operation, CancellationToken ct) + { + var partial = output + ".partial"; + operation.SetTotals(items.Count, items.Sum(i => i.Size)); + try + { + switch (format) + { + case CompressFormats.SevenZip: + long total = items.Sum(i => i.Size), reported = 0; + await SevenZipTool.CreateAsync(baseFolder, items.Select(i => i.EntryName).ToList(), partial, + level switch { CompressLevels.Fastest => 1, CompressLevels.Maximum => 9, _ => 5 }, + percent => + { + var now = total * percent / 100; + if (now > reported) + { + operation.AddProcessedBytes(now - reported); + reported = now; + } + }, ct); + if (total > reported) operation.AddProcessedBytes(total - reported); + foreach (var _ in items) operation.AddProcessedFile(); + break; + case CompressFormats.TarGz: + await Task.Run(() => WriteTarGz(level, items, emptyFolders, partial, operation, ct), ct); + break; + default: + await Task.Run(() => WriteZip(level, items, emptyFolders, partial, operation, ct), ct); + break; + } + File.Move(partial, output); + } + catch + { + try { if (File.Exists(partial)) File.Delete(partial); } catch { } + throw; + } + } + + private static CompressionLevel ZipLevel(string level) => level switch + { + CompressLevels.Fastest => CompressionLevel.Fastest, + CompressLevels.Maximum => CompressionLevel.SmallestSize, + _ => CompressionLevel.Optimal + }; + + private static void WriteZip(string level, IReadOnlyList items, IReadOnlyList emptyFolders, string path, ArchiveOperation operation, CancellationToken ct) + { + using var file = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None); + using var zip = new ZipArchive(file, ZipArchiveMode.Create); + foreach (var folder in emptyFolders) zip.CreateEntry(folder.TrimEnd('/') + "/"); + foreach (var item in items) + { + ct.ThrowIfCancellationRequested(); + operation.SetCurrent(item.EntryName); + try + { + var entry = zip.CreateEntry(item.EntryName, ZipLevel(level)); + entry.LastWriteTime = item.Modified; + using var input = new FileStream(item.AbsolutePath, FileMode.Open, FileAccess.Read, FileShare.Read); + using var output = new CountingStream(entry.Open(), operation.AddProcessedBytes, ct); + input.CopyTo(output); + operation.AddProcessedFile(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // An empty entry stays for the unreadable file: the zip itself is still valid + operation.AddFailure(item.EntryName, ex.Message); + } + } + } + + private static void WriteTarGz(string level, IReadOnlyList items, IReadOnlyList emptyFolders, string path, ArchiveOperation operation, CancellationToken ct) + { + using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); + using var gzip = new GZipStream(file, ZipLevel(level)); + using var tar = new TarWriter(gzip, TarEntryFormat.Pax, leaveOpen: false); + foreach (var folder in emptyFolders) + tar.WriteEntry(new PaxTarEntry(TarEntryType.Directory, folder.TrimEnd('/') + "/")); + foreach (var item in items) + { + ct.ThrowIfCancellationRequested(); + operation.SetCurrent(item.EntryName); + FileStream input; + try + { + input = new FileStream(item.AbsolutePath, FileMode.Open, FileAccess.Read, FileShare.Read); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + operation.AddFailure(item.EntryName, ex.Message); + continue; + } + using (input) + { + var entry = new PaxTarEntry(TarEntryType.RegularFile, item.EntryName) + { + ModificationTime = item.Modified, + DataStream = new ReadCountingStream(input, operation.AddProcessedBytes, ct) + }; + tar.WriteEntry(entry); + } + operation.AddProcessedFile(); + } + } + + /// The name the archive gets: the wanted one, or " (1)", " (2)"... when taken. + public static string FreeArchivePath(string folder, string baseName, string format) + { + var ext = CompressFormats.Extension(format); + var candidate = System.IO.Path.Combine(folder, baseName + ext); + for (int i = 1; File.Exists(candidate) || Directory.Exists(candidate) || File.Exists(candidate + ".partial"); i++) + candidate = System.IO.Path.Combine(folder, $"{baseName} ({i}){ext}"); + return candidate; + } + } + + /// A read-only wrapper that reports the bytes read (batched) and honours cancellation. + internal sealed class ReadCountingStream : Stream + { + private readonly Stream _inner; + private readonly Action _report; + private readonly CancellationToken _ct; + private long _pending; + + public ReadCountingStream(Stream inner, Action report, CancellationToken ct) + { + _inner = inner; + _report = report; + _ct = ct; + } + + private int Count(int read) + { + _ct.ThrowIfCancellationRequested(); + _pending += read; + if (_pending >= 1024 * 1024 || (read == 0 && _pending > 0)) + { + _report(_pending); + _pending = 0; + } + return read; + } + + public override int Read(byte[] buffer, int offset, int count) => Count(_inner.Read(buffer, offset, count)); + public override int Read(Span buffer) => Count(_inner.Read(buffer)); + + public override bool CanRead => true; + public override bool CanSeek => _inner.CanSeek; + public override bool CanWrite => false; + public override long Length => _inner.Length; + public override long Position { get => _inner.Position; set => _inner.Position = value; } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => _inner.Seek(offset, origin); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/TelegramDownloader/Services/Archives/ArchiveExtractor.cs b/TelegramDownloader/Services/Archives/ArchiveExtractor.cs new file mode 100644 index 0000000..dea1130 --- /dev/null +++ b/TelegramDownloader/Services/Archives/ArchiveExtractor.cs @@ -0,0 +1,547 @@ +using SharpCompress.Archives; +using SharpCompress.Common; +using SharpCompress.Readers; +using TelegramDownloader.Services.Api; + +namespace TelegramDownloader.Services.Archives +{ + /// What to do with an entry whose file already exists. + public enum OverwriteMode + { + /// Keep both: the extracted one gets " (1)", " (2)"... before the extension. + Rename, + Skip, + Overwrite + } + + /// Options of . + public sealed class ExtractOptions + { + public string? Password { get; init; } + public OverwriteMode Overwrite { get; init; } = OverwriteMode.Rename; + + /// Space left free on the disk (the extraction stops before eating it). + public long ReserveBytes { get; init; } = 256L * 1024 * 1024; + + /// Free space of the destination disk; null reads it from the drive (tests override it). + public long? FreeSpace { get; init; } + } + + /// An entry of an archive, as listed without extracting. + public sealed record ArchiveEntryInfo(string Path, bool IsDirectory, long Size, long CompressedSize, DateTime? Modified, bool IsEncrypted); + + /// What an archive contains. + public sealed record ArchiveListing( + string Format, + int VolumeCount, + bool IsEncrypted, + bool IsSolid, + int FileCount, + int FolderCount, + long TotalSize, + IReadOnlyList Entries, + bool Truncated); + + /// + /// Lists and extracts archives (zip, rar, 7z, tar, gz, bz2, xz, zst and + /// their multi-volume sets) with SharpCompress, sequentially (the fast way + /// for solid 7z/rar archives). + /// + /// Safety: every entry is written under the destination folder or not at + /// all. Absolute paths, drive letters and .. segments are refused, + /// links (symlinks, hard links) are never created, and no entry is written + /// through an existing link. The total written is bounded by the free + /// space of the disk minus , so a + /// compression bomb or an archive that lies about its sizes stops with + /// instead of filling it. + /// + public static class ArchiveExtractor + { + /// + /// An opened archive: random access (: zip, rar, 7z, + /// tar and their volumes) or a forward-only reader over one file + /// (: compressed tars and single .gz/.bz2/.xz/.zst, + /// which SharpCompress only reads as a stream). + /// + private sealed class Source : IDisposable + { + public IArchive? Archive { get; init; } + public IReader? Reader { get; init; } + + /// Reader mode: the file being read, to report progress by its position. + public FileStream? Input { get; init; } + + public void Dispose() + { + Reader?.Dispose(); + Input?.Dispose(); + Archive?.Dispose(); + } + } + + private static Source Open(IReadOnlyList volumes, string? password) + { + if (volumes.Count == 0) + throw new ArchiveOperationException(ArchiveErrorCodes.MissingVolume, "The first volume of the archive is missing"); + var options = new ReaderOptions { Password = string.IsNullOrEmpty(password) ? null : password, LeaveStreamOpen = false }; + try + { + return new Source + { + Archive = volumes.Count == 1 + ? ArchiveFactory.OpenArchive(volumes[0], options) + : ArchiveFactory.OpenArchive(volumes, options) + }; + } + catch (Exception ex) when (volumes.Count == 1 && StreamOnly(volumes[0].Name)) + { + // Compressed tar / single compressed file: only readable as a stream + FileStream? input = null; + try + { + input = new FileStream(volumes[0].FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + var reader = ReaderFactory.OpenReader(input, options with { LeaveStreamOpen = true }); + return new Source { Reader = reader, Input = input }; + } + catch (Exception readerError) + { + input?.Dispose(); + throw Translate(readerError, password, encrypted: false); + } + } + catch (Exception ex) + { + // A password was given and the archive did not open: its names are encrypted with another one + throw Translate(ex, password, encrypted: !string.IsNullOrEmpty(password)); + } + } + + /// Formats SharpCompress reads only as a stream: compressed tars and single compressed files. + private static bool StreamOnly(string name) + { + var lower = name.ToLowerInvariant(); + return new[] { ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tbz", ".tar.xz", ".txz", ".tar.zst", ".gz", ".bz2", ".xz", ".zst" } + .Any(lower.EndsWith); + } + + /// Lists the entries (at most ) and the totals. + public static ArchiveListing List(IReadOnlyList volumes, string? password, int maxEntries = 5000) + { + using var source = Open(volumes, password); + try + { + var entries = new List(); + int files = 0, folders = 0; + long total = 0; + bool encrypted = false; + foreach (var (e, _) in Sequence(source)) + { + encrypted |= e.IsEncrypted; + if (e.IsDirectory) folders++; + else + { + files++; + total += Math.Max(0, e.Size); + } + if (entries.Count < maxEntries) + entries.Add(new ArchiveEntryInfo(DisplayKey(e.Key, volumes[0].Name), e.IsDirectory, Math.Max(0, e.Size), Math.Max(0, e.CompressedSize), e.LastModifiedTime, e.IsEncrypted)); + } + var type = source.Archive?.Type ?? source.Reader!.Type; + return new ArchiveListing(FormatName(type, volumes[0].Name), volumes.Count, encrypted || source.Archive?.IsEncrypted == true, + source.Archive?.IsSolid ?? false, files, folders, total, entries, files + folders > entries.Count); + } + catch (ArchiveOperationException) { throw; } + catch (Exception ex) { throw Translate(ex, password, encrypted: false); } + } + + /// + /// Extracts every entry into (an absolute + /// folder, created when missing), reporting into . + /// Entries that cannot be written are reported as failures and skipped; + /// errors of the archive itself (password, damage, missing volume, no + /// space) stop the extraction with an . + /// + public static Task ExtractAsync(IReadOnlyList volumes, string destination, ExtractOptions options, ArchiveOperation operation, CancellationToken ct) => + Task.Run(() => Extract(volumes, destination, options, operation, ct), ct); + + private static void Extract(IReadOnlyList volumes, string destination, ExtractOptions options, ArchiveOperation operation, CancellationToken ct) + { + destination = Path.TrimEndingDirectorySeparator(Path.GetFullPath(destination)); + using var source = Open(volumes, options.Password); + bool encrypted = false; + try + { + Directory.CreateDirectory(destination); + long free = options.FreeSpace ?? FreeSpaceOf(destination); + long budget = free - options.ReserveBytes; + + // Progress: by bytes written when the totals are known up front, + // by the position in the file for a stream (sizes come as it is read) + var streaming = source.Archive == null; + long inputReported = 0; + void ReportInput() + { + var position = source.Input!.Position; + if (position > inputReported) + { + operation.AddProcessedBytes(position - inputReported); + inputReported = position; + } + } + + if (!streaming) + { + int files = 0; + long total = 0; + foreach (var e in source.Archive!.Entries) + { + encrypted |= e.IsEncrypted; + if (e.IsDirectory) continue; + files++; + total += Math.Max(0, e.Size); + } + encrypted |= source.Archive.IsEncrypted; + if (encrypted && string.IsNullOrEmpty(options.Password)) + throw new ArchiveOperationException(ArchiveErrorCodes.PasswordRequired, "The archive is protected with a password"); + if (total > budget) + throw new ArchiveOperationException(ArchiveErrorCodes.NotEnoughSpace, + $"Not enough free space: the archive needs {HelperService.SizeSuffix(total)} and {HelperService.SizeSuffix(Math.Max(0, budget))} are available"); + operation.SetTotals(files, total); + } + else + { + operation.SetTotals(0, source.Input!.Length); + } + + long written = 0; + foreach (var (entry, writeTo) in Sequence(source)) + { + ct.ThrowIfCancellationRequested(); + var key = DisplayKey(entry.Key, volumes[0].Name); + if (!string.IsNullOrEmpty(entry.LinkTarget)) + { + operation.AddFailure(key, "Links are not extracted"); + continue; + } + if (!TryTargetPath(destination, key, out var target, out var reason)) + { + operation.AddFailure(key, reason!); + continue; + } + if (entry.IsDirectory) + { + if (ThroughLink(destination, target, includeLast: true)) operation.AddFailure(key, "The path goes through a link"); + else Directory.CreateDirectory(target); + continue; + } + if (ThroughLink(destination, target, includeLast: false)) + { + operation.AddFailure(key, "The path goes through a link"); + continue; + } + + operation.SetCurrent(key); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + if (File.Exists(target) || Directory.Exists(target)) + { + if (options.Overwrite == OverwriteMode.Skip || Directory.Exists(target) || IsLink(target)) + { + if (!streaming) operation.AddProcessedBytes(Math.Max(0, entry.Size)); + operation.AddProcessedFile(); + continue; + } + if (options.Overwrite == OverwriteMode.Rename) target = FreeName(target); + } + + try + { + using (var file = new FileStream(target, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var counter = new CountingStream(file, delta => + { + written += delta; + if (written > budget) + throw new ArchiveOperationException(ArchiveErrorCodes.NotEnoughSpace, "The disk is running out of space: the extraction was stopped"); + if (streaming) ReportInput(); + else operation.AddProcessedBytes(delta); + }, ct)) + { + writeTo(counter); + } + if (entry.LastModifiedTime is { } modified) + { + try { File.SetLastWriteTime(target, modified); } catch { /* not important */ } + } + operation.AddProcessedFile(); + if (streaming) ReportInput(); + } + catch (Exception ex) + { + TryDelete(target); + if (ex is OperationCanceledException or ArchiveOperationException) throw; + // Damage / password errors of the archive stop everything; disk errors of one file do not + if (ex is SharpCompressException or InvalidDataException) throw Translate(ex, options.Password, encrypted || entry.IsEncrypted); + operation.AddFailure(key, ex.Message); + } + } + } + catch (ArchiveOperationException) { throw; } + catch (OperationCanceledException) { throw; } + catch (Exception ex) { throw Translate(ex, options.Password, encrypted); } + } + + /// + /// The entries in archive order with a way to write each one: solid + /// archives and 7z are read sequentially (random access would decode + /// the solid block again for every entry), the others entry by entry. + /// + private static IEnumerable<(IEntry Entry, Action WriteTo)> Sequence(Source source) + { + if (source.Reader is { } streamReader) + { + while (streamReader.MoveToNextEntry()) + yield return (streamReader.Entry, stream => streamReader.WriteEntryTo(stream)); + yield break; + } + var archive = source.Archive!; + if (archive.Type == ArchiveType.SevenZip || archive.IsSolid) + { + using var reader = archive.ExtractAllEntries(); + while (reader.MoveToNextEntry()) + yield return (reader.Entry, stream => reader.WriteEntryTo(stream)); + } + else + { + foreach (var entry in archive.Entries) + { + yield return (entry, stream => + { + using var input = entry.OpenEntryStream(); + input.CopyTo(stream); + }); + } + } + } + + /// + /// The absolute path an entry is written to, or why it is refused: + /// absolute, drive-qualified, .. segments, or empty. + /// Characters Windows cannot store are replaced with _. + /// + public static bool TryTargetPath(string destination, string? key, out string target, out string? reason) + { + target = string.Empty; + reason = null; + var normalized = (key ?? string.Empty).Replace('\\', '/'); + if (normalized.StartsWith('/') || (normalized.Length > 1 && normalized[1] == ':')) + { + reason = "Absolute paths are not extracted"; + return false; + } + var segments = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries).Where(s => s != ".").ToList(); + if (segments.Count == 0) + { + reason = "The entry has no name"; + return false; + } + if (segments.Any(s => s == ".." || s.Trim() == "..")) + { + reason = "Paths that leave the destination are not extracted"; + return false; + } + var invalid = Path.GetInvalidFileNameChars(); + var safe = segments.Select(s => new string(s.Select(c => invalid.Contains(c) ? '_' : c).ToArray())).ToArray(); + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.Combine(new[] { destination }.Concat(safe).ToArray()))); + if (!LocalPathGuard.IsSameOrInside(destination, full) || string.Equals(full, destination, StringComparison.OrdinalIgnoreCase)) + { + reason = "Paths that leave the destination are not extracted"; + return false; + } + target = full; + return true; + } + + /// True when a folder between and (and the target itself with ) is a link. + public static bool ThroughLink(string root, string target, bool includeLast) + { + var relative = Path.GetRelativePath(root, target); + var segments = relative.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + var current = root; + var count = includeLast ? segments.Length : segments.Length - 1; + for (int i = 0; i < count; i++) + { + current = Path.Combine(current, segments[i]); + if (IsLink(current)) return true; + if (!Directory.Exists(current) && !File.Exists(current)) return false; + } + return false; + } + + private static bool IsLink(string path) + { + try + { + FileSystemInfo info = Directory.Exists(path) ? new DirectoryInfo(path) : new FileInfo(path); + return info.Exists && (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.LinkTarget != null); + } + catch + { + return false; + } + } + + /// a.txt → a (1).txt, a (2).txt... (the first name not taken). + public static string FreeName(string path) + { + var dir = Path.GetDirectoryName(path)!; + var name = Path.GetFileNameWithoutExtension(path); + var ext = Path.GetExtension(path); + for (int i = 1; ; i++) + { + var candidate = Path.Combine(dir, $"{name} ({i}){ext}"); + if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate; + } + } + + private static long FreeSpaceOf(string folder) + { + try + { + return new DriveInfo(Path.GetPathRoot(folder)!).AvailableFreeSpace; + } + catch + { + return long.MaxValue / 2; // unknown (some container mounts): only the reserve is enforced + } + } + + private static void TryDelete(string path) + { + try { if (File.Exists(path)) File.Delete(path); } catch { } + } + + /// The entry name; a single-file .gz/.bz2/.xz without one is named after the archive. + private static string DisplayKey(string? key, string archiveName) + { + if (!string.IsNullOrWhiteSpace(key)) return key.Replace('\\', '/'); + var set = ArchiveNames.SetOf(archiveName); + return set?.BaseName ?? Path.GetFileNameWithoutExtension(archiveName); + } + + private static string FormatName(ArchiveType type, string firstVolume) + { + var lower = firstVolume.ToLowerInvariant(); + if (type == ArchiveType.Tar) + { + if (lower.EndsWith(".gz") || lower.EndsWith(".tgz")) return "tar.gz"; + if (lower.EndsWith(".bz2") || lower.EndsWith(".tbz2") || lower.EndsWith(".tbz")) return "tar.bz2"; + if (lower.EndsWith(".xz") || lower.EndsWith(".txz")) return "tar.xz"; + if (lower.EndsWith(".zst")) return "tar.zst"; + } + return type switch + { + ArchiveType.SevenZip => "7z", + ArchiveType.GZip => "gz", + _ => type.ToString().ToLowerInvariant() + }; + } + + /// Maps the exceptions of SharpCompress to the codes the clients understand. + public static ArchiveOperationException Translate(Exception ex, string? password, bool encrypted) + { + if (ex is ArchiveOperationException own) return own; + var hasPassword = !string.IsNullOrEmpty(password); + switch (ex) + { + case SharpCompress.Common.CryptographicException: + return hasPassword + ? new ArchiveOperationException(ArchiveErrorCodes.WrongPassword, "The password is not correct", ex) + : new ArchiveOperationException(ArchiveErrorCodes.PasswordRequired, "The archive is protected with a password", ex); + case MultiVolumeExtractionException: + case MultipartStreamRequiredException: + case IncompleteArchiveException: + return new ArchiveOperationException(ArchiveErrorCodes.MissingVolume, "A volume of the archive is missing or incomplete", ex); + case NotSupportedException: + return new ArchiveOperationException(ArchiveErrorCodes.Unsupported, "This archive format or compression method is not supported", ex); + } + if (encrypted && hasPassword && ex is SharpCompressException or InvalidDataException or InvalidOperationException) + return new ArchiveOperationException(ArchiveErrorCodes.WrongPassword, "The password is not correct", ex); + if (ex.Message.Contains("Cannot determine", StringComparison.OrdinalIgnoreCase)) + return new ArchiveOperationException(ArchiveErrorCodes.Unsupported, "Not an archive, or a format that is not supported", ex); + if (ex is SharpCompressException or InvalidDataException or EndOfStreamException or InvalidOperationException) + return new ArchiveOperationException(ArchiveErrorCodes.Corrupt, "The archive is damaged or incomplete", ex); + return new ArchiveOperationException(ArchiveErrorCodes.Corrupt, ex.Message, ex); + } + } + + /// + /// A write-only wrapper that reports the bytes written (in batches of about + /// 1 MB, the rest on dispose) and honours cancellation. + /// + internal sealed class CountingStream : Stream + { + private readonly Stream _inner; + private readonly Action _report; + private readonly CancellationToken _ct; + private long _pending; + + public CountingStream(Stream inner, Action report, CancellationToken ct) + { + _inner = inner; + _report = report; + _ct = ct; + } + + private void Count(int bytes) + { + _ct.ThrowIfCancellationRequested(); + _pending += bytes; + if (_pending >= 1024 * 1024) Flush(true); + } + + private void Flush(bool report) + { + if (!report || _pending == 0) return; + var delta = _pending; + _pending = 0; + _report(delta); + } + + public override void Write(byte[] buffer, int offset, int count) + { + _inner.Write(buffer, offset, count); + Count(count); + } + + public override void Write(ReadOnlySpan buffer) + { + _inner.Write(buffer); + Count(buffer.Length); + } + + public override void WriteByte(byte value) + { + _inner.WriteByte(value); + Count(1); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + try { Flush(true); } + finally { _inner.Dispose(); } + } + base.Dispose(disposing); + } + + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => _inner.Length; + public override long Position { get => _inner.Position; set => throw new NotSupportedException(); } + public override void Flush() => _inner.Flush(); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } +} diff --git a/TelegramDownloader/Services/Archives/ArchiveNames.cs b/TelegramDownloader/Services/Archives/ArchiveNames.cs new file mode 100644 index 0000000..e58a41c --- /dev/null +++ b/TelegramDownloader/Services/Archives/ArchiveNames.cs @@ -0,0 +1,140 @@ +using System.Text.RegularExpressions; + +namespace TelegramDownloader.Services.Archives +{ + /// + /// The volumes of one archive: a single file, or the parts of a multi-volume + /// archive (x.part1.rar, x.part2.rar; x.rar, x.r00; + /// x.7z.001, x.7z.002; x.zip, x.z01). + /// + /// Identifies the set inside its folder (lower case base name + kind). + /// Name without the archive and volume extensions (x), used for the extraction folder. + /// Name of the volume extraction starts from. + /// Named like a volume of a set (it may still have one volume only). + public sealed record ArchiveSet(string Key, string BaseName, string FirstVolume, bool IsMultiVolume) + { + /// True when is a volume of this set. + public bool Contains(string fileName) => ArchiveNames.SetOf(fileName) is { } other && other.Key == Key; + } + + /// Recognises archives and multi-volume sets by file name. + public static class ArchiveNames + { + // name.part1.rar / name.part01.rar + private static readonly Regex RarPart = new(@"^(?.+)\.part(?\d+)\.rar$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + // name.r00, name.r01... (old RAR volumes; the first one is name.rar) + private static readonly Regex RarOld = new(@"^(?.+)\.r(?\d{2,3})$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + // name.7z.001, name.zip.001, name.rar.001... + private static readonly Regex Numbered = new(@"^(?.+)\.(?7z|zip|rar|tar)\.(?\d{3})$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + // name.z01, name.z02... (split zip; the last one is name.zip) + private static readonly Regex ZipPart = new(@"^(?.+)\.z(?\d{2})$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// Single-file archive extensions, longest first (".tar.gz" before ".gz"). + private static readonly string[] Extensions = + { + ".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst", ".tgz", ".tbz2", ".tbz", ".txz", + ".zip", ".rar", ".7z", ".tar", ".gz", ".bz2", ".xz", ".zst", ".cbz", ".cbr", ".cb7" + }; + + /// Formats that can be extracted (shown by the capabilities endpoint). + public static IReadOnlyList ExtractFormats { get; } = new[] { "zip", "rar", "7z", "tar", "tar.gz", "tar.bz2", "tar.xz", "gz", "bz2", "xz", "zst" }; + + /// The archive set a file belongs to, or null when it is not an archive. + public static ArchiveSet? SetOf(string? fileName) + { + if (string.IsNullOrWhiteSpace(fileName)) return null; + var name = Path.GetFileName(fileName.Replace('\\', '/')); + + var m = RarPart.Match(name); + if (m.Success) + { + var digits = m.Groups["n"].Value.Length; + var b = m.Groups["base"].Value; + return new ArchiveSet(b.ToLowerInvariant() + "|rarpart", b, $"{b}.part{1.ToString().PadLeft(digits, '0')}.rar", true); + } + + m = Numbered.Match(name); + if (m.Success) + { + var b = m.Groups["base"].Value; + var ext = m.Groups["ext"].Value; + return new ArchiveSet($"{b.ToLowerInvariant()}|{ext.ToLowerInvariant()}.nnn", b, $"{b}.{ext}.001", true); + } + + m = RarOld.Match(name); + if (m.Success) + { + var b = m.Groups["base"].Value; + return new ArchiveSet(b.ToLowerInvariant() + "|rarold", b, b + ".rar", true); + } + + m = ZipPart.Match(name); + if (m.Success) + { + var b = m.Groups["base"].Value; + return new ArchiveSet(b.ToLowerInvariant() + "|zipsplit", b, b + ".zip", true); + } + + foreach (var ext in Extensions) + { + if (!name.EndsWith(ext, StringComparison.OrdinalIgnoreCase) || name.Length == ext.Length) continue; + var b = name[..^ext.Length]; + // name.rar may be the first volume of an old-style set (name.r00...); + // name.zip may be the last one of a split zip (name.z01...). The set key + // is shared so the siblings are found; FirstVolume is this file. + var key = ext.ToLowerInvariant() switch + { + ".rar" => b.ToLowerInvariant() + "|rarold", + ".zip" => b.ToLowerInvariant() + "|zipsplit", + _ => b.ToLowerInvariant() + "|" + ext.ToLowerInvariant() + }; + return new ArchiveSet(key, b, name, false); + } + return null; + } + + /// True when the file name is an archive or a volume of one. + public static bool IsArchive(string? fileName) => SetOf(fileName) != null; + + /// + /// The volumes of present in , + /// in reading order (the first volume first). Empty when the first volume is missing. + /// + public static IReadOnlyList VolumesIn(string folder, ArchiveSet set) + { + var dir = new DirectoryInfo(folder); + if (!dir.Exists) return Array.Empty(); + var files = dir.EnumerateFiles() + .Where(f => !f.Attributes.HasFlag(FileAttributes.ReparsePoint) && set.Contains(f.Name)) + .ToList(); + if (files.Count == 0) return Array.Empty(); + var kind = set.Key[(set.Key.IndexOf('|') + 1)..]; + if (kind == "rarpart" || kind.EndsWith(".nnn", StringComparison.Ordinal)) + { + // part1 / .001 first, whatever the zero padding of the names + var ordered = files.OrderBy(f => VolumeNumber(f.Name)).ToList(); + return VolumeNumber(ordered[0].Name) == 1 ? ordered : Array.Empty(); + } + var first = files.FirstOrDefault(f => string.Equals(f.Name, set.FirstVolume, StringComparison.OrdinalIgnoreCase)); + if (first == null) return Array.Empty(); + if (kind == "zipsplit") + { + // Split zip: name.z01, name.z02 ... then name.zip last + return files.Where(f => f != first).OrderBy(f => VolumeNumber(f.Name)).Append(first).ToList(); + } + return files.OrderBy(f => f == first ? -1 : VolumeNumber(f.Name)).ToList(); + } + + /// Number of a volume (1 for part1 / .001, 0 for .r00 / .z00...); -1 for the plain name. + public static int VolumeNumber(string fileName) + { + var name = Path.GetFileName(fileName); + foreach (var regex in new[] { RarPart, Numbered, RarOld, ZipPart }) + { + var m = regex.Match(name); + if (m.Success && int.TryParse(m.Groups["n"].Value, out var n)) return n; + } + return -1; + } + } +} diff --git a/TelegramDownloader/Services/Archives/ArchiveOperation.cs b/TelegramDownloader/Services/Archives/ArchiveOperation.cs new file mode 100644 index 0000000..add02f9 --- /dev/null +++ b/TelegramDownloader/Services/Archives/ArchiveOperation.cs @@ -0,0 +1,196 @@ +namespace TelegramDownloader.Services.Archives +{ + /// Values of . + public static class ArchiveKinds + { + public const string Extract = "extract"; + public const string Compress = "compress"; + } + + /// Values of . + public static class ArchivePhases + { + /// Waiting for the operation in front of it (one runs at a time). + public const string Queued = "queued"; + + /// Opening the archive / walking the selection; totals not known yet. + public const string Preparing = "preparing"; + + /// Extracting or compressing; the totals are known. + public const string Working = "working"; + + public const string Done = "done"; + public const string Failed = "failed"; + public const string Cancelled = "cancelled"; + + public static bool IsFinal(string phase) => phase == Done || phase == Failed || phase == Cancelled; + } + + /// Values of : why a failed operation stopped. + public static class ArchiveErrorCodes + { + public const string PasswordRequired = "password_required"; + public const string WrongPassword = "wrong_password"; + public const string NotEnoughSpace = "not_enough_space"; + public const string MissingVolume = "missing_volume"; + public const string Unsupported = "unsupported"; + public const string Corrupt = "corrupt"; + public const string NotFound = "not_found"; + public const string ToolMissing = "tool_missing"; + } + + /// An entry that could not be extracted or added. + public sealed record ArchiveFailure(string Path, string Reason); + + /// Immutable copy of an . + public sealed record ArchiveOperationSnapshot( + string Id, + string Kind, + string Source, + string? Destination, + bool Automatic, + string Phase, + int TotalFiles, + long TotalBytes, + int ProcessedFiles, + long ProcessedBytes, + string? CurrentItem, + int FailedCount, + IReadOnlyList Failed, + bool ArchivesDeleted, + bool CancelRequested, + string? Error, + string? ErrorCode, + DateTime StartedAt, + DateTime? FinishedAt, + long Version); + + /// + /// Live state of one extraction or compression. Every mutation bumps + /// and raises (the events hub + /// throttles it). Thread-safe. + /// + public sealed class ArchiveOperation + { + public const int MaxFailuresKept = 100; + + private readonly object _lock = new(); + private readonly CancellationTokenSource _cts = new(); + private readonly List _failed = new(); + private readonly Func _clock; + + private string _phase = ArchivePhases.Queued; + private int _totalFiles, _processedFiles, _failedCount; + private long _totalBytes, _processedBytes, _version; + private string? _current, _error, _errorCode, _destination; + private bool _archivesDeleted; + private DateTime? _finishedAt; + + public ArchiveOperation(string kind, string source, string? destination, bool automatic, Func? clock = null) + { + _clock = clock ?? (() => DateTime.UtcNow); + Id = Guid.NewGuid().ToString("N"); + Kind = kind; + Source = source; + _destination = destination; + Automatic = automatic; + StartedAt = _clock(); + } + + public string Id { get; } + public string Kind { get; } + + /// Archive path (extract) or a description of the selection (compress), relative to the local root. + public string Source { get; } + + /// Started by "extract when the download finishes". + public bool Automatic { get; } + public DateTime StartedAt { get; } + + public event Action? Changed; + + public CancellationToken Token => _cts.Token; + public bool CancelRequested => _cts.IsCancellationRequested; + public string Phase { get { lock (_lock) return _phase; } } + public bool IsFinished { get { lock (_lock) return ArchivePhases.IsFinal(_phase); } } + public DateTime? FinishedAt { get { lock (_lock) return _finishedAt; } } + public int FailedCount { get { lock (_lock) return _failedCount; } } + public string? Destination { get { lock (_lock) return _destination; } } + + public Task Completion { get; internal set; } = Task.CompletedTask; + + public void Cancel() + { + if (IsFinished || _cts.IsCancellationRequested) return; + try { _cts.Cancel(); } catch (ObjectDisposedException) { } + Mutate(() => { }); + } + + public void SetPreparing() => Mutate(() => { if (_phase == ArchivePhases.Queued) _phase = ArchivePhases.Preparing; }); + + public void SetTotals(int files, long bytes) => Mutate(() => + { + _totalFiles = files; + _totalBytes = bytes; + if (!ArchivePhases.IsFinal(_phase)) _phase = ArchivePhases.Working; + }); + + public void SetDestination(string destination) => Mutate(() => _destination = destination); + public void SetCurrent(string? item) => Mutate(() => _current = item); + public void AddProcessedFile() => Mutate(() => _processedFiles++); + public void AddProcessedBytes(long bytes) => Mutate(() => _processedBytes += bytes); + public void SetArchivesDeleted() => Mutate(() => _archivesDeleted = true); + + public void AddFailure(string path, string reason) => Mutate(() => + { + _failedCount++; + if (_failed.Count < MaxFailuresKept) _failed.Add(new ArchiveFailure(path, reason)); + }); + + internal void Finish(string phase, string? error = null, string? errorCode = null) => Mutate(() => + { + if (ArchivePhases.IsFinal(_phase)) return; + _phase = phase; + _error = error; + _errorCode = errorCode; + _current = null; + _finishedAt = _clock(); + }); + + public ArchiveOperationSnapshot Snapshot() + { + lock (_lock) + { + return new ArchiveOperationSnapshot(Id, Kind, Source, _destination, Automatic, _phase, + _totalFiles, _totalBytes, _processedFiles, _processedBytes, _current, + _failedCount, _failed.ToList(), _archivesDeleted, _cts.IsCancellationRequested, + _error, _errorCode, StartedAt, _finishedAt, _version); + } + } + + private void Mutate(Action change) + { + lock (_lock) + { + change(); + _version++; + } + try { Changed?.Invoke(this); } + catch { /* a listener must never break the operation */ } + } + } + + /// + /// An error that stops an archive operation with a code the clients can + /// translate (). + /// + public sealed class ArchiveOperationException : Exception + { + public ArchiveOperationException(string code, string message, Exception? inner = null) : base(message, inner) + { + Code = code; + } + + public string Code { get; } + } +} diff --git a/TelegramDownloader/Services/Archives/ArchiveOperationRegistry.cs b/TelegramDownloader/Services/Archives/ArchiveOperationRegistry.cs new file mode 100644 index 0000000..b153a94 --- /dev/null +++ b/TelegramDownloader/Services/Archives/ArchiveOperationRegistry.cs @@ -0,0 +1,136 @@ +using System.Collections.Concurrent; + +namespace TelegramDownloader.Services.Archives +{ + /// Outcome of . + public enum ArchiveCancelResult + { + NotFound, + AlreadyFinished, + Cancelling + } + + /// + /// The extractions and compressions of the server. They run one at a time + /// (they are CPU and disk bound; on a NAS two at once only slow both down): + /// the rest wait as queued. Finished operations stay readable for + /// . + /// + public sealed class ArchiveOperationRegistry + { + public static readonly TimeSpan Retention = TimeSpan.FromMinutes(30); + + private readonly ConcurrentDictionary _operations = new(StringComparer.Ordinal); + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly Func _clock; + private readonly ILogger? _logger; + + public ArchiveOperationRegistry(ILogger? logger = null) : this(null, logger) { } + + public ArchiveOperationRegistry(Func? clock, ILogger? logger = null) + { + _clock = clock ?? (() => DateTime.UtcNow); + _logger = logger; + } + + /// Raised on every change of any operation. + public event Action? Changed; + + /// Raised once when an operation ends (done, failed or cancelled). + public event Action? Finished; + + /// + /// Registers an operation and runs when its turn + /// comes. It ends as done, cancelled or failed + /// (with the code of an ). + /// + public ArchiveOperation Start(string kind, string source, string? destination, bool automatic, + Func work) + { + Prune(); + var operation = new ArchiveOperation(kind, source, destination, automatic, _clock); + operation.Changed += OnChanged; + _operations[operation.Id] = operation; + operation.Completion = Task.Run(() => RunAsync(operation, work)); + return operation; + } + + private async Task RunAsync(ArchiveOperation operation, Func work) + { + var entered = false; + try + { + await _gate.WaitAsync(operation.Token); + entered = true; + operation.SetPreparing(); + await work(operation, operation.Token); + operation.Finish(ArchivePhases.Done); + } + catch (OperationCanceledException) when (operation.CancelRequested) + { + operation.Finish(ArchivePhases.Cancelled); + } + catch (ArchiveOperationException ex) + { + _logger?.LogWarning("Archive operation {Id} ({Kind}) failed: {Code} {Message}", operation.Id, operation.Kind, ex.Code, ex.Message); + operation.Finish(ArchivePhases.Failed, ex.Message, ex.Code); + } + catch (Exception ex) + { + _logger?.LogError(ex, "Archive operation {Id} ({Kind}) failed", operation.Id, operation.Kind); + operation.Finish(ArchivePhases.Failed, ex.Message); + } + finally + { + if (entered) _gate.Release(); + try { Finished?.Invoke(operation); } + catch (Exception ex) { _logger?.LogDebug(ex, "Archive operation finish listener failed"); } + } + } + + private void OnChanged(ArchiveOperation operation) + { + try { Changed?.Invoke(operation); } + catch (Exception ex) { _logger?.LogDebug(ex, "Archive operation listener failed"); } + } + + public ArchiveOperation? Get(string id) + { + Prune(); + return _operations.TryGetValue(id, out var operation) ? operation : null; + } + + /// Running and queued operations first, then the recent ones, newest first. + public IReadOnlyList Snapshots() + { + Prune(); + return _operations.Values + .Select(o => o.Snapshot()) + .OrderBy(s => ArchivePhases.IsFinal(s.Phase)) + .ThenByDescending(s => s.StartedAt) + .ToList(); + } + + public IReadOnlyList Running() => _operations.Values.Where(o => !o.IsFinished).ToList(); + + public ArchiveCancelResult TryCancel(string id) + { + var operation = Get(id); + if (operation == null) return ArchiveCancelResult.NotFound; + if (operation.IsFinished) return ArchiveCancelResult.AlreadyFinished; + operation.Cancel(); + return ArchiveCancelResult.Cancelling; + } + + public void Prune() + { + var limit = _clock() - Retention; + foreach (var (id, operation) in _operations) + { + var finished = operation.FinishedAt; + if (finished.HasValue && finished.Value < limit && _operations.TryRemove(id, out var removed)) + removed.Changed -= OnChanged; + } + } + } +} diff --git a/TelegramDownloader/Services/Archives/ArchiveOperationService.cs b/TelegramDownloader/Services/Archives/ArchiveOperationService.cs new file mode 100644 index 0000000..d396ac8 --- /dev/null +++ b/TelegramDownloader/Services/Archives/ArchiveOperationService.cs @@ -0,0 +1,222 @@ +using TelegramDownloader.Models; +using TelegramDownloader.Services.Api; + +namespace TelegramDownloader.Services.Archives +{ + /// Options of an extraction. + public sealed class ExtractRequestOptions + { + /// Folder to extract into, relative to the local root; null = the folder of the archive. + public string? Destination { get; init; } + + /// Extract into a new folder named after the archive (inside the destination). + public bool IntoFolder { get; init; } = true; + + public OverwriteMode Overwrite { get; init; } = OverwriteMode.Rename; + public string? Password { get; init; } + + /// Delete the archive (every volume) when everything was extracted without failures. + public bool DeleteArchive { get; init; } + } + + /// Options of a compression. + public sealed class CompressRequestOptions + { + /// Folder the archive is written to, relative to the local root; null = the folder of the selection. + public string? Destination { get; init; } + + /// Archive name without extension; null = named after the selection. + public string? Name { get; init; } + + public string Format { get; init; } = CompressFormats.Zip; + public string Level { get; init; } = CompressLevels.Normal; + } + + /// + /// Starts extractions and compressions of local files on the + /// and announces how they ended as + /// a notification. Paths are relative to the local root. + /// + public sealed class ArchiveOperationService + { + private readonly ArchiveOperationRegistry _registry; + private readonly ILogger _logger; + + public ArchiveOperationService(ArchiveOperationRegistry registry, ILogger logger) + { + _registry = registry; + _logger = logger; + _registry.Finished += Announce; + } + + public ArchiveOperationRegistry Registry => _registry; + + private static string Relative(string root, string absolute) + { + var relative = System.IO.Path.GetRelativePath(root, absolute).Replace('\\', '/'); + return relative == "." ? string.Empty : relative; + } + + /// + /// Resolves a folder of the local root that may be written to: inside the + /// root and not reached through a link that leaves it. + /// + public static bool TryResolveFolder(string root, string? path, out string absolute, out string? error) + { + root = System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(root)); + if (!LocalPathGuard.TryResolve(root, path, out absolute, out _, out error)) return false; + if (ArchiveExtractor.ThroughLink(root, absolute, includeLast: true)) + { + error = "The path goes through a link"; + return false; + } + return true; + } + + /// Extracts the archive at (any volume of a set) in the background. + public ArchiveOperation StartExtract(string root, string archivePath, ExtractRequestOptions options, bool automatic = false) + { + root = System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(root)); + var source = (archivePath ?? string.Empty).Replace('\\', '/').TrimStart('/'); + return _registry.Start(ArchiveKinds.Extract, source, null, automatic, async (operation, ct) => + { + if (!TryResolveFolder(root, source, out var archiveAbsolute, out var error) || !File.Exists(archiveAbsolute)) + throw new ArchiveOperationException(ArchiveErrorCodes.NotFound, error ?? "The archive does not exist"); + var set = ArchiveNames.SetOf(archiveAbsolute) + ?? throw new ArchiveOperationException(ArchiveErrorCodes.Unsupported, "Not an archive, or a format that is not supported"); + var folder = System.IO.Path.GetDirectoryName(archiveAbsolute)!; + var volumes = ArchiveNames.VolumesIn(folder, set); + if (volumes.Count == 0) + throw new ArchiveOperationException(ArchiveErrorCodes.MissingVolume, $"The first volume ({set.FirstVolume}) is not in the folder"); + + string destination; + if (options.Destination != null) + { + if (!TryResolveFolder(root, options.Destination, out destination, out error)) + throw new ArchiveOperationException(ArchiveErrorCodes.NotFound, error ?? "Invalid destination"); + } + else destination = folder; + if (options.IntoFolder) + { + var named = System.IO.Path.Combine(destination, Sanitize(set.BaseName)); + // A file with the folder's name: pick a free name rather than failing + destination = File.Exists(named) ? ArchiveExtractor.FreeName(named) : named; + } + if (ArchiveExtractor.ThroughLink(root, destination, includeLast: true)) + throw new ArchiveOperationException(ArchiveErrorCodes.NotFound, "The destination goes through a link"); + operation.SetDestination(Relative(root, destination)); + + await ArchiveExtractor.ExtractAsync(volumes, destination, + new ExtractOptions { Password = options.Password, Overwrite = options.Overwrite }, operation, ct); + + if (options.DeleteArchive && operation.FailedCount == 0) + { + var failed = false; + foreach (var volume in volumes) + { + try { volume.Delete(); } + catch (Exception ex) + { + failed = true; + operation.AddFailure(Relative(root, volume.FullName), "Could not delete the archive: " + ex.Message); + } + } + if (!failed) operation.SetArchivesDeleted(); + } + }); + } + + /// + /// Compresses (files and folders of one folder) + /// into one archive in the background. + /// + public ArchiveOperation StartCompress(string root, IReadOnlyList paths, CompressRequestOptions options) + { + root = System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(root)); + var list = paths.Select(p => p.Replace('\\', '/').Trim('/')).Distinct(StringComparer.Ordinal).ToList(); + var source = list.Count == 1 ? list[0] : $"{list.Count} items"; + return _registry.Start(ArchiveKinds.Compress, source, null, false, async (operation, ct) => + { + var absolutes = new List(); + foreach (var path in list) + { + if (!TryResolveFolder(root, path, out var absolute, out var error) || (!File.Exists(absolute) && !Directory.Exists(absolute))) + throw new ArchiveOperationException(ArchiveErrorCodes.NotFound, $"{path}: {error ?? "not found"}"); + if (string.Equals(absolute, root, StringComparison.OrdinalIgnoreCase)) + throw new ArchiveOperationException(ArchiveErrorCodes.NotFound, "The local root cannot be compressed"); + absolutes.Add(absolute); + } + var baseFolder = System.IO.Path.GetDirectoryName(absolutes[0])!; + + string destination = baseFolder; + if (options.Destination != null && !TryResolveFolder(root, options.Destination, out destination, out var destError)) + throw new ArchiveOperationException(ArchiveErrorCodes.NotFound, destError ?? "Invalid destination"); + Directory.CreateDirectory(destination); + + var name = Sanitize(string.IsNullOrWhiteSpace(options.Name) + ? (absolutes.Count == 1 ? StripArchiveExtension(System.IO.Path.GetFileName(absolutes[0])) : System.IO.Path.GetFileName(baseFolder)) + : options.Name.Trim()); + if (string.IsNullOrEmpty(name)) name = "archive"; + var output = ArchiveCompressor.FreeArchivePath(destination, name, options.Format); + operation.SetDestination(Relative(root, output)); + + var skipped = new List(); + var emptyFolders = new List(); + var items = ArchiveCompressor.Collect(baseFolder, absolutes, skipped, emptyFolders, ct); + foreach (var link in skipped) operation.AddFailure(link, "Links are not added"); + // Never put the archive inside itself + items.RemoveAll(i => string.Equals(i.AbsolutePath, output, StringComparison.OrdinalIgnoreCase)); + if (options.Format == CompressFormats.SevenZip && !SevenZipTool.Available) + throw new ArchiveOperationException(ArchiveErrorCodes.ToolMissing, "7-Zip is not installed on the server"); + + await ArchiveCompressor.CreateAsync(options.Format, options.Level, baseFolder, items, emptyFolders, output, operation, ct); + }); + } + + /// Fotos.zip → Fotos, backup.tar.gz → backup, notas.txt → notas. + private static string StripArchiveExtension(string name) + { + var set = ArchiveNames.SetOf(name); + if (set != null) return set.BaseName; + var dot = name.LastIndexOf('.'); + return dot > 0 ? name[..dot] : name; + } + + private static string Sanitize(string name) + { + var invalid = System.IO.Path.GetInvalidFileNameChars(); + var clean = new string(name.Select(c => invalid.Contains(c) ? '_' : c).ToArray()).Trim().TrimEnd('.'); + return clean is "." or ".." ? "_" : clean; + } + + /// One notification when an operation ends. + private void Announce(ArchiveOperation operation) + { + try + { + var s = operation.Snapshot(); + var name = System.IO.Path.GetFileName(s.Source.TrimEnd('/')); + var extract = s.Kind == ArchiveKinds.Extract; + var nm = new NotificationModel(); + switch (s.Phase) + { + case ArchivePhases.Done when s.FailedCount == 0: + nm.sendEvent(new Notification(extract ? $"{name} extracted to /{s.Destination}" : $"{s.Destination} created", + extract ? "Extraction completed" : "Compression completed", NotificationTypes.Success)); + break; + case ArchivePhases.Done: + nm.sendEvent(new Notification($"{name}: {s.FailedCount} entries could not be processed", + extract ? "Extraction completed with errors" : "Compression completed with errors", NotificationTypes.Warn)); + break; + case ArchivePhases.Failed: + nm.sendEvent(new Notification($"{name}: {s.Error}", extract ? "Extraction failed" : "Compression failed", NotificationTypes.Error)); + break; + } + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Could not announce archive operation {Id}", operation.Id); + } + } + } +} diff --git a/TelegramDownloader/Services/Archives/AutoExtract.cs b/TelegramDownloader/Services/Archives/AutoExtract.cs new file mode 100644 index 0000000..2eb4540 --- /dev/null +++ b/TelegramDownloader/Services/Archives/AutoExtract.cs @@ -0,0 +1,206 @@ +using TelegramDownloader.Models; + +namespace TelegramDownloader.Services.Archives +{ + /// + /// "Extract when the download finishes" for one download request: every + /// file the request downloads carries it. Files of the same request share + /// , which is how the volumes of a multi-volume archive + /// are known to belong together. The password lives in memory only. + /// + public sealed class AutoExtractTag + { + public AutoExtractTag(string groupId, bool deleteArchives, string? password = null) + { + GroupId = groupId; + DeleteArchives = deleteArchives; + Password = string.IsNullOrEmpty(password) ? null : password; + } + + public string GroupId { get; } + + /// Delete the archive (all its volumes) after a complete extraction. + public bool DeleteArchives { get; } + + /// Not persisted: after a restart a protected archive fails with password_required and is kept. + public string? Password { get; } + + public static AutoExtractTag New(bool deleteArchives, string? password) => + new(Guid.NewGuid().ToString("N"), deleteArchives, password); + } + + /// + /// The of the download request being queued, + /// flowing through the async calls of the download pipeline (which creates + /// the transfers deep inside), so its signature does not change. + /// + public static class AutoExtractScope + { + private static readonly AsyncLocal _current = new(); + + public static AutoExtractTag? Current => _current.Value; + + public static IDisposable Begin(AutoExtractTag? tag) + { + var previous = _current.Value; + _current.Value = tag; + return new Restore(previous); + } + + private sealed class Restore : IDisposable + { + private readonly AutoExtractTag? _previous; + public Restore(AutoExtractTag? previous) => _previous = previous; + public void Dispose() => _current.Value = _previous; + } + } + + /// + /// What the download pipeline tells about tagged files: queued + /// (), written completely () or + /// given up (: error or cancelled). Paths are absolute. + /// + public static class AutoExtractSignals + { + public static event Action? Expected; + public static event Action? Ready; + public static event Action? Abandoned; + + public static void RaiseExpected(string path, AutoExtractTag? tag) { if (tag != null) Expected?.Invoke(path, tag); } + public static void RaiseReady(string path, AutoExtractTag? tag) { if (tag != null) Ready?.Invoke(path, tag); } + public static void RaiseAbandoned(string path, AutoExtractTag? tag) { if (tag != null) Abandoned?.Invoke(path, tag); } + } + + /// + /// Decides when a downloaded archive can be extracted: a single archive as + /// soon as it is written; a multi-volume set once no volume of it is still + /// downloading in the same request (and the first volume is on disk). + /// Each set is extracted once per request. Pure logic: the extraction + /// itself is the start callback. + /// + public sealed class AutoExtractCoordinator + { + private enum State { Pending, Ready, Abandoned } + + private sealed class Group + { + public Group(AutoExtractTag tag) => Tag = tag; + public AutoExtractTag Tag { get; set; } + public Dictionary Files { get; } = new(StringComparer.OrdinalIgnoreCase); + public HashSet Started { get; } = new(StringComparer.OrdinalIgnoreCase); + public DateTime Touched { get; set; } + } + + private static readonly TimeSpan GroupLifetime = TimeSpan.FromDays(7); + + private readonly object _lock = new(); + private readonly Dictionary _groups = new(StringComparer.Ordinal); + private readonly Action _start; + private readonly Func _firstVolumeExists; + private readonly Func _clock; + + /// Extracts the archive that has the given absolute path among its volumes. + /// Whether the first volume of a set is in the folder (null: checks the disk). + public AutoExtractCoordinator(Action start, Func? firstVolumeExists = null, Func? clock = null) + { + _start = start; + _firstVolumeExists = firstVolumeExists ?? ((folder, set) => ArchiveNames.VolumesIn(folder, set).Count > 0); + _clock = clock ?? (() => DateTime.UtcNow); + } + + private Group GroupOf(AutoExtractTag tag) + { + if (!_groups.TryGetValue(tag.GroupId, out var group)) + { + group = new Group(tag); + _groups[tag.GroupId] = group; + } + // A resumed download brings a tag without the password: keep the one we had + if (group.Tag.Password == null && tag.Password != null) group.Tag = tag; + group.Touched = _clock(); + return group; + } + + public void Expected(string path, AutoExtractTag tag) + { + if (!ArchiveNames.IsArchive(path)) return; + lock (_lock) + { + Prune(); + GroupOf(tag).Files[Normalize(path)] = State.Pending; + } + } + + public void Abandoned(string path, AutoExtractTag tag) + { + if (!ArchiveNames.IsArchive(path)) return; + lock (_lock) GroupOf(tag).Files[Normalize(path)] = State.Abandoned; + } + + public void Ready(string path, AutoExtractTag tag) + { + var set = ArchiveNames.SetOf(path); + if (set == null) return; + path = Normalize(path); + var folder = Path.GetDirectoryName(path)!; + var setId = folder + "|" + set.Key; + string? first = null; + AutoExtractTag? startTag = null; + lock (_lock) + { + Prune(); + var group = GroupOf(tag); + group.Files[path] = State.Ready; + if (group.Started.Contains(setId)) return; + + // Another volume of the set is still on its way (or failed): wait for it + var siblings = group.Files.Where(f => string.Equals(Path.GetDirectoryName(f.Key), folder, StringComparison.OrdinalIgnoreCase) + && set.Contains(Path.GetFileName(f.Key))); + if (siblings.Any(f => f.Value != State.Ready)) return; + if (!_firstVolumeExists(folder, set)) return; + + group.Started.Add(setId); + first = path; // any volume: the extraction finds the first one + startTag = group.Tag; + } + _start(first!, startTag!); + } + + private static string Normalize(string path) => Path.GetFullPath(path); + + private void Prune() + { + var limit = _clock() - GroupLifetime; + foreach (var id in _groups.Where(g => g.Value.Touched < limit).Select(g => g.Key).ToList()) + _groups.Remove(id); + } + } + + /// Connects a single-file download with the auto-extraction. + public static class AutoExtractDownloads + { + /// + /// Marks with and tells + /// the auto-extraction about it: expected now, ready once its run ended + /// completed (the file is closed), abandoned when it fails or is + /// canceled. A retry that later completes still makes it ready. + /// Nothing happens without a tag. + /// + public static void Attach(DownloadModel model, string destPath, AutoExtractTag? tag) + { + if (tag == null) return; + model.AutoExtract = tag; + AutoExtractSignals.RaiseExpected(destPath, tag); + model.RunFinished += (s, e) => + { + if (model.state == StateTask.Completed) AutoExtractSignals.RaiseReady(destPath, tag); + else if (model.state == StateTask.Error || model.state == StateTask.Canceled) AutoExtractSignals.RaiseAbandoned(destPath, tag); + }; + // Canceled while still queued: it never runs + model.EventStatechanged += (s, e) => + { + if (model.state == StateTask.Canceled && !model.IsRunning) AutoExtractSignals.RaiseAbandoned(destPath, tag); + }; + } + } +} diff --git a/TelegramDownloader/Services/Archives/AutoExtractService.cs b/TelegramDownloader/Services/Archives/AutoExtractService.cs new file mode 100644 index 0000000..6b00e7a --- /dev/null +++ b/TelegramDownloader/Services/Archives/AutoExtractService.cs @@ -0,0 +1,73 @@ +using TelegramDownloader.Data; +using TelegramDownloader.Models; +using TelegramDownloader.Services.Api; + +namespace TelegramDownloader.Services.Archives +{ + /// + /// Connects the download pipeline () with + /// the extractions: archives downloaded with "extract when finished" are + /// extracted into a folder named after them, next to them, and deleted + /// afterwards when the request asked for it and nothing failed. + /// + public sealed class AutoExtractService : IHostedService + { + private readonly ArchiveOperationService _archives; + private readonly ILogger _logger; + private readonly AutoExtractCoordinator _coordinator; + + public AutoExtractService(ArchiveOperationService archives, ILogger logger) + { + _archives = archives; + _logger = logger; + _coordinator = new AutoExtractCoordinator(Start); + } + + public Task StartAsync(CancellationToken cancellationToken) + { + AutoExtractSignals.Expected += OnExpected; + AutoExtractSignals.Ready += OnReady; + AutoExtractSignals.Abandoned += OnAbandoned; + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + AutoExtractSignals.Expected -= OnExpected; + AutoExtractSignals.Ready -= OnReady; + AutoExtractSignals.Abandoned -= OnAbandoned; + return Task.CompletedTask; + } + + private void OnExpected(string path, AutoExtractTag tag) => Safe(() => _coordinator.Expected(path, tag)); + private void OnReady(string path, AutoExtractTag tag) => Safe(() => _coordinator.Ready(path, tag)); + private void OnAbandoned(string path, AutoExtractTag tag) => Safe(() => _coordinator.Abandoned(path, tag)); + + private void Safe(Action action) + { + try { action(); } + catch (Exception ex) { _logger.LogWarning(ex, "Auto-extract bookkeeping failed"); } + } + + private void Start(string archivePath, AutoExtractTag tag) + { + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(FileService.LOCALDIR)); + var absolute = Path.GetFullPath(archivePath); + if (!LocalPathGuard.IsSameOrInside(root, absolute)) + { + _logger.LogWarning("Not extracting {Path}: it is outside the local files", archivePath); + new NotificationModel().sendEvent(new Notification($"{Path.GetFileName(archivePath)} is outside the local files", "Extraction skipped", NotificationTypes.Warn)); + return; + } + var relative = Path.GetRelativePath(root, absolute).Replace('\\', '/'); + _logger.LogInformation("Extracting downloaded archive {Path}", relative); + _archives.StartExtract(root, relative, new ExtractRequestOptions + { + IntoFolder = true, + Overwrite = OverwriteMode.Rename, + Password = tag.Password, + DeleteArchive = tag.DeleteArchives + }, automatic: true); + } + } +} diff --git a/TelegramDownloader/Services/Archives/SevenZipTool.cs b/TelegramDownloader/Services/Archives/SevenZipTool.cs new file mode 100644 index 0000000..4d140b0 --- /dev/null +++ b/TelegramDownloader/Services/Archives/SevenZipTool.cs @@ -0,0 +1,110 @@ +using System.Diagnostics; +using System.Text; +using System.Text.RegularExpressions; + +namespace TelegramDownloader.Services.Archives +{ + /// + /// The 7-Zip command line (7zz, 7z or 7za), when the + /// server has it: it is what creates .7z archives. Looked up once in + /// TFM_7ZIP_PATH, the PATH and the default Windows folder. The Docker + /// image installs it unless built with INCLUDE_7ZIP=false. + /// + public static class SevenZipTool + { + private static readonly Lazy _path = new(Locate); + private static readonly Regex Percent = new(@"(\d{1,3})%", RegexOptions.Compiled); + + /// Full path of the executable, or null when the server has none. + public static string? Path => _path.Value; + + public static bool Available => Path != null; + + private static string? Locate() + { + var configured = Environment.GetEnvironmentVariable("TFM_7ZIP_PATH"); + if (!string.IsNullOrWhiteSpace(configured) && File.Exists(configured)) return configured; + + var names = OperatingSystem.IsWindows() ? new[] { "7zz.exe", "7z.exe", "7za.exe" } : new[] { "7zz", "7z", "7za" }; + var dirs = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(System.IO.Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + foreach (var name in names) + foreach (var dir in dirs) + { + try + { + var candidate = System.IO.Path.Combine(dir.Trim('"'), name); + if (File.Exists(candidate)) return candidate; + } + catch { /* malformed PATH entry */ } + } + + if (OperatingSystem.IsWindows()) + { + foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 }) + { + var candidate = System.IO.Path.Combine(Environment.GetFolderPath(folder), "7-Zip", "7z.exe"); + if (File.Exists(candidate)) return candidate; + } + } + return null; + } + + /// + /// Creates a 7z archive at with the files + /// (relative to ), + /// reporting the percentage. Killed on cancellation. + /// + public static async Task CreateAsync(string workingFolder, IReadOnlyList entries, string output, int level, + Action onPercent, CancellationToken ct) + { + var exe = Path ?? throw new ArchiveOperationException(ArchiveErrorCodes.ToolMissing, "7-Zip is not installed on the server"); + var listFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"tfm-7z-{Guid.NewGuid():N}.txt"); + await File.WriteAllLinesAsync(listFile, entries, new UTF8Encoding(false), ct); + try + { + var psi = new ProcessStartInfo(exe) + { + WorkingDirectory = workingFolder, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8 + }; + foreach (var arg in new[] { "a", "-t7z", $"-mx={level}", "-bsp1", "-bso0", "-bse2", "-y", "-scsUTF-8", output, "@" + listFile }) + psi.ArgumentList.Add(arg); + + using var process = new Process { StartInfo = psi }; + var errors = new StringBuilder(); + process.Start(); + using var registration = ct.Register(() => + { + try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { } + }); + + var readOut = Task.Run(async () => + { + var buffer = new char[256]; + int read; + while ((read = await process.StandardOutput.ReadAsync(buffer, 0, buffer.Length)) > 0) + { + var matches = Percent.Matches(new string(buffer, 0, read)); + if (matches.Count > 0 && int.TryParse(matches[^1].Groups[1].Value, out var p)) onPercent(Math.Clamp(p, 0, 100)); + } + }); + var readErr = Task.Run(async () => errors.Append(await process.StandardError.ReadToEndAsync())); + await process.WaitForExitAsync(CancellationToken.None); + await Task.WhenAll(readOut, readErr); + ct.ThrowIfCancellationRequested(); + // 0 = ok, 1 = warnings (some file could not be read), anything else = fatal + if (process.ExitCode > 1) + throw new ArchiveOperationException(ArchiveErrorCodes.Corrupt, $"7-Zip failed ({process.ExitCode}): {errors.ToString().Trim()}"); + } + finally + { + try { File.Delete(listFile); } catch { } + } + } + } +} diff --git a/TelegramDownloader/TelegramDownloader.csproj b/TelegramDownloader/TelegramDownloader.csproj index ca800e4..f6a560d 100644 --- a/TelegramDownloader/TelegramDownloader.csproj +++ b/TelegramDownloader/TelegramDownloader.csproj @@ -35,6 +35,7 @@ + diff --git a/Test/ArchivesTest.cs b/Test/ArchivesTest.cs new file mode 100644 index 0000000..7e9d9dd --- /dev/null +++ b/Test/ArchivesTest.cs @@ -0,0 +1,593 @@ +using System.Formats.Tar; +using System.IO.Compression; +using TelegramDownloader.Controllers.Api.V1; +using TelegramDownloader.Services.Archives; + +namespace Test +{ + /// Recognising archives and the volumes of multi-volume sets by name. + public class ArchiveNamesTest + { + private string _dir = null!; + + [SetUp] + public void SetUp() => _dir = Directory.CreateTempSubdirectory("tfm-names-").FullName; + + [TearDown] + public void TearDown() => Directory.Delete(_dir, true); + + private void Touch(params string[] names) + { + foreach (var n in names) File.WriteAllText(Path.Combine(_dir, n), "x"); + } + + [TestCase("Fotos.zip", "Fotos")] + [TestCase("Disco.rar", "Disco")] + [TestCase("Backup.7z", "Backup")] + [TestCase("src.tar.gz", "src")] + [TestCase("src.tgz", "src")] + public void A_single_archive_is_named_after_its_file(string name, string baseName) + { + var set = ArchiveNames.SetOf(name)!; + Assert.That(set.BaseName, Is.EqualTo(baseName)); + Assert.That(set.FirstVolume, Is.EqualTo(name)); + Assert.That(set.IsMultiVolume, Is.False); + } + + [TestCase("notes.txt")] + [TestCase("song.mp3")] + [TestCase("")] + public void Other_files_are_not_archives(string name) + { + Assert.That(ArchiveNames.IsArchive(name), Is.False); + } + + [Test] + public void The_parts_of_a_rar_set_belong_together() + { + var one = ArchiveNames.SetOf("Peli.part1.rar")!; + var two = ArchiveNames.SetOf("Peli.part2.rar")!; + Assert.That(two.Key, Is.EqualTo(one.Key)); + Assert.That(two.FirstVolume, Is.EqualTo("Peli.part1.rar")); + Assert.That(two.BaseName, Is.EqualTo("Peli")); + } + + [Test] + public void Numbered_7z_volumes_belong_together() + { + Assert.That(ArchiveNames.SetOf("a.7z.002")!.Key, Is.EqualTo(ArchiveNames.SetOf("a.7z.001")!.Key)); + Assert.That(ArchiveNames.SetOf("a.7z.002")!.FirstVolume, Is.EqualTo("a.7z.001")); + } + + [Test] + public void Old_style_rar_volumes_start_at_the_rar_file() + { + var set = ArchiveNames.SetOf("Disco.r00")!; + Assert.That(set.Key, Is.EqualTo(ArchiveNames.SetOf("Disco.rar")!.Key)); + Assert.That(set.FirstVolume, Is.EqualTo("Disco.rar")); + } + + [Test] + public void Volumes_are_read_in_order_whatever_the_zero_padding() + { + Touch("v.part10.rar", "v.part2.rar", "v.part1.rar", "other.part1.rar"); + var volumes = ArchiveNames.VolumesIn(_dir, ArchiveNames.SetOf("v.part10.rar")!); + Assert.That(volumes.Select(v => v.Name), Is.EqualTo(new[] { "v.part1.rar", "v.part2.rar", "v.part10.rar" })); + } + + [Test] + public void A_set_without_its_first_volume_has_no_volumes() + { + Touch("v.part2.rar", "v.part3.rar"); + Assert.That(ArchiveNames.VolumesIn(_dir, ArchiveNames.SetOf("v.part2.rar")!), Is.Empty); + } + + [Test] + public void A_split_zip_ends_with_the_zip_file() + { + Touch("s.zip", "s.z02", "s.z01"); + var volumes = ArchiveNames.VolumesIn(_dir, ArchiveNames.SetOf("s.z01")!); + Assert.That(volumes.Select(v => v.Name), Is.EqualTo(new[] { "s.z01", "s.z02", "s.zip" })); + } + } + + /// Base of the tests that need a folder and run operations. + public abstract class ArchiveTestBase + { + protected string Dir = null!; + protected static string Fixture(string name) => Path.Combine(TestContext.CurrentContext.TestDirectory, "Fixtures", "Archives", name); + + [SetUp] + public void CreateDir() => Dir = Directory.CreateTempSubdirectory("tfm-archive-").FullName; + + [TearDown] + public void DeleteDir() + { + try { Directory.Delete(Dir, true); } catch { } + } + + protected static ArchiveOperation NewOperation() => new(ArchiveKinds.Extract, "test", null, false); + + protected string Copy(string fixture) + { + var target = Path.Combine(Dir, fixture); + File.Copy(Fixture(fixture), target); + return target; + } + + protected static IReadOnlyList Volumes(string path) => + ArchiveNames.VolumesIn(Path.GetDirectoryName(path)!, ArchiveNames.SetOf(path)!); + + protected Task Extract(string archive, string destination, ExtractOptions? options = null, ArchiveOperation? operation = null) => + ArchiveExtractor.ExtractAsync(Volumes(archive), destination, options ?? new ExtractOptions(), operation ?? NewOperation(), CancellationToken.None); + + protected string MakeZip(string name, params (string Entry, string Text)[] entries) + { + var path = Path.Combine(Dir, name); + using var zip = ZipFile.Open(path, ZipArchiveMode.Create); + foreach (var (entry, text) in entries) + { + using var w = new StreamWriter(zip.CreateEntry(entry).Open()); + w.Write(text); + } + return path; + } + + protected static async Task Finished(ArchiveOperation operation) + { + await operation.Completion.WaitAsync(TimeSpan.FromSeconds(30)); + return operation; + } + } + + /// Extracting: formats, volumes, passwords and the safety rules. + public class ArchiveExtractorTest : ArchiveTestBase + { + [Test] + public async Task Extracts_a_7z_with_its_folders() + { + var archive = Copy("plain.7z"); + await Extract(archive, Path.Combine(Dir, "out")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "album", "readme.txt")), Is.EqualTo("Hola mundo\n")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "album", "disc 2", "track.txt")), Is.EqualTo("pista dos\n")); + } + + [Test] + public async Task Extracts_a_multi_volume_7z_from_any_volume() + { + Copy("multi.7z.001"); + Copy("multi.7z.002"); + var last = Copy("multi.7z.003"); + await Extract(last, Path.Combine(Dir, "out")); + Assert.That(new FileInfo(Path.Combine(Dir, "out", "big.bin")).Length, Is.EqualTo(40000)); + Assert.That(File.Exists(Path.Combine(Dir, "out", "album", "readme.txt")), Is.True); + } + + [Test] + public void A_missing_volume_stops_with_missing_volume() + { + Copy("multi.7z.001"); + var third = Copy("multi.7z.003"); + var ex = Assert.ThrowsAsync(() => Extract(third, Path.Combine(Dir, "out"))); + Assert.That(ex!.Code, Is.AnyOf(ArchiveErrorCodes.MissingVolume, ArchiveErrorCodes.Corrupt)); + } + + [Test] + public void A_protected_archive_without_password_asks_for_it() + { + var archive = Copy("secret.7z"); + var ex = Assert.ThrowsAsync(() => Extract(archive, Path.Combine(Dir, "out"))); + Assert.That(ex!.Code, Is.EqualTo(ArchiveErrorCodes.PasswordRequired)); + } + + [Test] + public void A_wrong_password_is_reported() + { + var archive = Copy("secret.zip"); + var ex = Assert.ThrowsAsync(() => Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { Password = "nope" })); + Assert.That(ex!.Code, Is.EqualTo(ArchiveErrorCodes.WrongPassword)); + } + + [Test] + public void A_wrong_password_for_encrypted_names_is_reported() + { + var archive = Copy("secret.7z"); + var ex = Assert.ThrowsAsync(() => Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { Password = "nope" })); + Assert.That(ex!.Code, Is.EqualTo(ArchiveErrorCodes.WrongPassword)); + } + + [Test] + public async Task Extracts_an_aes_zip_with_its_password() + { + var archive = Copy("secret.zip"); + await Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { Password = "1234" }); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "album", "readme.txt")), Is.EqualTo("Hola mundo\n")); + } + + [Test] + public async Task Extracts_a_7z_with_encrypted_names_with_its_password() + { + var archive = Copy("secret.7z"); + await Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { Password = "1234" }); + Assert.That(File.Exists(Path.Combine(Dir, "out", "album", "disc 2", "track.txt")), Is.True); + } + + [Test] + public async Task Entries_that_climb_out_of_the_destination_are_not_written() + { + var archive = MakeZip("evil.zip", ("../escaped.txt", "x"), ("ok.txt", "fine"), ("a/../../also.txt", "x")); + var operation = NewOperation(); + await Extract(archive, Path.Combine(Dir, "out"), operation: operation); + Assert.That(File.Exists(Path.Combine(Dir, "escaped.txt")), Is.False); + Assert.That(File.Exists(Path.Combine(Dir, "also.txt")), Is.False); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "ok.txt")), Is.EqualTo("fine")); + Assert.That(operation.Snapshot().FailedCount, Is.EqualTo(2)); + } + + [Test] + public void Absolute_entry_paths_are_refused() + { + Assert.That(ArchiveExtractor.TryTargetPath(Dir, "/etc/passwd", out _, out var reason), Is.False); + Assert.That(reason, Is.Not.Null); + Assert.That(ArchiveExtractor.TryTargetPath(Dir, "C:/Windows/x.dll", out _, out _), Is.False); + } + + [Test] + public async Task Links_in_a_tar_are_not_created() + { + var path = Path.Combine(Dir, "links.tar"); + using (var file = File.Create(path)) + using (var tar = new TarWriter(file, TarEntryFormat.Pax)) + { + tar.WriteEntry(new PaxTarEntry(TarEntryType.SymbolicLink, "passwd") { LinkName = "/etc/passwd" }); + tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, "real.txt") { DataStream = new MemoryStream("ok"u8.ToArray()) }); + } + var operation = NewOperation(); + await Extract(path, Path.Combine(Dir, "out"), operation: operation); + Assert.That(File.Exists(Path.Combine(Dir, "out", "passwd")), Is.False); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "real.txt")), Is.EqualTo("ok")); + Assert.That(operation.Snapshot().Failed.Single().Reason, Does.Contain("Links")); + } + + [Test] + public void Stops_before_starting_when_the_disk_has_no_room() + { + var archive = MakeZip("big.zip", ("a.txt", new string('a', 10_000))); + var ex = Assert.ThrowsAsync(() => + Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { FreeSpace = 5_000, ReserveBytes = 0 })); + Assert.That(ex!.Code, Is.EqualTo(ArchiveErrorCodes.NotEnoughSpace)); + Assert.That(File.Exists(Path.Combine(Dir, "out", "a.txt")), Is.False); + } + + [Test] + public async Task Existing_files_are_kept_and_the_new_one_renamed_by_default() + { + var archive = MakeZip("a.zip", ("note.txt", "new")); + Directory.CreateDirectory(Path.Combine(Dir, "out")); + File.WriteAllText(Path.Combine(Dir, "out", "note.txt"), "old"); + await Extract(archive, Path.Combine(Dir, "out")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "note.txt")), Is.EqualTo("old")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "note (1).txt")), Is.EqualTo("new")); + } + + [Test] + public async Task Skip_leaves_existing_files_alone() + { + var archive = MakeZip("a.zip", ("note.txt", "new")); + Directory.CreateDirectory(Path.Combine(Dir, "out")); + File.WriteAllText(Path.Combine(Dir, "out", "note.txt"), "old"); + await Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { Overwrite = OverwriteMode.Skip }); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "note.txt")), Is.EqualTo("old")); + Assert.That(File.Exists(Path.Combine(Dir, "out", "note (1).txt")), Is.False); + } + + [Test] + public async Task Overwrite_replaces_existing_files() + { + var archive = MakeZip("a.zip", ("note.txt", "new")); + Directory.CreateDirectory(Path.Combine(Dir, "out")); + File.WriteAllText(Path.Combine(Dir, "out", "note.txt"), "old"); + await Extract(archive, Path.Combine(Dir, "out"), new ExtractOptions { Overwrite = OverwriteMode.Overwrite }); + Assert.That(File.ReadAllText(Path.Combine(Dir, "out", "note.txt")), Is.EqualTo("new")); + } + + [Test] + public async Task Reports_the_totals_and_the_progress() + { + var archive = MakeZip("a.zip", ("one.txt", "12345"), ("two.txt", "123")); + var operation = NewOperation(); + await Extract(archive, Path.Combine(Dir, "out"), operation: operation); + var s = operation.Snapshot(); + Assert.That((s.TotalFiles, s.TotalBytes, s.ProcessedFiles, s.ProcessedBytes), Is.EqualTo((2, 8L, 2, 8L))); + } + + [Test] + public void A_damaged_file_is_reported_as_not_an_archive_or_corrupt() + { + var path = Path.Combine(Dir, "broken.zip"); + File.WriteAllText(path, "this is not a zip file at all"); + var ex = Assert.ThrowsAsync(() => Extract(path, Path.Combine(Dir, "out"))); + Assert.That(ex!.Code, Is.AnyOf(ArchiveErrorCodes.Unsupported, ArchiveErrorCodes.Corrupt)); + } + + [Test] + public void Lists_the_entries_and_totals_without_extracting() + { + var listing = ArchiveExtractor.List(Volumes(Copy("plain.7z")), null); + Assert.That(listing.Format, Is.EqualTo("7z")); + Assert.That(listing.FileCount, Is.EqualTo(2)); + Assert.That(listing.TotalSize, Is.EqualTo(21)); + Assert.That(listing.Entries.Select(e => e.Path), Does.Contain("album/disc 2/track.txt")); + Assert.That(Directory.GetFiles(Dir), Has.Length.EqualTo(1)); + } + + [Test] + public void Listing_an_archive_with_encrypted_names_needs_the_password() + { + var ex = Assert.Throws(() => ArchiveExtractor.List(Volumes(Copy("secret.7z")), null)); + Assert.That(ex!.Code, Is.EqualTo(ArchiveErrorCodes.PasswordRequired)); + } + } + + /// Compressing and the background operations around both. + public class ArchiveOperationServiceTest : ArchiveTestBase + { + private ArchiveOperationService _service = null!; + + [SetUp] + public void CreateService() => _service = new ArchiveOperationService(new ArchiveOperationRegistry(), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + + private void Folder(string path, params (string Name, string Text)[] files) + { + Directory.CreateDirectory(Path.Combine(Dir, path)); + foreach (var (name, text) in files) File.WriteAllText(Path.Combine(Dir, path, name), text); + } + + [Test] + public async Task Extracts_into_a_folder_named_after_the_archive() + { + Copy("plain.7z"); + var operation = await Finished(_service.StartExtract(Dir, "plain.7z", new ExtractRequestOptions())); + Assert.That(operation.Phase, Is.EqualTo(ArchivePhases.Done)); + Assert.That(operation.Destination, Is.EqualTo("plain")); + Assert.That(File.Exists(Path.Combine(Dir, "plain", "album", "readme.txt")), Is.True); + } + + [Test] + public async Task Deletes_every_volume_after_a_complete_extraction_when_asked() + { + Copy("multi.7z.001"); + Copy("multi.7z.002"); + Copy("multi.7z.003"); + var operation = await Finished(_service.StartExtract(Dir, "multi.7z.002", new ExtractRequestOptions { DeleteArchive = true })); + Assert.That(operation.Snapshot().ArchivesDeleted, Is.True); + Assert.That(Directory.GetFiles(Dir), Is.Empty); + Assert.That(File.Exists(Path.Combine(Dir, "multi", "big.bin")), Is.True); + } + + [Test] + public async Task Keeps_the_archive_when_an_entry_failed() + { + MakeZip("evil.zip", ("../x.txt", "x"), ("ok.txt", "ok")); + var operation = await Finished(_service.StartExtract(Dir, "evil.zip", new ExtractRequestOptions { DeleteArchive = true })); + Assert.That(operation.Snapshot().ArchivesDeleted, Is.False); + Assert.That(File.Exists(Path.Combine(Dir, "evil.zip")), Is.True); + } + + [Test] + public async Task A_failed_extraction_keeps_the_archive_and_says_why() + { + Copy("secret.7z"); + var operation = await Finished(_service.StartExtract(Dir, "secret.7z", new ExtractRequestOptions { DeleteArchive = true })); + var s = operation.Snapshot(); + Assert.That((s.Phase, s.ErrorCode), Is.EqualTo((ArchivePhases.Failed, ArchiveErrorCodes.PasswordRequired))); + Assert.That(File.Exists(Path.Combine(Dir, "secret.7z")), Is.True); + } + + [Test] + public async Task Refuses_an_archive_outside_the_root() + { + var operation = await Finished(_service.StartExtract(Dir, "../elsewhere.zip", new ExtractRequestOptions())); + Assert.That(operation.Snapshot().ErrorCode, Is.EqualTo(ArchiveErrorCodes.NotFound)); + } + + [TestCase(CompressFormats.Zip)] + [TestCase(CompressFormats.TarGz)] + public async Task A_compressed_folder_extracts_back_the_same(string format) + { + Folder("docs/sub", ("b.txt", "bee")); + Folder("docs", ("a.txt", "ay")); + var compress = await Finished(_service.StartCompress(Dir, new[] { "docs" }, new CompressRequestOptions { Format = format })); + Assert.That(compress.Phase, Is.EqualTo(ArchivePhases.Done), compress.Snapshot().Error); + Assert.That(compress.Destination, Is.EqualTo("docs" + CompressFormats.Extension(format))); + + await Extract(Path.Combine(Dir, compress.Destination!), Path.Combine(Dir, "back")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "back", "docs", "a.txt")), Is.EqualTo("ay")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "back", "docs", "sub", "b.txt")), Is.EqualTo("bee")); + } + + [Test] + public async Task Creates_7z_archives_with_7zip() + { + if (!SevenZipTool.Available) Assert.Ignore("7-Zip is not installed"); + Folder("docs", ("a.txt", "ay")); + var compress = await Finished(_service.StartCompress(Dir, new[] { "docs/a.txt" }, new CompressRequestOptions { Format = CompressFormats.SevenZip })); + Assert.That(compress.Phase, Is.EqualTo(ArchivePhases.Done), compress.Snapshot().Error); + await Extract(Path.Combine(Dir, "docs", "a.7z"), Path.Combine(Dir, "back")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "back", "a.txt")), Is.EqualTo("ay")); + } + + [Test] + public async Task A_taken_name_gets_a_number() + { + Folder("docs", ("a.txt", "ay")); + File.WriteAllText(Path.Combine(Dir, "docs", "a.zip"), "already here"); + var compress = await Finished(_service.StartCompress(Dir, new[] { "docs/a.txt" }, new CompressRequestOptions())); + Assert.That(compress.Destination, Is.EqualTo("docs/a (1).zip")); + Assert.That(File.ReadAllText(Path.Combine(Dir, "docs", "a.zip")), Is.EqualTo("already here")); + } + + [Test] + public async Task Several_items_are_named_after_their_folder() + { + Folder("Vacaciones", ("1.jpg", "1"), ("2.jpg", "2")); + var compress = await Finished(_service.StartCompress(Dir, new[] { "Vacaciones/1.jpg", "Vacaciones/2.jpg" }, new CompressRequestOptions())); + Assert.That(compress.Destination, Is.EqualTo("Vacaciones/Vacaciones.zip")); + } + + [Test] + public async Task A_cancelled_compression_leaves_no_archive() + { + Folder("docs", ("a.txt", new string('a', 1000))); + var registry = new ArchiveOperationRegistry(); + var blocker = new TaskCompletionSource(); + // Holds the queue so the compression is still queued when cancelled + registry.Start(ArchiveKinds.Extract, "blocker", null, false, (_, _) => blocker.Task); + var service = new ArchiveOperationService(registry, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + var compress = service.StartCompress(Dir, new[] { "docs" }, new CompressRequestOptions()); + compress.Cancel(); + blocker.SetResult(); + await Finished(compress); + Assert.That(compress.Phase, Is.EqualTo(ArchivePhases.Cancelled)); + Assert.That(Directory.GetFiles(Dir, "*.zip*", SearchOption.AllDirectories), Is.Empty); + } + + [Test] + public async Task Operations_run_one_at_a_time() + { + var registry = new ArchiveOperationRegistry(); + var first = new TaskCompletionSource(); + var a = registry.Start(ArchiveKinds.Extract, "a", null, false, (_, _) => first.Task); + var b = registry.Start(ArchiveKinds.Extract, "b", null, false, (_, _) => Task.CompletedTask); + await Task.Delay(100); + Assert.That(b.Phase, Is.EqualTo(ArchivePhases.Queued)); + first.SetResult(); + await Finished(b); + Assert.That((a.Phase, b.Phase), Is.EqualTo((ArchivePhases.Done, ArchivePhases.Done))); + } + } + + /// When a downloaded archive is extracted. + public class AutoExtractCoordinatorTest + { + private readonly List _started = new(); + private readonly HashSet _onDisk = new(StringComparer.OrdinalIgnoreCase); + private AutoExtractCoordinator _coordinator = null!; + private static readonly string Folder = Path.Combine(Path.GetTempPath(), "dl"); + private static string P(string name) => Path.Combine(Folder, name); + + [SetUp] + public void SetUp() + { + _started.Clear(); + _onDisk.Clear(); + _coordinator = new AutoExtractCoordinator((path, _) => _started.Add(Path.GetFileName(path)), + (folder, set) => _onDisk.Contains(set.FirstVolume) || _onDisk.Any(n => set.Contains(n) && ArchiveNames.VolumeNumber(n) == 1)); + } + + private void Download(AutoExtractTag tag, params string[] names) + { + foreach (var n in names) _coordinator.Expected(P(n), tag); + } + + private void Finish(AutoExtractTag tag, string name) + { + _onDisk.Add(name); + _coordinator.Ready(P(name), tag); + } + + [Test] + public void A_single_archive_is_extracted_when_it_finishes() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "fotos.zip"); + Finish(tag, "fotos.zip"); + Assert.That(_started, Is.EqualTo(new[] { "fotos.zip" })); + } + + [Test] + public void A_multi_volume_set_waits_for_its_last_volume() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "peli.part1.rar", "peli.part2.rar", "peli.part3.rar"); + Finish(tag, "peli.part3.rar"); + Finish(tag, "peli.part1.rar"); + Assert.That(_started, Is.Empty); + Finish(tag, "peli.part2.rar"); + Assert.That(_started, Has.Count.EqualTo(1)); + } + + [Test] + public void A_failed_volume_keeps_the_set_from_being_extracted() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "a.7z.001", "a.7z.002"); + _coordinator.Abandoned(P("a.7z.002"), tag); + Finish(tag, "a.7z.001"); + Assert.That(_started, Is.Empty); + } + + [Test] + public void A_retried_volume_that_completes_releases_the_set() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "a.7z.001", "a.7z.002"); + _coordinator.Abandoned(P("a.7z.002"), tag); + Finish(tag, "a.7z.001"); + Finish(tag, "a.7z.002"); + Assert.That(_started, Has.Count.EqualTo(1)); + } + + [Test] + public void A_set_is_extracted_once() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "x.zip"); + Finish(tag, "x.zip"); + _coordinator.Ready(P("x.zip"), tag); + Assert.That(_started, Has.Count.EqualTo(1)); + } + + [Test] + public void Waits_for_the_first_volume_when_it_is_not_on_disk() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "b.part2.rar"); + Finish(tag, "b.part2.rar"); + Assert.That(_started, Is.Empty); + } + + [Test] + public void Other_files_of_the_download_are_ignored() + { + var tag = AutoExtractTag.New(false, null); + Download(tag, "song.mp3", "y.zip"); + Finish(tag, "y.zip"); + Assert.That(_started, Is.EqualTo(new[] { "y.zip" })); + } + + [Test] + public void A_resumed_volume_keeps_the_password_of_its_request() + { + AutoExtractTag? used = null; + var coordinator = new AutoExtractCoordinator((_, t) => used = t, (_, _) => true); + var original = new AutoExtractTag("g1", true, "secret"); + coordinator.Expected(P("c.zip"), original); + coordinator.Ready(P("c.zip"), new AutoExtractTag("g1", true)); + Assert.That(used!.Password, Is.EqualTo("secret")); + } + } + + /// The local folder a channel download goes to when the channel folders are kept. + public class TransfersTargetFolderTest + { + [TestCase("/music/rock/", "music/rock")] + [TestCase("/", "")] + [TestCase("Files/", "")] + [TestCase(null, "")] + public void Channel_folders_map_to_local_folders(string? filterPath, string expected) + { + Assert.That(TransfersController.ChannelFolderOf(filterPath), Is.EqualTo(expected)); + } + } +} diff --git a/Test/Fixtures/Archives/multi.7z.001 b/Test/Fixtures/Archives/multi.7z.001 new file mode 100644 index 0000000000000000000000000000000000000000..ca1182f689fe7d3ebd5964ce58aa5d60534b080c GIT binary patch literal 16384 zcmV+bK>xotdc3bE8~_C75BZz%oB#j-0000a0000000012k{YIPX>)X8AY^ZI3P^8k zVIXaFZe(u?vjal3objRRi?@_(wv}F41NAm=#e7VJM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gO@^wt19?$L3jJ*-BVOy8w$jyydv1`X63!CmI_i8Jqz^PI;u+x(|mAn z^|GY{tFPwEx99S3iUhV0MU6C+^J;J*E!pCW@duK+Rzfz<=aMYNuJBd(@fLL-nxCT) z^X87i=PS~$w0+u*`Um$pkT*S;{Iy)V4R@PM4{j5Q23YhTbu%&%URu7mn2@mM>fPt{ znRiZe^5OvU#F%o7JZ9sFA-%9++WW3nXEr=&#&#h21sflkl<^tZ{3b#U<69grjprn>jNLXS^7tZ|G zRNlI{nQMG_B6UZccT(CmQ|WZJ2w498h&wP?@c!Rt#hv7UcbDp_?QjX)qOQ4O0u=!y OjBe57I_+AiGi+8(q^=wQ literal 0 HcmV?d00001 diff --git a/Test/Fixtures/Archives/multi.7z.002 b/Test/Fixtures/Archives/multi.7z.002 new file mode 100644 index 0000000000000000000000000000000000000000..aa3f037ac3e913ece735822548b273bf69071a99 GIT binary patch literal 16384 zcmV+bK>xq4ys_6bRr9r#NXxfsi03 z?o}b1IL8=4g(~@UAjRzSf|U)BE>9tL&Tx$_VxApCJLWw>K+2Z131le7ds0YLy zloAqRc-)havLLJJAW2jZ6WuLsLw-Lbp7O{1ocm$fq_u(i*r~;;jVRM7sF=HF#9TU4 z?4*tmu{9V@9}+D~$WFYri-xwN?2oBRzWEF|_8KR=;3q*~d0O*3q8tF+oi_cI4L}ja zA7?m~#tJd!{UxC_aNAjRJNd>yS&rN!;=+I6Yp$hn$w*ldYDG72ydmG3CYw83A`?98 zZQ6{r&8_0yD;nIFs~Pv!<>~8bzQD@@i>#d8+IVxTg<*V=XhG{Yf*GE1 zIdFs;jbRIe0EJhCL@|UA&_JD5)HV4vTS*81n!FDhtVFu!UGQWyR%7BNu?i3vDha6! zNF^1-$^?52_;CQ_y)|7uWh)*{fghZR)OQSIG9r&mquK}`JJP%c5C^A*T}(lt7E+$Z z{c+Mz8VVBV?NlxjV5h1Tr zyM8DEFaBhp)9_}%#}9f)LzZAS$fXcS2&9*-fh&Xy1=eOi=72as)vpS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pTP8N@Utg9d@)@M1zaD)7Hs!+3rALB4JWH|ou~ zAtQG%e-=PZ290c^m$+sJxrib!0iejAr1`*{p!N)g%BXj%arj)XAZ%m??g-0Z$*B6i zR)uaCGWg=#rbUJks*XNsPzAD7K6l+E-qE}&0mYTCj}2w8Xt$Z9;>_rW{IdU0&XdY`frj%4zim&ks#FC z4xBkh)V^cJKV5yOIy#o_3#|vaK)+0faeSAR;U#`c4T`?vVsRkRdoFynRJk|CM=&0x zv!L=~kV)!fL-bLJmm3I?J^g(`dFX_Api^=TSgYn91f&E4J-L*8Na(>t2gsoh0`(o{ z8=ZVVqWvRjDJnv6{sgjmXgTgK*E`je4dtQ&D62{Q2O6&8!bsRTYiS;x-lnBy{}_lr z9Zl!c`3oTQ1?)z=Stg7k^@Ec%C=q9!@|+9GsTmbGR37aSrJfOnvRn~lx+n^;Q?Zfp z@xX0{91ia#;#5Quil|B+cw4EpfnNFU@g7vphU5?JGLlnwN1%HP#$MK#n9A}jmiSfT zI~IrajW{ND&8$it{BG}f==y!nfg$#2ZEa1i`6odLxm_~A6v2t_2}V^bWGLHnLoLvp z8T8eQIdrOy#A;_*L1Sj)^e3V^#E$(NXcEK;4VgOIg}wM`Ml)jy@0w3 z_Q8HotRz?Ch>>D(=F({~9_*AdDh+& z>AOp@v2sUmryWb`004nA2d+<_2Hg)`y$6cTkCB?Dqu0HuAe|d|uaO01SZ=3ISdzH$DIWA?aFX literal 0 HcmV?d00001 diff --git a/Test/Fixtures/Archives/plain.7z b/Test/Fixtures/Archives/plain.7z new file mode 100644 index 0000000000000000000000000000000000000000..a61614e14bb19a4c5244a8d90b90172a9cdb021d GIT binary patch literal 229 zcmXr7+Ou9=hJnRRL3zt!1_)4s($DjcwJ|b?6l4~cBr2rj7jt>!=OilRmgc48a{-k! z8ndtCKR+oif&cZZIs46Q{}rAJ{KUBJ(1~5=J*8f5jlIGZFRXG0eQJ2xW( aqcSriBWo;!00RS0!!s_%_?^;%3=9B;jab3} literal 0 HcmV?d00001 diff --git a/Test/Fixtures/Archives/secret.7z b/Test/Fixtures/Archives/secret.7z new file mode 100644 index 0000000000000000000000000000000000000000..30fe5fc944ad13d865d4f4252d4a3611564ac4de GIT binary patch literal 302 zcmV+}0nz?9dc3bE8~_Av%aM4{000000000!000000000a{EJL1c^t!_GOYoMQWX?onCzqz)F zG}mcG{Wcj(scQ|X29F3o@TQ0G%m?=&7;KO-6s~^)9XL!dcGdiNO6fvo$(WT)_w)`~7Ss2T>@WHl-(cBLe{e1zi9T0003141lMB1_}Y5I82`a0L*+dtIC5
    wbU*CKHDj>q*)T1@n~}+$0avJ~0PO(*0SE>46c>X6n9s-{ z!7yRY^fK|5yNpl;a0;KfybQ?Zg4mF-hXxk1@ok6k8IKw;h|t%EIzs_S`=c8Vj|*gb vX1~I24^n(Ve1vKxA})}v+yb`}5i`h^;qnxUWvrky$-n}H(}9620uEpROsIri literal 0 HcmV?d00001 diff --git a/Test/MobileBulkAndSearchTest.cs b/Test/MobileBulkAndSearchTest.cs index 3e39865..d407e5e 100644 --- a/Test/MobileBulkAndSearchTest.cs +++ b/Test/MobileBulkAndSearchTest.cs @@ -152,7 +152,7 @@ public void CapabilitiesAdvertiseExactFeatureSet() "playlist.bulkAdd", "search.global", "channels.refresh", "channels.refreshProgress", "stream.localTranscode", "events.hub", "search.v1", "files.thumbnails", "files.content", "files.preload", "local.copyMove", "shares.browse", "setup.write", "transfers.remove", "system.admin", "webAuth.passkeys", "files.deleteOperations", "messages.content", "transfers.pauseUploads", "library.seriesFolders", "library.scanFolders", "messages.browse", "channels.refreshSequential", - "player.sync", "audio.transcode", "library.fileFilters", "files.cue", "files.audioInfo" + "player.sync", "audio.transcode", "library.fileFilters", "files.cue", "files.audioInfo", "local.archives", "transfers.autoExtract" })); } } diff --git a/Test/Test.csproj b/Test/Test.csproj index 7de9980..7b71f5a 100644 --- a/Test/Test.csproj +++ b/Test/Test.csproj @@ -31,4 +31,9 @@ + + + + + From eb5ba798e59e600588976ba8298bc618832c669a Mon Sep 17 00:00:00 2001 From: Mateo Date: Fri, 4 Dec 2026 19:10:14 +0100 Subject: [PATCH 2/2] feat(web): extract and compress local files, and extract downloads when they finish - Local files: Extract... (with the archive contents, password, existing files policy, delete afterwards) and Compress... (zip, 7z, tar.gz). - Download to the server (channels and chat): option to extract the archives when they finish and delete them afterwards. - Progress cards next to the delete ones (also for the automatic extractions) and in the transfers popover. --- .../apps/web/src/features/chat/chatActions.ts | 10 +- .../components/DownloadMessagesDialog.tsx | 7 +- .../features/files/DownloadToServerDialog.tsx | 8 +- .../files/archives/ArchiveDialogs.test.tsx | 115 ++++++++ .../files/archives/ArchiveDialogs.tsx | 269 ++++++++++++++++++ .../archives/ArchiveOperationsSummary.tsx | 19 ++ .../files/archives/ArchiveProgressHost.tsx | 23 ++ .../files/archives/ArchiveProgressPanel.tsx | 123 ++++++++ .../files/archives/AutoExtractFields.tsx | 35 +++ .../features/files/archives/archiveNames.ts | 21 ++ .../features/files/archives/archiveStore.ts | 58 ++++ .../features/files/archives/archiveText.ts | 67 +++++ .../files/archives/archiveTracker.test.ts | 165 +++++++++++ .../features/files/archives/archiveTracker.ts | 146 ++++++++++ .../files/archives/autoExtractOptions.ts | 18 ++ .../files/deletes/DeleteProgressPanel.tsx | 2 +- .../features/local/pages/LocalFilesPage.tsx | 53 +++- .../ClientApp/apps/web/src/i18n/es/files.ts | 57 ++++ .../ClientApp/apps/web/src/i18n/gl/files.ts | 57 ++++ .../apps/web/src/lib/useServerFeature.ts | 8 + .../apps/web/src/shell/AppLayout.tsx | 8 +- .../ClientApp/apps/web/src/shell/TopBar.tsx | 2 + .../packages/api-client/src/client.ts | 2 + .../packages/api-client/src/index.ts | 2 + .../api-client/src/modules/archives.ts | 41 +++ .../packages/api-client/src/types/archives.ts | 120 ++++++++ .../packages/api-client/src/types/events.ts | 3 + .../api-client/src/types/transfers.ts | 12 + 28 files changed, 1441 insertions(+), 10 deletions(-) create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.test.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveOperationsSummary.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressHost.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressPanel.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/AutoExtractFields.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveNames.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveStore.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveText.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.test.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/archives/autoExtractOptions.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/lib/useServerFeature.ts create mode 100644 TelegramDownloader/ClientApp/packages/api-client/src/modules/archives.ts create mode 100644 TelegramDownloader/ClientApp/packages/api-client/src/types/archives.ts diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/chat/chatActions.ts b/TelegramDownloader/ClientApp/apps/web/src/features/chat/chatActions.ts index 2ce9171..323e20d 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/chat/chatActions.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/chat/chatActions.ts @@ -28,10 +28,16 @@ async function findIndexedFile(channelId: string, m: ApiChatMessageDto): Promise } /** Queues the attachments in the server downloads; `targetPath` is a local folder (`/` is the root). True when it was queued. */ -export async function downloadMessages(channelId: string, messageIds: number[], targetPath?: string): Promise { +export async function downloadMessages( + channelId: string, + messageIds: number[], + targetPath?: string, + /** `extractArchives`... of "extract when the download finishes". */ + extra?: { extractArchives?: boolean; deleteArchivesAfterExtract?: boolean; archivePassword?: string | null } +): Promise { if (!messageIds.length) return false; try { - const res = await api.transfers.downloadMessages({ chatId: Number(channelId), messageIds, targetPath }); + const res = await api.transfers.downloadMessages({ chatId: Number(channelId), messageIds, targetPath, ...extra }); toast.success(t('Download queued'), { description: [ t('{count} files sent to the server downloads', { count: res.accepted }), diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/chat/components/DownloadMessagesDialog.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/chat/components/DownloadMessagesDialog.tsx index ad5c278..b4c872e 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/chat/components/DownloadMessagesDialog.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/chat/components/DownloadMessagesDialog.tsx @@ -1,6 +1,8 @@ import { Button, Dialog, DialogContent } from '@tfm/ui'; import { HardDriveDownload } from 'lucide-react'; import { useState } from 'react'; +import { AutoExtractFields } from '@/features/files/archives/AutoExtractFields'; +import { autoExtractBody, NO_AUTO_EXTRACT } from '@/features/files/archives/autoExtractOptions'; import { FolderBrowser } from '@/features/files/FolderBrowser'; import { createLocalFolder, listLocalFolders, localRel } from '@/features/files/local'; import { t } from '@/i18n'; @@ -10,12 +12,14 @@ import { downloadMessages } from '../chatActions'; export function DownloadMessagesDialog({ channelId, ids, onClose, onQueued }: { channelId: string; ids: number[] | null; onClose: () => void; onQueued: () => void }) { const [path, setPath] = useState('/'); const [busy, setBusy] = useState(false); + const [autoExtract, setAutoExtract] = useState(NO_AUTO_EXTRACT); const submit = async () => { if (!ids) return; setBusy(true); - const queued = await downloadMessages(channelId, ids, `/${localRel(path)}`); + const queued = await downloadMessages(channelId, ids, `/${localRel(path)}`, autoExtractBody(autoExtract)); setBusy(false); if (!queued) return; + setAutoExtract(NO_AUTO_EXTRACT); onClose(); onQueued(); }; @@ -41,6 +45,7 @@ export function DownloadMessagesDialog({ channelId, ids, onClose, onQueued }: {

    {t('Destination')}: /{localRel(path)}

    + diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/DownloadToServerDialog.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/DownloadToServerDialog.tsx index f51d338..2eddd1c 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/DownloadToServerDialog.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/DownloadToServerDialog.tsx @@ -4,6 +4,8 @@ import { useState } from 'react'; import { useNavigate } from 'react-router'; import { t } from '@/i18n'; import { api, errorMessage } from '@/lib/api'; +import { AutoExtractFields } from './archives/AutoExtractFields'; +import { autoExtractBody, NO_AUTO_EXTRACT } from './archives/autoExtractOptions'; import { FolderBrowser } from './FolderBrowser'; import { createLocalFolder, listLocalFolders, localRel } from './local'; @@ -22,6 +24,7 @@ export function DownloadToServerDialog({ request, onClose }: { request: Download const [mode, setMode] = useState<'structure' | 'folder'>('folder'); const [path, setPath] = useState('/'); const [busy, setBusy] = useState(false); + const [autoExtract, setAutoExtract] = useState(NO_AUTO_EXTRACT); const submit = async () => { if (!request) return; @@ -31,12 +34,14 @@ export function DownloadToServerDialog({ request, onClose }: { request: Download channelId: request.channelId, fileIds: request.fileIds, targetPath: mode === 'structure' ? null : localRel(path), - sharedCollectionId: request.collectionId ?? null + sharedCollectionId: request.collectionId ?? null, + ...autoExtractBody(autoExtract) }); toast.success(t('{count} downloads queued', { count: res.accepted }), { description: res.skipped.length ? t('{count} could not be resolved', { count: res.skipped.length }) : undefined, action: { label: t('Transfers'), onClick: () => navigate('/transfers') } }); + setAutoExtract(NO_AUTO_EXTRACT); onClose(); } catch (error) { toast.error(t('Could not start the download'), { description: errorMessage(error) }); @@ -87,6 +92,7 @@ export function DownloadToServerDialog({ request, onClose }: { request: Download {t('Destination')}: /{localRel(path)}

    )} + diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.test.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.test.tsx new file mode 100644 index 0000000..606b960 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.test.tsx @@ -0,0 +1,115 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { ApiError } from '@tfm/api-client'; +import { TooltipProvider } from '@tfm/ui'; +import type { ReactNode } from 'react'; +import { MemoryRouter } from 'react-router'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@/lib/api', () => ({ + api: { + archives: { entries: vi.fn(), extract: vi.fn(), compress: vi.fn(), info: vi.fn(), get: vi.fn() }, + transfers: { startDownload: vi.fn() }, + system: { capabilities: vi.fn() } + }, + errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)) +})); + +vi.mock('@/lib/realtime', async () => { + const { create } = await import('zustand'); + return { useRealtime: create(() => ({ eventsStatus: 'connected' })), getEventsHub: vi.fn(async () => ({ on: () => () => undefined })) }; +}); + +const { api } = await import('@/lib/api'); +const { resetServerFeatures } = await import('@/lib/serverFeatures'); +const { ExtractDialog } = await import('./ArchiveDialogs'); +const { DownloadToServerDialog } = await import('../DownloadToServerDialog'); + +function wrap(node: ReactNode) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + {node} + + + ); +} + +const listing = { + format: 'rar', + volumeCount: 3, + isEncrypted: false, + isSolid: false, + fileCount: 2, + folderCount: 1, + totalSize: 2048, + truncated: false, + entries: [ + { path: 'cd1', isDirectory: true, size: 0, compressedSize: 0, isEncrypted: false }, + { path: 'cd1/01.flac', isDirectory: false, size: 2048, compressedSize: 1000, isEncrypted: false } + ] +}; + +beforeEach(() => { + vi.mocked(api.archives.entries).mockReset(); + vi.mocked(api.archives.extract).mockReset(); + vi.mocked(api.archives.get).mockReset(); + vi.mocked(api.transfers.startDownload).mockReset(); + resetServerFeatures(); +}); + +describe('', () => { + it('shows what the archive contains', async () => { + vi.mocked(api.archives.entries).mockResolvedValue(listing); + wrap( undefined} />); + expect(await screen.findByText('cd1/01.flac')).toBeInTheDocument(); + expect(screen.getByText(/RAR · 2 files · 2(\.0)? KB · 3 volumes/)).toBeInTheDocument(); + }); + + it('asks for the password of a protected archive to list it', async () => { + vi.mocked(api.archives.entries).mockRejectedValue(new ApiError('password_required', 'protected', 400)); + wrap( undefined} />); + expect(await screen.findByText('Write the password to see what it contains.')).toBeInTheDocument(); + }); + + it('extracts into a folder named after the archive, with the chosen options', async () => { + vi.mocked(api.archives.entries).mockResolvedValue(listing); + vi.mocked(api.archives.extract).mockResolvedValue({ operationId: 'op1' }); + vi.mocked(api.archives.get).mockRejectedValue(new Error('later')); + const onClose = vi.fn(); + wrap(); + expect(screen.getByText('The files go to the folder "Album", next to the archive.')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('Password'), { target: { value: 'pw' } }); + fireEvent.click(screen.getByRole('checkbox', { name: 'Delete the archive when everything is extracted' })); + fireEvent.click(screen.getByRole('button', { name: 'Extract' })); + await vi.waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(api.archives.extract).toHaveBeenCalledWith({ path: 'dl/Album.part1.rar', intoFolder: true, overwrite: 'rename', password: 'pw', deleteArchive: true }); + }); +}); + +describe(' extract option', () => { + const request = { channelId: '1', fileIds: ['f1'], label: 'Peli.part1.rar' }; + + it('is not offered by servers that cannot extract downloads', async () => { + vi.mocked(api.system.capabilities).mockResolvedValue({ apiVersion: 1, serverVersion: 'x', features: [] }); + wrap( undefined} />); + await screen.findByRole('dialog'); + expect(screen.queryByText('Extract the archives when they finish')).toBeNull(); + }); + + it('asks the server to extract and delete the archives when they finish', async () => { + vi.mocked(api.system.capabilities).mockResolvedValue({ apiVersion: 1, serverVersion: 'x', features: ['transfers.autoExtract'] }); + vi.mocked(api.transfers.startDownload).mockResolvedValue({ accepted: 1, skipped: [], taskId: null }); + wrap( undefined} />); + fireEvent.click(await screen.findByRole('switch', { name: /Extract the archives when they finish/ })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Delete the archives when everything is extracted' })); + fireEvent.click(screen.getByRole('button', { name: 'Download' })); + await vi.waitFor(() => expect(api.transfers.startDownload).toHaveBeenCalled()); + expect(vi.mocked(api.transfers.startDownload).mock.calls[0][0]).toMatchObject({ + extractArchives: true, + deleteArchivesAfterExtract: true, + archivePassword: null + }); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.tsx new file mode 100644 index 0000000..e8dc11b --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveDialogs.tsx @@ -0,0 +1,269 @@ +import { isApiError, type ArchiveFormat, type ArchiveLevel, type ArchiveOverwrite } from '@tfm/api-client'; +import { Button, Checkbox, Dialog, DialogContent, Field, Input, Select, Spinner, Switch, toast } from '@tfm/ui'; +import { useQuery } from '@tanstack/react-query'; +import { File, FileArchive, Folder, Lock, PackageOpen } from 'lucide-react'; +import { useState } from 'react'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { formatBytes } from '@/lib/format'; +import { archiveBaseName } from './archiveNames'; +import { archiveErrorText } from './archiveText'; +import { startCompress, startExtract } from './archiveTracker'; + +export interface ExtractTarget { + /** Archive path relative to the local root (any volume of a set). */ + path: string; + name: string; +} + +export interface CompressTarget { + /** Items of one folder, relative to the local root. */ + paths: string[]; + /** Name proposed for the archive (without extension). */ + defaultName: string; +} + +const ENTRIES_SHOWN = 200; + +/** What the archive contains, loaded when the dialog opens (and again with a password). */ +function ArchiveContents({ path, password }: { path: string; password: string }) { + const { data, error, isLoading } = useQuery({ + queryKey: ['archive-entries', path, password], + queryFn: ({ signal }) => api.archives.entries({ path, password: password || null, maxEntries: ENTRIES_SHOWN }, signal), + retry: false, + staleTime: 60_000 + }); + if (isLoading) + return ( +
    + +
    + ); + if (error) { + const code = isApiError(error) ? (error.code as Parameters[0]) : null; + const message = code === 'password_required' ? t('Write the password to see what it contains.') : archiveErrorText(code, errorMessage(error)); + return

    {message}

    ; + } + if (!data) return null; + return ( +
    +

    + {[ + data.format.toUpperCase(), + t('{count} files', { count: data.fileCount }), + formatBytes(data.totalSize), + data.volumeCount > 1 ? t('{count} volumes', { count: data.volumeCount }) : null + ] + .filter(Boolean) + .join(' · ')} + {data.isEncrypted && } +

    +
      + {data.entries.map((e) => ( +
    • + {e.isDirectory ? : } + + {e.path} + + {!e.isDirectory && {formatBytes(e.size)}} +
    • + ))} + {data.truncated && ( +
    • {t('and {count} more', { count: data.fileCount + data.folderCount - data.entries.length })}
    • + )} +
    +
    + ); +} + +export function ExtractDialog({ target, onClose }: { target: ExtractTarget | null; onClose(): void }) { + const [intoFolder, setIntoFolder] = useState(true); + const [overwrite, setOverwrite] = useState('rename'); + const [password, setPassword] = useState(''); + const [listedWith, setListedWith] = useState(''); + const [deleteArchive, setDeleteArchive] = useState(false); + const [busy, setBusy] = useState(false); + const base = target ? archiveBaseName(target.name) : ''; + + const close = () => { + setPassword(''); + setListedWith(''); + onClose(); + }; + + const submit = async () => { + if (!target) return; + setBusy(true); + try { + await startExtract({ path: target.path, intoFolder, overwrite, password: password || null, deleteArchive }); + close(); + } catch (error) { + toast.error(t('Could not start the extraction'), { description: errorMessage(error) }); + } finally { + setBusy(false); + } + }; + + return ( + !o && close()}> + + + + + } + > + {target && ( +
    + + + + {({ id }) => ( + + id={id} + value={overwrite} + onValueChange={setOverwrite} + options={[ + { value: 'rename', label: t('Keep both (rename the new one)') }, + { value: 'skip', label: t('Skip them') }, + { value: 'overwrite', label: t('Overwrite them') } + ]} + /> + )} + + + {({ id }) => ( +
    + setPassword(e.target.value)} + className="flex-1" + /> + +
    + )} +
    + setDeleteArchive(v === true)} + label={t('Delete the archive when everything is extracted')} + /> +
    + )} +
    +
    + ); +} + +const FORMAT_LABELS: Record = { zip: 'ZIP', '7z': '7z', 'tar.gz': 'TAR.GZ' }; + +export function CompressDialog({ target, onClose }: { target: CompressTarget | null; onClose(): void }) { + const { data: info } = useQuery({ queryKey: ['archive-info'], queryFn: ({ signal }) => api.archives.info(signal), staleTime: Infinity }); + const [name, setName] = useState(null); + const [format, setFormat] = useState('zip'); + const [level, setLevel] = useState('normal'); + const [busy, setBusy] = useState(false); + const value = name ?? target?.defaultName ?? ''; + const formats = info?.createFormats ?? ['zip', 'tar.gz']; + + const close = () => { + setName(null); + onClose(); + }; + + const submit = async () => { + if (!target) return; + setBusy(true); + try { + await startCompress({ paths: target.paths, name: value.trim() || null, format, level }); + close(); + } catch (error) { + toast.error(t('Could not start the compression'), { description: errorMessage(error) }); + } finally { + setBusy(false); + } + }; + + return ( + !o && close()}> + 1 ? t('{count} items', { count: target.paths.length }) : target?.paths[0]?.split('/').pop()} + footer={ + <> + + + + } + > +
    + + {({ id }) => setName(e.target.value)} trailing={.{format}} />} + + + {({ id }) => ( + id={id} value={format} onValueChange={setFormat} options={formats.map((f) => ({ value: f, label: FORMAT_LABELS[f] ?? f }))} /> + )} + + + {({ id }) => ( + + id={id} + value={level} + onValueChange={setLevel} + options={[ + { value: 'fastest', label: t('Fastest') }, + { value: 'normal', label: t('Normal') }, + { value: 'maximum', label: t('Maximum (slower)') } + ]} + /> + )} + +
    +
    +
    + ); +} + +/** Both dialogs of the local files page (lazy chunk). */ +export default function ArchiveDialogs({ + extract, + compress, + onCloseExtract, + onCloseCompress +}: { + extract: ExtractTarget | null; + compress: CompressTarget | null; + onCloseExtract(): void; + onCloseCompress(): void; +}) { + return ( + <> + + + + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveOperationsSummary.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveOperationsSummary.tsx new file mode 100644 index 0000000..986d277 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveOperationsSummary.tsx @@ -0,0 +1,19 @@ +import { Progress } from '@tfm/ui'; +import { archivePercent, isActiveArchive, useArchives } from './archiveStore'; +import { archiveTitle } from './archiveText'; + +/** Extractions and compressions in flight, in the transfers popover (store only, no lazy chunk). */ +export function ArchiveOperationsSummary() { + const active = useArchives((s) => s.ops).filter(isActiveArchive); + if (active.length === 0) return null; + return ( +
    + {active.map(({ id, dto }) => ( +
    + {archiveTitle(dto)} + +
    + ))} +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressHost.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressHost.tsx new file mode 100644 index 0000000..450761c --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressHost.tsx @@ -0,0 +1,23 @@ +import { lazy, Suspense, useEffect } from 'react'; +import { useArchives } from './archiveStore'; + +const ArchiveProgressPanel = lazy(() => import('./ArchiveProgressPanel')); + +/** + * Rendered once by the layout, next to the delete progress. At startup it + * subscribes to `ArchiveProgress` (lazy chunk), so the extractions the server + * starts after a download show up too; the cards are a lazy chunk loaded + * with the first operation. + */ +export function ArchiveProgressHost() { + const any = useArchives((s) => s.ops.length > 0); + useEffect(() => { + void import('./archiveTracker').then((m) => m.listenToArchiveProgress()); + }, []); + if (!any) return null; + return ( + + + + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressPanel.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressPanel.tsx new file mode 100644 index 0000000..ce2f3bd --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/ArchiveProgressPanel.tsx @@ -0,0 +1,123 @@ +import { Button, cn, IconButton, Progress } from '@tfm/ui'; +import { AlertTriangle, Ban, CheckCircle2, ChevronDown, FileArchive, PackageOpen, X } from 'lucide-react'; +import { useState } from 'react'; +import { t } from '@/i18n'; +import { archivePercent, isActiveArchive, useArchives, type TrackedArchive } from './archiveStore'; +import { archiveErrorText, archivePhaseText, archiveResultText, archiveTitle } from './archiveText'; +import { cancelArchive, dismissArchive } from './archiveTracker'; + +function StatusIcon({ op }: { op: TrackedArchive }) { + const cls = 'mt-0.5 size-4.5 shrink-0'; + const { phase, failedCount, kind } = op.dto; + if (phase === 'done' && failedCount === 0) return ; + if (phase === 'done' || phase === 'failed') return ; + if (phase === 'cancelled') return ; + return kind === 'extract' ? : ; +} + +function tone(op: TrackedArchive) { + const { phase, failedCount } = op.dto; + if (phase === 'failed') return 'danger' as const; + if (phase === 'cancelled' || (phase === 'done' && failedCount > 0)) return 'warning' as const; + if (phase === 'done') return 'success' as const; + return 'accent' as const; +} + +export function ArchiveCard({ op }: { op: TrackedArchive }) { + const [open, setOpen] = useState(false); + const { dto } = op; + const active = isActiveArchive(op); + const result = archiveResultText(dto); + const more = dto.failedCount - dto.failed.length; + + return ( +
    +
    + +
    +

    + {archiveTitle(dto)} +

    + {dto.automatic &&

    {t('After the download')}

    } + {active &&

    {archivePhaseText(dto)}

    } + {result && ( +

    + {result} +

    + )} +
    + {!active && ( + dismissArchive(op.id)}> + + + )} +
    + + + + {active && dto.currentItem && ( +

    + {dto.currentItem} +

    + )} + {dto.phase === 'failed' &&

    {archiveErrorText(dto.errorCode, dto.error)}

    } + +
    + {dto.failedCount > 0 ? ( + + ) : ( + + )} + {active && ( + + )} +
    + + {open && dto.failedCount > 0 && ( +
      + {dto.failed.map((f, i) => ( +
    • + + {f.path} + + {f.reason && ( + + {f.reason} + + )} +
    • + ))} + {more > 0 &&
    • {t('and {count} more', { count: more })}
    • } +
    + )} +
    + ); +} + +/** The progress cards of the running and just finished extractions and compressions (lazy chunk). */ +export default function ArchiveProgressPanel() { + const ops = useArchives((s) => s.ops); + return ( +
    + {ops.map((op) => ( + + ))} +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/AutoExtractFields.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/AutoExtractFields.tsx new file mode 100644 index 0000000..6c87658 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/AutoExtractFields.tsx @@ -0,0 +1,35 @@ +import { Checkbox, Field, Input, Switch } from '@tfm/ui'; +import { t } from '@/i18n'; +import { useServerFeature } from '@/lib/useServerFeature'; +import { AUTO_EXTRACT_FEATURE } from './archiveStore'; +import type { AutoExtractOptions } from './autoExtractOptions'; + +/** The options in the download dialogs; hidden on servers without `transfers.autoExtract`. */ +export function AutoExtractFields({ value, onChange }: { value: AutoExtractOptions; onChange(value: AutoExtractOptions): void }) { + const supported = useServerFeature(AUTO_EXTRACT_FEATURE); + if (!supported) return null; + return ( +
    + onChange({ ...value, extract })} + label={t('Extract the archives when they finish')} + description={t('Zip, rar, 7z, tar... into a folder named after each one. Split archives are extracted once every part is downloaded.')} + /> + {value.extract && ( + <> + onChange({ ...value, deleteAfter: v === true })} + label={t('Delete the archives when everything is extracted')} + /> + + {({ id }) => ( + onChange({ ...value, password: e.target.value })} /> + )} + + + )} +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveNames.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveNames.ts new file mode 100644 index 0000000..94ea2ac --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveNames.ts @@ -0,0 +1,21 @@ +/** + * Archive names, as the server recognises them (`ArchiveNames.cs`): single + * archives and the volumes of multi-volume sets (`.part1.rar`, `.r00`, + * `.7z.001`, `.z01`). + */ +const SINGLE = /\.(zip|rar|7z|tar|tgz|tbz2?|txz|gz|bz2|xz|zst|cbz|cbr|cb7)$/i; +const VOLUME = /(\.(7z|zip|rar|tar)\.\d{3}|\.r\d{2,3}|\.z\d{2})$/i; + +export function isArchiveName(name: string): boolean { + return SINGLE.test(name) || VOLUME.test(name); +} + +/** "Fotos.zip" → "Fotos", "src.tar.gz" → "src", "Peli.part1.rar" → "Peli", "a.7z.001" → "a". */ +export function archiveBaseName(name: string): string { + return name + .replace(/\.part\d+\.rar$/i, '') + .replace(/\.(7z|zip|rar|tar)\.\d{3}$/i, '') + .replace(/\.(r\d{2,3}|z\d{2})$/i, '') + .replace(/\.tar\.(gz|bz2|xz|zst)$/i, '') + .replace(SINGLE, ''); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveStore.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveStore.ts new file mode 100644 index 0000000..71503e4 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveStore.ts @@ -0,0 +1,58 @@ +import { isFinalArchivePhase, type ApiArchiveOperationDto } from '@tfm/api-client'; +import { create } from 'zustand'; + +/** + * Extractions and compressions of local files shown by + * on every page: the ones started here and the automatic ones the server + * starts when a download finishes. In the initial bundle: state only (the + * server calls are in `archiveTracker.ts`). + */ + +export interface TrackedArchive { + /** Server operation id. */ + id: string; + dto: ApiArchiveOperationDto; + /** `Date.now()` of the last news (hub or poll). */ + lastUpdate: number; + cancelling?: boolean; +} + +interface ArchiveState { + ops: TrackedArchive[]; + upsert: (dto: ApiArchiveOperationDto) => void; + patch: (id: string, patch: Partial) => void; + remove: (id: string) => void; +} + +export const ARCHIVES_FEATURE = 'local.archives'; +export const AUTO_EXTRACT_FEATURE = 'transfers.autoExtract'; + +export const useArchives = create()((set) => ({ + ops: [], + upsert: (dto) => + set((s) => { + const existing = s.ops.find((o) => o.id === dto.id); + if (!existing) return { ops: [...s.ops, { id: dto.id, dto, lastUpdate: Date.now() }] }; + // A late hub message must not move an operation back + if (isFinalArchivePhase(existing.dto.phase) && !isFinalArchivePhase(dto.phase)) return s; + return { + ops: s.ops.map((o) => + o.id === dto.id ? { ...o, dto, lastUpdate: Date.now(), cancelling: o.cancelling && !isFinalArchivePhase(dto.phase) } : o + ) + }; + }), + patch: (id, patch) => set((s) => ({ ops: s.ops.map((o) => (o.id === id ? { ...o, ...patch } : o)) })), + remove: (id) => set((s) => ({ ops: s.ops.filter((o) => o.id !== id) })) +})); + +export function isActiveArchive(op: Pick): boolean { + return !isFinalArchivePhase(op.dto.phase); +} + +/** 0-100, or undefined while it is queued or the totals are not known. */ +export function archivePercent(dto: ApiArchiveOperationDto): number | undefined { + if (dto.phase === 'done') return 100; + if (dto.phase === 'queued' || dto.phase === 'preparing') return undefined; + if (dto.totalBytes <= 0 && dto.totalFiles <= 0) return isFinalArchivePhase(dto.phase) ? 100 : undefined; + return dto.progress; +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveText.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveText.ts new file mode 100644 index 0000000..0e40990 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveText.ts @@ -0,0 +1,67 @@ +import type { ApiArchiveOperationDto, ArchiveErrorCode } from '@tfm/api-client'; +import { t } from '@/i18n'; +import { formatBytes } from '@/lib/format'; + +const baseName = (path: string | null | undefined) => (path ?? '').replace(/\/+$/, '').split('/').pop() || (path ?? ''); + +/** "Extracting Album.rar", "Album.rar extracted", "Fotos.zip created"... */ +export function archiveTitle(dto: ApiArchiveOperationDto): string { + if (dto.kind === 'extract') { + const name = baseName(dto.source); + if (dto.phase === 'done') return t('{name} extracted', { name }); + if (dto.phase === 'failed') return t('Could not extract {name}', { name }); + if (dto.phase === 'cancelled') return t('Extraction of {name} cancelled', { name }); + return t('Extracting {name}', { name }); + } + const name = baseName(dto.destination) || baseName(dto.source); + if (dto.phase === 'done') return t('{name} created', { name }); + if (dto.phase === 'failed') return t('Could not create {name}', { name }); + if (dto.phase === 'cancelled') return t('Compression of {name} cancelled', { name }); + return t('Creating {name}', { name }); +} + +/** Second line while it runs. */ +export function archivePhaseText(dto: ApiArchiveOperationDto): string { + switch (dto.phase) { + case 'queued': + return t('Waiting for the operation in progress'); + case 'preparing': + return t('Preparing...'); + default: + if (dto.totalBytes > 0) + return t('{done} of {total}', { done: formatBytes(dto.processedBytes), total: formatBytes(dto.totalBytes) }); + return dto.processedFiles > 0 ? t('{count} files', { count: dto.processedFiles }) : t('Working...'); + } +} + +/** Where the result is, once finished. */ +export function archiveResultText(dto: ApiArchiveOperationDto): string | undefined { + if (dto.phase !== 'done' || !dto.destination) return undefined; + const where = `/${dto.destination}`; + if (dto.kind === 'compress') return where; + return dto.archivesDeleted ? t('In {path} (archive deleted)', { path: where }) : t('In {path}', { path: where }); +} + +/** The reason of a failed operation, translated from its code. */ +export function archiveErrorText(code: ArchiveErrorCode | null | undefined, fallback?: string | null): string { + switch (code) { + case 'password_required': + return t('The archive is protected with a password.'); + case 'wrong_password': + return t('The password is not correct.'); + case 'not_enough_space': + return t('There is not enough free space on the server disk.'); + case 'missing_volume': + return t('A part of the archive is missing: put every volume in the same folder.'); + case 'unsupported': + return t('This archive format is not supported.'); + case 'corrupt': + return t('The archive is damaged or incomplete.'); + case 'not_found': + return t('The file or folder no longer exists.'); + case 'tool_missing': + return t('7-Zip is not installed on the server.'); + default: + return fallback || t('The operation failed.'); + } +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.test.ts new file mode 100644 index 0000000..786543a --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.test.ts @@ -0,0 +1,165 @@ +import { ApiError, type ApiArchiveOperationDto } from '@tfm/api-client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const hubHandlers: ((dto: ApiArchiveOperationDto) => void)[] = []; + +vi.mock('@/lib/api', () => ({ + api: { archives: { extract: vi.fn(), compress: vi.fn(), get: vi.fn(), cancel: vi.fn() } }, + errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)) +})); + +vi.mock('@/lib/realtime', async () => { + const { create } = await import('zustand'); + return { + useRealtime: create(() => ({ eventsStatus: 'disconnected' })), + getEventsHub: vi.fn(async () => ({ + on: (_name: string, handler: (dto: ApiArchiveOperationDto) => void) => { + hubHandlers.push(handler); + return () => undefined; + } + })) + }; +}); + +const { api } = await import('@/lib/api'); +const { queryClient } = await import('@/lib/queryClient'); +const { useArchives, archivePercent } = await import('./archiveStore'); +const tracker = await import('./archiveTracker'); +const { archiveErrorText, archiveResultText, archiveTitle } = await import('./archiveText'); +const { archiveBaseName, isArchiveName } = await import('./archiveNames'); + +function dto(patch: Partial = {}): ApiArchiveOperationDto { + return { + id: 'op1', + kind: 'extract', + source: 'descargas/Album.rar', + destination: 'descargas/Album', + automatic: false, + phase: 'working', + totalFiles: 10, + totalBytes: 1000, + processedFiles: 2, + processedBytes: 250, + progress: 25, + currentItem: 'cd1/01.flac', + failedCount: 0, + failed: [], + archivesDeleted: false, + cancelRequested: false, + startedAt: '2026-12-04T10:00:00Z', + ...patch + }; +} + +const ops = () => useArchives.getState().ops; + +beforeEach(() => { + tracker.__resetArchiveTracker(); + hubHandlers.length = 0; + vi.mocked(api.archives.get).mockReset(); + vi.mocked(api.archives.extract).mockReset(); + vi.mocked(api.archives.cancel).mockReset(); +}); + +afterEach(() => vi.useRealTimers()); + +describe('archive tracking', () => { + it('shows an extraction it started at once', async () => { + vi.mocked(api.archives.extract).mockResolvedValue({ operationId: 'op1' }); + vi.mocked(api.archives.get).mockResolvedValue(dto({ phase: 'queued' })); + await tracker.startExtract({ path: 'descargas/Album.rar' }); + expect(api.archives.extract).toHaveBeenCalledWith({ path: 'descargas/Album.rar' }); + expect(ops().map((o) => o.dto.phase)).toEqual(['queued']); + }); + + it('shows the extractions the server starts after a download (hub)', async () => { + tracker.listenToArchiveProgress(); + await vi.waitFor(() => expect(hubHandlers).toHaveLength(1)); + hubHandlers[0](dto({ id: 'auto', automatic: true })); + expect(ops().map((o) => o.id)).toEqual(['auto']); + }); + + it('ignores a late progress message after the end', () => { + tracker.applyArchiveProgress(dto({ phase: 'failed', errorCode: 'corrupt' })); + tracker.applyArchiveProgress(dto({ phase: 'working' })); + expect(ops()[0].dto.phase).toBe('failed'); + }); + + it('reloads the local file listings when one ends', () => { + const invalidate = vi.spyOn(queryClient, 'invalidateQueries'); + tracker.applyArchiveProgress(dto({ phase: 'done', progress: 100 })); + expect(invalidate).toHaveBeenCalled(); + invalidate.mockRestore(); + }); + + it('takes a successful one out of the panel after a while, but keeps a failed one', () => { + vi.useFakeTimers(); + tracker.applyArchiveProgress(dto({ id: 'ok', phase: 'done' })); + tracker.applyArchiveProgress(dto({ id: 'ko', phase: 'failed', errorCode: 'wrong_password' })); + vi.advanceTimersByTime(tracker.AUTO_DISMISS_MS + 10); + expect(ops().map((o) => o.id)).toEqual(['ko']); + }); + + it('polls a running operation when the hub brings no news', async () => { + tracker.applyArchiveProgress(dto()); + useArchives.getState().patch('op1', { lastUpdate: 0 }); + vi.mocked(api.archives.get).mockResolvedValue(dto({ processedBytes: 900, progress: 90 })); + await tracker.pollArchivesOnce(Date.now()); + expect(ops()[0].dto.progress).toBe(90); + }); + + it('forgets an operation the server no longer knows', async () => { + tracker.applyArchiveProgress(dto()); + useArchives.getState().patch('op1', { lastUpdate: 0 }); + vi.mocked(api.archives.get).mockRejectedValue(new ApiError('not_found', 'gone', 404)); + await tracker.pollArchivesOnce(Date.now()); + expect(ops()).toEqual([]); + }); + + it('asks the server to cancel and shows it while it stops', async () => { + tracker.applyArchiveProgress(dto()); + vi.mocked(api.archives.cancel).mockResolvedValue(dto({ cancelRequested: true })); + await tracker.cancelArchive('op1'); + expect(api.archives.cancel).toHaveBeenCalledWith('op1'); + expect(ops()[0].dto.cancelRequested).toBe(true); + }); +}); + +describe('archive texts', () => { + it('names the operation after the archive or the archive created', () => { + expect(archiveTitle(dto())).toBe('Extracting Album.rar'); + expect(archiveTitle(dto({ phase: 'done' }))).toBe('Album.rar extracted'); + expect(archiveTitle(dto({ kind: 'compress', source: '3 items', destination: 'fotos/Viaje.zip', phase: 'done' }))).toBe('Viaje.zip created'); + }); + + it('says where the files went and whether the archive was deleted', () => { + expect(archiveResultText(dto({ phase: 'done', archivesDeleted: true }))).toBe('In /descargas/Album (archive deleted)'); + }); + + it('explains the failures by their code', () => { + expect(archiveErrorText('password_required')).toMatch(/password/); + expect(archiveErrorText(undefined, 'boom')).toBe('boom'); + }); + + it('has no percentage while queued', () => { + expect(archivePercent(dto({ phase: 'queued' }))).toBeUndefined(); + expect(archivePercent(dto())).toBe(25); + }); +}); + +describe('archive names', () => { + it.each(['a.zip', 'b.RAR', 'c.7z', 'd.tar.gz', 'e.part2.rar', 'f.7z.003', 'g.r01', 'h.z01'])('%s is an archive', (name) => { + expect(isArchiveName(name)).toBe(true); + }); + + it.each(['song.mp3', 'notes.txt', 'zip', 'video.mkv'])('%s is not an archive', (name) => { + expect(isArchiveName(name)).toBe(false); + }); + + it('proposes the folder name of an archive', () => { + expect(archiveBaseName('Peli.part1.rar')).toBe('Peli'); + expect(archiveBaseName('src.tar.gz')).toBe('src'); + expect(archiveBaseName('a.7z.001')).toBe('a'); + expect(archiveBaseName('Fotos.zip')).toBe('Fotos'); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.ts new file mode 100644 index 0000000..b27337b --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/archiveTracker.ts @@ -0,0 +1,146 @@ +import { isApiError, isFinalArchivePhase, type ApiArchiveOperationDto, type CompressRequest, type ExtractArchiveRequest } from '@tfm/api-client'; +import { fileManagerQueryKey } from '@tfm/file-manager'; +import { api } from '@/lib/api'; +import { queryClient } from '@/lib/queryClient'; +import { getEventsHub, useRealtime } from '@/lib/realtime'; +import { isActiveArchive, useArchives } from './archiveStore'; + +/** + * Starts and follows the extractions and compressions. Progress arrives as + * `ArchiveProgress` on /hubs/events (also for the automatic extractions the + * server starts after a download); a 1 s poll covers a hub that is down. + * When one ends, the local file listings are reloaded. + */ + +export const POLL_INTERVAL_MS = 1000; +const STALE_WITHOUT_HUB_MS = 900; +const STALE_WITH_HUB_MS = 5000; +/** A successful operation leaves the panel after this long. */ +export const AUTO_DISMISS_MS = 8000; + +/** File manager provider of the local files (`LOCAL_PROVIDER_ID`; not imported to keep this module small). */ +const LOCAL_PROVIDER_ID = 'local'; + +const finished = new Set(); +const dismissTimers = new Map>(); + +/** Applies a server state (hub, poll, start or cancel answer). */ +export function applyArchiveProgress(dto: ApiArchiveOperationDto): void { + useArchives.getState().upsert(dto); + if (isFinalArchivePhase(dto.phase)) onFinished(dto); + else ensurePolling(); +} + +function onFinished(dto: ApiArchiveOperationDto): void { + if (finished.has(dto.id)) return; + finished.add(dto.id); + void queryClient.invalidateQueries({ queryKey: fileManagerQueryKey(LOCAL_PROVIDER_ID) }); + if (dto.phase === 'done' && dto.failedCount === 0) { + dismissTimers.set( + dto.id, + setTimeout(() => dismissArchive(dto.id), AUTO_DISMISS_MS) + ); + } +} + +export async function startExtract(body: ExtractArchiveRequest): Promise { + listenToArchiveProgress(); + const { operationId } = await api.archives.extract(body); + await track(operationId); +} + +export async function startCompress(body: CompressRequest): Promise { + listenToArchiveProgress(); + const { operationId } = await api.archives.compress(body); + await track(operationId); +} + +/** Shows an operation at once (the hub may be slower than the answer). */ +async function track(id: string): Promise { + try { + applyArchiveProgress(await api.archives.get(id)); + } catch { + // The hub or the poll will bring it + } +} + +export async function cancelArchive(id: string): Promise { + const op = useArchives.getState().ops.find((o) => o.id === id); + if (!op || !isActiveArchive(op) || op.cancelling) return; + useArchives.getState().patch(id, { cancelling: true }); + try { + const dto = await api.archives.cancel(id); + if (dto) applyArchiveProgress(dto); + } catch (error) { + if (!(isApiError(error) && error.status === 409)) useArchives.getState().patch(id, { cancelling: false }); + } + useArchives.getState().patch(id, { lastUpdate: 0 }); // poll right away +} + +export function dismissArchive(id: string): void { + const timer = dismissTimers.get(id); + if (timer) clearTimeout(timer); + dismissTimers.delete(id); + useArchives.getState().remove(id); +} + +let hubListening = false; + +/** + * Listens to `ArchiveProgress` for the whole session (called by the host at + * startup), so automatic extractions show up even when nothing was started here. + */ +export function listenToArchiveProgress(): void { + if (hubListening) return; + hubListening = true; + void getEventsHub() + .then((hub) => hub.on('ArchiveProgress', (dto) => applyArchiveProgress(dto))) + .catch(() => { + hubListening = false; + }); +} + +let pollTimer: ReturnType | null = null; +const inFlight = new Set(); + +function ensurePolling(): void { + if (pollTimer) return; + pollTimer = setInterval(() => void pollArchivesOnce(), POLL_INTERVAL_MS); +} + +/** One poll round: every running operation without recent news is read from the server. */ +export async function pollArchivesOnce(now = Date.now()): Promise { + const active = useArchives.getState().ops.filter(isActiveArchive); + if (active.length === 0) { + if (pollTimer) clearInterval(pollTimer); + pollTimer = null; + return; + } + const staleAfter = useRealtime.getState().eventsStatus === 'connected' ? STALE_WITH_HUB_MS : STALE_WITHOUT_HUB_MS; + await Promise.all( + active + .filter((o) => now - o.lastUpdate >= staleAfter && !inFlight.has(o.id)) + .map(async (o) => { + inFlight.add(o.id); + try { + applyArchiveProgress(await api.archives.get(o.id)); + } catch (error) { + // Expired or unknown: it ended long ago + if (isApiError(error) && error.status === 404) dismissArchive(o.id); + } finally { + inFlight.delete(o.id); + } + }) + ); +} + +/** Test helper. */ +export function __resetArchiveTracker(): void { + finished.clear(); + for (const timer of dismissTimers.values()) clearTimeout(timer); + dismissTimers.clear(); + if (pollTimer) clearInterval(pollTimer); + pollTimer = null; + hubListening = false; + useArchives.setState({ ops: [] }); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/autoExtractOptions.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/autoExtractOptions.ts new file mode 100644 index 0000000..d237cd7 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/archives/autoExtractOptions.ts @@ -0,0 +1,18 @@ +/** "Extract when the download finishes" of a download to the server. */ +export interface AutoExtractOptions { + extract: boolean; + deleteAfter: boolean; + password: string; +} + +export const NO_AUTO_EXTRACT: AutoExtractOptions = { extract: false, deleteAfter: false, password: '' }; + +/** The fields of the download request (`extractArchives`...); nothing when it is off. */ +export function autoExtractBody(options: AutoExtractOptions) { + if (!options.extract) return {}; + return { + extractArchives: true, + deleteArchivesAfterExtract: options.deleteAfter, + archivePassword: options.password || null + }; +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/DeleteProgressPanel.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/DeleteProgressPanel.tsx index 956810a..0219e87 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/DeleteProgressPanel.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/DeleteProgressPanel.tsx @@ -130,7 +130,7 @@ export default function DeleteProgressPanel() { return (
    {ops.map((op) => ( diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx index c389330..e216429 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx @@ -1,6 +1,9 @@ import { baseName, FileManager, parentPath, type FileAction, type FileEntry } from '@tfm/file-manager'; -import { CloudUpload, HardDrive } from 'lucide-react'; -import { useMemo, useState } from 'react'; +import { CloudUpload, FileArchive, HardDrive, PackageOpen } from 'lucide-react'; +import { lazy, Suspense, useMemo, useState } from 'react'; +import type { CompressTarget, ExtractTarget } from '@/features/files/archives/ArchiveDialogs'; +import { isArchiveName } from '@/features/files/archives/archiveNames'; +import { ARCHIVES_FEATURE } from '@/features/files/archives/archiveStore'; import { dtoOf } from '@/features/files/entries'; import { confirmDelete, fmLocale, reportError, reportSuccess } from '@/features/files/fileManagerOptions'; import { useEntryDescriber } from '@/features/files/describeEntry'; @@ -10,12 +13,24 @@ import { fileManagerStrings } from '@/features/files/strings'; import { useRoutePath } from '@/features/files/useRoutePath'; import { getLanguage, t } from '@/i18n'; import { api } from '@/lib/api'; +import { useServerFeature } from '@/lib/useServerFeature'; import { PageHeader } from '@/shell/PageHeader'; import { useUi } from '@/stores/ui'; import { UploadToTelegramDialog } from '../components/UploadToTelegramDialog'; import { createLocalProvider } from '../lib/localProvider'; const strings = fileManagerStrings(); +const ArchiveDialogs = lazy(() => import('@/features/files/archives/ArchiveDialogs')); + +/** Proposed archive name: the item's (without extension), or the folder's for several. */ +function compressName(entries: FileEntry[], currentPath: string): string { + if (entries.length === 1) { + const e = entries[0]; + const dot = e.name.lastIndexOf('.'); + return e.kind === 'file' && dot > 0 ? e.name.slice(0, dot) : e.name; + } + return baseName(currentPath) || t('Archive'); +} /** `/local/*`: the server local files (download target, upload source). */ export default function LocalFilesPage() { @@ -24,6 +39,9 @@ export default function LocalFilesPage() { const [uploading, setUploading] = useState(null); const provider = useMemo(() => createLocalProvider(t('Local files')), []); const describeEntry = useEntryDescriber(); + const archives = useServerFeature(ARCHIVES_FEATURE); + const [extracting, setExtracting] = useState(null); + const [compressing, setCompressing] = useState(null); const source: MediaSource = useMemo( () => ({ @@ -57,9 +75,28 @@ export default function LocalFilesPage() { { id: localRel(ctx.currentPath), name: baseName(ctx.currentPath), kind: 'folder', path: ctx.currentPath, parentPath: parentPath(ctx.currentPath) } ]) }, + { + id: 'tfm:extract', + label: t('Extract...'), + icon: , + group: 'b-archive', + order: 10, + selection: 'single', + when: (entries) => archives && entries[0]?.kind === 'file' && isArchiveName(entries[0].name), + run: (entries) => setExtracting({ path: entries[0].id, name: entries[0].name }) + }, + { + id: 'tfm:compress', + label: t('Compress...'), + icon: , + group: 'b-archive', + order: 11, + when: () => archives, + run: (entries, ctx) => setCompressing({ paths: entries.map((e) => e.id), defaultName: compressName(entries, ctx.currentPath) }) + }, ...mediaActions(source) ], - [source] + [source, archives] ); return ( @@ -82,6 +119,16 @@ export default function LocalFilesPage() { className="mt-2 flex-1" /> setUploading(null)} /> + {(extracting || compressing) && ( + + setExtracting(null)} + onCloseCompress={() => setCompressing(null)} + /> + + )}
    ); } diff --git a/TelegramDownloader/ClientApp/apps/web/src/i18n/es/files.ts b/TelegramDownloader/ClientApp/apps/web/src/i18n/es/files.ts index 95e8ad7..d4cddf1 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/i18n/es/files.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/i18n/es/files.ts @@ -135,6 +135,63 @@ const files: Record = { 'Missing file: {name}': 'Falta el fichero: {name}', 'Play from this track': 'Reproducir desde esta pista', 'Audio files not found next to the cue sheet: {names}': 'No se encontraron los ficheros de audio junto a la hoja cue: {names}', + // Archives (extract / compress) + 'Write the password to see what it contains.': 'Escribe la contraseña para ver qué contiene.', + '{count} volumes': '{count} volúmenes', + 'Protected with a password': 'Protegido con contraseña', + 'Could not start the extraction': 'No se pudo empezar a descomprimir', + 'Extract': 'Descomprimir', + 'Into a new folder': 'En una carpeta nueva', + 'The files go to the folder "{name}", next to the archive.': 'Los ficheros van a la carpeta «{name}», junto al comprimido.', + 'The files go next to the archive.': 'Los ficheros van junto al comprimido.', + 'Files that already exist': 'Ficheros que ya existen', + 'Keep both (rename the new one)': 'Conservar los dos (renombrar el nuevo)', + 'Skip them': 'Omitirlos', + 'Overwrite them': 'Sobrescribirlos', + 'Only for protected archives.': 'Solo para comprimidos protegidos.', + 'See contents': 'Ver contenido', + 'Delete the archive when everything is extracted': 'Borrar el comprimido cuando todo esté descomprimido', + 'Could not start the compression': 'No se pudo empezar a comprimir', + 'Compress': 'Comprimir', + 'Archive name': 'Nombre del comprimido', + 'It is saved in the same folder.': 'Se guarda en la misma carpeta.', + 'Format': 'Formato', + '7z needs 7-Zip on the server.': '7z necesita 7-Zip en el servidor.', + 'Compression': 'Compresión', + 'Fastest': 'La más rápida', + 'Normal': 'Normal', + 'Maximum (slower)': 'Máxima (más lenta)', + 'After the download': 'Al terminar la descarga', + '{count} entries could not be processed': '{count} entradas no se pudieron procesar', + 'Extract the archives when they finish': 'Descomprimir los comprimidos al terminar', + 'Zip, rar, 7z, tar... into a folder named after each one. Split archives are extracted once every part is downloaded.': 'Zip, rar, 7z, tar... en una carpeta con el nombre de cada uno. Los comprimidos por partes se descomprimen cuando se han descargado todas.', + 'Delete the archives when everything is extracted': 'Borrar los comprimidos cuando todo esté descomprimido', + 'Only for protected archives. It is not saved: after a server restart they are kept without extracting.': 'Solo para comprimidos protegidos. No se guarda: si el servidor se reinicia, se conservan sin descomprimir.', + '{name} extracted': '{name} descomprimido', + 'Could not extract {name}': 'No se pudo descomprimir {name}', + 'Extraction of {name} cancelled': 'Descompresión de {name} cancelada', + 'Extracting {name}': 'Descomprimiendo {name}', + '{name} created': '{name} creado', + 'Could not create {name}': 'No se pudo crear {name}', + 'Compression of {name} cancelled': 'Compresión de {name} cancelada', + 'Creating {name}': 'Creando {name}', + 'Waiting for the operation in progress': 'Esperando a la operación en curso', + '{done} of {total}': '{done} de {total}', + 'Working...': 'Trabajando...', + 'In {path} (archive deleted)': 'En {path} (comprimido borrado)', + 'In {path}': 'En {path}', + 'The archive is protected with a password.': 'El comprimido está protegido con contraseña.', + 'The password is not correct.': 'La contraseña no es correcta.', + 'There is not enough free space on the server disk.': 'No hay espacio libre suficiente en el disco del servidor.', + 'A part of the archive is missing: put every volume in the same folder.': 'Falta una parte del comprimido: pon todos los volúmenes en la misma carpeta.', + 'This archive format is not supported.': 'Este formato de comprimido no está soportado.', + 'The archive is damaged or incomplete.': 'El comprimido está dañado o incompleto.', + 'The file or folder no longer exists.': 'El fichero o la carpeta ya no existe.', + '7-Zip is not installed on the server.': '7-Zip no está instalado en el servidor.', + 'The operation failed.': 'La operación ha fallado.', + 'Archive': 'Comprimido', + 'Extract...': 'Descomprimir...', + 'Compress...': 'Comprimir...' }; export default files; diff --git a/TelegramDownloader/ClientApp/apps/web/src/i18n/gl/files.ts b/TelegramDownloader/ClientApp/apps/web/src/i18n/gl/files.ts index 84edf89..53a29f4 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/i18n/gl/files.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/i18n/gl/files.ts @@ -135,6 +135,63 @@ const files: Record = { 'Missing file: {name}': 'Falta o ficheiro: {name}', 'Play from this track': 'Reproducir desde esta pista', 'Audio files not found next to the cue sheet: {names}': 'Non se atoparon os ficheiros de audio xunto á folla cue: {names}', + // Archives (extract / compress) + 'Write the password to see what it contains.': 'Escribe o contrasinal para ver que contén.', + '{count} volumes': '{count} volumes', + 'Protected with a password': 'Protexido con contrasinal', + 'Could not start the extraction': 'Non se puido comezar a descomprimir', + 'Extract': 'Descomprimir', + 'Into a new folder': 'Nun cartafol novo', + 'The files go to the folder "{name}", next to the archive.': 'Os ficheiros van ao cartafol «{name}», xunto ao comprimido.', + 'The files go next to the archive.': 'Os ficheiros van xunto ao comprimido.', + 'Files that already exist': 'Ficheiros que xa existen', + 'Keep both (rename the new one)': 'Conservar os dous (renomear o novo)', + 'Skip them': 'Omitilos', + 'Overwrite them': 'Sobrescribilos', + 'Only for protected archives.': 'Só para comprimidos protexidos.', + 'See contents': 'Ver contido', + 'Delete the archive when everything is extracted': 'Borrar o comprimido cando todo estea descomprimido', + 'Could not start the compression': 'Non se puido comezar a comprimir', + 'Compress': 'Comprimir', + 'Archive name': 'Nome do comprimido', + 'It is saved in the same folder.': 'Gárdase no mesmo cartafol.', + 'Format': 'Formato', + '7z needs 7-Zip on the server.': '7z necesita 7-Zip no servidor.', + 'Compression': 'Compresión', + 'Fastest': 'A máis rápida', + 'Normal': 'Normal', + 'Maximum (slower)': 'Máxima (máis lenta)', + 'After the download': 'Ao rematar a descarga', + '{count} entries could not be processed': '{count} entradas non se puideron procesar', + 'Extract the archives when they finish': 'Descomprimir os comprimidos ao rematar', + 'Zip, rar, 7z, tar... into a folder named after each one. Split archives are extracted once every part is downloaded.': 'Zip, rar, 7z, tar... nun cartafol co nome de cada un. Os comprimidos por partes descomprímense cando se descargaron todas.', + 'Delete the archives when everything is extracted': 'Borrar os comprimidos cando todo estea descomprimido', + 'Only for protected archives. It is not saved: after a server restart they are kept without extracting.': 'Só para comprimidos protexidos. Non se garda: se o servidor se reinicia, consérvanse sen descomprimir.', + '{name} extracted': '{name} descomprimido', + 'Could not extract {name}': 'Non se puido descomprimir {name}', + 'Extraction of {name} cancelled': 'Descompresión de {name} cancelada', + 'Extracting {name}': 'Descomprimindo {name}', + '{name} created': '{name} creado', + 'Could not create {name}': 'Non se puido crear {name}', + 'Compression of {name} cancelled': 'Compresión de {name} cancelada', + 'Creating {name}': 'Creando {name}', + 'Waiting for the operation in progress': 'Agardando pola operación en curso', + '{done} of {total}': '{done} de {total}', + 'Working...': 'Traballando...', + 'In {path} (archive deleted)': 'En {path} (comprimido borrado)', + 'In {path}': 'En {path}', + 'The archive is protected with a password.': 'O comprimido está protexido con contrasinal.', + 'The password is not correct.': 'O contrasinal non é correcto.', + 'There is not enough free space on the server disk.': 'Non hai espazo libre abondo no disco do servidor.', + 'A part of the archive is missing: put every volume in the same folder.': 'Falta unha parte do comprimido: pon todos os volumes no mesmo cartafol.', + 'This archive format is not supported.': 'Este formato de comprimido non está soportado.', + 'The archive is damaged or incomplete.': 'O comprimido está danado ou incompleto.', + 'The file or folder no longer exists.': 'O ficheiro ou o cartafol xa non existe.', + '7-Zip is not installed on the server.': '7-Zip non está instalado no servidor.', + 'The operation failed.': 'A operación fallou.', + 'Archive': 'Comprimido', + 'Extract...': 'Descomprimir...', + 'Compress...': 'Comprimir...' }; export default files; diff --git a/TelegramDownloader/ClientApp/apps/web/src/lib/useServerFeature.ts b/TelegramDownloader/ClientApp/apps/web/src/lib/useServerFeature.ts new file mode 100644 index 0000000..31b2dbb --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/lib/useServerFeature.ts @@ -0,0 +1,8 @@ +import { useQuery } from '@tanstack/react-query'; +import { serverFeatures } from './serverFeatures'; + +/** True when the server advertises `feature` (false while loading or on old servers). */ +export function useServerFeature(feature: string): boolean { + const { data } = useQuery({ queryKey: ['server-features'], queryFn: serverFeatures, staleTime: Infinity }); + return data?.has(feature) ?? false; +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/shell/AppLayout.tsx b/TelegramDownloader/ClientApp/apps/web/src/shell/AppLayout.tsx index 65724b3..9ef8cdd 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/shell/AppLayout.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/shell/AppLayout.tsx @@ -1,6 +1,7 @@ import { cn, Spinner } from '@tfm/ui'; import { Suspense } from 'react'; import { Outlet, useNavigation } from 'react-router'; +import { ArchiveProgressHost } from '@/features/files/archives/ArchiveProgressHost'; import { DeleteProgressHost } from '@/features/files/deletes/DeleteProgressHost'; import { ChannelCommands } from '@/features/maintenance/ChannelCommands'; import { PlayerSlot } from '@/features/player/PlayerSlot'; @@ -71,14 +72,17 @@ export function AppLayout() { loading ? 'scale-x-75 opacity-100' : 'scale-x-0 opacity-0' )} /> - {/* The wrapper anchors the delete progress above the player and the bottom nav */} + {/* The wrapper anchors the delete and archive progress above the player and the bottom nav */}
    }>
    - +
    + + +
    diff --git a/TelegramDownloader/ClientApp/apps/web/src/shell/TopBar.tsx b/TelegramDownloader/ClientApp/apps/web/src/shell/TopBar.tsx index 2b6e51e..dd4a434 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/shell/TopBar.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/shell/TopBar.tsx @@ -46,6 +46,7 @@ import { } from 'lucide-react'; import { Link, useNavigate } from 'react-router'; import { useTelegramStatus } from '@/auth/useTelegramStatus'; +import { ArchiveOperationsSummary } from '@/features/files/archives/ArchiveOperationsSummary'; import { DeleteOperationsSummary } from '@/features/files/deletes/DeleteOperationsSummary'; import { getLanguage, LANGUAGES, setLanguage, t, type Language } from '@/i18n'; import { LanguageFlag } from './LanguageFlag'; @@ -140,6 +141,7 @@ function TransfersIndicator() {

    {t('Connecting to the server...')}

    )} + diff --git a/TelegramDownloader/ClientApp/packages/api-client/src/client.ts b/TelegramDownloader/ClientApp/packages/api-client/src/client.ts index 1970cf5..1dcae4a 100644 --- a/TelegramDownloader/ClientApp/packages/api-client/src/client.ts +++ b/TelegramDownloader/ClientApp/packages/api-client/src/client.ts @@ -3,6 +3,7 @@ import { createAuthApi } from './modules/auth'; import { createChannelsApi } from './modules/channels'; import { createConfigApi } from './modules/config'; import { createDeleteOperationsApi } from './modules/deleteOperations'; +import { createArchivesApi } from './modules/archives'; import { createFilesApi } from './modules/files'; import { createLibraryApi } from './modules/library'; import { createLocalApi } from './modules/local'; @@ -33,6 +34,7 @@ export function createApiClient(options: HttpClientOptions = {}) { transfers: createTransfersApi(http), local: createLocalApi(http), deleteOperations: createDeleteOperationsApi(http), + archives: createArchivesApi(http), playlists: createPlaylistsApi(http), player: createPlayerApi(http), shares: createSharesApi(http), diff --git a/TelegramDownloader/ClientApp/packages/api-client/src/index.ts b/TelegramDownloader/ClientApp/packages/api-client/src/index.ts index dc587b1..26fdbc5 100644 --- a/TelegramDownloader/ClientApp/packages/api-client/src/index.ts +++ b/TelegramDownloader/ClientApp/packages/api-client/src/index.ts @@ -8,6 +8,7 @@ export * from './types/auth'; export type * from './types/channels'; export * from './types/config'; export * from './types/deleteOperations'; +export * from './types/archives'; export type * from './types/files'; export * from './types/library'; export type * from './types/local'; @@ -25,6 +26,7 @@ export { createAuthApi, type AuthApi } from './modules/auth'; export { createChannelsApi, type ChannelsApi } from './modules/channels'; export { createConfigApi, type ConfigApi } from './modules/config'; export { createDeleteOperationsApi, type DeleteOperationsApi } from './modules/deleteOperations'; +export { createArchivesApi, type ArchivesApi } from './modules/archives'; export { createFilesApi, type FilesApi } from './modules/files'; export { createLibraryApi, type LibraryApi } from './modules/library'; export { createLocalApi, type LocalApi } from './modules/local'; diff --git a/TelegramDownloader/ClientApp/packages/api-client/src/modules/archives.ts b/TelegramDownloader/ClientApp/packages/api-client/src/modules/archives.ts new file mode 100644 index 0000000..a8bc028 --- /dev/null +++ b/TelegramDownloader/ClientApp/packages/api-client/src/modules/archives.ts @@ -0,0 +1,41 @@ +import type { HttpClient } from '../http'; +import type { + ApiArchiveInfoDto, + ApiArchiveListingDto, + ApiArchiveOperationDto, + ArchiveEntriesRequest, + ArchiveOperationStartedDto, + CompressRequest, + ExtractArchiveRequest +} from '../types/archives'; + +const LOCAL = '/api/v1/local/archives'; +const OPS = '/api/v1/archive-operations'; +const enc = encodeURIComponent; + +/** + * Archives of the local files (capability `local.archives`): list, extract + * and compress. Extractions and compressions run in the background one at + * a time; follow them with {@link get} or the `ArchiveProgress` message of + * /hubs/events. + */ +export function createArchivesApi(http: HttpClient) { + return { + /** GET /api/v1/local/archives/info: formats this server extracts and creates. */ + info: (signal?: AbortSignal) => http.get(`${LOCAL}/info`, { signal }), + /** POST /api/v1/local/archives/entries: what an archive contains (400 `password_required`...). */ + entries: (body: ArchiveEntriesRequest, signal?: AbortSignal) => http.post(`${LOCAL}/entries`, body, { signal }), + /** POST /api/v1/local/archives/extract (202) */ + extract: (body: ExtractArchiveRequest) => http.post(`${LOCAL}/extract`, body), + /** POST /api/v1/local/archives/compress (202) */ + compress: (body: CompressRequest) => http.post(`${LOCAL}/compress`, body), + /** GET /api/v1/archive-operations: queued and running first, then those finished in the last 30 minutes. */ + list: (signal?: AbortSignal) => http.get(OPS, { signal }), + /** GET /api/v1/archive-operations/{id} */ + get: (id: string, signal?: AbortSignal) => http.get(`${OPS}/${enc(id)}`, { signal }), + /** POST /api/v1/archive-operations/{id}/cancel (202; 409 when it already finished) */ + cancel: (id: string) => http.post(`${OPS}/${enc(id)}/cancel`) + }; +} + +export type ArchivesApi = ReturnType; diff --git a/TelegramDownloader/ClientApp/packages/api-client/src/types/archives.ts b/TelegramDownloader/ClientApp/packages/api-client/src/types/archives.ts new file mode 100644 index 0000000..31917f3 --- /dev/null +++ b/TelegramDownloader/ClientApp/packages/api-client/src/types/archives.ts @@ -0,0 +1,120 @@ +/** Archives of the local files (capability `local.archives`). Mirrors `Models/Api/ArchiveDtos.cs`. */ + +export type ArchiveOperationKind = 'extract' | 'compress'; +export type ArchiveOperationPhase = 'queued' | 'preparing' | 'working' | 'done' | 'failed' | 'cancelled'; +export type ArchiveErrorCode = + | 'password_required' + | 'wrong_password' + | 'not_enough_space' + | 'missing_volume' + | 'unsupported' + | 'corrupt' + | 'not_found' + | 'tool_missing'; +export type ArchiveFormat = 'zip' | '7z' | 'tar.gz'; +export type ArchiveLevel = 'fastest' | 'normal' | 'maximum'; +export type ArchiveOverwrite = 'rename' | 'skip' | 'overwrite'; + +/** GET /api/v1/local/archives/info */ +export interface ApiArchiveInfoDto { + extractFormats: string[]; + /** `zip`, `tar.gz`, and `7z` when 7-Zip is installed. */ + createFormats: ArchiveFormat[]; + sevenZipAvailable: boolean; + levels: ArchiveLevel[]; +} + +/** Body of POST /api/v1/local/archives/entries */ +export interface ArchiveEntriesRequest { + /** Archive (any volume of a set), relative to the local root. */ + path: string; + password?: string | null; + maxEntries?: number; +} + +export interface ApiArchiveEntryDto { + path: string; + isDirectory: boolean; + size: number; + compressedSize: number; + modified?: string | null; + isEncrypted: boolean; +} + +export interface ApiArchiveListingDto { + format: string; + volumeCount: number; + isEncrypted: boolean; + isSolid: boolean; + fileCount: number; + folderCount: number; + /** Size once extracted. */ + totalSize: number; + entries: ApiArchiveEntryDto[]; + truncated: boolean; +} + +/** Body of POST /api/v1/local/archives/extract */ +export interface ExtractArchiveRequest { + path: string; + /** Folder to extract into (relative to the local root); default the folder of the archive. */ + destination?: string | null; + /** Into a new folder named after the archive (default true). */ + intoFolder?: boolean; + overwrite?: ArchiveOverwrite; + password?: string | null; + /** Delete every volume after a complete extraction. */ + deleteArchive?: boolean; +} + +/** Body of POST /api/v1/local/archives/compress */ +export interface CompressRequest { + /** Items of one folder, relative to the local root. */ + paths: string[]; + destination?: string | null; + /** Without extension; default the item's or the folder's name. */ + name?: string | null; + format?: ArchiveFormat; + level?: ArchiveLevel; +} + +export interface ArchiveOperationStartedDto { + operationId: string; +} + +export interface ApiArchiveFailureDto { + path: string; + reason: string; +} + +/** GET /api/v1/archive-operations/{id} and the `ArchiveProgress` message of /hubs/events. */ +export interface ApiArchiveOperationDto { + id: string; + kind: ArchiveOperationKind; + /** Archive (extract) or selection (compress), relative to the local root. */ + source: string; + /** Folder extracted into / archive created, relative to the local root. */ + destination?: string | null; + /** Started by "extract when the download finishes". */ + automatic: boolean; + phase: ArchiveOperationPhase; + totalFiles: number; + totalBytes: number; + processedFiles: number; + processedBytes: number; + /** 0-100. */ + progress: number; + currentItem?: string | null; + failedCount: number; + failed: ApiArchiveFailureDto[]; + archivesDeleted: boolean; + cancelRequested: boolean; + error?: string | null; + errorCode?: ArchiveErrorCode | null; + startedAt: string; + finishedAt?: string | null; +} + +export function isFinalArchivePhase(phase: ArchiveOperationPhase): boolean { + return phase === 'done' || phase === 'failed' || phase === 'cancelled'; +} diff --git a/TelegramDownloader/ClientApp/packages/api-client/src/types/events.ts b/TelegramDownloader/ClientApp/packages/api-client/src/types/events.ts index 1bc4dc0..22f80b1 100644 --- a/TelegramDownloader/ClientApp/packages/api-client/src/types/events.ts +++ b/TelegramDownloader/ClientApp/packages/api-client/src/types/events.ts @@ -2,6 +2,7 @@ // PROVISIONAL where marked: the hub is written by the API agent in parallel; align at merge. import type { ApiChannelRefreshProgressDto, ApiChannelRefreshResultDto } from './channels'; import type { ApiDeleteOperationDto } from './deleteOperations'; +import type { ApiArchiveOperationDto } from './archives'; import type { ApiLibraryScanStateDto } from './library'; import type { PlayerDataChangedEvent } from './player'; import type { SystemMetricsDto } from './system'; @@ -84,6 +85,8 @@ export interface EventsHubMessages { Metrics: MetricsEvent; LibraryScan: LibraryScanEvent; DeleteProgress: DeleteProgressEvent; + /** An extraction or compression of local files (also the ones started by "extract when the download finishes"). */ + ArchiveProgress: ApiArchiveOperationDto; /** Favourites, history or resume positions changed (from any device). */ PlayerDataChanged: PlayerDataChangedEvent; } diff --git a/TelegramDownloader/ClientApp/packages/api-client/src/types/transfers.ts b/TelegramDownloader/ClientApp/packages/api-client/src/types/transfers.ts index 18f4e35..ec98337 100644 --- a/TelegramDownloader/ClientApp/packages/api-client/src/types/transfers.ts +++ b/TelegramDownloader/ClientApp/packages/api-client/src/types/transfers.ts @@ -130,6 +130,12 @@ export interface StartDownloadRequest { targetPath?: string | null; /** Set when downloading from a shared collection instead of an owned channel. */ sharedCollectionId?: string | null; + /** Extract the archives when their download finishes (capability `transfers.autoExtract`). */ + extractArchives?: boolean; + /** With `extractArchives`: delete each archive (every volume) after a complete extraction. */ + deleteArchivesAfterExtract?: boolean; + /** With `extractArchives`: password of protected archives (kept in memory by the server). */ + archivePassword?: string | null; } /** Body of `POST /api/v1/transfers/uploads`. */ @@ -161,6 +167,12 @@ export interface DownloadMessagesRequest { messageIds: number[]; /** Destination folder relative to the server local root. */ targetPath?: string | null; + /** Extract the archives when their download finishes (capability `transfers.autoExtract`). */ + extractArchives?: boolean; + /** With `extractArchives`: delete each archive (every volume) after a complete extraction. */ + deleteArchivesAfterExtract?: boolean; + /** With `extractArchives`: password of protected archives (kept in memory by the server). */ + archivePassword?: string | null; } /** Result returned when a transfer batch has been queued. */