mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-25 06:46:59 +00:00
feat: integrate platform capabilities for enhanced download management
- Refactored `DownloadAll` component to utilize platform capabilities for download types, improving flexibility in handling various download methods. - Introduced `buildEnabledDownloadModes` function to determine available download modes based on user settings and platform capabilities. - Updated `FileRow` and `PanelGeneral` components to conditionally render download options based on platform capabilities. - Added tests for new functionalities in `DownloadAll`, `FileRow`, and `PanelGeneral` to ensure correct behavior under different platform conditions. - Enhanced error handling for unsupported download methods, providing clearer feedback to users.
This commit is contained in:
1 parent
b5fdc8ebbe
commit
d424837e66
17 files changed
+417
-178
No files matched your search
+22
-123
@@ -2,17 +2,18 @@ import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-l
|
||||
import { FaDownload } from 'react-icons/fa';
|
||||
import { useAppSelector } from '~/hooks';
|
||||
import { toast } from 'react-toastify';
|
||||
import { SimpleQueue } from '~/util/SimpleQueue';
|
||||
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
|
||||
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
||||
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
||||
import { downloadZipAsBlob, downloadZipViaSavePicker, ZipSourceFile } from '~/util/streamZip';
|
||||
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
||||
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
export function DownloadAll() {
|
||||
const files = useAppSelector(selectFiles);
|
||||
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
|
||||
const { download, capabilities } = usePlatform();
|
||||
|
||||
if (capabilities.downloadTypes.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const downloadAllAsync = async () => {
|
||||
const fileList = Object.values(files);
|
||||
@@ -36,12 +37,16 @@ export function DownloadAll() {
|
||||
|
||||
// Single file: direct blob download, no ZIP / directory picker.
|
||||
if (completeFiles.length === 1) {
|
||||
downloadSingleBlob(completeFiles[0]);
|
||||
const file = completeFiles[0];
|
||||
await download.saveOne({
|
||||
url: file.decrypted,
|
||||
fileName: decryptedDownloadName(file),
|
||||
});
|
||||
toast.success('已开始下载');
|
||||
return;
|
||||
}
|
||||
|
||||
const modes = buildEnabledModes(batchSettings);
|
||||
const modes = buildEnabledDownloadModes(batchSettings, capabilities.downloadTypes);
|
||||
if (modes.length === 0) {
|
||||
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
|
||||
return;
|
||||
@@ -49,9 +54,17 @@ export function DownloadAll() {
|
||||
|
||||
toast.warning('开始下载,请稍候');
|
||||
|
||||
const manyInput = {
|
||||
files: completeFiles.map((file) => ({
|
||||
url: file.decrypted,
|
||||
fileName: decryptedDownloadName(file),
|
||||
})),
|
||||
rememberDirectory: batchSettings.rememberDirectory,
|
||||
};
|
||||
|
||||
for (const mode of modes) {
|
||||
try {
|
||||
const result = await runMode(mode, completeFiles, batchSettings.rememberDirectory);
|
||||
const result = await download.saveMany(mode, manyInput);
|
||||
if (result === 'ok') {
|
||||
return;
|
||||
}
|
||||
@@ -79,120 +92,6 @@ export function DownloadAll() {
|
||||
);
|
||||
}
|
||||
|
||||
type BatchMode = 'directory' | 'streamingZip' | 'blobZip';
|
||||
|
||||
function buildEnabledModes(
|
||||
settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
|
||||
): BatchMode[] {
|
||||
const modes: BatchMode[] = [];
|
||||
if (settings.directoryPicker && supportsDirectoryPicker()) {
|
||||
modes.push('directory');
|
||||
}
|
||||
if (settings.streamingZip && supportsStreamingZipDownload()) {
|
||||
modes.push('streamingZip');
|
||||
}
|
||||
if (settings.blobZip) {
|
||||
modes.push('blobZip');
|
||||
}
|
||||
return modes;
|
||||
}
|
||||
|
||||
async function runMode(
|
||||
mode: BatchMode,
|
||||
completeFiles: DecryptedAudioFile[],
|
||||
rememberDirectory: boolean,
|
||||
): Promise<'ok' | 'cancelled'> {
|
||||
switch (mode) {
|
||||
case 'directory':
|
||||
return downloadToDirectory(completeFiles, rememberDirectory);
|
||||
case 'streamingZip':
|
||||
return downloadStreamingZip(completeFiles);
|
||||
case 'blobZip':
|
||||
await downloadBlobZip(completeFiles);
|
||||
return 'ok';
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadToDirectory(
|
||||
completeFiles: DecryptedAudioFile[],
|
||||
remember: boolean,
|
||||
): Promise<'ok' | 'cancelled'> {
|
||||
const dir = await resolveWritableDirectory(remember);
|
||||
if (!dir) {
|
||||
return 'cancelled';
|
||||
}
|
||||
|
||||
const fileCount = completeFiles.length;
|
||||
const queue = new SimpleQueue(8);
|
||||
const promises = completeFiles.map(async (file) => {
|
||||
try {
|
||||
await queue.enter();
|
||||
await writeFileToDirectory(file, dir);
|
||||
} catch (e) {
|
||||
console.error(`下载失败: ${file.fileName}`, e);
|
||||
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
|
||||
throw e;
|
||||
} finally {
|
||||
queue.leave();
|
||||
}
|
||||
});
|
||||
|
||||
const promiseResults = await Promise.allSettled(promises);
|
||||
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
|
||||
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
|
||||
toast[level](`成功下载: ${success}/${fileCount}首`);
|
||||
|
||||
if (success === 0) {
|
||||
throw new Error('未能写入任何文件到所选目录');
|
||||
}
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
function decryptedDownloadName(file: DecryptedAudioFile): string {
|
||||
return `${file.cleanName}.${file.ext}`;
|
||||
}
|
||||
|
||||
async function writeFileToDirectory(file: DecryptedAudioFile, dir: FileSystemDirectoryHandle) {
|
||||
const fileHandle = await dir.getFileHandle(decryptedDownloadName(file), { create: true });
|
||||
const fileStream = await fileHandle.createWritable();
|
||||
try {
|
||||
const res = await fetch(file.decrypted);
|
||||
if (!res.ok) {
|
||||
throw new Error(`无法读取文件: ${decryptedDownloadName(file)} (${res.status})`);
|
||||
}
|
||||
if (!res.body) {
|
||||
await fileStream.write(await res.arrayBuffer());
|
||||
await fileStream.close();
|
||||
return;
|
||||
}
|
||||
await res.body.pipeTo(fileStream);
|
||||
} catch (e) {
|
||||
await fileStream.abort();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function toZipSources(files: DecryptedAudioFile[]): ZipSourceFile[] {
|
||||
return files.map((file) => ({
|
||||
name: decryptedDownloadName(file),
|
||||
url: file.decrypted,
|
||||
}));
|
||||
}
|
||||
|
||||
function downloadSingleBlob(file: DecryptedAudioFile) {
|
||||
triggerAnchorDownload(file.decrypted, decryptedDownloadName(file));
|
||||
}
|
||||
|
||||
async function downloadStreamingZip(completeFiles: DecryptedAudioFile[]): Promise<'ok' | 'cancelled'> {
|
||||
const sources = toZipSources(completeFiles);
|
||||
const result = await downloadZipViaSavePicker(sources);
|
||||
if (result === 'ok') {
|
||||
toast.success(`已导出 ZIP(${completeFiles.length} 首)`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function downloadBlobZip(completeFiles: DecryptedAudioFile[]): Promise<void> {
|
||||
await downloadZipAsBlob(toZipSources(completeFiles));
|
||||
toast.success(`已开始下载 ZIP(${completeFiles.length} 首)`);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { DownloadAll } from '~/components/DownloadAll';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||
|
||||
test('hides download-all control when platform has no downloadTypes', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: {
|
||||
request: () => Promise.resolve(null as never),
|
||||
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||
},
|
||||
downloadTypes: [],
|
||||
});
|
||||
|
||||
renderWithProviders(<DownloadAll />, { platform });
|
||||
|
||||
expect(screen.queryByTitle('下载全部')).not.toBeInTheDocument();
|
||||
expect(document.getElementById('downloadAll')).toBeNull();
|
||||
});
|
||||
|
||||
test('renders download-all control when PackZip is available', () => {
|
||||
renderWithProviders(<DownloadAll />);
|
||||
|
||||
expect(screen.getByTitle('下载全部')).toBeInTheDocument();
|
||||
expect(document.getElementById('downloadAll')).not.toBeNull();
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { DecryptedAudioFile, deleteFile, ProcessState } from './fileListingSlice
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { FileError } from './FileError';
|
||||
import classNames from 'classnames';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
interface FileRowProps {
|
||||
id: string;
|
||||
@@ -10,7 +11,9 @@ interface FileRowProps {
|
||||
|
||||
export function FileRow({ id, file }: FileRowProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
const { capabilities } = usePlatform();
|
||||
const isDecrypted = file.state === ProcessState.COMPLETE;
|
||||
const showDownload = capabilities.downloadTypes.length > 0;
|
||||
|
||||
const decryptedName = file.cleanName + '.' + file.ext;
|
||||
|
||||
@@ -32,18 +35,20 @@ export function FileRow({ id, file }: FileRowProps) {
|
||||
</div>
|
||||
|
||||
<div className="card-actions justify-end">
|
||||
<a
|
||||
href={file.decrypted}
|
||||
download={decryptedName}
|
||||
title={`下载: ${decryptedName}`}
|
||||
className={classNames('btn', {
|
||||
'btn-primary': file.decrypted,
|
||||
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
||||
})}
|
||||
data-testid="audio-download"
|
||||
>
|
||||
下载
|
||||
</a>
|
||||
{showDownload && (
|
||||
<a
|
||||
href={file.decrypted}
|
||||
download={decryptedName}
|
||||
title={`下载: ${decryptedName}`}
|
||||
className={classNames('btn', {
|
||||
'btn-primary': file.decrypted,
|
||||
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
||||
})}
|
||||
data-testid="audio-download"
|
||||
>
|
||||
下载
|
||||
</a>
|
||||
)}
|
||||
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
|
||||
删除
|
||||
</button>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||
import { untouchedFile } from './__fixture__/file-list';
|
||||
import { FileRow } from '../FileRow';
|
||||
@@ -14,4 +15,19 @@ test('should render basic title (done)', () => {
|
||||
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
|
||||
|
||||
expect(screen.getAllByTestId('file-row')).toHaveLength(1);
|
||||
expect(screen.getByTestId('audio-download')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('hides single-file download when platform has no downloadTypes', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: {
|
||||
request: () => Promise.resolve(null as never),
|
||||
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||
},
|
||||
downloadTypes: [],
|
||||
});
|
||||
|
||||
renderWithProviders(<FileRow id="file://done" file={completedFile} />, { platform });
|
||||
|
||||
expect(screen.queryByTestId('audio-download')).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -2,15 +2,19 @@ import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
|
||||
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
|
||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
export function PanelGeneral() {
|
||||
const dispatch = useAppDispatch();
|
||||
const batch = useAppSelector(selectStagingBatchDownloadSettings);
|
||||
const canDirectoryPicker = supportsDirectoryPicker();
|
||||
const canStreamingZip = supportsStreamingZipDownload();
|
||||
const { capabilities } = usePlatform();
|
||||
const downloadTypes = new Set(capabilities.downloadTypes);
|
||||
const canDirectoryPicker = downloadTypes.has(BatchDownloadType.SelectDirectory);
|
||||
const canStreamingZip = downloadTypes.has(BatchDownloadType.StreamZip);
|
||||
const canBlobZip = downloadTypes.has(BatchDownloadType.PackZip);
|
||||
const [hasRememberedDir, setHasRememberedDir] = useState(false);
|
||||
|
||||
const refreshRemembered = useCallback(() => {
|
||||
@@ -57,7 +61,7 @@ export function PanelGeneral() {
|
||||
description={
|
||||
canDirectoryPicker
|
||||
? '通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。'
|
||||
: '当前浏览器不支持 showDirectoryPicker。'
|
||||
: '当前环境不支持选择目录批量下载。'
|
||||
}
|
||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||
/>
|
||||
@@ -93,20 +97,26 @@ export function PanelGeneral() {
|
||||
description={
|
||||
canStreamingZip
|
||||
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
|
||||
: '当前浏览器不支持 showSaveFilePicker,无法流式写出 ZIP。'
|
||||
: '当前环境不支持流式写出 ZIP。'
|
||||
}
|
||||
onChange={(checked) => setBatch('streamingZip', checked)}
|
||||
/>
|
||||
|
||||
<BatchOption
|
||||
id={idBlobZip}
|
||||
checked={batch.blobZip}
|
||||
checked={batch.blobZip && canBlobZip}
|
||||
disabled={!canBlobZip}
|
||||
dimmed={!canBlobZip}
|
||||
title="生成单个 ZIP 并触发下载"
|
||||
description={
|
||||
<>
|
||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
||||
</>
|
||||
canBlobZip ? (
|
||||
<>
|
||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
||||
</>
|
||||
) : (
|
||||
'当前环境不支持打包 ZIP 下载。'
|
||||
)
|
||||
}
|
||||
onChange={(checked) => setBatch('blobZip', checked)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral';
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||
|
||||
const stubCrypto = {
|
||||
request: () => Promise.resolve(null as never),
|
||||
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||
};
|
||||
|
||||
test('disables directory and streaming options when only PackZip is capable', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
});
|
||||
|
||||
renderWithProviders(<PanelGeneral />, { platform });
|
||||
|
||||
expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).not.toBeDisabled();
|
||||
});
|
||||
|
||||
test('disables pack-zip when capability is absent', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
downloadTypes: [],
|
||||
});
|
||||
|
||||
renderWithProviders(<PanelGeneral />, { platform });
|
||||
|
||||
expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeDisabled();
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import { AndroidImportType, BatchDownloadType } from '~/platform/capabilities';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
|
||||
import { createPlatformProvider } from '~/platform/createPlatformProvider';
|
||||
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
import { NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
|
||||
function createMockCrypto(overrides: Partial<BrowserCrypto> = {}): BrowserCrypto {
|
||||
return {
|
||||
@@ -22,6 +22,7 @@ describe('BrowserProvider', () => {
|
||||
expect(provider.id).toBe('browser');
|
||||
expect(provider.capabilities).toEqual({
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
directFsAccess: false,
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: [],
|
||||
});
|
||||
@@ -112,14 +113,31 @@ describe('BrowserProvider', () => {
|
||||
expect(loadCrypto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('unwired download methods throw NotImplementedError', async () => {
|
||||
test('download.saveMany rejects types outside downloadTypes', async () => {
|
||||
const provider = createBrowserProvider({
|
||||
crypto: createMockCrypto(),
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
});
|
||||
|
||||
await expect(provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toBeInstanceOf(
|
||||
NotImplementedError,
|
||||
);
|
||||
await expect(
|
||||
provider.download.saveMany(BatchDownloadType.SelectDirectory, {
|
||||
files: [{ url: 'blob:x', fileName: 'a.flac' }],
|
||||
}),
|
||||
).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||
});
|
||||
|
||||
test('download.saveOne works when PackZip is available', async () => {
|
||||
const saveOne = vi.fn().mockResolvedValue(undefined);
|
||||
const provider = createBrowserProvider({
|
||||
crypto: createMockCrypto(),
|
||||
download: {
|
||||
saveOne,
|
||||
saveMany: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
await provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' });
|
||||
expect(saveOne).toHaveBeenCalledWith({ url: 'blob:x', fileName: 'a.flac' });
|
||||
});
|
||||
|
||||
test('settings.load returns null when storage is empty', async () => {
|
||||
@@ -138,6 +156,6 @@ describe('BrowserProvider', () => {
|
||||
expect(provider.id).toBe('browser');
|
||||
expect(provider.capabilities.nativeKeyAccess).toEqual([]);
|
||||
expect(provider.capabilities.androidKeyAccess).toBe(AndroidImportType.None);
|
||||
expect(provider.capabilities.downloadTypes).not.toContain(BatchDownloadType.DirectWrite);
|
||||
expect(provider.capabilities.directFsAccess).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import { createBrowserDownload } from '~/platform/browser/browserDownload';
|
||||
import { NotSupportedMethod } from '~/platform/errors';
|
||||
import * as triggerDownload from '~/util/triggerDownload';
|
||||
|
||||
describe('createBrowserDownload', () => {
|
||||
test('saveOne triggers anchor download when any type is available', async () => {
|
||||
const spy = vi.spyOn(triggerDownload, 'triggerAnchorDownload').mockImplementation(() => undefined);
|
||||
const download = createBrowserDownload([BatchDownloadType.PackZip]);
|
||||
|
||||
await download.saveOne({ url: 'blob:x', fileName: 'a.flac' });
|
||||
|
||||
expect(spy).toHaveBeenCalledWith('blob:x', 'a.flac');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test('saveOne throws NotSupportedMethod when downloadTypes is empty', async () => {
|
||||
const download = createBrowserDownload([]);
|
||||
|
||||
await expect(download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toSatisfy((err: unknown) => {
|
||||
return err instanceof NotSupportedMethod && err.capability === 'download.saveOne';
|
||||
});
|
||||
});
|
||||
|
||||
test('saveMany rejects types outside downloadTypes', async () => {
|
||||
const download = createBrowserDownload([BatchDownloadType.PackZip]);
|
||||
|
||||
await expect(
|
||||
download.saveMany(BatchDownloadType.SelectDirectory, { files: [{ url: 'blob:x', fileName: 'a.flac' }] }),
|
||||
).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||
|
||||
await expect(
|
||||
download.saveMany(BatchDownloadType.StreamZip, { files: [{ url: 'blob:x', fileName: 'a.flac' }] }),
|
||||
).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||
|
||||
const allOn: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'> = {
|
||||
directoryPicker: true,
|
||||
streamingZip: true,
|
||||
blobZip: true,
|
||||
};
|
||||
|
||||
const allOff: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'> = {
|
||||
directoryPicker: false,
|
||||
streamingZip: false,
|
||||
blobZip: false,
|
||||
};
|
||||
|
||||
describe('buildEnabledDownloadModes', () => {
|
||||
test('intersects settings with capabilities in fallback order', () => {
|
||||
expect(
|
||||
buildEnabledDownloadModes(allOn, [
|
||||
BatchDownloadType.SelectDirectory,
|
||||
BatchDownloadType.StreamZip,
|
||||
BatchDownloadType.PackZip,
|
||||
]),
|
||||
).toEqual([BatchDownloadType.SelectDirectory, BatchDownloadType.StreamZip, BatchDownloadType.PackZip]);
|
||||
});
|
||||
|
||||
test('omits modes disabled in settings even when capable', () => {
|
||||
expect(
|
||||
buildEnabledDownloadModes({ directoryPicker: false, streamingZip: true, blobZip: true }, [
|
||||
BatchDownloadType.SelectDirectory,
|
||||
BatchDownloadType.StreamZip,
|
||||
BatchDownloadType.PackZip,
|
||||
]),
|
||||
).toEqual([BatchDownloadType.StreamZip, BatchDownloadType.PackZip]);
|
||||
});
|
||||
|
||||
test('omits modes missing from capabilities even when enabled in settings', () => {
|
||||
expect(buildEnabledDownloadModes(allOn, [BatchDownloadType.PackZip])).toEqual([BatchDownloadType.PackZip]);
|
||||
});
|
||||
|
||||
test('returns empty when no overlap', () => {
|
||||
expect(buildEnabledDownloadModes(allOff, [BatchDownloadType.PackZip])).toEqual([]);
|
||||
expect(buildEnabledDownloadModes(allOn, [])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,6 @@ import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError }
|
||||
describe('platform capabilities enums', () => {
|
||||
test('BatchDownloadType members stay stable', () => {
|
||||
expect(BatchDownloadType).toEqual({
|
||||
DirectWrite: 'DirectWrite',
|
||||
SelectDirectory: 'SelectDirectory',
|
||||
StreamZip: 'StreamZip',
|
||||
PackZip: 'PackZip',
|
||||
@@ -60,8 +59,8 @@ describe('NotSupportedMethod', () => {
|
||||
});
|
||||
|
||||
test('accepts a custom message', () => {
|
||||
const err = new NotSupportedMethod('download.saveMany', 'DirectWrite unavailable in browser');
|
||||
expect(err.message).toBe('DirectWrite unavailable in browser');
|
||||
const err = new NotSupportedMethod('download.saveMany', 'SelectDirectory unavailable on this platform');
|
||||
expect(err.message).toBe('SelectDirectory unavailable on this platform');
|
||||
expect(err.capability).toBe('download.saveMany');
|
||||
});
|
||||
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
import { AndroidImportType, type BatchDownloadType, type NativeImportType } from '~/platform/capabilities';
|
||||
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
import { AndroidImportType, type NativeImportType } from '~/platform/capabilities';
|
||||
import { NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
import type {
|
||||
AndroidAdbImportOptions,
|
||||
DownloadManyInput,
|
||||
DownloadOneInput,
|
||||
NativeImportResult,
|
||||
PlatformCapabilities,
|
||||
} from '~/platform/types';
|
||||
import type { AndroidAdbImportOptions, NativeImportResult, PlatformCapabilities } from '~/platform/types';
|
||||
import { createBrowserDownload, type BrowserDownload } from './browserDownload';
|
||||
import { loadDecryptWorkerCrypto, type BrowserCrypto } from './browserCrypto';
|
||||
import { createBrowserSettingsIo, DEFAULT_SETTINGS_STORAGE_KEY, type SettingsStorage } from './browserSettingsIo';
|
||||
import { detectBrowserDownloadTypes } from './detectDownloadCapabilities';
|
||||
|
||||
function notImplemented(capability: string): Promise<never> {
|
||||
return Promise.reject(new NotImplementedError(capability));
|
||||
}
|
||||
|
||||
function notSupported(capability: string): Promise<never> {
|
||||
return Promise.reject(new NotSupportedMethod(capability));
|
||||
}
|
||||
@@ -32,19 +23,29 @@ export interface BrowserProviderOptions {
|
||||
crypto?: BrowserCrypto;
|
||||
/** Defaults to dynamic-importing decrypt-worker/client. Injected in tests. */
|
||||
loadCrypto?: () => Promise<BrowserCrypto>;
|
||||
/** Override download backend (tests). Defaults to FS Access / ZIP helpers. */
|
||||
download?: BrowserDownload;
|
||||
/** Override detected `downloadTypes` (tests). */
|
||||
downloadTypes?: PlatformCapabilities['downloadTypes'];
|
||||
/** Override `directFsAccess` (tests). Browser default is `false`. */
|
||||
directFsAccess?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-browser `PlatformProvider`.
|
||||
* Capabilities follow runtime File System Access / save-picker probing (no DirectWrite).
|
||||
* Capabilities follow runtime File System Access / save-picker probing (`directFsAccess: false`).
|
||||
* `settings` persists production settings via localStorage (or injected storage).
|
||||
* `crypto` binds to the decrypt worker only inside `init()` (dynamic import; no construct-time Worker).
|
||||
* `download` currently throws `NotImplementedError` (not yet delegated to download helpers).
|
||||
* `download` delegates to anchor / directory picker / streaming ZIP / pack ZIP helpers.
|
||||
* Native and ADB key import throw `NotSupportedMethod` (`nativeKeyAccess` empty, `androidKeyAccess` None).
|
||||
*/
|
||||
export function createBrowserProvider(options: BrowserProviderOptions = {}): PlatformProvider {
|
||||
const downloadTypes = Object.freeze(
|
||||
options.downloadTypes ? [...options.downloadTypes] : detectBrowserDownloadTypes(),
|
||||
);
|
||||
const capabilities: PlatformCapabilities = Object.freeze({
|
||||
downloadTypes: Object.freeze(detectBrowserDownloadTypes()),
|
||||
downloadTypes,
|
||||
directFsAccess: options.directFsAccess ?? false,
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: Object.freeze([] as NativeImportType[]),
|
||||
});
|
||||
@@ -54,6 +55,8 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
||||
options.settingsStorageKey ?? DEFAULT_SETTINGS_STORAGE_KEY,
|
||||
);
|
||||
|
||||
const download = options.download ?? createBrowserDownload(downloadTypes);
|
||||
|
||||
const loadCrypto = options.loadCrypto ?? loadDecryptWorkerCrypto;
|
||||
let backend: BrowserCrypto | null = options.crypto ?? null;
|
||||
let initPromise: Promise<void> | null = options.crypto ? Promise.resolve() : null;
|
||||
@@ -97,10 +100,7 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
||||
save: (settings) => settingsIo.save(settings),
|
||||
},
|
||||
|
||||
download: {
|
||||
saveOne: (_input: DownloadOneInput) => notImplemented('download.saveOne'),
|
||||
saveMany: (_type: BatchDownloadType, _input: DownloadManyInput) => notImplemented('download.saveMany'),
|
||||
},
|
||||
download,
|
||||
|
||||
keys: {
|
||||
importNative: (_targets: readonly NativeImportType[]): Promise<NativeImportResult> =>
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { toast } from 'react-toastify';
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import { NotSupportedMethod } from '~/platform/errors';
|
||||
import type { DownloadManyInput, DownloadManyResult, DownloadOneInput } from '~/platform/types';
|
||||
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
||||
import { SimpleQueue } from '~/util/SimpleQueue';
|
||||
import { downloadZipAsBlob, downloadZipViaSavePicker, type ZipSourceFile } from '~/util/streamZip';
|
||||
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
||||
|
||||
export interface BrowserDownload {
|
||||
saveOne(input: DownloadOneInput): Promise<void>;
|
||||
saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Browser download backend: single-file anchor download plus batch directory / ZIP modes.
|
||||
* Modes not listed in `downloadTypes` reject with `NotSupportedMethod`.
|
||||
*/
|
||||
export function createBrowserDownload(downloadTypes: readonly BatchDownloadType[]): BrowserDownload {
|
||||
const supported = new Set(downloadTypes);
|
||||
|
||||
return {
|
||||
saveOne(input: DownloadOneInput): Promise<void> {
|
||||
if (supported.size === 0) {
|
||||
return Promise.reject(new NotSupportedMethod('download.saveOne'));
|
||||
}
|
||||
triggerAnchorDownload(input.url, input.fileName);
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
async saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult> {
|
||||
if (!supported.has(type)) {
|
||||
throw new NotSupportedMethod('download.saveMany', `${type} unavailable on this platform`);
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case BatchDownloadType.SelectDirectory:
|
||||
return downloadToDirectory(input.files, input.rememberDirectory ?? false);
|
||||
case BatchDownloadType.StreamZip:
|
||||
return downloadStreamingZip(input.files);
|
||||
case BatchDownloadType.PackZip:
|
||||
await downloadBlobZip(input.files);
|
||||
return 'ok';
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function downloadToDirectory(files: DownloadManyInput['files'], remember: boolean): Promise<DownloadManyResult> {
|
||||
const dir = await resolveWritableDirectory(remember);
|
||||
if (!dir) {
|
||||
return 'cancelled';
|
||||
}
|
||||
|
||||
const fileCount = files.length;
|
||||
const queue = new SimpleQueue(8);
|
||||
const promises = files.map(async (file) => {
|
||||
try {
|
||||
await queue.enter();
|
||||
await writeFileToDirectory(file.url, file.fileName, dir);
|
||||
} catch (e) {
|
||||
console.error(`下载失败: ${file.fileName}`, e);
|
||||
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
|
||||
throw e;
|
||||
} finally {
|
||||
queue.leave();
|
||||
}
|
||||
});
|
||||
|
||||
const promiseResults = await Promise.allSettled(promises);
|
||||
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
|
||||
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
|
||||
toast[level](`成功下载: ${success}/${fileCount}首`);
|
||||
|
||||
if (success === 0) {
|
||||
throw new Error('未能写入任何文件到所选目录');
|
||||
}
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
async function writeFileToDirectory(url: string, fileName: string, dir: FileSystemDirectoryHandle) {
|
||||
const fileHandle = await dir.getFileHandle(fileName, { create: true });
|
||||
const fileStream = await fileHandle.createWritable();
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
throw new Error(`无法读取文件: ${fileName} (${res.status})`);
|
||||
}
|
||||
if (!res.body) {
|
||||
await fileStream.write(await res.arrayBuffer());
|
||||
await fileStream.close();
|
||||
return;
|
||||
}
|
||||
await res.body.pipeTo(fileStream);
|
||||
} catch (e) {
|
||||
await fileStream.abort();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function toZipSources(files: DownloadManyInput['files']): ZipSourceFile[] {
|
||||
return files.map((file) => ({
|
||||
name: file.fileName,
|
||||
url: file.url,
|
||||
}));
|
||||
}
|
||||
|
||||
async function downloadStreamingZip(files: DownloadManyInput['files']): Promise<DownloadManyResult> {
|
||||
const result = await downloadZipViaSavePicker(toZipSources(files));
|
||||
if (result === 'ok') {
|
||||
toast.success(`已导出 ZIP(${files.length} 首)`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function downloadBlobZip(files: DownloadManyInput['files']): Promise<void> {
|
||||
await downloadZipAsBlob(toZipSources(files));
|
||||
toast.success(`已开始下载 ZIP(${files.length} 首)`);
|
||||
}
|
||||
@@ -3,7 +3,8 @@ import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/ba
|
||||
|
||||
/**
|
||||
* Runtime download modes for the browser provider.
|
||||
* Same probing order as `DownloadAll` (directory picker → streaming ZIP → pack ZIP; no DirectWrite).
|
||||
* Order: directory picker → streaming ZIP → pack ZIP.
|
||||
* UI must read `capabilities.downloadTypes` rather than calling these probes directly.
|
||||
*/
|
||||
export function detectBrowserDownloadTypes(): BatchDownloadType[] {
|
||||
const types: BatchDownloadType[] = [];
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||
|
||||
/**
|
||||
* Intersect user batch-download settings with platform `downloadTypes`.
|
||||
* Order matches browser fallback: SelectDirectory → StreamZip → PackZip.
|
||||
* Native direct-disk write is gated by `capabilities.directFsAccess`, not these modes.
|
||||
*/
|
||||
export function buildEnabledDownloadModes(
|
||||
settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
|
||||
downloadTypes: readonly BatchDownloadType[],
|
||||
): BatchDownloadType[] {
|
||||
const available = new Set(downloadTypes);
|
||||
const modes: BatchDownloadType[] = [];
|
||||
|
||||
if (settings.directoryPicker && available.has(BatchDownloadType.SelectDirectory)) {
|
||||
modes.push(BatchDownloadType.SelectDirectory);
|
||||
}
|
||||
if (settings.streamingZip && available.has(BatchDownloadType.StreamZip)) {
|
||||
modes.push(BatchDownloadType.StreamZip);
|
||||
}
|
||||
if (settings.blobZip && available.has(BatchDownloadType.PackZip)) {
|
||||
modes.push(BatchDownloadType.PackZip);
|
||||
}
|
||||
|
||||
return modes;
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
/** Batch download modes a platform may expose via `capabilities.downloadTypes`. */
|
||||
export enum BatchDownloadType {
|
||||
/** Native client writes decrypted files to disk (beside source or fixed directory). */
|
||||
DirectWrite = 'DirectWrite',
|
||||
/** Existing File System Access directory picker. */
|
||||
SelectDirectory = 'SelectDirectory',
|
||||
/** Existing streaming ZIP via `showSaveFilePicker`. */
|
||||
|
||||
@@ -32,7 +32,7 @@ export class PlatformNotInitializedError extends Error {
|
||||
|
||||
/**
|
||||
* Thrown when the current platform explicitly does not support a method / mode
|
||||
* (e.g. Browser `keys.importNative`, or `saveMany(DirectWrite)` when not in `downloadTypes`).
|
||||
* (e.g. Browser `keys.importNative`, or `saveMany(type)` when `type` ∉ `downloadTypes`).
|
||||
* Callers should use `instanceof` / `code` — never treat as a silent no-op.
|
||||
*/
|
||||
export class NotSupportedMethod extends Error {
|
||||
|
||||
@@ -7,6 +7,11 @@ import type { AndroidImportType, BatchDownloadType, NativeImportType } from './c
|
||||
export interface PlatformCapabilities {
|
||||
/** Supported batch/single download modes (array). */
|
||||
downloadTypes: readonly BatchDownloadType[];
|
||||
/**
|
||||
* Whether the platform can write decrypted files directly to the local filesystem
|
||||
* (e.g. beside source or a fixed output directory). Gates DirectWrite-related settings UI.
|
||||
*/
|
||||
directFsAccess: boolean;
|
||||
/** Android key import path (single value). */
|
||||
androidKeyAccess: AndroidImportType;
|
||||
/** One-click native import targets (array; empty = unsupported). */
|
||||
|
||||
Reference in new issue
Block a user