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()}>
+
+
+ {t('Cancel')}
+
+ } loading={busy} onClick={() => void submit()}>
+ {t('Extract')}
+
+ >
+ }
+ >
+ {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"
+ />
+ setListedWith(password)}>
+ {t('See contents')}
+
+
+ )}
+
+
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={
+ <>
+
+ {t('Cancel')}
+
+ } loading={busy} disabled={!value.trim()} onClick={() => void submit()}>
+ {t('Compress')}
+
+ >
+ }
+ >
+
+
+ {({ 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 ? (
+ setOpen((v) => !v)}
+ >
+ {t('{count} entries could not be processed', { count: dto.failedCount })}
+
+
+ ) : (
+
+ )}
+ {active && (
+ void cancelArchive(op.id)}>
+ {op.cancelling || dto.cancelRequested ? t('Cancelling...') : t('Cancel')}
+
+ )}
+
+
+ {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...')}
)}
+
{t('Open transfers')}
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. */
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 0000000..ca1182f
Binary files /dev/null and b/Test/Fixtures/Archives/multi.7z.001 differ
diff --git a/Test/Fixtures/Archives/multi.7z.002 b/Test/Fixtures/Archives/multi.7z.002
new file mode 100644
index 0000000..aa3f037
Binary files /dev/null and b/Test/Fixtures/Archives/multi.7z.002 differ
diff --git a/Test/Fixtures/Archives/multi.7z.003 b/Test/Fixtures/Archives/multi.7z.003
new file mode 100644
index 0000000..2620d2f
Binary files /dev/null and b/Test/Fixtures/Archives/multi.7z.003 differ
diff --git a/Test/Fixtures/Archives/plain.7z b/Test/Fixtures/Archives/plain.7z
new file mode 100644
index 0000000..a61614e
Binary files /dev/null and b/Test/Fixtures/Archives/plain.7z differ
diff --git a/Test/Fixtures/Archives/secret.7z b/Test/Fixtures/Archives/secret.7z
new file mode 100644
index 0000000..30fe5fc
Binary files /dev/null and b/Test/Fixtures/Archives/secret.7z differ
diff --git a/Test/Fixtures/Archives/secret.zip b/Test/Fixtures/Archives/secret.zip
new file mode 100644
index 0000000..786846a
Binary files /dev/null and b/Test/Fixtures/Archives/secret.zip differ
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 @@
+
+
+
+
+