mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-27 23:56:59 +00:00
Compare commits
4
Commits
79e5b45e6b
...
c8bb7d4430
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8bb7d4430 | ||
|
|
6571dc5344 | ||
|
|
4d688af4ca | ||
|
|
b9c8d5b3cd |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { NavLink, Route, Routes } from 'react-router';
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router';
|
||||
import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
|
||||
import { Bounce, ToastContainer } from 'react-toastify';
|
||||
|
||||
@@ -6,7 +6,8 @@ import { Footer } from '~/components/Footer';
|
||||
import { FaqHome } from '~/faq/FaqHome';
|
||||
import { FAQ_PAGES } from '~/faq/FAQPages';
|
||||
import { SettingsHome } from '~/features/settings/SettingsHome';
|
||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
|
||||
import { getSettingsTabs, hasOneClickImportCapability, ONE_CLICK_TAB_ID } from '~/features/settings/settingsTabs';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { FaqTab } from '~/tabs/FaqTab';
|
||||
import { MainTab } from '~/tabs/MainTab';
|
||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
||||
@@ -15,6 +16,10 @@ const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${
|
||||
|
||||
/** Main chrome (nav / routes / toast / footer). Render only after platform `init()` resolves. */
|
||||
export function AppLayout() {
|
||||
const { capabilities } = usePlatform();
|
||||
const settingsTabs = getSettingsTabs(capabilities);
|
||||
const showOneClick = hasOneClickImportCapability(capabilities);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
||||
@@ -37,9 +42,10 @@ export function AppLayout() {
|
||||
<Route path="/" Component={MainTab} />
|
||||
<Route path="/settings" Component={SettingsTab}>
|
||||
<Route index Component={SettingsHome} />
|
||||
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
|
||||
{Object.entries(settingsTabs).map(([key, { Tab }]) => (
|
||||
<Route key={key} path={key} Component={Tab} />
|
||||
))}
|
||||
{!showOneClick && <Route path={ONE_CLICK_TAB_ID} element={<Navigate to="/settings/general" replace />} />}
|
||||
</Route>
|
||||
<Route path="/questions" Component={FaqTab}>
|
||||
<Route index Component={FaqHome} />
|
||||
|
||||
@@ -2,14 +2,17 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||
import { commitStagingChange, discardStagingChanges } from './settingsSlice';
|
||||
import { selectIsSettingsNotSaved } from './settingsSelector';
|
||||
import { Outlet } from 'react-router';
|
||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs.tsx';
|
||||
import { getSettingsTabs } from '~/features/settings/settingsTabs.tsx';
|
||||
import { MdOutlineSettingsBackupRestore } from 'react-icons/md';
|
||||
import { toast } from 'react-toastify';
|
||||
import { ResponsiveNav } from '../nav/ResponsiveNav';
|
||||
import { TabNavLink } from '../nav/TabNavLink';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
export function Settings() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { capabilities } = usePlatform();
|
||||
const settingsTabs = getSettingsTabs(capabilities);
|
||||
|
||||
const handleResetSettings = () => {
|
||||
dispatch(discardStagingChanges());
|
||||
@@ -35,7 +38,7 @@ export function Settings() {
|
||||
navigationClassName="overflow-x-auto pb-[2px] md:pb-0 h-full items-start [&]:md:flex"
|
||||
navigation={
|
||||
<div role="tablist" className="tabs gap-1 flex-nowrap md:flex-col grow items-center">
|
||||
{Object.entries(SETTINGS_TABS).map(([id, { name }]) => (
|
||||
{Object.entries(settingsTabs).map(([id, { name }]) => (
|
||||
<TabNavLink key={id} to={`/settings/${id}`}>
|
||||
{name}
|
||||
</TabNavLink>
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||
import type { PlatformCapabilities } from '~/platform/types';
|
||||
import { getSettingsTabs, hasOneClickImportCapability, ONE_CLICK_TAB_ID } from '../settingsTabs';
|
||||
|
||||
const baseCaps = (overrides: Partial<PlatformCapabilities> = {}): PlatformCapabilities => ({
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
directFsAccess: false,
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('settingsTabs', () => {
|
||||
test('hasOneClickImportCapability is false for browser defaults', () => {
|
||||
expect(hasOneClickImportCapability(baseCaps())).toBe(false);
|
||||
});
|
||||
|
||||
test('hasOneClickImportCapability is true with nativeKeyAccess', () => {
|
||||
expect(hasOneClickImportCapability(baseCaps({ nativeKeyAccess: [NativeImportType.QQMusic] }))).toBe(true);
|
||||
});
|
||||
|
||||
test('hasOneClickImportCapability is true with Adb', () => {
|
||||
expect(hasOneClickImportCapability(baseCaps({ androidKeyAccess: AndroidImportType.Adb }))).toBe(true);
|
||||
});
|
||||
|
||||
test('getSettingsTabs omits one-click without capability', () => {
|
||||
const tabs = getSettingsTabs(baseCaps());
|
||||
expect(Object.keys(tabs)).toEqual(['general', 'qmc', 'kwm', 'kgg', 'qtfm']);
|
||||
expect(tabs[ONE_CLICK_TAB_ID]).toBeUndefined();
|
||||
});
|
||||
|
||||
test('getSettingsTabs inserts one-click after general when capable', () => {
|
||||
const tabs = getSettingsTabs(baseCaps({ nativeKeyAccess: [NativeImportType.Kugou] }));
|
||||
expect(Object.keys(tabs)).toEqual(['general', ONE_CLICK_TAB_ID, 'qmc', 'kwm', 'kgg', 'qtfm']);
|
||||
expect(tabs[ONE_CLICK_TAB_ID]?.name).toBe('一键导入');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
kugouImportKeys,
|
||||
kwm2ImportKeys,
|
||||
qmc2ImportKeys,
|
||||
qtfmAndroidUpdateKey,
|
||||
} from '~/features/settings/settingsSlice';
|
||||
import type { NativeImportResult } from '~/platform/types';
|
||||
import type { AppDispatch } from '~/store';
|
||||
|
||||
/** Apply native/ADB import payload into staging. Caller may commit immediately (one-click import). */
|
||||
export function applyNativeImportResult(dispatch: AppDispatch, result: NativeImportResult): number {
|
||||
let count = 0;
|
||||
if (result.qmc2?.length) {
|
||||
dispatch(qmc2ImportKeys(result.qmc2));
|
||||
count += result.qmc2.length;
|
||||
}
|
||||
if (result.kwm2?.length) {
|
||||
dispatch(kwm2ImportKeys(result.kwm2));
|
||||
count += result.kwm2.length;
|
||||
}
|
||||
if (result.kugou?.length) {
|
||||
dispatch(kugouImportKeys(result.kugou));
|
||||
count += result.kugou.length;
|
||||
}
|
||||
if (result.qtfm?.android !== undefined) {
|
||||
dispatch(qtfmAndroidUpdateKey({ deviceKey: result.qtfm.android }));
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
@@ -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,16 @@ 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 showBatchDownload = downloadTypes.size > 0;
|
||||
const canDirectWrite = capabilities.directFsAccess;
|
||||
const [hasRememberedDir, setHasRememberedDir] = useState(false);
|
||||
const [pickingDirectory, setPickingDirectory] = useState(false);
|
||||
|
||||
const refreshRemembered = useCallback(() => {
|
||||
hasRememberedDirectoryHandle()
|
||||
@@ -37,90 +46,171 @@ 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">
|
||||
<h2 className="text-2xl font-bold mb-4">通用设置</h2>
|
||||
|
||||
<h3 className="text-xl font-semibold mb-2">批量下载</h3>
|
||||
<p className="text-sm text-base-content/80 mb-4">
|
||||
点击「下载全部」时,将按下方勾选项的顺序依次尝试。若选中的模式均不可用或全部失败,会弹出提示。
|
||||
</p>
|
||||
{showBatchDownload && (
|
||||
<>
|
||||
<h3 className="text-xl font-semibold mb-2">批量下载</h3>
|
||||
<p className="text-sm text-base-content/80 mb-4">
|
||||
点击「下载全部」时,将按下方勾选项的顺序依次尝试。若选中的模式均不可用或全部失败,会弹出提示。
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<BatchOption
|
||||
id={idDir}
|
||||
checked={batch.directoryPicker && canDirectoryPicker}
|
||||
disabled={!canDirectoryPicker}
|
||||
dimmed={!canDirectoryPicker}
|
||||
title="使用选择目录批量下载"
|
||||
description={
|
||||
canDirectoryPicker
|
||||
? '通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。'
|
||||
: '当前环境不支持选择目录批量下载。'
|
||||
}
|
||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||
/>
|
||||
|
||||
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker && canDirectoryPicker ? '' : 'opacity-50'}`}>
|
||||
<BatchOption
|
||||
id={idRemember}
|
||||
checked={batch.rememberDirectory}
|
||||
disabled={!batch.directoryPicker || !canDirectoryPicker}
|
||||
title="记住输出目录"
|
||||
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
|
||||
onChange={(checked) => setBatch('rememberDirectory', checked)}
|
||||
/>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-base-content/70">{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-xs btn-ghost"
|
||||
disabled={!hasRememberedDir}
|
||||
onClick={() => void handleClearDirectory()}
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BatchOption
|
||||
id={idStreamZip}
|
||||
checked={batch.streamingZip && canStreamingZip}
|
||||
disabled={!canStreamingZip}
|
||||
dimmed={!canStreamingZip}
|
||||
title="流式生成 ZIP"
|
||||
description={
|
||||
canStreamingZip
|
||||
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
|
||||
: '当前环境不支持流式写出 ZIP。'
|
||||
}
|
||||
onChange={(checked) => setBatch('streamingZip', checked)}
|
||||
/>
|
||||
|
||||
<BatchOption
|
||||
id={idBlobZip}
|
||||
checked={batch.blobZip && canBlobZip}
|
||||
disabled={!canBlobZip}
|
||||
dimmed={!canBlobZip}
|
||||
title="生成单个 ZIP 并触发下载"
|
||||
description={
|
||||
canBlobZip ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
{canDirectoryPicker && (
|
||||
<>
|
||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
||||
<BatchOption
|
||||
id={idDir}
|
||||
checked={batch.directoryPicker}
|
||||
title="使用选择目录批量下载"
|
||||
description="通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。"
|
||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||
/>
|
||||
|
||||
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker ? '' : 'opacity-50'}`}>
|
||||
<BatchOption
|
||||
id={idRemember}
|
||||
checked={batch.rememberDirectory}
|
||||
disabled={!batch.directoryPicker}
|
||||
title="记住输出目录"
|
||||
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
|
||||
onChange={(checked) => setBatch('rememberDirectory', checked)}
|
||||
/>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-base-content/70">
|
||||
{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-xs btn-ghost"
|
||||
disabled={!hasRememberedDir}
|
||||
onClick={() => void handleClearDirectory()}
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
'当前环境不支持打包 ZIP 下载。'
|
||||
)
|
||||
}
|
||||
onChange={(checked) => setBatch('blobZip', checked)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canStreamingZip && (
|
||||
<BatchOption
|
||||
id={idStreamZip}
|
||||
checked={batch.streamingZip}
|
||||
title="流式生成 ZIP"
|
||||
description="边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。"
|
||||
onChange={(checked) => setBatch('streamingZip', checked)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canBlobZip && (
|
||||
<BatchOption
|
||||
id={idBlobZip}
|
||||
checked={batch.blobZip}
|
||||
title="生成单个 ZIP 并触发下载"
|
||||
description={
|
||||
<>
|
||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
||||
</>
|
||||
}
|
||||
onChange={(checked) => setBatch('blobZip', checked)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{canDirectWrite && (
|
||||
<>
|
||||
<h3 className={`text-xl font-semibold mb-2 ${showBatchDownload ? 'mt-8' : ''}`}>解密后自动保存</h3>
|
||||
<p className="text-sm text-base-content/80 mb-4">解密完成后直接保存到本机,无需再手动下载。</p>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<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}
|
||||
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={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={pickingDirectory}
|
||||
onClick={() => void handlePickDirectory()}
|
||||
>
|
||||
{pickingDirectory ? '选择中…' : '选择文件夹'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BatchOption
|
||||
id={idDeleteSource}
|
||||
checked={directWrite.deleteSourceAfterDecrypt}
|
||||
title="保存成功后删除加密文件"
|
||||
description="仅在写出成功后删除;请先确认已有备份。"
|
||||
onChange={(checked) => dispatch(updateDirectWriteSetting({ deleteSourceAfterDecrypt: checked }))}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -129,15 +219,14 @@ type BatchOptionProps = {
|
||||
id: string;
|
||||
checked: boolean;
|
||||
disabled?: boolean;
|
||||
dimmed?: boolean;
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
onChange: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
function BatchOption({ id, checked, disabled, dimmed, title, description, onChange }: BatchOptionProps) {
|
||||
function BatchOption({ id, checked, disabled, title, description, onChange }: BatchOptionProps) {
|
||||
return (
|
||||
<label className={`flex items-start gap-2 ${dimmed ? 'opacity-50' : ''}`}>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { useId, useMemo, useState } from 'react';
|
||||
import { Navigate } from 'react-router';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { applyNativeImportResult } from '~/features/settings/applyNativeImportResult';
|
||||
import { commitStagingChange } from '~/features/settings/settingsSlice';
|
||||
import { hasOneClickImportCapability } from '~/features/settings/settingsTabs';
|
||||
import { AndroidImportType, NativeImportType } from '~/platform/capabilities';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
const NATIVE_IMPORT_LABELS: Record<NativeImportType, string> = {
|
||||
[NativeImportType.QQMusic]: 'QQ 音乐',
|
||||
[NativeImportType.Kuwo]: '酷我音乐',
|
||||
[NativeImportType.Kugou]: '酷狗音乐',
|
||||
[NativeImportType.QingTing]: '蜻蜓 FM',
|
||||
};
|
||||
|
||||
function selectedFromCaps(types: readonly NativeImportType[]): Record<NativeImportType, boolean> {
|
||||
return {
|
||||
[NativeImportType.QQMusic]: types.includes(NativeImportType.QQMusic),
|
||||
[NativeImportType.Kuwo]: types.includes(NativeImportType.Kuwo),
|
||||
[NativeImportType.Kugou]: types.includes(NativeImportType.Kugou),
|
||||
[NativeImportType.QingTing]: types.includes(NativeImportType.QingTing),
|
||||
};
|
||||
}
|
||||
|
||||
export function PanelOneClick() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { capabilities, keys } = usePlatform();
|
||||
const nativeTypes = capabilities.nativeKeyAccess;
|
||||
const canAdb = capabilities.androidKeyAccess === AndroidImportType.Adb;
|
||||
const canShow = hasOneClickImportCapability(capabilities);
|
||||
|
||||
const [selected, setSelected] = useState(() => selectedFromCaps(nativeTypes));
|
||||
const [importingNative, setImportingNative] = useState(false);
|
||||
const [importingAdb, setImportingAdb] = useState(false);
|
||||
|
||||
const nativeTargets = useMemo(() => nativeTypes.filter((type) => selected[type]), [nativeTypes, selected]);
|
||||
|
||||
const idNative = useId();
|
||||
const idAdb = useId();
|
||||
|
||||
if (!canShow) {
|
||||
return <Navigate to="/settings/general" replace />;
|
||||
}
|
||||
|
||||
const finishImport = (count: number, emptyMessage: string) => {
|
||||
if (count === 0) {
|
||||
toast.info(emptyMessage);
|
||||
return;
|
||||
}
|
||||
dispatch(commitStagingChange());
|
||||
toast.success(`成功导入 ${count} 项密钥`);
|
||||
};
|
||||
|
||||
const handleImportNative = async () => {
|
||||
if (nativeTargets.length === 0) {
|
||||
toast.warning('请至少勾选一个客户端');
|
||||
return;
|
||||
}
|
||||
setImportingNative(true);
|
||||
try {
|
||||
const result = await keys.importNative(nativeTargets);
|
||||
finishImport(applyNativeImportResult(dispatch, result), '未导入到新密钥');
|
||||
} catch (e) {
|
||||
toast.error(`一键导入失败: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setImportingNative(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportAdb = async () => {
|
||||
setImportingAdb(true);
|
||||
try {
|
||||
const targets = nativeTargets.length > 0 ? nativeTargets : undefined;
|
||||
const result = await keys.importAndroidAdb({ targets });
|
||||
finishImport(applyNativeImportResult(dispatch, result), 'ADB 未导入到新密钥');
|
||||
} catch (e) {
|
||||
toast.error(`ADB 导入失败: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setImportingAdb(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-0 flex-col grow px-1">
|
||||
<h2 className="text-2xl font-bold mb-4">一键导入</h2>
|
||||
<p className="text-sm text-base-content/80 mb-4">
|
||||
从本机已安装的客户端读取密钥并立即保存生效。各格式页的「导入数据库…」仍可单独使用。
|
||||
</p>
|
||||
|
||||
{nativeTypes.length > 0 && (
|
||||
<section className="mb-8" aria-labelledby={idNative}>
|
||||
<h3 id={idNative} className="text-xl font-semibold mb-2">
|
||||
本机客户端
|
||||
</h3>
|
||||
<div className="flex flex-col gap-3 mb-4">
|
||||
{nativeTypes.map((type) => {
|
||||
const checkboxId = `${idNative}-${type}`;
|
||||
return (
|
||||
<label key={type} className="flex items-start gap-2" htmlFor={checkboxId}>
|
||||
<input
|
||||
id={checkboxId}
|
||||
type="checkbox"
|
||||
className="checkbox checkbox-sm mt-0.5"
|
||||
checked={selected[type]}
|
||||
onChange={(e) => setSelected((prev) => ({ ...prev, [type]: e.target.checked }))}
|
||||
/>
|
||||
<span className="font-medium">{NATIVE_IMPORT_LABELS[type]}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={importingNative || nativeTargets.length === 0}
|
||||
onClick={() => void handleImportNative()}
|
||||
>
|
||||
{importingNative ? '导入中…' : '开始导入'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{canAdb && (
|
||||
<section aria-labelledby={idAdb}>
|
||||
<h3 id={idAdb} className="text-xl font-semibold mb-2">
|
||||
Android ADB
|
||||
</h3>
|
||||
<p className="text-sm text-base-content/70 mb-4">
|
||||
通过 ADB 从已连接设备拉取密钥。若上方已勾选客户端,将仅导入对应格式;未勾选时导入全部支持项。
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-outline btn-sm"
|
||||
disabled={importingAdb}
|
||||
onClick={() => void handleImportAdb()}
|
||||
>
|
||||
{importingAdb ? '导入中…' : '从 ADB 导入'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</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';
|
||||
@@ -8,7 +9,7 @@ const stubCrypto = {
|
||||
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||
};
|
||||
|
||||
test('disables directory and streaming options when only PackZip is capable', () => {
|
||||
test('shows only capable batch-download options', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
@@ -16,20 +17,84 @@ test('disables directory and streaming options when only PackZip is capable', ()
|
||||
|
||||
renderWithProviders(<PanelGeneral />, { platform });
|
||||
|
||||
expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
|
||||
expect(screen.queryByLabelText(/使用选择目录批量下载/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/流式生成 ZIP/)).not.toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).not.toBeDisabled();
|
||||
});
|
||||
|
||||
test('disables pack-zip when capability is absent', () => {
|
||||
test('hides batch-download section when downloadTypes is empty', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
downloadTypes: [],
|
||||
directFsAccess: true,
|
||||
});
|
||||
|
||||
renderWithProviders(<PanelGeneral />, { platform });
|
||||
|
||||
expect(screen.getByLabelText(/使用选择目录批量下载/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
|
||||
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeDisabled();
|
||||
expect(screen.queryByRole('heading', { name: '批量下载' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/使用选择目录批量下载/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/流式生成 ZIP/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/生成单个 ZIP 并触发下载/)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { name: '解密后自动保存' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('hides DirectWrite section when directFsAccess is false', () => {
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
directFsAccess: false,
|
||||
});
|
||||
|
||||
renderWithProviders(<PanelGeneral />, { platform });
|
||||
|
||||
expect(screen.queryByRole('heading', { name: '解密后自动保存' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('保存位置')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('文件夹路径')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: '选择文件夹' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/保存成功后删除加密文件/)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { name: '批量下载' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows 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');
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router';
|
||||
import { toast } from 'react-toastify';
|
||||
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import type { NativeImportResult } from '~/platform/types';
|
||||
import { renderWithProviders, screen, waitFor } from '~/test-utils/test-helper';
|
||||
import { PanelOneClick } from '../PanelOneClick';
|
||||
import { Settings } from '~/features/settings/Settings';
|
||||
|
||||
vi.mock('react-toastify', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const stubCrypto = {
|
||||
request: () => Promise.resolve(null as never),
|
||||
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||
};
|
||||
|
||||
function renderPanel(platform = createBrowserProvider({ crypto: stubCrypto })) {
|
||||
return renderWithProviders(
|
||||
<MemoryRouter initialEntries={['/settings/one-click']}>
|
||||
<Routes>
|
||||
<Route path="/settings/one-click" element={<PanelOneClick />} />
|
||||
<Route path="/settings/general" element={<div>通用设置页</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
{ platform },
|
||||
);
|
||||
}
|
||||
|
||||
test('redirects to general when platform has no one-click capability', async () => {
|
||||
renderPanel();
|
||||
expect(await screen.findByText('通用设置页')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('heading', { name: '一键导入' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('renders native checkboxes, commits production, and reports import count', async () => {
|
||||
const user = userEvent.setup();
|
||||
const importNative = vi.fn().mockImplementation((targets: readonly NativeImportType[]) => {
|
||||
const result: NativeImportResult = {};
|
||||
if (targets.includes(NativeImportType.QQMusic)) {
|
||||
result.qmc2 = [{ name: 'a.mflac', ekey: 'ekey-1' }];
|
||||
}
|
||||
if (targets.includes(NativeImportType.Kugou)) {
|
||||
result.kugou = [{ audioHash: 'hash-1', ekey: 'ekey-2' }];
|
||||
}
|
||||
if (targets.includes(NativeImportType.QingTing)) {
|
||||
result.qtfm = { android: 'deadbeef' };
|
||||
}
|
||||
return Promise.resolve(result);
|
||||
});
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
nativeKeyAccess: [NativeImportType.QQMusic, NativeImportType.Kugou, NativeImportType.QingTing],
|
||||
keys: {
|
||||
importNative,
|
||||
importAndroidAdb: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
const { store } = renderPanel(platform);
|
||||
|
||||
expect(screen.getByRole('heading', { name: '一键导入' })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('QQ 音乐')).toBeChecked();
|
||||
expect(screen.getByLabelText('酷狗音乐')).toBeChecked();
|
||||
expect(screen.getByLabelText('蜻蜓 FM')).toBeChecked();
|
||||
expect(screen.queryByRole('button', { name: '从 ADB 导入' })).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByLabelText('酷狗音乐'));
|
||||
await user.click(screen.getByRole('button', { name: '开始导入' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(importNative).toHaveBeenCalledWith([NativeImportType.QQMusic, NativeImportType.QingTing]);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(store.getState().settings.production.qmc2.keys).toMatchObject({ 'a.mflac': 'ekey-1' });
|
||||
});
|
||||
expect(store.getState().settings.production.kugou.keys).toEqual({});
|
||||
expect(store.getState().settings.production.qtfm.android).toBe('deadbeef');
|
||||
expect(store.getState().settings.dirty).toBe(false);
|
||||
expect(toast.success).toHaveBeenCalledWith('成功导入 2 项密钥');
|
||||
});
|
||||
|
||||
test('shows ADB block, auto-saves importAndroidAdb result', async () => {
|
||||
const user = userEvent.setup();
|
||||
const importAndroidAdb = vi.fn().mockResolvedValue({
|
||||
kwm2: [{ rid: '1', quality: '2000', ekey: 'k' }],
|
||||
} satisfies NativeImportResult);
|
||||
const platform = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
androidKeyAccess: AndroidImportType.Adb,
|
||||
nativeKeyAccess: [NativeImportType.Kuwo],
|
||||
keys: {
|
||||
importNative: vi.fn(),
|
||||
importAndroidAdb,
|
||||
},
|
||||
});
|
||||
|
||||
const { store } = renderPanel(platform);
|
||||
|
||||
expect(screen.getByRole('button', { name: '从 ADB 导入' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: '从 ADB 导入' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(importAndroidAdb).toHaveBeenCalledWith({ targets: [NativeImportType.Kuwo] });
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(store.getState().settings.production.kwm2.keys).toMatchObject({ '1-2000': 'k' });
|
||||
});
|
||||
expect(store.getState().settings.dirty).toBe(false);
|
||||
expect(toast.success).toHaveBeenCalledWith('成功导入 1 项密钥');
|
||||
});
|
||||
|
||||
test('settings sidebar omits 一键导入 without capability and includes it when capable', () => {
|
||||
const without = createBrowserProvider({ crypto: stubCrypto });
|
||||
const { unmount } = renderWithProviders(
|
||||
<MemoryRouter initialEntries={['/settings/general']}>
|
||||
<Routes>
|
||||
<Route path="/settings" element={<Settings />}>
|
||||
<Route path="general" element={<div />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
{ platform: without },
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('tab', { name: '一键导入' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('tab', { name: '通用设置' })).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
const withNative = createBrowserProvider({
|
||||
crypto: stubCrypto,
|
||||
nativeKeyAccess: [NativeImportType.QQMusic],
|
||||
});
|
||||
renderWithProviders(
|
||||
<MemoryRouter initialEntries={['/settings/general']}>
|
||||
<Routes>
|
||||
<Route path="/settings" element={<Settings />}>
|
||||
<Route path="general" element={<div />} />
|
||||
<Route path="one-click" element={<div />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
{ platform: withNative },
|
||||
);
|
||||
|
||||
expect(screen.getByRole('tab', { name: '一键导入' })).toBeInTheDocument();
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { FC } from 'react';
|
||||
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
|
||||
import { PanelOneClick } from '~/features/settings/panels/PanelOneClick.tsx';
|
||||
import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
|
||||
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
|
||||
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
|
||||
import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
||||
import { AndroidImportType } from '~/platform/capabilities';
|
||||
import type { PlatformCapabilities } from '~/platform/types';
|
||||
|
||||
export type SettingsTabDef = { name: string; Tab: FC };
|
||||
|
||||
/**
|
||||
* Settings UI route ids → panels.
|
||||
@@ -13,11 +18,38 @@ import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
||||
* - `kwm` ↔ state `kwm2`
|
||||
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
|
||||
* - `qtfm` ↔ state `qtfm`
|
||||
* - `one-click` ↔ platform native / ADB key import (only when capable)
|
||||
*/
|
||||
export const SETTINGS_TABS: Record<string, { name: string; Tab: FC }> = {
|
||||
export const ONE_CLICK_TAB_ID = 'one-click';
|
||||
|
||||
const CORE_SETTINGS_TABS: Record<string, SettingsTabDef> = {
|
||||
general: { name: '通用设置', Tab: PanelGeneral },
|
||||
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
|
||||
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
|
||||
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
|
||||
qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing },
|
||||
} as const;
|
||||
};
|
||||
|
||||
const ONE_CLICK_TAB: SettingsTabDef = { name: '一键导入', Tab: PanelOneClick };
|
||||
|
||||
/** True when the platform can show the one-click import settings tab. */
|
||||
export function hasOneClickImportCapability(capabilities: PlatformCapabilities): boolean {
|
||||
return capabilities.nativeKeyAccess.length > 0 || capabilities.androidKeyAccess === AndroidImportType.Adb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings tabs for the current platform.
|
||||
* Registers `one-click` only when `nativeKeyAccess` or ADB import is available.
|
||||
*/
|
||||
export function getSettingsTabs(capabilities: PlatformCapabilities): Record<string, SettingsTabDef> {
|
||||
if (!hasOneClickImportCapability(capabilities)) {
|
||||
return CORE_SETTINGS_TABS;
|
||||
}
|
||||
|
||||
const { general, ...rest } = CORE_SETTINGS_TABS;
|
||||
return {
|
||||
general,
|
||||
[ONE_CLICK_TAB_ID]: ONE_CLICK_TAB,
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
@@ -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(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -151,8 +152,8 @@ describe('BrowserProvider', () => {
|
||||
await expect(provider.settings.load()).resolves.toBeNull();
|
||||
});
|
||||
|
||||
test('createPlatformProvider defaults to browser', () => {
|
||||
const provider = createPlatformProvider();
|
||||
test('createPlatformProvider defaults to browser outside Tauri', () => {
|
||||
const provider = createPlatformProvider({ runtime: 'browser' });
|
||||
expect(provider.id).toBe('browser');
|
||||
expect(provider.capabilities.nativeKeyAccess).toEqual([]);
|
||||
expect(provider.capabilities.androidKeyAccess).toBe(AndroidImportType.None);
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||
import { createPlatformProvider } from '~/platform/createPlatformProvider';
|
||||
import { detectPlatformRuntime } from '~/platform/detectPlatform';
|
||||
import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
|
||||
import { createTauriProvider, DEFAULT_TAURI_CAPABILITIES } from '~/platform/tauri/TauriProvider';
|
||||
import type { PlatformCapabilities } from '~/platform/types';
|
||||
|
||||
function expectNotImplemented(err: unknown, capability: string): boolean {
|
||||
return err instanceof NotImplementedError && err.code === 'NOT_IMPLEMENTED' && err.capability === capability;
|
||||
}
|
||||
|
||||
function expectNotSupported(err: unknown, capability: string): boolean {
|
||||
return err instanceof NotSupportedMethod && err.code === 'NOT_SUPPORTED' && err.capability === capability;
|
||||
}
|
||||
|
||||
const emptyCaps: PlatformCapabilities = {
|
||||
downloadTypes: [],
|
||||
directFsAccess: false,
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: [],
|
||||
};
|
||||
|
||||
describe('TauriProvider stub', () => {
|
||||
test('declares target desktop capabilities', () => {
|
||||
const provider = createTauriProvider();
|
||||
|
||||
expect(provider.id).toBe('tauri');
|
||||
expect(provider.capabilities).toEqual(DEFAULT_TAURI_CAPABILITIES);
|
||||
expect(provider.capabilities.directFsAccess).toBe(true);
|
||||
expect(provider.capabilities.androidKeyAccess).toBe(AndroidImportType.Adb);
|
||||
expect(provider.capabilities.nativeKeyAccess).toEqual([
|
||||
NativeImportType.QQMusic,
|
||||
NativeImportType.Kuwo,
|
||||
NativeImportType.Kugou,
|
||||
NativeImportType.QingTing,
|
||||
]);
|
||||
expect(provider.capabilities.downloadTypes).toEqual([]);
|
||||
});
|
||||
|
||||
test('exposes every PlatformProvider method', () => {
|
||||
const provider = createTauriProvider();
|
||||
|
||||
expect(typeof provider.init).toBe('function');
|
||||
expect(typeof provider.crypto.request).toBe('function');
|
||||
expect(typeof provider.crypto.enqueueDecrypt).toBe('function');
|
||||
expect(typeof provider.settings.load).toBe('function');
|
||||
expect(typeof provider.settings.save).toBe('function');
|
||||
expect(typeof provider.download.saveOne).toBe('function');
|
||||
expect(typeof provider.download.saveMany).toBe('function');
|
||||
expect(typeof provider.download.pickDirectory).toBe('function');
|
||||
expect(typeof provider.keys.importNative).toBe('function');
|
||||
expect(typeof provider.keys.importAndroidAdb).toBe('function');
|
||||
});
|
||||
|
||||
test('init resolves without side effects and is idempotent', async () => {
|
||||
const provider = createTauriProvider();
|
||||
await expect(Promise.all([provider.init(), provider.init()])).resolves.toEqual([undefined, undefined]);
|
||||
await expect(provider.init()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('declared backends throw NotImplementedError', async () => {
|
||||
const provider = createTauriProvider();
|
||||
|
||||
await expect(provider.crypto.request('VERSION', null)).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotImplemented(err, 'crypto.request'),
|
||||
);
|
||||
await expect(
|
||||
provider.crypto.enqueueDecrypt({
|
||||
fileId: 'file://1',
|
||||
blobURI: 'blob://in',
|
||||
options: { fileName: 'a.bin' },
|
||||
}),
|
||||
).rejects.toSatisfy((err: unknown) => expectNotImplemented(err, 'crypto.enqueueDecrypt'));
|
||||
|
||||
await expect(provider.settings.load()).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotImplemented(err, 'settings.load'),
|
||||
);
|
||||
await expect(provider.settings.save({} as never)).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotImplemented(err, 'settings.save'),
|
||||
);
|
||||
|
||||
await expect(provider.download.pickDirectory()).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotImplemented(err, 'download.pickDirectory'),
|
||||
);
|
||||
|
||||
await expect(provider.keys.importNative([NativeImportType.QQMusic])).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotImplemented(err, 'keys.importNative'),
|
||||
);
|
||||
await expect(provider.keys.importAndroidAdb({})).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotImplemented(err, 'keys.importAndroidAdb'),
|
||||
);
|
||||
});
|
||||
|
||||
test('empty downloadTypes reject batch/single download with NotSupportedMethod', async () => {
|
||||
const provider = createTauriProvider();
|
||||
|
||||
await expect(provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotSupported(err, 'download.saveOne'),
|
||||
);
|
||||
await expect(
|
||||
provider.download.saveMany(BatchDownloadType.PackZip, {
|
||||
files: [{ url: 'blob:x', fileName: 'a.flac' }],
|
||||
}),
|
||||
).rejects.toSatisfy((err: unknown) => expectNotSupported(err, 'download.saveMany'));
|
||||
await expect(
|
||||
provider.download.saveMany(BatchDownloadType.SelectDirectory, {
|
||||
files: [{ url: 'blob:x', fileName: 'a.flac' }],
|
||||
}),
|
||||
).rejects.toSatisfy((err: unknown) => expectNotSupported(err, 'download.saveMany'));
|
||||
});
|
||||
|
||||
test('undeclared key / pickDirectory capabilities throw NotSupportedMethod', async () => {
|
||||
const provider = createTauriProvider({ capabilities: emptyCaps });
|
||||
|
||||
await expect(provider.download.pickDirectory()).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotSupported(err, 'download.pickDirectory'),
|
||||
);
|
||||
await expect(provider.keys.importNative([NativeImportType.QQMusic])).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotSupported(err, 'keys.importNative'),
|
||||
);
|
||||
await expect(provider.keys.importAndroidAdb({})).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotSupported(err, 'keys.importAndroidAdb'),
|
||||
);
|
||||
});
|
||||
|
||||
test('saveMany still NotImplemented when a download type is explicitly declared', async () => {
|
||||
const provider = createTauriProvider({
|
||||
capabilities: {
|
||||
...DEFAULT_TAURI_CAPABILITIES,
|
||||
downloadTypes: [BatchDownloadType.SelectDirectory],
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
provider.download.saveMany(BatchDownloadType.SelectDirectory, {
|
||||
files: [{ url: 'blob:x', fileName: 'a.flac' }],
|
||||
}),
|
||||
).rejects.toSatisfy((err: unknown) => expectNotImplemented(err, 'download.saveMany.SelectDirectory'));
|
||||
await expect(
|
||||
provider.download.saveMany(BatchDownloadType.PackZip, {
|
||||
files: [{ url: 'blob:x', fileName: 'a.flac' }],
|
||||
}),
|
||||
).rejects.toSatisfy((err: unknown) => expectNotSupported(err, 'download.saveMany'));
|
||||
});
|
||||
|
||||
test('importNative rejects empty or unsupported targets with NotSupportedMethod', async () => {
|
||||
const provider = createTauriProvider({
|
||||
capabilities: {
|
||||
...DEFAULT_TAURI_CAPABILITIES,
|
||||
nativeKeyAccess: [NativeImportType.QQMusic],
|
||||
},
|
||||
});
|
||||
|
||||
await expect(provider.keys.importNative([])).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotSupported(err, 'keys.importNative'),
|
||||
);
|
||||
await expect(provider.keys.importNative([NativeImportType.Kuwo])).rejects.toSatisfy((err: unknown) =>
|
||||
expectNotSupported(err, 'keys.importNative'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('detectPlatformRuntime / createPlatformProvider', () => {
|
||||
test('jsdom defaults to browser runtime', () => {
|
||||
expect(detectPlatformRuntime()).toBe('browser');
|
||||
expect(createPlatformProvider().id).toBe('browser');
|
||||
});
|
||||
|
||||
test('createPlatformProvider switches to Tauri when runtime is forced', () => {
|
||||
const provider = createPlatformProvider({ runtime: 'tauri' });
|
||||
expect(provider.id).toBe('tauri');
|
||||
expect(provider.capabilities.directFsAccess).toBe(true);
|
||||
expect(provider.capabilities.nativeKeyAccess.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('createPlatformProvider({ runtime: "browser" }) stays browser', () => {
|
||||
const provider = createPlatformProvider({ runtime: 'browser' });
|
||||
expect(provider.id).toBe('browser');
|
||||
expect(provider.capabilities.directFsAccess).toBe(false);
|
||||
});
|
||||
|
||||
test('window.__TAURI_INTERNALS__ selects tauri runtime', () => {
|
||||
const w = window as Window & { __TAURI_INTERNALS__?: unknown };
|
||||
w.__TAURI_INTERNALS__ = {};
|
||||
try {
|
||||
expect(detectPlatformRuntime()).toBe('tauri');
|
||||
} finally {
|
||||
delete w.__TAURI_INTERNALS__;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,12 @@ export interface BrowserProviderOptions {
|
||||
downloadTypes?: PlatformCapabilities['downloadTypes'];
|
||||
/** Override `directFsAccess` (tests). Browser default is `false`. */
|
||||
directFsAccess?: boolean;
|
||||
/** Override `nativeKeyAccess` (tests). Browser default is `[]`. */
|
||||
nativeKeyAccess?: PlatformCapabilities['nativeKeyAccess'];
|
||||
/** Override `androidKeyAccess` (tests). Browser default is `None`. */
|
||||
androidKeyAccess?: PlatformCapabilities['androidKeyAccess'];
|
||||
/** Override `keys` backend (tests). Defaults to `NotSupportedMethod` for both methods. */
|
||||
keys?: PlatformProvider['keys'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,8 +52,8 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
||||
const capabilities: PlatformCapabilities = Object.freeze({
|
||||
downloadTypes,
|
||||
directFsAccess: options.directFsAccess ?? false,
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: Object.freeze([] as NativeImportType[]),
|
||||
androidKeyAccess: options.androidKeyAccess ?? AndroidImportType.None,
|
||||
nativeKeyAccess: Object.freeze(options.nativeKeyAccess ? [...options.nativeKeyAccess] : ([] as NativeImportType[])),
|
||||
});
|
||||
|
||||
const settingsIo = createBrowserSettingsIo(
|
||||
@@ -102,7 +108,7 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
||||
|
||||
download,
|
||||
|
||||
keys: {
|
||||
keys: options.keys ?? {
|
||||
importNative: (_targets: readonly NativeImportType[]): Promise<NativeImportResult> =>
|
||||
notSupported('keys.importNative'),
|
||||
importAndroidAdb: (_opts: AndroidAdbImportOptions): Promise<NativeImportResult> =>
|
||||
|
||||
@@ -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'));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import { createBrowserProvider } from './browser/BrowserProvider';
|
||||
import { detectPlatformRuntime, type PlatformRuntime } from './detectPlatform';
|
||||
import type { PlatformProvider } from './PlatformProvider';
|
||||
import { createTauriProvider } from './tauri/TauriProvider';
|
||||
|
||||
export interface CreatePlatformProviderOptions {
|
||||
/** Override runtime detection (tests). Defaults to {@link detectPlatformRuntime}. */
|
||||
runtime?: PlatformRuntime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the active platform backend.
|
||||
* Currently always returns the browser provider; native (e.g. Tauri) switching can be added here later.
|
||||
* Defaults to Browser; switches to the Tauri stub when the Tauri runtime is detected
|
||||
* (or when `runtime: 'tauri'` is passed explicitly).
|
||||
*/
|
||||
export function createPlatformProvider(): PlatformProvider {
|
||||
export function createPlatformProvider(options: CreatePlatformProviderOptions = {}): PlatformProvider {
|
||||
const runtime = options.runtime ?? detectPlatformRuntime();
|
||||
if (runtime === 'tauri') {
|
||||
return createTauriProvider();
|
||||
}
|
||||
return createBrowserProvider();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export type PlatformRuntime = 'browser' | 'tauri';
|
||||
|
||||
type TauriWindow = Window & {
|
||||
__TAURI__?: unknown;
|
||||
__TAURI_INTERNALS__?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* Detect whether the app is running inside a Tauri webview.
|
||||
* Checks `import.meta.env.TAURI_ENV_PLATFORM` (Tauri 2 Vite) and window globals.
|
||||
*/
|
||||
export function detectPlatformRuntime(): PlatformRuntime {
|
||||
const envPlatform = import.meta.env.TAURI_ENV_PLATFORM;
|
||||
if (typeof envPlatform === 'string' && envPlatform.length > 0) {
|
||||
return 'tauri';
|
||||
}
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
return 'browser';
|
||||
}
|
||||
|
||||
const w = window as TauriWindow;
|
||||
if (w.__TAURI_INTERNALS__ != null || w.__TAURI__ != null) {
|
||||
return 'tauri';
|
||||
}
|
||||
|
||||
return 'browser';
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||
import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
import type {
|
||||
AndroidAdbImportOptions,
|
||||
DownloadManyInput,
|
||||
DownloadOneInput,
|
||||
NativeImportResult,
|
||||
PlatformCapabilities,
|
||||
} from '~/platform/types';
|
||||
|
||||
/** Target capability set for the desktop/native shell (methods not wired yet). */
|
||||
export const DEFAULT_TAURI_CAPABILITIES: PlatformCapabilities = Object.freeze({
|
||||
// Native uses DirectWrite (`directFsAccess`); no browser-style batch/ZIP download modes.
|
||||
downloadTypes: Object.freeze([] as BatchDownloadType[]),
|
||||
directFsAccess: true,
|
||||
androidKeyAccess: AndroidImportType.Adb,
|
||||
nativeKeyAccess: Object.freeze([
|
||||
NativeImportType.QQMusic,
|
||||
NativeImportType.Kuwo,
|
||||
NativeImportType.Kugou,
|
||||
NativeImportType.QingTing,
|
||||
]),
|
||||
});
|
||||
|
||||
function notImplemented(capability: string): Promise<never> {
|
||||
return Promise.reject(new NotImplementedError(capability));
|
||||
}
|
||||
|
||||
function notSupported(capability: string, message?: string): Promise<never> {
|
||||
return Promise.reject(new NotSupportedMethod(capability, message));
|
||||
}
|
||||
|
||||
export interface TauriProviderOptions {
|
||||
/** Override declared capabilities (tests / partial shells). */
|
||||
capabilities?: PlatformCapabilities;
|
||||
}
|
||||
|
||||
/**
|
||||
* Native (Tauri) `PlatformProvider` stub.
|
||||
* Declares desktop target capabilities; every method exists, but declared backends throw
|
||||
* `NotImplementedError` until native commands are wired. Calls outside `capabilities`
|
||||
* throw `NotSupportedMethod`. Construction and `init()` have no side effects.
|
||||
*/
|
||||
export function createTauriProvider(options: TauriProviderOptions = {}): PlatformProvider {
|
||||
const source = options.capabilities ?? DEFAULT_TAURI_CAPABILITIES;
|
||||
const capabilities: PlatformCapabilities = Object.freeze({
|
||||
downloadTypes: Object.freeze([...source.downloadTypes]),
|
||||
directFsAccess: source.directFsAccess,
|
||||
androidKeyAccess: source.androidKeyAccess,
|
||||
nativeKeyAccess: Object.freeze([...source.nativeKeyAccess]),
|
||||
});
|
||||
|
||||
const downloadTypeSet = new Set(capabilities.downloadTypes);
|
||||
const nativeAccessSet = new Set(capabilities.nativeKeyAccess);
|
||||
|
||||
return {
|
||||
id: 'tauri',
|
||||
capabilities,
|
||||
|
||||
init(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
crypto: {
|
||||
request: (_action, _payload) => notImplemented('crypto.request'),
|
||||
enqueueDecrypt: (_payload, _onPreProcess) => notImplemented('crypto.enqueueDecrypt'),
|
||||
},
|
||||
|
||||
settings: {
|
||||
load: () => notImplemented('settings.load'),
|
||||
save: (_settings) => notImplemented('settings.save'),
|
||||
},
|
||||
|
||||
download: {
|
||||
saveOne: (_input: DownloadOneInput) => {
|
||||
if (downloadTypeSet.size === 0) {
|
||||
return notSupported('download.saveOne');
|
||||
}
|
||||
return notImplemented('download.saveOne');
|
||||
},
|
||||
|
||||
saveMany: (type: BatchDownloadType, _input: DownloadManyInput) => {
|
||||
if (!downloadTypeSet.has(type)) {
|
||||
return notSupported('download.saveMany', `${type} unavailable on this platform`);
|
||||
}
|
||||
return notImplemented(`download.saveMany.${type}`);
|
||||
},
|
||||
|
||||
pickDirectory: () => {
|
||||
if (!capabilities.directFsAccess) {
|
||||
return notSupported('download.pickDirectory');
|
||||
}
|
||||
return notImplemented('download.pickDirectory');
|
||||
},
|
||||
},
|
||||
|
||||
keys: {
|
||||
importNative: (targets: readonly NativeImportType[]) => {
|
||||
if (nativeAccessSet.size === 0) {
|
||||
return notSupported('keys.importNative');
|
||||
}
|
||||
if (targets.length === 0) {
|
||||
return notSupported('keys.importNative', 'No native import targets selected');
|
||||
}
|
||||
const unsupported = targets.filter((t) => !nativeAccessSet.has(t));
|
||||
if (unsupported.length > 0) {
|
||||
return notSupported('keys.importNative', `Unsupported native import target(s): ${unsupported.join(', ')}`);
|
||||
}
|
||||
return notImplemented('keys.importNative');
|
||||
},
|
||||
|
||||
importAndroidAdb: (_opts: AndroidAdbImportOptions): Promise<NativeImportResult> => {
|
||||
if (capabilities.androidKeyAccess !== AndroidImportType.Adb) {
|
||||
return notSupported('keys.importAndroidAdb');
|
||||
}
|
||||
return notImplemented('keys.importAndroidAdb');
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
Vendored
+6
@@ -1,5 +1,11 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
/** Present when bundled under Tauri 2 Vite (`TAURI_ENV_PLATFORM`). */
|
||||
readonly TAURI_ENV_PLATFORM?: string;
|
||||
readonly VITE_ENABLE_PERF_LOG?: string;
|
||||
}
|
||||
|
||||
module 'virtual:pwa-register' {
|
||||
/**
|
||||
* See: {@link https://vite-pwa-org.netlify.app/guide/prompt-for-update.html}
|
||||
|
||||
Reference in new issue
Block a user