feat(#10): add batch download settings and capabilities

- Introduced new batch download settings in the settings slice, allowing users to configure options for directory picking, streaming ZIP downloads, and blob ZIP downloads.
- Implemented a new general settings panel for managing batch download preferences.
- Added utility functions to handle directory selection and ZIP file creation.
- Updated the download logic to support multiple download modes based on user preferences.
- Enhanced documentation to reflect changes in batch download functionality.
This commit is contained in:
鲁树人 committed 2026-10-21 10:24:21 +09:00
1 parent 3059f495ab
commit 07d160c547
16 files changed
+660 -55

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
export function supportsDirectoryPicker(): boolean {
return typeof window !== 'undefined' && typeof window.showDirectoryPicker === 'function';
}
export function supportsSaveFilePicker(): boolean {
return typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function';
}
export function supportsStreamingZipDownload(): boolean {
return supportsSaveFilePicker();
}
+65
View File
@@ -0,0 +1,65 @@
import { get, set, del } from 'idb-keyval';
import { isAbortError } from '~/util/fsPicker';
const DIRECTORY_HANDLE_KEY = 'um-react-batch-download-dir';
export async function getRememberedDirectoryHandle(): Promise<FileSystemDirectoryHandle | null> {
try {
const handle = await get<FileSystemDirectoryHandle>(DIRECTORY_HANDLE_KEY);
return handle ?? null;
} catch {
return null;
}
}
export async function setRememberedDirectoryHandle(handle: FileSystemDirectoryHandle): Promise<void> {
await set(DIRECTORY_HANDLE_KEY, handle);
}
export async function clearRememberedDirectoryHandle(): Promise<void> {
await del(DIRECTORY_HANDLE_KEY);
}
export async function hasRememberedDirectoryHandle(): Promise<boolean> {
return (await getRememberedDirectoryHandle()) !== null;
}
export async function verifyDirectoryPermission(
handle: FileSystemDirectoryHandle,
mode: FileSystemPermissionMode = 'readwrite',
): Promise<boolean> {
const opts: FileSystemHandlePermissionDescriptor = { mode };
if ((await handle.queryPermission(opts)) === 'granted') {
return true;
}
if ((await handle.requestPermission(opts)) === 'granted') {
return true;
}
return false;
}
/**
* Resolve a writable directory: remembered handle (if allowed) → picker.
* Returns null when the user cancels the picker.
*/
export async function resolveWritableDirectory(remember: boolean): Promise<FileSystemDirectoryHandle | null> {
if (remember) {
const remembered = await getRememberedDirectoryHandle();
if (remembered && (await verifyDirectoryPermission(remembered))) {
return remembered;
}
}
try {
const dir = await window.showDirectoryPicker({ mode: 'readwrite' });
if (remember) {
await setRememberedDirectoryHandle(dir);
}
return dir;
} catch (e) {
if (isAbortError(e)) {
return null;
}
throw e;
}
}
+4
View File
@@ -0,0 +1,4 @@
/** True when the user cancelled a File System Access picker (or similar AbortError). */
export function isAbortError(e: unknown): boolean {
return e instanceof DOMException && e.name === 'AbortError';
}
+160
View File
@@ -0,0 +1,160 @@
import { Zip, ZipPassThrough } from 'fflate';
import { isAbortError } from '~/util/fsPicker';
import { triggerAnchorDownload } from '~/util/triggerDownload';
export interface ZipSourceFile {
/** Path inside the ZIP (UTF-8; non-ASCII gets Language Encoding Flag). */
name: string;
/** Blob URL or other fetchable URL of file contents. */
url: string;
}
/**
* Build a streaming ZIP (STORE / no recompression) from fetchable URLs.
* Filenames with non-ASCII characters get ZIP UTF-8 (LEF) via fflate.
*/
export function createZipReadableStream(files: ZipSourceFile[]): ReadableStream<Uint8Array> {
const zip = new Zip();
return new ReadableStream<Uint8Array>({
start(controller) {
zip.ondata = (err, data, final) => {
if (err) {
controller.error(err);
return;
}
controller.enqueue(data);
if (final) {
controller.close();
}
};
void (async () => {
try {
const usedNames = new Set<string>();
for (const file of files) {
const name = uniqueZipName(file.name, usedNames);
const entry = new ZipPassThrough(name);
zip.add(entry);
const res = await fetch(file.url);
if (!res.ok) {
throw new Error(`无法读取文件: ${file.name} (${res.status})`);
}
if (!res.body) {
const buf = new Uint8Array(await res.arrayBuffer());
entry.push(buf, true);
continue;
}
const reader = res.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) {
entry.push(new Uint8Array(0), true);
break;
}
entry.push(value, false);
}
}
zip.end();
} catch (e) {
zip.terminate();
controller.error(e);
}
})();
},
cancel() {
zip.terminate();
},
});
}
/** Split `name.ext` → base + ext (ext includes the leading dot). */
function splitBaseExt(name: string): { base: string; ext: string } {
const dot = name.lastIndexOf('.');
if (dot > 0) {
return { base: name.slice(0, dot), ext: name.slice(dot) };
}
return { base: name, ext: '' };
}
function uniqueZipName(name: string, used: Set<string>): string {
if (!used.has(name)) {
used.add(name);
return name;
}
const { base, ext } = splitBaseExt(name);
let i = 2;
let candidate: string;
do {
candidate = `${base} (${i})${ext}`;
i += 1;
} while (used.has(candidate));
used.add(candidate);
return candidate;
}
export function defaultZipFileName(files: ZipSourceFile[]): string {
const now = new Date();
const date = [
now.getFullYear(),
String(now.getMonth() + 1).padStart(2, '0'),
String(now.getDate()).padStart(2, '0'),
].join('-');
const first = files[0]?.name ?? '已解密的音乐';
const stem = splitBaseExt(first).base || '已解密的音乐';
return `${date} - ${stem} 等.zip`;
}
export async function downloadZipViaSavePicker(
files: ZipSourceFile[],
suggestedName = defaultZipFileName(files),
): Promise<'ok' | 'cancelled'> {
let handle: FileSystemFileHandle;
try {
handle = await window.showSaveFilePicker({
suggestedName,
types: [
{
description: 'ZIP archive',
accept: { 'application/zip': ['.zip'] },
},
],
});
} catch (e) {
if (isAbortError(e)) {
return 'cancelled';
}
throw e;
}
const writable = await handle.createWritable();
try {
await createZipReadableStream(files).pipeTo(writable);
} catch (e) {
try {
await writable.abort();
} catch {
// ignore
}
throw e;
}
return 'ok';
}
export async function downloadZipAsBlob(files: ZipSourceFile[], filename = defaultZipFileName(files)): Promise<void> {
const blob = await new Response(createZipReadableStream(files), {
headers: { 'Content-Type': 'application/zip' },
}).blob();
const objectUrl = URL.createObjectURL(blob);
try {
triggerAnchorDownload(objectUrl, filename);
} finally {
// Revoke after a short delay so the download can start.
setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
}
}
+9
View File
@@ -0,0 +1,9 @@
/** Programmatically trigger a browser file download via a temporary anchor. */
export function triggerAnchorDownload(href: string, filename: string): void {
const anchor = document.createElement('a');
anchor.href = href;
anchor.download = filename;
document.body.append(anchor);
anchor.click();
anchor.remove();
}