feat: add direct write settings to enhance file saving options

- Introduced `DirectWriteSettings` and integrated it into the settings model for improved file saving capabilities.
- Implemented merging logic for direct write settings in `mergeSettings` to ensure defaults are applied correctly.
- Updated `PanelGeneral` component to allow users to configure direct write options, including output mode and directory path.
- Enhanced selectors to retrieve staging and production direct write settings.
- Added tests to validate the functionality of direct write settings and their integration within the settings management system.
This commit is contained in:
鲁树人 committed 2026-11-06 04:05:47 +09:00
1 parent 79e5b45e6b
commit b9c8d5b3cd
10 files changed
+291 -5

No files matched your search

@@ -38,6 +38,11 @@ describe('stagingToProduction / productionToStaging', () => {
streamingZip: true,
blobZip: false,
},
directWrite: {
outputMode: 'fixedDirectory',
fixedDirectoryPath: '/out',
deleteSourceAfterDecrypt: true,
},
},
qmc2: {
allowFuzzyNameSearch: false,
@@ -60,6 +65,11 @@ describe('stagingToProduction / productionToStaging', () => {
streamingZip: true,
blobZip: false,
},
directWrite: {
outputMode: 'fixedDirectory',
fixedDirectoryPath: '/out',
deleteSourceAfterDecrypt: true,
},
},
qmc2: {
allowFuzzyNameSearch: false,
@@ -172,6 +182,7 @@ describe('mergeSettings', () => {
} as unknown as ProductionSettings);
expect(merged.general.batchDownload).toEqual(settingsSlice.getInitialState().production.general.batchDownload);
expect(merged.general.directWrite).toEqual(settingsSlice.getInitialState().production.general.directWrite);
expect(merged.qmc2).toEqual({ allowFuzzyNameSearch: false, keys: { 'a.mflac': 'ek' } });
// only keys matching /^(\d+)-(\w+)$/
expect(merged.kwm2.keys).toEqual({ '1-2000': 'kw', '2-hi': 'y' });
@@ -189,6 +200,11 @@ describe('mergeSettings', () => {
streamingZip: false,
blobZip: true,
},
directWrite: {
outputMode: 'fixedDirectory',
fixedDirectoryPath: '/music/out',
deleteSourceAfterDecrypt: true,
},
},
qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } },
kwm2: { keys: { '9-1000': 'kw' } },
@@ -203,4 +219,41 @@ describe('mergeSettings', () => {
expect(roundTrip.kugou).toEqual(merged.kugou);
expect(roundTrip.qtfm).toEqual(merged.qtfm);
});
test('mergeSettings fills directWrite defaults and ignores invalid fields', () => {
const merged = mergeSettings({
general: {
directWrite: {
outputMode: 'nope',
fixedDirectoryPath: 42,
deleteSourceAfterDecrypt: 'yes',
},
},
} as unknown as ProductionSettings);
expect(merged.general.directWrite).toEqual({
outputMode: 'besideSource',
fixedDirectoryPath: null,
deleteSourceAfterDecrypt: false,
});
});
test('mergeSettings keeps valid directWrite values when batchDownload omitted', () => {
const merged = mergeSettings({
general: {
directWrite: {
outputMode: 'fixedDirectory',
fixedDirectoryPath: null,
deleteSourceAfterDecrypt: true,
},
},
} as unknown as ProductionSettings);
expect(merged.general.directWrite).toEqual({
outputMode: 'fixedDirectory',
fixedDirectoryPath: null,
deleteSourceAfterDecrypt: true,
});
expect(merged.general.batchDownload).toEqual(settingsSlice.getInitialState().production.general.batchDownload);
});
});
+98 -3
View File
@@ -1,7 +1,12 @@
import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
import { selectStagingBatchDownloadSettings, selectStagingDirectWriteSettings } from '../settingsSelector';
import {
BatchDownloadSettings,
DirectWriteOutputMode,
updateBatchDownloadSetting,
updateDirectWriteSetting,
} from '../settingsSlice';
import { BatchDownloadType } from '~/platform/capabilities';
import { usePlatform } from '~/platform/PlatformContext';
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
@@ -10,12 +15,15 @@ import { toast } from 'react-toastify';
export function PanelGeneral() {
const dispatch = useAppDispatch();
const batch = useAppSelector(selectStagingBatchDownloadSettings);
const { capabilities } = usePlatform();
const directWrite = useAppSelector(selectStagingDirectWriteSettings);
const { capabilities, download } = 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 canDirectWrite = capabilities.directFsAccess;
const [hasRememberedDir, setHasRememberedDir] = useState(false);
const [pickingDirectory, setPickingDirectory] = useState(false);
const refreshRemembered = useCallback(() => {
hasRememberedDirectoryHandle()
@@ -37,10 +45,27 @@ export function PanelGeneral() {
toast.info('已清除记住的输出目录');
};
const handlePickDirectory = async () => {
setPickingDirectory(true);
try {
const path = await download.pickDirectory();
if (path) {
dispatch(updateDirectWriteSetting({ fixedDirectoryPath: path, outputMode: 'fixedDirectory' }));
}
} catch (e) {
toast.error(`无法选择文件夹: ${e instanceof Error ? e.message : String(e)}`);
} finally {
setPickingDirectory(false);
}
};
const idDir = useId();
const idRemember = useId();
const idStreamZip = useId();
const idBlobZip = useId();
const idOutputMode = useId();
const idFixedPath = useId();
const idDeleteSource = useId();
return (
<div className="min-h-0 flex-col grow px-1">
@@ -121,6 +146,76 @@ export function PanelGeneral() {
onChange={(checked) => setBatch('blobZip', checked)}
/>
</div>
<h3 className="text-xl font-semibold mt-8 mb-2">解密后自动保存</h3>
<p className="text-sm text-base-content/80 mb-4">
{canDirectWrite
? '解密完成后直接保存到本机,无需再手动下载。'
: '当前环境无法直接保存到本机,请使用上方的批量下载。此项设置会保留,在桌面客户端中生效。'}
</p>
<div className={`flex flex-col gap-3 ${canDirectWrite ? '' : 'opacity-50'}`}>
<div className="flex flex-col gap-1">
<label htmlFor={idOutputMode} className="font-medium">
保存位置
</label>
<select
id={idOutputMode}
className="select select-bordered select-sm w-full max-w-md"
value={directWrite.outputMode}
disabled={!canDirectWrite}
onChange={(e) =>
dispatch(updateDirectWriteSetting({ outputMode: e.target.value as DirectWriteOutputMode }))
}
>
<option value="besideSource">原文件所在文件夹</option>
<option value="fixedDirectory">指定文件夹</option>
</select>
<span className="text-sm text-base-content/70">
{directWrite.outputMode === 'besideSource'
? '解密后的文件保存在加密文件旁边。'
: '解密后的文件保存到下方指定的文件夹。'}
</span>
</div>
<div className="flex flex-col gap-1">
<label htmlFor={idFixedPath} className="font-medium">
文件夹路径
</label>
<div className="flex flex-wrap items-center gap-2 max-w-xl">
<input
id={idFixedPath}
type="text"
className="input input-bordered input-sm min-w-0 flex-1"
placeholder="/path/to/output"
value={directWrite.fixedDirectoryPath ?? ''}
disabled={!canDirectWrite || directWrite.outputMode !== 'fixedDirectory'}
onChange={(e) =>
dispatch(
updateDirectWriteSetting({ fixedDirectoryPath: e.target.value === '' ? null : e.target.value }),
)
}
/>
<button
type="button"
className="btn btn-sm btn-outline"
disabled={!canDirectWrite || pickingDirectory}
onClick={() => void handlePickDirectory()}
>
{pickingDirectory ? '选择中…' : '选择文件夹'}
</button>
</div>
</div>
<BatchOption
id={idDeleteSource}
checked={directWrite.deleteSourceAfterDecrypt}
disabled={!canDirectWrite}
title="保存成功后删除加密文件"
description="仅在写出成功后删除;请先确认已有备份。"
onChange={(checked) => dispatch(updateDirectWriteSetting({ deleteSourceAfterDecrypt: checked }))}
/>
</div>
</div>
);
}
@@ -1,3 +1,4 @@
import userEvent from '@testing-library/user-event';
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral';
import { BatchDownloadType } from '~/platform/capabilities';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
@@ -33,3 +34,61 @@ test('disables pack-zip when capability is absent', () => {
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeDisabled();
});
test('disables DirectWrite controls when directFsAccess is false', () => {
const platform = createBrowserProvider({
crypto: stubCrypto,
downloadTypes: [BatchDownloadType.PackZip],
directFsAccess: false,
});
renderWithProviders(<PanelGeneral />, { platform });
expect(screen.getByLabelText('保存位置')).toBeDisabled();
expect(screen.getByLabelText('文件夹路径')).toBeDisabled();
expect(screen.getByRole('button', { name: '选择文件夹' })).toBeDisabled();
expect(screen.getByLabelText(/保存成功后删除加密文件/)).toBeDisabled();
});
test('enables DirectWrite controls when directFsAccess is true', () => {
const platform = createBrowserProvider({
crypto: stubCrypto,
downloadTypes: [BatchDownloadType.PackZip],
directFsAccess: true,
});
renderWithProviders(<PanelGeneral />, { platform });
expect(screen.getByLabelText('保存位置')).not.toBeDisabled();
// Path stays disabled until outputMode is fixedDirectory (default besideSource).
expect(screen.getByLabelText('文件夹路径')).toBeDisabled();
expect(screen.getByRole('button', { name: '选择文件夹' })).not.toBeDisabled();
expect(screen.getByLabelText(/保存成功后删除加密文件/)).not.toBeDisabled();
});
test('pickDirectory button writes path into fixedDirectoryPath', async () => {
const user = userEvent.setup();
const pickDirectory = vi.fn().mockResolvedValue('/music/unlocked');
const platform = createBrowserProvider({
crypto: stubCrypto,
downloadTypes: [BatchDownloadType.PackZip],
directFsAccess: true,
download: {
saveOne: vi.fn(),
saveMany: vi.fn(),
pickDirectory,
},
});
const { store } = renderWithProviders(<PanelGeneral />, { platform });
await user.click(screen.getByRole('button', { name: '选择文件夹' }));
expect(pickDirectory).toHaveBeenCalledOnce();
expect(store.getState().settings.staging.general.directWrite).toEqual({
outputMode: 'fixedDirectory',
fixedDirectoryPath: '/music/unlocked',
deleteSourceAfterDecrypt: false,
});
expect(screen.getByLabelText('文件夹路径')).toHaveValue('/music/unlocked');
});
+20
View File
@@ -6,7 +6,9 @@ import {
setProductionChanges,
ProductionSettings,
DEFAULT_BATCH_DOWNLOAD_SETTINGS,
DEFAULT_DIRECT_WRITE_SETTINGS,
BatchDownloadSettings,
DirectWriteSettings,
} from './settingsSlice';
import { enumObject } from '~/util/objects';
import { getLogger } from '~/util/logUtils';
@@ -28,11 +30,29 @@ function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined):
return result;
}
function mergeDirectWrite(source: Partial<DirectWriteSettings> | undefined): DirectWriteSettings {
const result = { ...DEFAULT_DIRECT_WRITE_SETTINGS };
if (!source) {
return result;
}
if (source.outputMode === 'besideSource' || source.outputMode === 'fixedDirectory') {
result.outputMode = source.outputMode;
}
if (source.fixedDirectoryPath === null || typeof source.fixedDirectoryPath === 'string') {
result.fixedDirectoryPath = source.fixedDirectoryPath;
}
if (typeof source.deleteSourceAfterDecrypt === 'boolean') {
result.deleteSourceAfterDecrypt = source.deleteSourceAfterDecrypt;
}
return result;
}
/** Normalize / sanitize loaded production settings against defaults. Exported for tests. */
export function mergeSettings(settings: ProductionSettings): ProductionSettings {
const draft = deepClone(settingsSlice.getInitialState().production);
draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload);
draft.general.directWrite = mergeDirectWrite(settings?.general?.directWrite);
if (settings?.qmc2) {
const { allowFuzzyNameSearch, keys } = settings.qmc2;
@@ -14,3 +14,6 @@ export const selectIsSettingsNotSaved = (state: RootState) => state.settings.dir
export const selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.general.batchDownload;
export const selectStagingDirectWriteSettings = (state: RootState) => state.settings.staging.general.directWrite;
export const selectFinalDirectWriteSettings = (state: RootState) => state.settings.production.general.directWrite;
+36 -2
View File
@@ -32,9 +32,20 @@ export interface BatchDownloadSettings {
blobZip: boolean;
}
/** Where native clients write decrypted files (gated by `capabilities.directFsAccess`). */
export type DirectWriteOutputMode = 'besideSource' | 'fixedDirectory';
export interface DirectWriteSettings {
outputMode: DirectWriteOutputMode;
/** Absolute path when `outputMode` is `fixedDirectory`; unused in the browser UI. */
fixedDirectoryPath: string | null;
deleteSourceAfterDecrypt: boolean;
}
export interface StagingSettings {
general: {
batchDownload: BatchDownloadSettings;
directWrite: DirectWriteSettings;
};
qmc2: {
keys: StagingQMCv2Key[];
@@ -56,6 +67,7 @@ export interface StagingSettings {
export interface ProductionSettings {
general: {
batchDownload: BatchDownloadSettings;
directWrite: DirectWriteSettings;
};
qmc2: {
keys: ProductionQMCv2Keys; // { [fileName]: ekey }
@@ -81,6 +93,12 @@ export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = {
blobZip: true,
};
export const DEFAULT_DIRECT_WRITE_SETTINGS: DirectWriteSettings = {
outputMode: 'besideSource',
fixedDirectoryPath: null,
deleteSourceAfterDecrypt: false,
};
export interface SettingsState {
dirty: boolean;
staging: StagingSettings;
@@ -90,14 +108,20 @@ export interface SettingsState {
const initialState: SettingsState = {
dirty: false,
staging: {
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
general: {
batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS },
directWrite: { ...DEFAULT_DIRECT_WRITE_SETTINGS },
},
qmc2: { allowFuzzyNameSearch: true, keys: [] },
kwm2: { keys: [] },
qtfm: { ...EMPTY_QTFM_SETTINGS },
kugou: { keys: [] },
},
production: {
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
general: {
batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS },
directWrite: { ...DEFAULT_DIRECT_WRITE_SETTINGS },
},
qmc2: { allowFuzzyNameSearch: true, keys: {} },
kwm2: { keys: {} },
kugou: { keys: {} },
@@ -108,6 +132,7 @@ const initialState: SettingsState = {
export const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
general: {
batchDownload: { ...staging.general.batchDownload },
directWrite: { ...staging.general.directWrite },
},
qmc2: {
keys: stagingKeyToProduction(staging.qmc2.keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue),
@@ -125,6 +150,7 @@ export const stagingToProduction = (staging: StagingSettings): ProductionSetting
export const productionToStaging = (production: ProductionSettings): StagingSettings => ({
general: {
batchDownload: { ...production.general.batchDownload },
directWrite: { ...production.general.directWrite },
},
qmc2: {
keys: productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging),
@@ -184,6 +210,13 @@ export const settingsSlice = createSlice({
state.staging.general.batchDownload[key] = value;
state.dirty = true;
},
updateDirectWriteSetting(state, { payload }: PayloadAction<Partial<DirectWriteSettings>>) {
state.staging.general.directWrite = {
...state.staging.general.directWrite,
...payload,
};
state.dirty = true;
},
discardStagingChanges: (state) => {
state.dirty = false;
state.staging = productionToStaging(state.production);
@@ -224,6 +257,7 @@ export const {
qtfmAndroidUpdateKey,
updateBatchDownloadSetting,
updateDirectWriteSetting,
commitStagingChange,
discardStagingChanges,
+7
View File
@@ -60,6 +60,13 @@ export interface PlatformProvider {
* Declared type not wired yet → `NotImplementedError`.
*/
saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult>;
/**
* Native folder picker for DirectWrite `fixedDirectoryPath`.
* Resolves to an absolute path, or `null` if the user cancels.
* `!capabilities.directFsAccess` → `NotSupportedMethod` (browsers cannot expose OS paths).
* Declared but not wired (stub) → `NotImplementedError`.
*/
pickDirectory(): Promise<string | null>;
};
keys: {
@@ -133,6 +133,7 @@ describe('BrowserProvider', () => {
download: {
saveOne,
saveMany: vi.fn(),
pickDirectory: vi.fn(),
},
});
@@ -33,4 +33,12 @@ describe('createBrowserDownload', () => {
download.saveMany(BatchDownloadType.StreamZip, { files: [{ url: 'blob:x', fileName: 'a.flac' }] }),
).rejects.toBeInstanceOf(NotSupportedMethod);
});
test('pickDirectory throws NotSupportedMethod (no OS path in browser)', async () => {
const download = createBrowserDownload([BatchDownloadType.PackZip]);
await expect(download.pickDirectory()).rejects.toSatisfy((err: unknown) => {
return err instanceof NotSupportedMethod && err.capability === 'download.pickDirectory';
});
});
});
+6
View File
@@ -10,11 +10,13 @@ import { triggerAnchorDownload } from '~/util/triggerDownload';
export interface BrowserDownload {
saveOne(input: DownloadOneInput): Promise<void>;
saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult>;
pickDirectory(): Promise<string | null>;
}
/**
* Browser download backend: single-file anchor download plus batch directory / ZIP modes.
* Modes not listed in `downloadTypes` reject with `NotSupportedMethod`.
* `pickDirectory` always rejects: the browser cannot return an OS path string.
*/
export function createBrowserDownload(downloadTypes: readonly BatchDownloadType[]): BrowserDownload {
const supported = new Set(downloadTypes);
@@ -43,6 +45,10 @@ export function createBrowserDownload(downloadTypes: readonly BatchDownloadType[
return 'ok';
}
},
pickDirectory(): Promise<string | null> {
return Promise.reject(new NotSupportedMethod('download.pickDirectory'));
},
};
}