From d424837e66c9670132f65b4e4b229ca1770cf02b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B2=81=E6=A0=91=E4=BA=BA?= Date: Sun, 1 Nov 2026 11:32:04 +0900 Subject: [PATCH] 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. --- src/components/DownloadAll.tsx | 145 +++--------------- src/components/__tests__/DownloadAll.test.tsx | 25 +++ src/features/file-listing/FileRow.tsx | 29 ++-- .../file-listing/__tests__/FileRow.test.tsx | 16 ++ src/features/settings/panels/PanelGeneral.tsx | 30 ++-- .../panels/__tests__/PanelGeneral.test.tsx | 35 +++++ .../__tests__/BrowserProvider.test.ts | 30 +++- .../__tests__/browserDownload.test.ts | 36 +++++ .../buildEnabledDownloadModes.test.ts | 46 ++++++ src/platform/__tests__/capabilities.test.ts | 5 +- src/platform/browser/BrowserProvider.ts | 40 ++--- src/platform/browser/browserDownload.ts | 119 ++++++++++++++ .../browser/detectDownloadCapabilities.ts | 3 +- src/platform/buildEnabledDownloadModes.ts | 27 ++++ src/platform/capabilities.ts | 2 - src/platform/errors.ts | 2 +- src/platform/types.ts | 5 + 17 files changed, 417 insertions(+), 178 deletions(-) create mode 100644 src/components/__tests__/DownloadAll.test.tsx create mode 100644 src/features/settings/panels/__tests__/PanelGeneral.test.tsx create mode 100644 src/platform/__tests__/browserDownload.test.ts create mode 100644 src/platform/__tests__/buildEnabledDownloadModes.test.ts create mode 100644 src/platform/browser/browserDownload.ts create mode 100644 src/platform/buildEnabledDownloadModes.ts diff --git a/src/components/DownloadAll.tsx b/src/components/DownloadAll.tsx index 3694d3a..149865c 100644 --- a/src/components/DownloadAll.tsx +++ b/src/components/DownloadAll.tsx @@ -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, -): 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 { - await downloadZipAsBlob(toZipSources(completeFiles)); - toast.success(`已开始下载 ZIP(${completeFiles.length} 首)`); -} diff --git a/src/components/__tests__/DownloadAll.test.tsx b/src/components/__tests__/DownloadAll.test.tsx new file mode 100644 index 0000000..5ace343 --- /dev/null +++ b/src/components/__tests__/DownloadAll.test.tsx @@ -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(, { platform }); + + expect(screen.queryByTitle('下载全部')).not.toBeInTheDocument(); + expect(document.getElementById('downloadAll')).toBeNull(); +}); + +test('renders download-all control when PackZip is available', () => { + renderWithProviders(); + + expect(screen.getByTitle('下载全部')).toBeInTheDocument(); + expect(document.getElementById('downloadAll')).not.toBeNull(); +}); diff --git a/src/features/file-listing/FileRow.tsx b/src/features/file-listing/FileRow.tsx index b83bc66..2ba7d3f 100644 --- a/src/features/file-listing/FileRow.tsx +++ b/src/features/file-listing/FileRow.tsx @@ -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) {
- - 下载 - + {showDownload && ( + + 下载 + + )} diff --git a/src/features/file-listing/__tests__/FileRow.test.tsx b/src/features/file-listing/__tests__/FileRow.test.tsx index 1e58397..0a34064 100644 --- a/src/features/file-listing/__tests__/FileRow.test.tsx +++ b/src/features/file-listing/__tests__/FileRow.test.tsx @@ -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(); 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(, { platform }); + + expect(screen.queryByTestId('audio-download')).not.toBeInTheDocument(); }); diff --git a/src/features/settings/panels/PanelGeneral.tsx b/src/features/settings/panels/PanelGeneral.tsx index a91c81b..0327034 100644 --- a/src/features/settings/panels/PanelGeneral.tsx +++ b/src/features/settings/panels/PanelGeneral.tsx @@ -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)} /> - 在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约 - 500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。 - + canBlobZip ? ( + <> + 在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约 + 500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。 + + ) : ( + '当前环境不支持打包 ZIP 下载。' + ) } onChange={(checked) => setBatch('blobZip', checked)} /> diff --git a/src/features/settings/panels/__tests__/PanelGeneral.test.tsx b/src/features/settings/panels/__tests__/PanelGeneral.test.tsx new file mode 100644 index 0000000..b08ef68 --- /dev/null +++ b/src/features/settings/panels/__tests__/PanelGeneral.test.tsx @@ -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(, { 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(, { platform }); + + expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled(); + expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled(); + expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeDisabled(); +}); diff --git a/src/platform/__tests__/BrowserProvider.test.ts b/src/platform/__tests__/BrowserProvider.test.ts index 959d890..6d65d99 100644 --- a/src/platform/__tests__/BrowserProvider.test.ts +++ b/src/platform/__tests__/BrowserProvider.test.ts @@ -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 { 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); }); }); diff --git a/src/platform/__tests__/browserDownload.test.ts b/src/platform/__tests__/browserDownload.test.ts new file mode 100644 index 0000000..029625d --- /dev/null +++ b/src/platform/__tests__/browserDownload.test.ts @@ -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); + }); +}); diff --git a/src/platform/__tests__/buildEnabledDownloadModes.test.ts b/src/platform/__tests__/buildEnabledDownloadModes.test.ts new file mode 100644 index 0000000..50d4a4d --- /dev/null +++ b/src/platform/__tests__/buildEnabledDownloadModes.test.ts @@ -0,0 +1,46 @@ +import { BatchDownloadType } from '~/platform/capabilities'; +import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes'; +import type { BatchDownloadSettings } from '~/features/settings/settingsSlice'; + +const allOn: Pick = { + directoryPicker: true, + streamingZip: true, + blobZip: true, +}; + +const allOff: Pick = { + 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([]); + }); +}); diff --git a/src/platform/__tests__/capabilities.test.ts b/src/platform/__tests__/capabilities.test.ts index f529af8..eb70c90 100644 --- a/src/platform/__tests__/capabilities.test.ts +++ b/src/platform/__tests__/capabilities.test.ts @@ -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'); }); diff --git a/src/platform/browser/BrowserProvider.ts b/src/platform/browser/BrowserProvider.ts index e699f3d..be90872 100644 --- a/src/platform/browser/BrowserProvider.ts +++ b/src/platform/browser/BrowserProvider.ts @@ -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 { - return Promise.reject(new NotImplementedError(capability)); -} - function notSupported(capability: string): Promise { 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; + /** 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 | 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 => diff --git a/src/platform/browser/browserDownload.ts b/src/platform/browser/browserDownload.ts new file mode 100644 index 0000000..445e8f5 --- /dev/null +++ b/src/platform/browser/browserDownload.ts @@ -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; + saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise; +} + +/** + * 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 { + 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 { + 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 { + 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 { + const result = await downloadZipViaSavePicker(toZipSources(files)); + if (result === 'ok') { + toast.success(`已导出 ZIP(${files.length} 首)`); + } + return result; +} + +async function downloadBlobZip(files: DownloadManyInput['files']): Promise { + await downloadZipAsBlob(toZipSources(files)); + toast.success(`已开始下载 ZIP(${files.length} 首)`); +} diff --git a/src/platform/browser/detectDownloadCapabilities.ts b/src/platform/browser/detectDownloadCapabilities.ts index 8f84b50..c2ef18e 100644 --- a/src/platform/browser/detectDownloadCapabilities.ts +++ b/src/platform/browser/detectDownloadCapabilities.ts @@ -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[] = []; diff --git a/src/platform/buildEnabledDownloadModes.ts b/src/platform/buildEnabledDownloadModes.ts new file mode 100644 index 0000000..7a4dd56 --- /dev/null +++ b/src/platform/buildEnabledDownloadModes.ts @@ -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, + 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; +} diff --git a/src/platform/capabilities.ts b/src/platform/capabilities.ts index 5748e86..f603fab 100644 --- a/src/platform/capabilities.ts +++ b/src/platform/capabilities.ts @@ -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`. */ diff --git a/src/platform/errors.ts b/src/platform/errors.ts index 2b0c717..5ddb5e9 100644 --- a/src/platform/errors.ts +++ b/src/platform/errors.ts @@ -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 { diff --git a/src/platform/types.ts b/src/platform/types.ts index 8c44d0c..a939327 100644 --- a/src/platform/types.ts +++ b/src/platform/types.ts @@ -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). */