Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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<boolean> {
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 }),
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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();
};
Expand All @@ -41,6 +45,7 @@ export function DownloadMessagesDialog({ channelId, ids, onClose, onQueued }: {
<p className="text-xs text-fg-muted">
{t('Destination')}: <span className="font-medium text-fg">/{localRel(path)}</span>
</p>
<AutoExtractFields value={autoExtract} onChange={setAutoExtract} />
</div>
</DialogContent>
</Dialog>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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;
Expand All @@ -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) });
Expand Down Expand Up @@ -87,6 +92,7 @@ export function DownloadToServerDialog({ request, onClose }: { request: Download
{t('Destination')}: <span className="font-medium text-fg">/{localRel(path)}</span>
</p>
)}
<AutoExtractFields value={autoExtract} onChange={setAutoExtract} />
</div>
</DialogContent>
</Dialog>
Expand Down
Original file line number Diff line number Diff line change
@@ -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(
<QueryClientProvider client={client}>
<TooltipProvider>
<MemoryRouter>{node}</MemoryRouter>
</TooltipProvider>
</QueryClientProvider>
);
}

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('<ExtractDialog>', () => {
it('shows what the archive contains', async () => {
vi.mocked(api.archives.entries).mockResolvedValue(listing);
wrap(<ExtractDialog target={{ path: 'dl/Album.part1.rar', name: 'Album.part1.rar' }} onClose={() => 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(<ExtractDialog target={{ path: 'dl/secret.7z', name: 'secret.7z' }} onClose={() => 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(<ExtractDialog target={{ path: 'dl/Album.part1.rar', name: 'Album.part1.rar' }} onClose={onClose} />);
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('<DownloadToServerDialog> 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(<DownloadToServerDialog request={request} onClose={() => 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(<DownloadToServerDialog request={request} onClose={() => 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
});
});
});
Loading
Loading