mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-27 23:56:59 +00:00
Compare commits
11
Commits
d86323e38a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8bb7d4430 | ||
|
|
6571dc5344 | ||
|
|
4d688af4ca | ||
|
|
b9c8d5b3cd | ||
|
|
79e5b45e6b | ||
|
|
ef4cd9c21e | ||
|
|
94eab8ecf6 | ||
|
|
d424837e66 | ||
|
|
b5fdc8ebbe | ||
|
|
cb5531e9e4 | ||
|
|
cc688b85bd |
No files matched your search
@@ -92,8 +92,21 @@ docker run -d -p 8080:80 --name um-react um-react
|
|||||||
|
|
||||||
然后访问 `http://localhost:8080` 即可。
|
然后访问 `http://localhost:8080` 即可。
|
||||||
|
|
||||||
|
## 部署到子目录
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> 项目不支持运行在子目录下。
|
> 官方 Docker 镜像与默认构建产物按站点**根路径**(`/`)部署,不支持部署到子目录下。
|
||||||
|
|
||||||
|
若要部署到子目录(例如 `https://example.com/um-react/`),你需要重新使用 Vite 进行构建,并指定 `--base` 参数(路径以 `/` 开头、以 `/` 结尾)。
|
||||||
|
|
||||||
|
以部署到 `https://example.com/um-react/` 为例:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm exec vite build --base=/um-react/
|
||||||
|
pnpm build:finalize
|
||||||
|
```
|
||||||
|
|
||||||
|
部署时,服务器还需把该子目录下的所有前端路由回退到对应的 `index.html`(SPA)。
|
||||||
|
|
||||||
## 开发相关
|
## 开发相关
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,6 @@
|
|||||||
<link rel="icon" href="/favicon.ico" />
|
<link rel="icon" href="/favicon.ico" />
|
||||||
<link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
|
<link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
|
||||||
<meta name="theme-color" content="#4DBA87" />
|
<meta name="theme-color" content="#4DBA87" />
|
||||||
<script>
|
|
||||||
// 设置基础路径,如果希望部署在/music-unlock/,则改为 '/music-unlock/',默认部署在根路径
|
|
||||||
window.BASE_URL = '/';
|
|
||||||
</script>
|
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { minify } from 'terser';
|
import { minify } from 'terser';
|
||||||
import { readFileSync, writeFileSync, readdirSync } from 'fs';
|
import { readFileSync, writeFileSync, readdirSync } from 'fs';
|
||||||
|
|
||||||
for (const file of readdirSync('dist/assets')) {
|
const assetsDir = 'dist/um-react.assets';
|
||||||
|
|
||||||
|
for (const file of readdirSync(assetsDir)) {
|
||||||
if (!/\.(mjs|js)$/.test(file)) {
|
if (!/\.(mjs|js)$/.test(file)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -9,11 +11,11 @@ for (const file of readdirSync('dist/assets')) {
|
|||||||
console.log(`minifying ${file}...`);
|
console.log(`minifying ${file}...`);
|
||||||
const isModule = /\.mjs$/.test(file);
|
const isModule = /\.mjs$/.test(file);
|
||||||
|
|
||||||
const output = await minify(readFileSync(`dist/assets/${file}`, 'utf-8'), {
|
const output = await minify(readFileSync(`${assetsDir}/${file}`, 'utf-8'), {
|
||||||
compress: true,
|
compress: true,
|
||||||
mangle: true,
|
mangle: true,
|
||||||
module: isModule,
|
module: isModule,
|
||||||
});
|
});
|
||||||
|
|
||||||
writeFileSync(`dist/assets/${file}`, output.code);
|
writeFileSync(`${assetsDir}/${file}`, output.code);
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,28 @@
|
|||||||
import { renderWithProviders, screen, waitFor } from '~/test-utils/test-helper';
|
import { act, renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
import { AppRoot } from '~/components/AppRoot';
|
import { AppRoot } from '~/components/AppRoot';
|
||||||
|
|
||||||
vi.mock('../decrypt-worker/client', () => {
|
// Must match the dynamic import specifier used by browserCrypto (`~/decrypt-worker/client`).
|
||||||
|
// Plain functions: vitest `mockReset` clears vi.fn mockResolvedValue between tests.
|
||||||
|
vi.mock('~/decrypt-worker/client', () => {
|
||||||
return {
|
return {
|
||||||
workerClientBus: {
|
workerClientBus: {
|
||||||
request: vi.fn().mockResolvedValue('dummy'),
|
request: () => Promise.resolve('dummy'),
|
||||||
|
},
|
||||||
|
decryptionQueue: {
|
||||||
|
add: () => Promise.resolve({ decrypted: 'blob://dummy', ext: 'flac' }),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should be able to render App', async () => {
|
test('should be able to render App', async () => {
|
||||||
renderWithProviders(<AppRoot />);
|
await act(async () => {
|
||||||
|
renderWithProviders(<AppRoot />);
|
||||||
|
// Flush Suspense retry after platform.init() (dynamic import) settles.
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
// Should eventually load sdk version
|
// Platform Suspense gate + SDK version fetch
|
||||||
await waitFor(() => screen.getByTestId('sdk-version'));
|
expect(await screen.findByTestId('sdk-version')).toBeInTheDocument();
|
||||||
|
|
||||||
// Quick sanity check of known strings.
|
// Quick sanity check of known strings.
|
||||||
expect(screen.getByText(/音乐解锁/i)).toBeInTheDocument();
|
expect(screen.getByText(/音乐解锁/i)).toBeInTheDocument();
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { NavLink, Navigate, Route, Routes } from 'react-router';
|
||||||
|
import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
|
||||||
|
import { Bounce, ToastContainer } from 'react-toastify';
|
||||||
|
|
||||||
|
import { Footer } from '~/components/Footer';
|
||||||
|
import { FaqHome } from '~/faq/FaqHome';
|
||||||
|
import { FAQ_PAGES } from '~/faq/FAQPages';
|
||||||
|
import { SettingsHome } from '~/features/settings/SettingsHome';
|
||||||
|
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';
|
||||||
|
|
||||||
|
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
|
||||||
|
|
||||||
|
/** 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">
|
||||||
|
<NavLink to="/" role="tab" className={tabClassNames}>
|
||||||
|
<MdHome />
|
||||||
|
应用
|
||||||
|
</NavLink>
|
||||||
|
<NavLink to="/settings" role="tab" className={tabClassNames}>
|
||||||
|
<MdSettings />
|
||||||
|
设置
|
||||||
|
</NavLink>
|
||||||
|
<NavLink to="/questions" role="tab" className={tabClassNames}>
|
||||||
|
<MdQuestionAnswer />
|
||||||
|
答疑
|
||||||
|
</NavLink>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<main className="flex-1 flex justify-center min-h-0 overflow-auto">
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" Component={MainTab} />
|
||||||
|
<Route path="/settings" Component={SettingsTab}>
|
||||||
|
<Route index Component={SettingsHome} />
|
||||||
|
{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} />
|
||||||
|
{FAQ_PAGES.map(({ id, Component }) => (
|
||||||
|
<Route key={id} path={id} Component={Component} />
|
||||||
|
))}
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<ToastContainer
|
||||||
|
position="bottom-center"
|
||||||
|
autoClose={5000}
|
||||||
|
newestOnTop
|
||||||
|
closeOnClick={false}
|
||||||
|
pauseOnFocusLoss
|
||||||
|
draggable
|
||||||
|
theme="colored"
|
||||||
|
transition={Bounce}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Footer />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
+30
-63
@@ -1,77 +1,44 @@
|
|||||||
import { useEffect } from 'react';
|
import { Suspense } from 'react';
|
||||||
import { BrowserRouter, NavLink, Route, Routes } from 'react-router';
|
import { BrowserRouter } from 'react-router';
|
||||||
import { MdSettings, MdHome, MdQuestionAnswer } from 'react-icons/md';
|
|
||||||
|
|
||||||
import { MainTab } from '~/tabs/MainTab';
|
|
||||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
|
||||||
|
|
||||||
import { Provider } from 'react-redux';
|
import { Provider } from 'react-redux';
|
||||||
|
|
||||||
|
import { AppLayout } from '~/components/AppLayout';
|
||||||
import { persistSettings } from '~/features/settings/persistSettings';
|
import { persistSettings } from '~/features/settings/persistSettings';
|
||||||
|
import { createPlatformProvider } from '~/platform/createPlatformProvider';
|
||||||
|
import { PlatformLoadGuard } from '~/platform/PlatformLoadGuard';
|
||||||
|
import { PlatformProviderHost } from '~/platform/PlatformContext';
|
||||||
|
import { setPlatform } from '~/platform/platformSingleton';
|
||||||
import { setupStore } from '~/store';
|
import { setupStore } from '~/store';
|
||||||
import { Footer } from '~/components/Footer';
|
|
||||||
import { FaqTab } from '~/tabs/FaqTab';
|
|
||||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
|
|
||||||
import { Bounce, ToastContainer } from 'react-toastify';
|
|
||||||
import { SettingsHome } from '~/features/settings/SettingsHome';
|
|
||||||
import { FAQ_PAGES } from '~/faq/FAQPages';
|
|
||||||
import { FaqHome } from '~/faq/FaqHome';
|
|
||||||
|
|
||||||
// Private to this file only.
|
// Private to this file only.
|
||||||
const store = setupStore();
|
const store = setupStore();
|
||||||
|
const platform = createPlatformProvider();
|
||||||
|
|
||||||
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
|
const platformReady = platform.init().then(() => {
|
||||||
|
setPlatform(platform);
|
||||||
|
persistSettings(store, platform);
|
||||||
|
});
|
||||||
|
|
||||||
|
function AppBootFallback() {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 items-center justify-center min-h-0" role="status" aria-live="polite">
|
||||||
|
<span className="loading loading-spinner loading-lg text-primary" />
|
||||||
|
<span className="sr-only">加载中</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function AppRoot() {
|
export function AppRoot() {
|
||||||
useEffect(() => persistSettings(store), []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BrowserRouter basename={window.BASE_URL || '/'}>
|
<BrowserRouter basename={import.meta.env.BASE_URL}>
|
||||||
<Provider store={store}>
|
<Provider store={store}>
|
||||||
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
<PlatformProviderHost provider={platform}>
|
||||||
<NavLink to="/" role="tab" className={tabClassNames}>
|
<Suspense fallback={<AppBootFallback />}>
|
||||||
<MdHome />
|
<PlatformLoadGuard ready={platformReady}>
|
||||||
应用
|
<AppLayout />
|
||||||
</NavLink>
|
</PlatformLoadGuard>
|
||||||
<NavLink to="/settings" role="tab" className={tabClassNames}>
|
</Suspense>
|
||||||
<MdSettings />
|
</PlatformProviderHost>
|
||||||
设置
|
|
||||||
</NavLink>
|
|
||||||
<NavLink to="/questions" role="tab" className={tabClassNames}>
|
|
||||||
<MdQuestionAnswer />
|
|
||||||
答疑
|
|
||||||
</NavLink>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<main className="flex-1 flex justify-center min-h-0 overflow-auto">
|
|
||||||
<Routes>
|
|
||||||
<Route path="/" Component={MainTab} />
|
|
||||||
<Route path="/settings" Component={SettingsTab}>
|
|
||||||
<Route index Component={SettingsHome} />
|
|
||||||
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
|
|
||||||
<Route key={key} path={key} Component={Tab} />
|
|
||||||
))}
|
|
||||||
</Route>
|
|
||||||
<Route path="/questions" Component={FaqTab}>
|
|
||||||
<Route index Component={FaqHome} />
|
|
||||||
{FAQ_PAGES.map(({ id, Component }) => (
|
|
||||||
<Route key={id} path={id} Component={Component} />
|
|
||||||
))}
|
|
||||||
</Route>
|
|
||||||
</Routes>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<ToastContainer
|
|
||||||
position="bottom-center"
|
|
||||||
autoClose={5000}
|
|
||||||
newestOnTop
|
|
||||||
closeOnClick={false}
|
|
||||||
pauseOnFocusLoss
|
|
||||||
draggable
|
|
||||||
theme="colored"
|
|
||||||
transition={Bounce}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Footer />
|
|
||||||
</Provider>
|
</Provider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
|
|||||||
+22
-123
@@ -2,17 +2,18 @@ import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-l
|
|||||||
import { FaDownload } from 'react-icons/fa';
|
import { FaDownload } from 'react-icons/fa';
|
||||||
import { useAppSelector } from '~/hooks';
|
import { useAppSelector } from '~/hooks';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { SimpleQueue } from '~/util/SimpleQueue';
|
|
||||||
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
|
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
|
||||||
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
|
||||||
import { downloadZipAsBlob, downloadZipViaSavePicker, ZipSourceFile } from '~/util/streamZip';
|
|
||||||
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
|
||||||
|
|
||||||
export function DownloadAll() {
|
export function DownloadAll() {
|
||||||
const files = useAppSelector(selectFiles);
|
const files = useAppSelector(selectFiles);
|
||||||
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
|
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
|
||||||
|
const { download, capabilities } = usePlatform();
|
||||||
|
|
||||||
|
if (capabilities.downloadTypes.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const downloadAllAsync = async () => {
|
const downloadAllAsync = async () => {
|
||||||
const fileList = Object.values(files);
|
const fileList = Object.values(files);
|
||||||
@@ -36,12 +37,16 @@ export function DownloadAll() {
|
|||||||
|
|
||||||
// Single file: direct blob download, no ZIP / directory picker.
|
// Single file: direct blob download, no ZIP / directory picker.
|
||||||
if (completeFiles.length === 1) {
|
if (completeFiles.length === 1) {
|
||||||
downloadSingleBlob(completeFiles[0]);
|
const file = completeFiles[0];
|
||||||
|
await download.saveOne({
|
||||||
|
url: file.decrypted,
|
||||||
|
fileName: decryptedDownloadName(file),
|
||||||
|
});
|
||||||
toast.success('已开始下载');
|
toast.success('已开始下载');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const modes = buildEnabledModes(batchSettings);
|
const modes = buildEnabledDownloadModes(batchSettings, capabilities.downloadTypes);
|
||||||
if (modes.length === 0) {
|
if (modes.length === 0) {
|
||||||
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
|
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
|
||||||
return;
|
return;
|
||||||
@@ -49,9 +54,17 @@ export function DownloadAll() {
|
|||||||
|
|
||||||
toast.warning('开始下载,请稍候');
|
toast.warning('开始下载,请稍候');
|
||||||
|
|
||||||
|
const manyInput = {
|
||||||
|
files: completeFiles.map((file) => ({
|
||||||
|
url: file.decrypted,
|
||||||
|
fileName: decryptedDownloadName(file),
|
||||||
|
})),
|
||||||
|
rememberDirectory: batchSettings.rememberDirectory,
|
||||||
|
};
|
||||||
|
|
||||||
for (const mode of modes) {
|
for (const mode of modes) {
|
||||||
try {
|
try {
|
||||||
const result = await runMode(mode, completeFiles, batchSettings.rememberDirectory);
|
const result = await download.saveMany(mode, manyInput);
|
||||||
if (result === 'ok') {
|
if (result === 'ok') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -79,120 +92,6 @@ export function DownloadAll() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type BatchMode = 'directory' | 'streamingZip' | 'blobZip';
|
|
||||||
|
|
||||||
function buildEnabledModes(
|
|
||||||
settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
|
|
||||||
): BatchMode[] {
|
|
||||||
const modes: BatchMode[] = [];
|
|
||||||
if (settings.directoryPicker && supportsDirectoryPicker()) {
|
|
||||||
modes.push('directory');
|
|
||||||
}
|
|
||||||
if (settings.streamingZip && supportsStreamingZipDownload()) {
|
|
||||||
modes.push('streamingZip');
|
|
||||||
}
|
|
||||||
if (settings.blobZip) {
|
|
||||||
modes.push('blobZip');
|
|
||||||
}
|
|
||||||
return modes;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runMode(
|
|
||||||
mode: BatchMode,
|
|
||||||
completeFiles: DecryptedAudioFile[],
|
|
||||||
rememberDirectory: boolean,
|
|
||||||
): Promise<'ok' | 'cancelled'> {
|
|
||||||
switch (mode) {
|
|
||||||
case 'directory':
|
|
||||||
return downloadToDirectory(completeFiles, rememberDirectory);
|
|
||||||
case 'streamingZip':
|
|
||||||
return downloadStreamingZip(completeFiles);
|
|
||||||
case 'blobZip':
|
|
||||||
await downloadBlobZip(completeFiles);
|
|
||||||
return 'ok';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadToDirectory(
|
|
||||||
completeFiles: DecryptedAudioFile[],
|
|
||||||
remember: boolean,
|
|
||||||
): Promise<'ok' | 'cancelled'> {
|
|
||||||
const dir = await resolveWritableDirectory(remember);
|
|
||||||
if (!dir) {
|
|
||||||
return 'cancelled';
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileCount = completeFiles.length;
|
|
||||||
const queue = new SimpleQueue(8);
|
|
||||||
const promises = completeFiles.map(async (file) => {
|
|
||||||
try {
|
|
||||||
await queue.enter();
|
|
||||||
await writeFileToDirectory(file, dir);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`下载失败: ${file.fileName}`, e);
|
|
||||||
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
|
|
||||||
throw e;
|
|
||||||
} finally {
|
|
||||||
queue.leave();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const promiseResults = await Promise.allSettled(promises);
|
|
||||||
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
|
|
||||||
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
|
|
||||||
toast[level](`成功下载: ${success}/${fileCount}首`);
|
|
||||||
|
|
||||||
if (success === 0) {
|
|
||||||
throw new Error('未能写入任何文件到所选目录');
|
|
||||||
}
|
|
||||||
return 'ok';
|
|
||||||
}
|
|
||||||
|
|
||||||
function decryptedDownloadName(file: DecryptedAudioFile): string {
|
function decryptedDownloadName(file: DecryptedAudioFile): string {
|
||||||
return `${file.cleanName}.${file.ext}`;
|
return `${file.cleanName}.${file.ext}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function writeFileToDirectory(file: DecryptedAudioFile, dir: FileSystemDirectoryHandle) {
|
|
||||||
const fileHandle = await dir.getFileHandle(decryptedDownloadName(file), { create: true });
|
|
||||||
const fileStream = await fileHandle.createWritable();
|
|
||||||
try {
|
|
||||||
const res = await fetch(file.decrypted);
|
|
||||||
if (!res.ok) {
|
|
||||||
throw new Error(`无法读取文件: ${decryptedDownloadName(file)} (${res.status})`);
|
|
||||||
}
|
|
||||||
if (!res.body) {
|
|
||||||
await fileStream.write(await res.arrayBuffer());
|
|
||||||
await fileStream.close();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await res.body.pipeTo(fileStream);
|
|
||||||
} catch (e) {
|
|
||||||
await fileStream.abort();
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toZipSources(files: DecryptedAudioFile[]): ZipSourceFile[] {
|
|
||||||
return files.map((file) => ({
|
|
||||||
name: decryptedDownloadName(file),
|
|
||||||
url: file.decrypted,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
function downloadSingleBlob(file: DecryptedAudioFile) {
|
|
||||||
triggerAnchorDownload(file.decrypted, decryptedDownloadName(file));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadStreamingZip(completeFiles: DecryptedAudioFile[]): Promise<'ok' | 'cancelled'> {
|
|
||||||
const sources = toZipSources(completeFiles);
|
|
||||||
const result = await downloadZipViaSavePicker(sources);
|
|
||||||
if (result === 'ok') {
|
|
||||||
toast.success(`已导出 ZIP(${completeFiles.length} 首)`);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadBlobZip(completeFiles: DecryptedAudioFile[]): Promise<void> {
|
|
||||||
await downloadZipAsBlob(toZipSources(completeFiles));
|
|
||||||
toast.success(`已开始下载 ZIP(${completeFiles.length} 首)`);
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
import { MdInfoOutline } from 'react-icons/md';
|
import { MdInfoOutline } from 'react-icons/md';
|
||||||
import { workerClientBus } from '~/decrypt-worker/client';
|
|
||||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
const getSDKVersion = async (): Promise<string> => {
|
|
||||||
return workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
|
|
||||||
};
|
|
||||||
|
|
||||||
export function SDKVersion() {
|
export function SDKVersion() {
|
||||||
|
const { crypto } = usePlatform();
|
||||||
const refDialog = useRef<HTMLDialogElement>(null);
|
const refDialog = useRef<HTMLDialogElement>(null);
|
||||||
const [sdkVersion, setSdkVersion] = useState('...');
|
const [sdkVersion, setSdkVersion] = useState('...');
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null).then(setSdkVersion, () => setSdkVersion('N/A'));
|
||||||
}, []);
|
}, [crypto]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { DownloadAll } from '~/components/DownloadAll';
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
|
|
||||||
|
test('hides download-all control when platform has no downloadTypes', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
},
|
||||||
|
downloadTypes: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<DownloadAll />, { platform });
|
||||||
|
|
||||||
|
expect(screen.queryByTitle('下载全部')).not.toBeInTheDocument();
|
||||||
|
expect(document.getElementById('downloadAll')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders download-all control when PackZip is available', () => {
|
||||||
|
renderWithProviders(<DownloadAll />);
|
||||||
|
|
||||||
|
expect(screen.getByTitle('下载全部')).toBeInTheDocument();
|
||||||
|
expect(document.getElementById('downloadAll')).not.toBeNull();
|
||||||
|
});
|
||||||
@@ -2,6 +2,7 @@ import { DecryptedAudioFile, deleteFile, ProcessState } from './fileListingSlice
|
|||||||
import { useAppDispatch } from '~/hooks';
|
import { useAppDispatch } from '~/hooks';
|
||||||
import { FileError } from './FileError';
|
import { FileError } from './FileError';
|
||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
|
|
||||||
interface FileRowProps {
|
interface FileRowProps {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -10,7 +11,9 @@ interface FileRowProps {
|
|||||||
|
|
||||||
export function FileRow({ id, file }: FileRowProps) {
|
export function FileRow({ id, file }: FileRowProps) {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
const { capabilities } = usePlatform();
|
||||||
const isDecrypted = file.state === ProcessState.COMPLETE;
|
const isDecrypted = file.state === ProcessState.COMPLETE;
|
||||||
|
const showDownload = capabilities.downloadTypes.length > 0;
|
||||||
|
|
||||||
const decryptedName = file.cleanName + '.' + file.ext;
|
const decryptedName = file.cleanName + '.' + file.ext;
|
||||||
|
|
||||||
@@ -32,18 +35,20 @@ export function FileRow({ id, file }: FileRowProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="card-actions justify-end">
|
<div className="card-actions justify-end">
|
||||||
<a
|
{showDownload && (
|
||||||
href={file.decrypted}
|
<a
|
||||||
download={decryptedName}
|
href={file.decrypted}
|
||||||
title={`下载: ${decryptedName}`}
|
download={decryptedName}
|
||||||
className={classNames('btn', {
|
title={`下载: ${decryptedName}`}
|
||||||
'btn-primary': file.decrypted,
|
className={classNames('btn', {
|
||||||
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
'btn-primary': file.decrypted,
|
||||||
})}
|
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
||||||
data-testid="audio-download"
|
})}
|
||||||
>
|
data-testid="audio-download"
|
||||||
下载
|
>
|
||||||
</a>
|
下载
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
|
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
|
||||||
删除
|
删除
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
import { untouchedFile } from './__fixture__/file-list';
|
import { untouchedFile } from './__fixture__/file-list';
|
||||||
import { FileRow } from '../FileRow';
|
import { FileRow } from '../FileRow';
|
||||||
@@ -14,4 +15,19 @@ test('should render basic title (done)', () => {
|
|||||||
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
|
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
|
||||||
|
|
||||||
expect(screen.getAllByTestId('file-row')).toHaveLength(1);
|
expect(screen.getAllByTestId('file-row')).toHaveLength(1);
|
||||||
|
expect(screen.getByTestId('audio-download')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides single-file download when platform has no downloadTypes', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
},
|
||||||
|
downloadTypes: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<FileRow id="file://done" file={completedFile} />, { platform });
|
||||||
|
|
||||||
|
expect(screen.queryByTestId('audio-download')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import type { WorkerActionName } from '~/decrypt-worker/actions';
|
||||||
|
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||||
|
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import { setPlatform } from '~/platform/platformSingleton';
|
||||||
|
import { setupStore } from '~/store';
|
||||||
|
import { ListingMode, ProcessState, processFile, selectFiles } from '../fileListingSlice';
|
||||||
|
import { untouchedFile } from './__fixture__/file-list';
|
||||||
|
|
||||||
|
describe('processFile', () => {
|
||||||
|
test('parses headers via platform.crypto then enqueueDecrypts', async () => {
|
||||||
|
const request = vi.fn((action: WorkerActionName) => {
|
||||||
|
if (action === 'FIND_QMC_MUSICEX_NAME') {
|
||||||
|
return Promise.resolve('track.mflac');
|
||||||
|
}
|
||||||
|
return Promise.resolve(null);
|
||||||
|
});
|
||||||
|
const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
|
||||||
|
const crypto: BrowserCrypto = { request, enqueueDecrypt };
|
||||||
|
setPlatform(createBrowserProvider({ crypto }));
|
||||||
|
|
||||||
|
const fileId = 'file://untouched';
|
||||||
|
const store = setupStore({
|
||||||
|
fileListing: {
|
||||||
|
files: { [fileId]: { ...untouchedFile } },
|
||||||
|
displayMode: ListingMode.LIST,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await store.dispatch(processFile({ fileId }));
|
||||||
|
|
||||||
|
expect(result.type).toBe(processFile.fulfilled.type);
|
||||||
|
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||||
|
blobURI: untouchedFile.raw,
|
||||||
|
});
|
||||||
|
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||||
|
blobURI: untouchedFile.raw,
|
||||||
|
});
|
||||||
|
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||||
|
blobURI: untouchedFile.raw,
|
||||||
|
});
|
||||||
|
expect(enqueueDecrypt).toHaveBeenCalledTimes(1);
|
||||||
|
const [decryptPayload, onPreProcess] = enqueueDecrypt.mock.calls[0] as [
|
||||||
|
{ fileId: string; blobURI: string; options: { fileName: string } },
|
||||||
|
() => void,
|
||||||
|
];
|
||||||
|
expect(decryptPayload).toMatchObject({
|
||||||
|
fileId,
|
||||||
|
blobURI: untouchedFile.raw,
|
||||||
|
options: { fileName: untouchedFile.fileName },
|
||||||
|
});
|
||||||
|
expect(typeof onPreProcess).toBe('function');
|
||||||
|
|
||||||
|
const file = selectFiles(store.getState())[fileId];
|
||||||
|
expect(file.state).toBe(ProcessState.COMPLETE);
|
||||||
|
expect(file.decrypted).toBe('blob://out');
|
||||||
|
expect(file.ext).toBe('flac');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects when file id is missing', async () => {
|
||||||
|
const crypto: BrowserCrypto = {
|
||||||
|
request: vi.fn(),
|
||||||
|
enqueueDecrypt: vi.fn(),
|
||||||
|
};
|
||||||
|
setPlatform(createBrowserProvider({ crypto }));
|
||||||
|
const store = setupStore({
|
||||||
|
fileListing: {
|
||||||
|
files: {},
|
||||||
|
displayMode: ListingMode.LIST,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await store.dispatch(processFile({ fileId: 'missing' }));
|
||||||
|
expect(result.type).toBe(processFile.rejected.type);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,12 +4,12 @@ import type { RootState } from '~/store';
|
|||||||
|
|
||||||
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
||||||
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
||||||
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
|
|
||||||
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
||||||
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
||||||
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
|
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
|
||||||
import { selectKugouKey } from '~/features/kugou/keyLookup';
|
import { selectKugouKey } from '~/features/kugou/keyLookup';
|
||||||
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||||
|
import { getPlatform } from '~/platform/platformSingleton';
|
||||||
import { cleanFilename } from '~/util/cleanFilename';
|
import { cleanFilename } from '~/util/cleanFilename';
|
||||||
|
|
||||||
export enum ProcessState {
|
export enum ProcessState {
|
||||||
@@ -70,14 +70,15 @@ export const processFile = createAsyncThunk<
|
|||||||
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
|
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const { crypto } = getPlatform();
|
||||||
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
|
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
|
||||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||||
blobURI: file.raw,
|
blobURI: file.raw,
|
||||||
}),
|
}),
|
||||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||||
blobURI: file.raw,
|
blobURI: file.raw,
|
||||||
}),
|
}),
|
||||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||||
blobURI: file.raw,
|
blobURI: file.raw,
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
@@ -89,7 +90,7 @@ export const processFile = createAsyncThunk<
|
|||||||
kugouKey: selectKugouKey(state, kugouHdr),
|
kugouKey: selectKugouKey(state, kugouHdr),
|
||||||
qingTingAndroidKey: selectQtfmAndroidKey(state),
|
qingTingAndroidKey: selectQtfmAndroidKey(state),
|
||||||
};
|
};
|
||||||
return decryptionQueue.add({ fileId, blobURI: file.raw, options }, onPreProcess);
|
return crypto.enqueueDecrypt({ fileId, blobURI: file.raw, options }, onPreProcess);
|
||||||
});
|
});
|
||||||
|
|
||||||
export const fileListingSlice = createSlice({
|
export const fileListingSlice = createSlice({
|
||||||
|
|||||||
@@ -6,14 +6,15 @@ import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
|||||||
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
|
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
|
||||||
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
|
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
|
||||||
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
|
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
|
||||||
import { workerClientBus } from '~/decrypt-worker/client.ts';
|
|
||||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
|
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
|
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
|
||||||
|
|
||||||
export function PanelQingTing() {
|
export function PanelQingTing() {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
const { crypto } = usePlatform();
|
||||||
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
|
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
|
||||||
const setSecretKey = (secretKey: string) => {
|
const setSecretKey = (secretKey: string) => {
|
||||||
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
|
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
|
||||||
@@ -31,7 +32,7 @@ export function PanelQingTing() {
|
|||||||
const dataMap = parseQtfmDeviceInfoFromText(plainText);
|
const dataMap = parseQtfmDeviceInfoFromText(plainText);
|
||||||
if (dataMap) {
|
if (dataMap) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
workerClientBus
|
crypto
|
||||||
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
||||||
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
|
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,17 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
|
|||||||
import { commitStagingChange, discardStagingChanges } from './settingsSlice';
|
import { commitStagingChange, discardStagingChanges } from './settingsSlice';
|
||||||
import { selectIsSettingsNotSaved } from './settingsSelector';
|
import { selectIsSettingsNotSaved } from './settingsSelector';
|
||||||
import { Outlet } from 'react-router';
|
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 { MdOutlineSettingsBackupRestore } from 'react-icons/md';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { ResponsiveNav } from '../nav/ResponsiveNav';
|
import { ResponsiveNav } from '../nav/ResponsiveNav';
|
||||||
import { TabNavLink } from '../nav/TabNavLink';
|
import { TabNavLink } from '../nav/TabNavLink';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
|
|
||||||
export function Settings() {
|
export function Settings() {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
const { capabilities } = usePlatform();
|
||||||
|
const settingsTabs = getSettingsTabs(capabilities);
|
||||||
|
|
||||||
const handleResetSettings = () => {
|
const handleResetSettings = () => {
|
||||||
dispatch(discardStagingChanges());
|
dispatch(discardStagingChanges());
|
||||||
@@ -35,7 +38,7 @@ export function Settings() {
|
|||||||
navigationClassName="overflow-x-auto pb-[2px] md:pb-0 h-full items-start [&]:md:flex"
|
navigationClassName="overflow-x-auto pb-[2px] md:pb-0 h-full items-start [&]:md:flex"
|
||||||
navigation={
|
navigation={
|
||||||
<div role="tablist" className="tabs gap-1 flex-nowrap md:flex-col grow items-center">
|
<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}`}>
|
<TabNavLink key={id} to={`/settings/${id}`}>
|
||||||
{name}
|
{name}
|
||||||
</TabNavLink>
|
</TabNavLink>
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { configureStore } from '@reduxjs/toolkit';
|
||||||
|
import { afterEach, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import type { SettingsStorage } from '~/platform/browser/browserSettingsIo';
|
||||||
|
import { persistSettings, mergeSettings } from '../persistSettings';
|
||||||
|
import { settingsSlice, setProductionChanges, type ProductionSettings } from '../settingsSlice';
|
||||||
|
|
||||||
|
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
|
||||||
|
const data = { ...initial };
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
getItem(key: string) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
|
||||||
|
},
|
||||||
|
setItem(key: string, value: string) {
|
||||||
|
data[key] = value;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStore() {
|
||||||
|
return configureStore({
|
||||||
|
reducer: { settings: settingsSlice.reducer },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('persistSettings', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loads via provider, merges, and dispatches production', async () => {
|
||||||
|
const stored: ProductionSettings = {
|
||||||
|
...settingsSlice.getInitialState().production,
|
||||||
|
qmc2: {
|
||||||
|
allowFuzzyNameSearch: false,
|
||||||
|
keys: { 'a.mflac': 'ek' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const storage = createMemoryStorage({ 'um-react-settings': JSON.stringify(stored) });
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
const unsubscribe = persistSettings(store, provider);
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': 'ek' });
|
||||||
|
expect(store.getState().settings.production.qmc2.allowFuzzyNameSearch).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
unsubscribe();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ignores failed loads and keeps defaults', async () => {
|
||||||
|
const storage = createMemoryStorage({ 'um-react-settings': '{bad' });
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||||
|
const store = createStore();
|
||||||
|
const defaults = settingsSlice.getInitialState().production;
|
||||||
|
|
||||||
|
const unsubscribe = persistSettings(store, provider);
|
||||||
|
// Give the rejected load a turn to settle.
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(store.getState().settings.production).toEqual(defaults);
|
||||||
|
unsubscribe();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('debounced save writes production through provider', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||||
|
const store = createStore();
|
||||||
|
|
||||||
|
const unsubscribe = persistSettings(store, provider);
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
const next = mergeSettings({
|
||||||
|
...settingsSlice.getInitialState().production,
|
||||||
|
qmc2: { allowFuzzyNameSearch: true, keys: { 'b.mflac': 'x' } },
|
||||||
|
});
|
||||||
|
store.dispatch(setProductionChanges(next));
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(150);
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(JSON.parse(storage.data['um-react-settings'])).toEqual(next);
|
||||||
|
unsubscribe();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -38,6 +38,11 @@ describe('stagingToProduction / productionToStaging', () => {
|
|||||||
streamingZip: true,
|
streamingZip: true,
|
||||||
blobZip: false,
|
blobZip: false,
|
||||||
},
|
},
|
||||||
|
directWrite: {
|
||||||
|
outputMode: 'fixedDirectory',
|
||||||
|
fixedDirectoryPath: '/out',
|
||||||
|
deleteSourceAfterDecrypt: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
qmc2: {
|
qmc2: {
|
||||||
allowFuzzyNameSearch: false,
|
allowFuzzyNameSearch: false,
|
||||||
@@ -60,6 +65,11 @@ describe('stagingToProduction / productionToStaging', () => {
|
|||||||
streamingZip: true,
|
streamingZip: true,
|
||||||
blobZip: false,
|
blobZip: false,
|
||||||
},
|
},
|
||||||
|
directWrite: {
|
||||||
|
outputMode: 'fixedDirectory',
|
||||||
|
fixedDirectoryPath: '/out',
|
||||||
|
deleteSourceAfterDecrypt: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
qmc2: {
|
qmc2: {
|
||||||
allowFuzzyNameSearch: false,
|
allowFuzzyNameSearch: false,
|
||||||
@@ -172,6 +182,7 @@ describe('mergeSettings', () => {
|
|||||||
} as unknown as ProductionSettings);
|
} as unknown as ProductionSettings);
|
||||||
|
|
||||||
expect(merged.general.batchDownload).toEqual(settingsSlice.getInitialState().production.general.batchDownload);
|
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' } });
|
expect(merged.qmc2).toEqual({ allowFuzzyNameSearch: false, keys: { 'a.mflac': 'ek' } });
|
||||||
// only keys matching /^(\d+)-(\w+)$/
|
// only keys matching /^(\d+)-(\w+)$/
|
||||||
expect(merged.kwm2.keys).toEqual({ '1-2000': 'kw', '2-hi': 'y' });
|
expect(merged.kwm2.keys).toEqual({ '1-2000': 'kw', '2-hi': 'y' });
|
||||||
@@ -189,6 +200,11 @@ describe('mergeSettings', () => {
|
|||||||
streamingZip: false,
|
streamingZip: false,
|
||||||
blobZip: true,
|
blobZip: true,
|
||||||
},
|
},
|
||||||
|
directWrite: {
|
||||||
|
outputMode: 'fixedDirectory',
|
||||||
|
fixedDirectoryPath: '/music/out',
|
||||||
|
deleteSourceAfterDecrypt: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } },
|
qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } },
|
||||||
kwm2: { keys: { '9-1000': 'kw' } },
|
kwm2: { keys: { '9-1000': 'kw' } },
|
||||||
@@ -203,4 +219,41 @@ describe('mergeSettings', () => {
|
|||||||
expect(roundTrip.kugou).toEqual(merged.kugou);
|
expect(roundTrip.kugou).toEqual(merged.kugou);
|
||||||
expect(roundTrip.qtfm).toEqual(merged.qtfm);
|
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,17 +1,30 @@
|
|||||||
import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
|
import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
|
||||||
import { useAppDispatch, useAppSelector } from '~/hooks';
|
import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||||
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
|
import { selectStagingBatchDownloadSettings, selectStagingDirectWriteSettings } from '../settingsSelector';
|
||||||
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
|
import {
|
||||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
BatchDownloadSettings,
|
||||||
|
DirectWriteOutputMode,
|
||||||
|
updateBatchDownloadSetting,
|
||||||
|
updateDirectWriteSetting,
|
||||||
|
} from '../settingsSlice';
|
||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
|
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
export function PanelGeneral() {
|
export function PanelGeneral() {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
const batch = useAppSelector(selectStagingBatchDownloadSettings);
|
const batch = useAppSelector(selectStagingBatchDownloadSettings);
|
||||||
const canDirectoryPicker = supportsDirectoryPicker();
|
const directWrite = useAppSelector(selectStagingDirectWriteSettings);
|
||||||
const canStreamingZip = supportsStreamingZipDownload();
|
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 [hasRememberedDir, setHasRememberedDir] = useState(false);
|
||||||
|
const [pickingDirectory, setPickingDirectory] = useState(false);
|
||||||
|
|
||||||
const refreshRemembered = useCallback(() => {
|
const refreshRemembered = useCallback(() => {
|
||||||
hasRememberedDirectoryHandle()
|
hasRememberedDirectoryHandle()
|
||||||
@@ -33,84 +46,171 @@ export function PanelGeneral() {
|
|||||||
toast.info('已清除记住的输出目录');
|
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 idDir = useId();
|
||||||
const idRemember = useId();
|
const idRemember = useId();
|
||||||
const idStreamZip = useId();
|
const idStreamZip = useId();
|
||||||
const idBlobZip = useId();
|
const idBlobZip = useId();
|
||||||
|
const idOutputMode = useId();
|
||||||
|
const idFixedPath = useId();
|
||||||
|
const idDeleteSource = useId();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-0 flex-col grow px-1">
|
<div className="min-h-0 flex-col grow px-1">
|
||||||
<h2 className="text-2xl font-bold mb-4">通用设置</h2>
|
<h2 className="text-2xl font-bold mb-4">通用设置</h2>
|
||||||
|
|
||||||
<h3 className="text-xl font-semibold mb-2">批量下载</h3>
|
{showBatchDownload && (
|
||||||
<p className="text-sm text-base-content/80 mb-4">
|
<>
|
||||||
点击「下载全部」时,将按下方勾选项的顺序依次尝试。若选中的模式均不可用或全部失败,会弹出提示。
|
<h3 className="text-xl font-semibold mb-2">批量下载</h3>
|
||||||
</p>
|
<p className="text-sm text-base-content/80 mb-4">
|
||||||
|
点击「下载全部」时,将按下方勾选项的顺序依次尝试。若选中的模式均不可用或全部失败,会弹出提示。
|
||||||
|
</p>
|
||||||
|
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
<BatchOption
|
{canDirectoryPicker && (
|
||||||
id={idDir}
|
<>
|
||||||
checked={batch.directoryPicker && canDirectoryPicker}
|
<BatchOption
|
||||||
disabled={!canDirectoryPicker}
|
id={idDir}
|
||||||
dimmed={!canDirectoryPicker}
|
checked={batch.directoryPicker}
|
||||||
title="使用选择目录批量下载"
|
title="使用选择目录批量下载"
|
||||||
description={
|
description="通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。"
|
||||||
canDirectoryPicker
|
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||||
? '通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。'
|
/>
|
||||||
: '当前浏览器不支持 showDirectoryPicker。'
|
|
||||||
}
|
|
||||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker && canDirectoryPicker ? '' : 'opacity-50'}`}>
|
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker ? '' : 'opacity-50'}`}>
|
||||||
<BatchOption
|
<BatchOption
|
||||||
id={idRemember}
|
id={idRemember}
|
||||||
checked={batch.rememberDirectory}
|
checked={batch.rememberDirectory}
|
||||||
disabled={!batch.directoryPicker || !canDirectoryPicker}
|
disabled={!batch.directoryPicker}
|
||||||
title="记住输出目录"
|
title="记住输出目录"
|
||||||
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
|
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
|
||||||
onChange={(checked) => setBatch('rememberDirectory', checked)}
|
onChange={(checked) => setBatch('rememberDirectory', checked)}
|
||||||
/>
|
/>
|
||||||
<div className="flex items-center gap-2 text-sm">
|
<div className="flex items-center gap-2 text-sm">
|
||||||
<span className="text-base-content/70">{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}</span>
|
<span className="text-base-content/70">
|
||||||
<button
|
{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}
|
||||||
type="button"
|
</span>
|
||||||
className="btn btn-xs btn-ghost"
|
<button
|
||||||
disabled={!hasRememberedDir}
|
type="button"
|
||||||
onClick={() => void handleClearDirectory()}
|
className="btn btn-xs btn-ghost"
|
||||||
>
|
disabled={!hasRememberedDir}
|
||||||
清除
|
onClick={() => void handleClearDirectory()}
|
||||||
</button>
|
>
|
||||||
|
清除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</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>
|
</div>
|
||||||
</div>
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<BatchOption
|
{canDirectWrite && (
|
||||||
id={idStreamZip}
|
<>
|
||||||
checked={batch.streamingZip && canStreamingZip}
|
<h3 className={`text-xl font-semibold mb-2 ${showBatchDownload ? 'mt-8' : ''}`}>解密后自动保存</h3>
|
||||||
disabled={!canStreamingZip}
|
<p className="text-sm text-base-content/80 mb-4">解密完成后直接保存到本机,无需再手动下载。</p>
|
||||||
dimmed={!canStreamingZip}
|
|
||||||
title="流式生成 ZIP"
|
|
||||||
description={
|
|
||||||
canStreamingZip
|
|
||||||
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
|
|
||||||
: '当前浏览器不支持 showSaveFilePicker,无法流式写出 ZIP。'
|
|
||||||
}
|
|
||||||
onChange={(checked) => setBatch('streamingZip', checked)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<BatchOption
|
<div className="flex flex-col gap-3">
|
||||||
id={idBlobZip}
|
<div className="flex flex-col gap-1">
|
||||||
checked={batch.blobZip}
|
<label htmlFor={idOutputMode} className="font-medium">
|
||||||
title="生成单个 ZIP 并触发下载"
|
保存位置
|
||||||
description={
|
</label>
|
||||||
<>
|
<select
|
||||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
id={idOutputMode}
|
||||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
className="select select-bordered select-sm w-full max-w-md"
|
||||||
</>
|
value={directWrite.outputMode}
|
||||||
}
|
onChange={(e) =>
|
||||||
onChange={(checked) => setBatch('blobZip', checked)}
|
dispatch(updateDirectWriteSetting({ outputMode: e.target.value as DirectWriteOutputMode }))
|
||||||
/>
|
}
|
||||||
</div>
|
>
|
||||||
|
<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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -119,15 +219,14 @@ type BatchOptionProps = {
|
|||||||
id: string;
|
id: string;
|
||||||
checked: boolean;
|
checked: boolean;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
dimmed?: boolean;
|
|
||||||
title: string;
|
title: string;
|
||||||
description: ReactNode;
|
description: ReactNode;
|
||||||
onChange: (checked: boolean) => void;
|
onChange: (checked: boolean) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
function BatchOption({ id, checked, disabled, dimmed, title, description, onChange }: BatchOptionProps) {
|
function BatchOption({ id, checked, disabled, title, description, onChange }: BatchOptionProps) {
|
||||||
return (
|
return (
|
||||||
<label className={`flex items-start gap-2 ${dimmed ? 'opacity-50' : ''}`}>
|
<label className="flex items-start gap-2">
|
||||||
<input
|
<input
|
||||||
id={id}
|
id={id}
|
||||||
type="checkbox"
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
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';
|
||||||
|
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||||
|
|
||||||
|
const stubCrypto = {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
};
|
||||||
|
|
||||||
|
test('shows only capable batch-download options', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<PanelGeneral />, { platform });
|
||||||
|
|
||||||
|
expect(screen.queryByLabelText(/使用选择目录批量下载/)).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByLabelText(/流式生成 ZIP/)).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).not.toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides batch-download section when downloadTypes is empty', () => {
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
downloadTypes: [],
|
||||||
|
directFsAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(<PanelGeneral />, { platform });
|
||||||
|
|
||||||
|
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,15 +6,16 @@ import {
|
|||||||
setProductionChanges,
|
setProductionChanges,
|
||||||
ProductionSettings,
|
ProductionSettings,
|
||||||
DEFAULT_BATCH_DOWNLOAD_SETTINGS,
|
DEFAULT_BATCH_DOWNLOAD_SETTINGS,
|
||||||
|
DEFAULT_DIRECT_WRITE_SETTINGS,
|
||||||
BatchDownloadSettings,
|
BatchDownloadSettings,
|
||||||
|
DirectWriteSettings,
|
||||||
} from './settingsSlice';
|
} from './settingsSlice';
|
||||||
import { enumObject } from '~/util/objects';
|
import { enumObject } from '~/util/objects';
|
||||||
import { getLogger } from '~/util/logUtils';
|
import { getLogger } from '~/util/logUtils';
|
||||||
import { parseKwm2ProductionKey } from '~/features/kwm/types';
|
import { parseKwm2ProductionKey } from '~/features/kwm/types';
|
||||||
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
|
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
|
||||||
import { deepClone } from '~/util/deepClone';
|
import { deepClone } from '~/util/deepClone';
|
||||||
|
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||||
const DEFAULT_STORAGE_KEY = 'um-react-settings';
|
|
||||||
|
|
||||||
function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
|
function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
|
||||||
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
|
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
|
||||||
@@ -29,11 +30,29 @@ function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined):
|
|||||||
return result;
|
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. */
|
/** Normalize / sanitize loaded production settings against defaults. Exported for tests. */
|
||||||
export function mergeSettings(settings: ProductionSettings): ProductionSettings {
|
export function mergeSettings(settings: ProductionSettings): ProductionSettings {
|
||||||
const draft = deepClone(settingsSlice.getInitialState().production);
|
const draft = deepClone(settingsSlice.getInitialState().production);
|
||||||
|
|
||||||
draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload);
|
draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload);
|
||||||
|
draft.general.directWrite = mergeDirectWrite(settings?.general?.directWrite);
|
||||||
|
|
||||||
if (settings?.qmc2) {
|
if (settings?.qmc2) {
|
||||||
const { allowFuzzyNameSearch, keys } = settings.qmc2;
|
const { allowFuzzyNameSearch, keys } = settings.qmc2;
|
||||||
@@ -75,28 +94,47 @@ export function mergeSettings(settings: ProductionSettings): ProductionSettings
|
|||||||
return draft;
|
return draft;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function persistSettings(store: AppStore, storageKey = DEFAULT_STORAGE_KEY) {
|
/**
|
||||||
|
* Load production settings via `provider.settings`, merge into the store, and
|
||||||
|
* debounce-save on production changes. Storage details stay inside the provider.
|
||||||
|
*/
|
||||||
|
export function persistSettings(store: AppStore, provider: PlatformProvider) {
|
||||||
let lastSettings: unknown;
|
let lastSettings: unknown;
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
try {
|
const unsubscribe = store.subscribe(
|
||||||
const loadedSettings = JSON.parse(localStorage.getItem(storageKey) ?? '') as ProductionSettings;
|
|
||||||
if (loadedSettings) {
|
|
||||||
const mergedSettings = mergeSettings(loadedSettings);
|
|
||||||
store.dispatch(setProductionChanges(mergedSettings));
|
|
||||||
getLogger().debug('settings loaded');
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// load failed, ignore.
|
|
||||||
}
|
|
||||||
|
|
||||||
return store.subscribe(
|
|
||||||
debounce({ delay: 150 }, () => {
|
debounce({ delay: 150 }, () => {
|
||||||
const currentSettings = store.getState().settings.production;
|
const currentSettings = store.getState().settings.production;
|
||||||
if (lastSettings !== currentSettings) {
|
if (lastSettings !== currentSettings) {
|
||||||
lastSettings = currentSettings;
|
lastSettings = currentSettings;
|
||||||
localStorage.setItem(storageKey, JSON.stringify(currentSettings));
|
void provider.settings.save(currentSettings).then(
|
||||||
getLogger().debug('settings saved');
|
() => getLogger().debug('settings saved'),
|
||||||
|
() => {
|
||||||
|
// save failed; keep lastSettings so we do not spin-retry on every tick
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
void provider.settings
|
||||||
|
.load()
|
||||||
|
.then((loadedSettings) => {
|
||||||
|
if (cancelled || !loadedSettings) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const mergedSettings = mergeSettings(loadedSettings);
|
||||||
|
store.dispatch(setProductionChanges(mergedSettings));
|
||||||
|
// Avoid an immediate rewrite of the same production snapshot after load.
|
||||||
|
lastSettings = store.getState().settings.production;
|
||||||
|
getLogger().debug('settings loaded');
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
// load failed, ignore.
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -14,3 +14,6 @@ export const selectIsSettingsNotSaved = (state: RootState) => state.settings.dir
|
|||||||
|
|
||||||
export const selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
|
export const selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
|
||||||
export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.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;
|
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 {
|
export interface StagingSettings {
|
||||||
general: {
|
general: {
|
||||||
batchDownload: BatchDownloadSettings;
|
batchDownload: BatchDownloadSettings;
|
||||||
|
directWrite: DirectWriteSettings;
|
||||||
};
|
};
|
||||||
qmc2: {
|
qmc2: {
|
||||||
keys: StagingQMCv2Key[];
|
keys: StagingQMCv2Key[];
|
||||||
@@ -56,6 +67,7 @@ export interface StagingSettings {
|
|||||||
export interface ProductionSettings {
|
export interface ProductionSettings {
|
||||||
general: {
|
general: {
|
||||||
batchDownload: BatchDownloadSettings;
|
batchDownload: BatchDownloadSettings;
|
||||||
|
directWrite: DirectWriteSettings;
|
||||||
};
|
};
|
||||||
qmc2: {
|
qmc2: {
|
||||||
keys: ProductionQMCv2Keys; // { [fileName]: ekey }
|
keys: ProductionQMCv2Keys; // { [fileName]: ekey }
|
||||||
@@ -81,6 +93,12 @@ export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = {
|
|||||||
blobZip: true,
|
blobZip: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_DIRECT_WRITE_SETTINGS: DirectWriteSettings = {
|
||||||
|
outputMode: 'besideSource',
|
||||||
|
fixedDirectoryPath: null,
|
||||||
|
deleteSourceAfterDecrypt: false,
|
||||||
|
};
|
||||||
|
|
||||||
export interface SettingsState {
|
export interface SettingsState {
|
||||||
dirty: boolean;
|
dirty: boolean;
|
||||||
staging: StagingSettings;
|
staging: StagingSettings;
|
||||||
@@ -90,14 +108,20 @@ export interface SettingsState {
|
|||||||
const initialState: SettingsState = {
|
const initialState: SettingsState = {
|
||||||
dirty: false,
|
dirty: false,
|
||||||
staging: {
|
staging: {
|
||||||
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
|
general: {
|
||||||
|
batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS },
|
||||||
|
directWrite: { ...DEFAULT_DIRECT_WRITE_SETTINGS },
|
||||||
|
},
|
||||||
qmc2: { allowFuzzyNameSearch: true, keys: [] },
|
qmc2: { allowFuzzyNameSearch: true, keys: [] },
|
||||||
kwm2: { keys: [] },
|
kwm2: { keys: [] },
|
||||||
qtfm: { ...EMPTY_QTFM_SETTINGS },
|
qtfm: { ...EMPTY_QTFM_SETTINGS },
|
||||||
kugou: { keys: [] },
|
kugou: { keys: [] },
|
||||||
},
|
},
|
||||||
production: {
|
production: {
|
||||||
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
|
general: {
|
||||||
|
batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS },
|
||||||
|
directWrite: { ...DEFAULT_DIRECT_WRITE_SETTINGS },
|
||||||
|
},
|
||||||
qmc2: { allowFuzzyNameSearch: true, keys: {} },
|
qmc2: { allowFuzzyNameSearch: true, keys: {} },
|
||||||
kwm2: { keys: {} },
|
kwm2: { keys: {} },
|
||||||
kugou: { keys: {} },
|
kugou: { keys: {} },
|
||||||
@@ -108,6 +132,7 @@ const initialState: SettingsState = {
|
|||||||
export const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
|
export const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
|
||||||
general: {
|
general: {
|
||||||
batchDownload: { ...staging.general.batchDownload },
|
batchDownload: { ...staging.general.batchDownload },
|
||||||
|
directWrite: { ...staging.general.directWrite },
|
||||||
},
|
},
|
||||||
qmc2: {
|
qmc2: {
|
||||||
keys: stagingKeyToProduction(staging.qmc2.keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue),
|
keys: stagingKeyToProduction(staging.qmc2.keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue),
|
||||||
@@ -125,6 +150,7 @@ export const stagingToProduction = (staging: StagingSettings): ProductionSetting
|
|||||||
export const productionToStaging = (production: ProductionSettings): StagingSettings => ({
|
export const productionToStaging = (production: ProductionSettings): StagingSettings => ({
|
||||||
general: {
|
general: {
|
||||||
batchDownload: { ...production.general.batchDownload },
|
batchDownload: { ...production.general.batchDownload },
|
||||||
|
directWrite: { ...production.general.directWrite },
|
||||||
},
|
},
|
||||||
qmc2: {
|
qmc2: {
|
||||||
keys: productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging),
|
keys: productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging),
|
||||||
@@ -184,6 +210,13 @@ export const settingsSlice = createSlice({
|
|||||||
state.staging.general.batchDownload[key] = value;
|
state.staging.general.batchDownload[key] = value;
|
||||||
state.dirty = true;
|
state.dirty = true;
|
||||||
},
|
},
|
||||||
|
updateDirectWriteSetting(state, { payload }: PayloadAction<Partial<DirectWriteSettings>>) {
|
||||||
|
state.staging.general.directWrite = {
|
||||||
|
...state.staging.general.directWrite,
|
||||||
|
...payload,
|
||||||
|
};
|
||||||
|
state.dirty = true;
|
||||||
|
},
|
||||||
discardStagingChanges: (state) => {
|
discardStagingChanges: (state) => {
|
||||||
state.dirty = false;
|
state.dirty = false;
|
||||||
state.staging = productionToStaging(state.production);
|
state.staging = productionToStaging(state.production);
|
||||||
@@ -224,6 +257,7 @@ export const {
|
|||||||
|
|
||||||
qtfmAndroidUpdateKey,
|
qtfmAndroidUpdateKey,
|
||||||
updateBatchDownloadSetting,
|
updateBatchDownloadSetting,
|
||||||
|
updateDirectWriteSetting,
|
||||||
|
|
||||||
commitStagingChange,
|
commitStagingChange,
|
||||||
discardStagingChanges,
|
discardStagingChanges,
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
import type { FC } from 'react';
|
import type { FC } from 'react';
|
||||||
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
|
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 { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
|
||||||
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
|
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
|
||||||
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
|
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
|
||||||
import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.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.
|
* Settings UI route ids → panels.
|
||||||
@@ -13,11 +18,38 @@ import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
|||||||
* - `kwm` ↔ state `kwm2`
|
* - `kwm` ↔ state `kwm2`
|
||||||
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
|
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
|
||||||
* - `qtfm` ↔ state `qtfm`
|
* - `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 },
|
general: { name: '通用设置', Tab: PanelGeneral },
|
||||||
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
|
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
|
||||||
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
|
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
|
||||||
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
|
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
|
||||||
qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing },
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
+3
-2
@@ -1,6 +1,7 @@
|
|||||||
import { useDispatch, useSelector } from 'react-redux';
|
import { useDispatch, useSelector, useStore } from 'react-redux';
|
||||||
import type { TypedUseSelectorHook } from 'react-redux';
|
import type { TypedUseSelectorHook } from 'react-redux';
|
||||||
import type { RootState, AppDispatch } from './store';
|
import type { RootState, AppDispatch, AppStore } from './store';
|
||||||
|
|
||||||
export const useAppDispatch: () => AppDispatch = useDispatch;
|
export const useAppDispatch: () => AppDispatch = useDispatch;
|
||||||
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
||||||
|
export const useAppStore: () => AppStore = useStore;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { createContext, useContext, type PropsWithChildren } from 'react';
|
||||||
|
import type { PlatformProvider } from './PlatformProvider';
|
||||||
|
|
||||||
|
const PlatformReactContext = createContext<PlatformProvider | null>(null);
|
||||||
|
|
||||||
|
export function PlatformProviderHost({
|
||||||
|
provider,
|
||||||
|
children,
|
||||||
|
}: PropsWithChildren<{ provider: PlatformProvider }>): React.JSX.Element {
|
||||||
|
return <PlatformReactContext.Provider value={provider}>{children}</PlatformReactContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line react-refresh/only-export-components -- hook colocated with context host
|
||||||
|
export function usePlatform(): PlatformProvider {
|
||||||
|
const provider = useContext(PlatformReactContext);
|
||||||
|
if (!provider) {
|
||||||
|
throw new Error('usePlatform() must be used within PlatformProviderHost');
|
||||||
|
}
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { use, type PropsWithChildren, type ReactNode } from 'react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Suspends children until `ready` fulfills (e.g. `provider.init()` + `setPlatform`).
|
||||||
|
* Must be wrapped in `<Suspense fallback={...}>`.
|
||||||
|
*/
|
||||||
|
export function PlatformLoadGuard({ ready, children }: PropsWithChildren<{ ready: Promise<unknown> }>): ReactNode {
|
||||||
|
use(ready);
|
||||||
|
return children;
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import type { WorkerActionMap, WorkerActionName } from '~/decrypt-worker/actions';
|
||||||
|
import type { DecryptionResult } from '~/decrypt-worker/constants';
|
||||||
|
import type { DecryptCommandPayload } from '~/decrypt-worker/types';
|
||||||
|
import type { ProductionSettings } from '~/features/settings/settingsSlice';
|
||||||
|
import type { BatchDownloadType, NativeImportType } from './capabilities';
|
||||||
|
import type {
|
||||||
|
AndroidAdbImportOptions,
|
||||||
|
DownloadManyInput,
|
||||||
|
DownloadManyResult,
|
||||||
|
DownloadOneInput,
|
||||||
|
NativeImportResult,
|
||||||
|
PlatformCapabilities,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Platform backend for crypto, settings IO, download, and native key import.
|
||||||
|
*
|
||||||
|
* Conventions:
|
||||||
|
* - Every provider implements **all** methods; never omit methods or silently no-op.
|
||||||
|
* - Capability missing / platform will never support → `NotSupportedMethod`.
|
||||||
|
* - Declared / planned but not wired yet (stub) → `NotImplementedError`.
|
||||||
|
* - Heavy backends (e.g. decrypt worker) load only inside `init()`; constructing the provider
|
||||||
|
* and reading `crypto` must not create a Worker or fetch the worker chunk.
|
||||||
|
* - `capabilities` is the only UI switch source; UI must not call `supportsDirectoryPicker()` etc.
|
||||||
|
* (those helpers stay for BrowserProvider internal capability detection).
|
||||||
|
*/
|
||||||
|
export interface PlatformProvider {
|
||||||
|
readonly id: 'browser' | 'tauri';
|
||||||
|
readonly capabilities: PlatformCapabilities;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-shot async setup (idempotent). Browser: dynamically import decrypt-worker/client and create Worker.
|
||||||
|
* Must complete before the first successful `crypto.request` / `enqueueDecrypt` (unless a test injects crypto).
|
||||||
|
* May run in parallel with `settings.load`.
|
||||||
|
*/
|
||||||
|
init(): Promise<void>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RPC aligned with `WorkerActionMap`; UI should not import `decrypt-worker/client`.
|
||||||
|
* Obtaining this object has no side effects (no Worker).
|
||||||
|
*/
|
||||||
|
crypto: {
|
||||||
|
request<K extends WorkerActionName>(
|
||||||
|
action: K,
|
||||||
|
payload: WorkerActionMap[K]['req'],
|
||||||
|
): Promise<WorkerActionMap[K]['res']>;
|
||||||
|
enqueueDecrypt(payload: DecryptCommandPayload, onPreProcess?: () => void): Promise<DecryptionResult>;
|
||||||
|
};
|
||||||
|
|
||||||
|
settings: {
|
||||||
|
load(): Promise<ProductionSettings | null>;
|
||||||
|
save(settings: ProductionSettings): Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
download: {
|
||||||
|
/** Single file; no suitable download capability → `NotSupportedMethod`. */
|
||||||
|
saveOne(input: DownloadOneInput): Promise<void>;
|
||||||
|
/**
|
||||||
|
* Batch; `type` ∉ `capabilities.downloadTypes` → `NotSupportedMethod`.
|
||||||
|
* 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: {
|
||||||
|
/** Empty / unsupported `nativeKeyAccess` → `NotSupportedMethod`. */
|
||||||
|
importNative(targets: readonly NativeImportType[]): Promise<NativeImportResult>;
|
||||||
|
/** `androidKeyAccess !== Adb` → `NotSupportedMethod`. */
|
||||||
|
importAndroidAdb(opts: AndroidAdbImportOptions): Promise<NativeImportResult>;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
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 { NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||||
|
|
||||||
|
function createMockCrypto(overrides: Partial<BrowserCrypto> = {}): BrowserCrypto {
|
||||||
|
return {
|
||||||
|
request: vi.fn().mockResolvedValue('9.9.9'),
|
||||||
|
enqueueDecrypt: vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' }),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('BrowserProvider', () => {
|
||||||
|
test('jsdom without directory/save pickers exposes only PackZip', () => {
|
||||||
|
expect(typeof window.showDirectoryPicker).toBe('undefined');
|
||||||
|
expect(typeof window.showSaveFilePicker).toBe('undefined');
|
||||||
|
|
||||||
|
const provider = createBrowserProvider();
|
||||||
|
|
||||||
|
expect(provider.id).toBe('browser');
|
||||||
|
expect(provider.capabilities).toEqual({
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
directFsAccess: false,
|
||||||
|
androidKeyAccess: AndroidImportType.None,
|
||||||
|
nativeKeyAccess: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keys.importNative throws NotSupportedMethod', async () => {
|
||||||
|
const provider = createBrowserProvider();
|
||||||
|
|
||||||
|
await expect(provider.keys.importNative([])).rejects.toSatisfy((err: unknown) => {
|
||||||
|
return (
|
||||||
|
err instanceof NotSupportedMethod && err.code === 'NOT_SUPPORTED' && err.capability === 'keys.importNative'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keys.importAndroidAdb throws NotSupportedMethod', async () => {
|
||||||
|
const provider = createBrowserProvider();
|
||||||
|
|
||||||
|
await expect(provider.keys.importAndroidAdb({})).rejects.toBeInstanceOf(NotSupportedMethod);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('crypto before init rejects with PlatformNotInitializedError', async () => {
|
||||||
|
const loadCrypto = vi.fn();
|
||||||
|
const provider = createBrowserProvider({ loadCrypto });
|
||||||
|
|
||||||
|
await expect(provider.crypto.request('VERSION', null)).rejects.toSatisfy((err: unknown) => {
|
||||||
|
return (
|
||||||
|
err instanceof PlatformNotInitializedError &&
|
||||||
|
err.code === 'NOT_INITIALIZED' &&
|
||||||
|
err.capability === 'crypto.request'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
expect(loadCrypto).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('constructing provider does not call loadCrypto', () => {
|
||||||
|
const loadCrypto = vi.fn();
|
||||||
|
createBrowserProvider({ loadCrypto });
|
||||||
|
expect(loadCrypto).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('init loads crypto once and is idempotent under concurrency', async () => {
|
||||||
|
const request = vi.fn().mockResolvedValue('9.9.9');
|
||||||
|
const loadCrypto = vi.fn().mockResolvedValue(createMockCrypto({ request }));
|
||||||
|
const provider = createBrowserProvider({ loadCrypto });
|
||||||
|
|
||||||
|
await Promise.all([provider.init(), provider.init()]);
|
||||||
|
await provider.init();
|
||||||
|
|
||||||
|
expect(loadCrypto).toHaveBeenCalledTimes(1);
|
||||||
|
await expect(provider.crypto.request('VERSION', null)).resolves.toBe('9.9.9');
|
||||||
|
expect(request).toHaveBeenCalledWith('VERSION', null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('crypto.* waits for in-flight init', async () => {
|
||||||
|
let resolveLoad!: (value: BrowserCrypto) => void;
|
||||||
|
const loadCrypto = vi.fn(
|
||||||
|
() =>
|
||||||
|
new Promise<BrowserCrypto>((resolve) => {
|
||||||
|
resolveLoad = resolve;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const provider = createBrowserProvider({ loadCrypto });
|
||||||
|
|
||||||
|
const initPromise = provider.init();
|
||||||
|
const requestPromise = provider.crypto.request('VERSION', null);
|
||||||
|
|
||||||
|
resolveLoad(createMockCrypto());
|
||||||
|
await initPromise;
|
||||||
|
await expect(requestPromise).resolves.toBe('9.9.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('crypto uses injected backend without init', async () => {
|
||||||
|
const request = vi.fn().mockResolvedValue('injected');
|
||||||
|
const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
|
||||||
|
const loadCrypto = vi.fn();
|
||||||
|
const provider = createBrowserProvider({ crypto: { request, enqueueDecrypt }, loadCrypto });
|
||||||
|
|
||||||
|
await expect(provider.crypto.request('VERSION', null)).resolves.toBe('injected');
|
||||||
|
await expect(
|
||||||
|
provider.crypto.enqueueDecrypt({
|
||||||
|
fileId: 'file://1',
|
||||||
|
blobURI: 'blob://in',
|
||||||
|
options: { fileName: 'a.bin' },
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({ decrypted: 'blob://out', ext: 'flac' });
|
||||||
|
await expect(provider.init()).resolves.toBeUndefined();
|
||||||
|
expect(loadCrypto).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('download.saveMany rejects types outside downloadTypes', async () => {
|
||||||
|
const provider = createBrowserProvider({
|
||||||
|
crypto: createMockCrypto(),
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
});
|
||||||
|
|
||||||
|
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(),
|
||||||
|
pickDirectory: 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 () => {
|
||||||
|
const provider = createBrowserProvider({
|
||||||
|
settingsStorage: {
|
||||||
|
getItem: () => null,
|
||||||
|
setItem: () => undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(provider.settings.load()).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
expect(provider.capabilities.directFsAccess).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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__;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { loadDecryptWorkerCrypto } from '~/platform/browser/browserCrypto';
|
||||||
|
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||||
|
|
||||||
|
const { mockRequest, mockAdd } = vi.hoisted(() => ({
|
||||||
|
mockRequest: vi.fn(),
|
||||||
|
mockAdd: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('~/decrypt-worker/client', () => ({
|
||||||
|
workerClientBus: {
|
||||||
|
request: mockRequest,
|
||||||
|
},
|
||||||
|
decryptionQueue: {
|
||||||
|
add: mockAdd,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('loadDecryptWorkerCrypto', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockRequest.mockResolvedValue('1.2.3');
|
||||||
|
mockAdd.mockResolvedValue({ decrypted: 'blob://d', ext: 'mp3' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('request forwards to workerClientBus after dynamic import', async () => {
|
||||||
|
const crypto = await loadDecryptWorkerCrypto();
|
||||||
|
|
||||||
|
await expect(crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null)).resolves.toBe('1.2.3');
|
||||||
|
expect(mockRequest).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enqueueDecrypt forwards to decryptionQueue.add after dynamic import', async () => {
|
||||||
|
const crypto = await loadDecryptWorkerCrypto();
|
||||||
|
const onPreProcess = vi.fn();
|
||||||
|
const payload = {
|
||||||
|
fileId: 'file://1',
|
||||||
|
blobURI: 'blob://in',
|
||||||
|
options: { fileName: 'a.bin' },
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(crypto.enqueueDecrypt(payload, onPreProcess)).resolves.toEqual({
|
||||||
|
decrypted: 'blob://d',
|
||||||
|
ext: 'mp3',
|
||||||
|
});
|
||||||
|
expect(mockAdd).toHaveBeenCalledWith(payload, onPreProcess);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
|
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';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import {
|
||||||
|
createBrowserSettingsIo,
|
||||||
|
DEFAULT_SETTINGS_STORAGE_KEY,
|
||||||
|
type SettingsStorage,
|
||||||
|
} from '~/platform/browser/browserSettingsIo';
|
||||||
|
import { settingsSlice, type ProductionSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
|
||||||
|
const data = { ...initial };
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
getItem(key: string) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
|
||||||
|
},
|
||||||
|
setItem(key: string, value: string) {
|
||||||
|
data[key] = value;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sampleProduction(): ProductionSettings {
|
||||||
|
const production = structuredClone(settingsSlice.getInitialState().production);
|
||||||
|
production.qmc2.keys['demo.mflac'] = 'ekey-demo';
|
||||||
|
production.qmc2.allowFuzzyNameSearch = false;
|
||||||
|
production.general.batchDownload.blobZip = false;
|
||||||
|
return production;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('createBrowserSettingsIo', () => {
|
||||||
|
test('load returns null when key is missing or empty', async () => {
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const io = createBrowserSettingsIo(storage);
|
||||||
|
|
||||||
|
await expect(io.load()).resolves.toBeNull();
|
||||||
|
|
||||||
|
storage.setItem(DEFAULT_SETTINGS_STORAGE_KEY, '');
|
||||||
|
await expect(io.load()).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('save then load round-trips production settings', async () => {
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const io = createBrowserSettingsIo(storage, 'test-settings');
|
||||||
|
const settings = sampleProduction();
|
||||||
|
|
||||||
|
await io.save(settings);
|
||||||
|
|
||||||
|
expect(storage.data['test-settings']).toBe(JSON.stringify(settings));
|
||||||
|
await expect(io.load()).resolves.toEqual(settings);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('load rejects on invalid JSON', async () => {
|
||||||
|
const storage = createMemoryStorage({ [DEFAULT_SETTINGS_STORAGE_KEY]: '{not-json' });
|
||||||
|
const io = createBrowserSettingsIo(storage);
|
||||||
|
|
||||||
|
await expect(io.load()).rejects.toBeInstanceOf(SyntaxError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BrowserProvider.settings', () => {
|
||||||
|
test('round-trips through injected storage', async () => {
|
||||||
|
const storage = createMemoryStorage();
|
||||||
|
const provider = createBrowserProvider({ settingsStorage: storage, settingsStorageKey: 'um-test' });
|
||||||
|
const settings = sampleProduction();
|
||||||
|
|
||||||
|
await provider.settings.save(settings);
|
||||||
|
await expect(provider.settings.load()).resolves.toEqual(settings);
|
||||||
|
expect(JSON.parse(storage.data['um-test'])).toEqual(settings);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||||
|
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
const allOn: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'> = {
|
||||||
|
directoryPicker: true,
|
||||||
|
streamingZip: true,
|
||||||
|
blobZip: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const allOff: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'> = {
|
||||||
|
directoryPicker: false,
|
||||||
|
streamingZip: false,
|
||||||
|
blobZip: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('buildEnabledDownloadModes', () => {
|
||||||
|
test('intersects settings with capabilities in fallback order', () => {
|
||||||
|
expect(
|
||||||
|
buildEnabledDownloadModes(allOn, [
|
||||||
|
BatchDownloadType.SelectDirectory,
|
||||||
|
BatchDownloadType.StreamZip,
|
||||||
|
BatchDownloadType.PackZip,
|
||||||
|
]),
|
||||||
|
).toEqual([BatchDownloadType.SelectDirectory, BatchDownloadType.StreamZip, BatchDownloadType.PackZip]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('omits modes disabled in settings even when capable', () => {
|
||||||
|
expect(
|
||||||
|
buildEnabledDownloadModes({ directoryPicker: false, streamingZip: true, blobZip: true }, [
|
||||||
|
BatchDownloadType.SelectDirectory,
|
||||||
|
BatchDownloadType.StreamZip,
|
||||||
|
BatchDownloadType.PackZip,
|
||||||
|
]),
|
||||||
|
).toEqual([BatchDownloadType.StreamZip, BatchDownloadType.PackZip]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('omits modes missing from capabilities even when enabled in settings', () => {
|
||||||
|
expect(buildEnabledDownloadModes(allOn, [BatchDownloadType.PackZip])).toEqual([BatchDownloadType.PackZip]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns empty when no overlap', () => {
|
||||||
|
expect(buildEnabledDownloadModes(allOff, [BatchDownloadType.PackZip])).toEqual([]);
|
||||||
|
expect(buildEnabledDownloadModes(allOn, [])).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||||
|
import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||||
|
|
||||||
|
describe('platform capabilities enums', () => {
|
||||||
|
test('BatchDownloadType members stay stable', () => {
|
||||||
|
expect(BatchDownloadType).toEqual({
|
||||||
|
SelectDirectory: 'SelectDirectory',
|
||||||
|
StreamZip: 'StreamZip',
|
||||||
|
PackZip: 'PackZip',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('AndroidImportType members stay stable', () => {
|
||||||
|
expect(AndroidImportType).toEqual({
|
||||||
|
None: 'none',
|
||||||
|
Adb: 'adb',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('NativeImportType members stay stable', () => {
|
||||||
|
expect(NativeImportType).toEqual({
|
||||||
|
QQMusic: 'qqmusic',
|
||||||
|
Kuwo: 'kuwo',
|
||||||
|
Kugou: 'kugou',
|
||||||
|
QingTing: 'qtfm',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NotImplementedError', () => {
|
||||||
|
test('exposes code, capability, and default message', () => {
|
||||||
|
const err = new NotImplementedError('crypto.request');
|
||||||
|
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err).toBeInstanceOf(NotImplementedError);
|
||||||
|
expect(err.code).toBe('NOT_IMPLEMENTED');
|
||||||
|
expect(err.capability).toBe('crypto.request');
|
||||||
|
expect(err.name).toBe('NotImplementedError');
|
||||||
|
expect(err.message).toBe('Capability not implemented: crypto.request');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a custom message', () => {
|
||||||
|
const err = new NotImplementedError('settings.save', 'storage backend pending');
|
||||||
|
expect(err.message).toBe('storage backend pending');
|
||||||
|
expect(err.capability).toBe('settings.save');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NotSupportedMethod', () => {
|
||||||
|
test('exposes code, capability, and default message', () => {
|
||||||
|
const err = new NotSupportedMethod('keys.importNative');
|
||||||
|
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err).toBeInstanceOf(NotSupportedMethod);
|
||||||
|
expect(err.code).toBe('NOT_SUPPORTED');
|
||||||
|
expect(err.capability).toBe('keys.importNative');
|
||||||
|
expect(err.name).toBe('NotSupportedMethod');
|
||||||
|
expect(err.message).toBe('Capability not supported: keys.importNative');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a custom message', () => {
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is distinct from NotImplementedError', () => {
|
||||||
|
const unsupported = new NotSupportedMethod('keys.importNative');
|
||||||
|
const unimplemented = new NotImplementedError('keys.importNative');
|
||||||
|
|
||||||
|
expect(unsupported).not.toBeInstanceOf(NotImplementedError);
|
||||||
|
expect(unimplemented).not.toBeInstanceOf(NotSupportedMethod);
|
||||||
|
expect(unsupported.code).not.toBe(unimplemented.code);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PlatformNotInitializedError', () => {
|
||||||
|
test('exposes code, capability, and default message', () => {
|
||||||
|
const err = new PlatformNotInitializedError('crypto.request');
|
||||||
|
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err).toBeInstanceOf(PlatformNotInitializedError);
|
||||||
|
expect(err.code).toBe('NOT_INITIALIZED');
|
||||||
|
expect(err.capability).toBe('crypto.request');
|
||||||
|
expect(err.name).toBe('PlatformNotInitializedError');
|
||||||
|
expect(err.message).toBe('Platform not initialized; call init() before using crypto.request');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { AndroidImportType, type NativeImportType } from '~/platform/capabilities';
|
||||||
|
import { NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
|
||||||
|
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||||
|
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 notSupported(capability: string): Promise<never> {
|
||||||
|
return Promise.reject(new NotSupportedMethod(capability));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowserProviderOptions {
|
||||||
|
/** Defaults to `localStorage`. Injected in tests. */
|
||||||
|
settingsStorage?: SettingsStorage;
|
||||||
|
/** Defaults to `um-react-settings`. */
|
||||||
|
settingsStorageKey?: string;
|
||||||
|
/**
|
||||||
|
* Injected crypto backend (tests). When set, `crypto.*` works without loading the worker
|
||||||
|
* and `init()` resolves immediately.
|
||||||
|
*/
|
||||||
|
crypto?: BrowserCrypto;
|
||||||
|
/** Defaults to dynamic-importing decrypt-worker/client. Injected in tests. */
|
||||||
|
loadCrypto?: () => Promise<BrowserCrypto>;
|
||||||
|
/** Override download backend (tests). Defaults to FS Access / ZIP helpers. */
|
||||||
|
download?: BrowserDownload;
|
||||||
|
/** Override detected `downloadTypes` (tests). */
|
||||||
|
downloadTypes?: PlatformCapabilities['downloadTypes'];
|
||||||
|
/** Override `directFsAccess` (tests). Browser default is `false`. */
|
||||||
|
directFsAccess?: boolean;
|
||||||
|
/** 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'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-browser `PlatformProvider`.
|
||||||
|
* 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` 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,
|
||||||
|
directFsAccess: options.directFsAccess ?? false,
|
||||||
|
androidKeyAccess: options.androidKeyAccess ?? AndroidImportType.None,
|
||||||
|
nativeKeyAccess: Object.freeze(options.nativeKeyAccess ? [...options.nativeKeyAccess] : ([] as NativeImportType[])),
|
||||||
|
});
|
||||||
|
|
||||||
|
const settingsIo = createBrowserSettingsIo(
|
||||||
|
options.settingsStorage ?? localStorage,
|
||||||
|
options.settingsStorageKey ?? DEFAULT_SETTINGS_STORAGE_KEY,
|
||||||
|
);
|
||||||
|
|
||||||
|
const download = options.download ?? createBrowserDownload(downloadTypes);
|
||||||
|
|
||||||
|
const loadCrypto = options.loadCrypto ?? loadDecryptWorkerCrypto;
|
||||||
|
let backend: BrowserCrypto | null = options.crypto ?? null;
|
||||||
|
let initPromise: Promise<void> | null = options.crypto ? Promise.resolve() : null;
|
||||||
|
|
||||||
|
async function requireBackend(capability: string): Promise<BrowserCrypto> {
|
||||||
|
if (backend) {
|
||||||
|
return backend;
|
||||||
|
}
|
||||||
|
if (initPromise) {
|
||||||
|
await initPromise;
|
||||||
|
if (backend) {
|
||||||
|
return backend;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new PlatformNotInitializedError(capability);
|
||||||
|
}
|
||||||
|
|
||||||
|
const crypto: BrowserCrypto = {
|
||||||
|
request: (action, payload) => requireBackend('crypto.request').then((api) => api.request(action, payload)),
|
||||||
|
enqueueDecrypt: (payload, onPreProcess) =>
|
||||||
|
requireBackend('crypto.enqueueDecrypt').then((api) => api.enqueueDecrypt(payload, onPreProcess)),
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: 'browser',
|
||||||
|
capabilities,
|
||||||
|
|
||||||
|
init(): Promise<void> {
|
||||||
|
if (!initPromise) {
|
||||||
|
initPromise = loadCrypto().then((loaded) => {
|
||||||
|
backend = loaded;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return initPromise;
|
||||||
|
},
|
||||||
|
|
||||||
|
crypto,
|
||||||
|
|
||||||
|
settings: {
|
||||||
|
load: () => settingsIo.load(),
|
||||||
|
save: (settings) => settingsIo.save(settings),
|
||||||
|
},
|
||||||
|
|
||||||
|
download,
|
||||||
|
|
||||||
|
keys: options.keys ?? {
|
||||||
|
importNative: (_targets: readonly NativeImportType[]): Promise<NativeImportResult> =>
|
||||||
|
notSupported('keys.importNative'),
|
||||||
|
importAndroidAdb: (_opts: AndroidAdbImportOptions): Promise<NativeImportResult> =>
|
||||||
|
notSupported('keys.importAndroidAdb'),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { WorkerActionMap, WorkerActionName } from '~/decrypt-worker/actions';
|
||||||
|
import type { DecryptionResult } from '~/decrypt-worker/constants';
|
||||||
|
import type { DecryptCommandPayload } from '~/decrypt-worker/types';
|
||||||
|
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||||
|
|
||||||
|
export type BrowserCrypto = PlatformProvider['crypto'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lazily binds to decrypt-worker after a dynamic import.
|
||||||
|
* This module must not statically import `~/decrypt-worker/client` (Worker side effect).
|
||||||
|
*/
|
||||||
|
export async function loadDecryptWorkerCrypto(): Promise<BrowserCrypto> {
|
||||||
|
const { decryptionQueue, workerClientBus } = await import('~/decrypt-worker/client');
|
||||||
|
|
||||||
|
return {
|
||||||
|
request<K extends WorkerActionName>(
|
||||||
|
action: K,
|
||||||
|
payload: WorkerActionMap[K]['req'],
|
||||||
|
): Promise<WorkerActionMap[K]['res']> {
|
||||||
|
return workerClientBus.request(action, payload);
|
||||||
|
},
|
||||||
|
enqueueDecrypt(payload: DecryptCommandPayload, onPreProcess?: () => void): Promise<DecryptionResult> {
|
||||||
|
return decryptionQueue.add(payload, onPreProcess);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { toast } from 'react-toastify';
|
||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { NotSupportedMethod } from '~/platform/errors';
|
||||||
|
import type { DownloadManyInput, DownloadManyResult, DownloadOneInput } from '~/platform/types';
|
||||||
|
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
||||||
|
import { SimpleQueue } from '~/util/SimpleQueue';
|
||||||
|
import { downloadZipAsBlob, downloadZipViaSavePicker, type ZipSourceFile } from '~/util/streamZip';
|
||||||
|
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
||||||
|
|
||||||
|
export interface BrowserDownload {
|
||||||
|
saveOne(input: DownloadOneInput): Promise<void>;
|
||||||
|
saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult>;
|
||||||
|
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);
|
||||||
|
|
||||||
|
return {
|
||||||
|
saveOne(input: DownloadOneInput): Promise<void> {
|
||||||
|
if (supported.size === 0) {
|
||||||
|
return Promise.reject(new NotSupportedMethod('download.saveOne'));
|
||||||
|
}
|
||||||
|
triggerAnchorDownload(input.url, input.fileName);
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
|
||||||
|
async saveMany(type: BatchDownloadType, input: DownloadManyInput): Promise<DownloadManyResult> {
|
||||||
|
if (!supported.has(type)) {
|
||||||
|
throw new NotSupportedMethod('download.saveMany', `${type} unavailable on this platform`);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case BatchDownloadType.SelectDirectory:
|
||||||
|
return downloadToDirectory(input.files, input.rememberDirectory ?? false);
|
||||||
|
case BatchDownloadType.StreamZip:
|
||||||
|
return downloadStreamingZip(input.files);
|
||||||
|
case BatchDownloadType.PackZip:
|
||||||
|
await downloadBlobZip(input.files);
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
pickDirectory(): Promise<string | null> {
|
||||||
|
return Promise.reject(new NotSupportedMethod('download.pickDirectory'));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadToDirectory(files: DownloadManyInput['files'], remember: boolean): Promise<DownloadManyResult> {
|
||||||
|
const dir = await resolveWritableDirectory(remember);
|
||||||
|
if (!dir) {
|
||||||
|
return 'cancelled';
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileCount = files.length;
|
||||||
|
const queue = new SimpleQueue(8);
|
||||||
|
const promises = files.map(async (file) => {
|
||||||
|
try {
|
||||||
|
await queue.enter();
|
||||||
|
await writeFileToDirectory(file.url, file.fileName, dir);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`下载失败: ${file.fileName}`, e);
|
||||||
|
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
queue.leave();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const promiseResults = await Promise.allSettled(promises);
|
||||||
|
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
|
||||||
|
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
|
||||||
|
toast[level](`成功下载: ${success}/${fileCount}首`);
|
||||||
|
|
||||||
|
if (success === 0) {
|
||||||
|
throw new Error('未能写入任何文件到所选目录');
|
||||||
|
}
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeFileToDirectory(url: string, fileName: string, dir: FileSystemDirectoryHandle) {
|
||||||
|
const fileHandle = await dir.getFileHandle(fileName, { create: true });
|
||||||
|
const fileStream = await fileHandle.createWritable();
|
||||||
|
try {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`无法读取文件: ${fileName} (${res.status})`);
|
||||||
|
}
|
||||||
|
if (!res.body) {
|
||||||
|
await fileStream.write(await res.arrayBuffer());
|
||||||
|
await fileStream.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await res.body.pipeTo(fileStream);
|
||||||
|
} catch (e) {
|
||||||
|
await fileStream.abort();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toZipSources(files: DownloadManyInput['files']): ZipSourceFile[] {
|
||||||
|
return files.map((file) => ({
|
||||||
|
name: file.fileName,
|
||||||
|
url: file.url,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadStreamingZip(files: DownloadManyInput['files']): Promise<DownloadManyResult> {
|
||||||
|
const result = await downloadZipViaSavePicker(toZipSources(files));
|
||||||
|
if (result === 'ok') {
|
||||||
|
toast.success(`已导出 ZIP(${files.length} 首)`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadBlobZip(files: DownloadManyInput['files']): Promise<void> {
|
||||||
|
await downloadZipAsBlob(toZipSources(files));
|
||||||
|
toast.success(`已开始下载 ZIP(${files.length} 首)`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { ProductionSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
export const DEFAULT_SETTINGS_STORAGE_KEY = 'um-react-settings';
|
||||||
|
|
||||||
|
/** Minimal storage surface used by browser settings persistence. */
|
||||||
|
export type SettingsStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* localStorage-backed settings IO for the browser provider.
|
||||||
|
* `load` returns `null` when the key is missing or empty; invalid JSON rejects.
|
||||||
|
*/
|
||||||
|
export function createBrowserSettingsIo(
|
||||||
|
storage: SettingsStorage = localStorage,
|
||||||
|
storageKey = DEFAULT_SETTINGS_STORAGE_KEY,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
// async: matches PlatformProvider.settings.load(): Promise<...> (sync localStorage).
|
||||||
|
// eslint-disable-next-line @typescript-eslint/require-await -- interface requires Promise
|
||||||
|
async load(): Promise<ProductionSettings | null> {
|
||||||
|
const raw = storage.getItem(storageKey);
|
||||||
|
if (raw == null || raw === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return JSON.parse(raw) as ProductionSettings;
|
||||||
|
},
|
||||||
|
|
||||||
|
// async: matches PlatformProvider.settings.save(): Promise<void> (sync localStorage).
|
||||||
|
// eslint-disable-next-line @typescript-eslint/require-await -- interface requires Promise
|
||||||
|
async save(settings: ProductionSettings): Promise<void> {
|
||||||
|
storage.setItem(storageKey, JSON.stringify(settings));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runtime download modes for the browser provider.
|
||||||
|
* 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[] = [];
|
||||||
|
if (supportsDirectoryPicker()) {
|
||||||
|
types.push(BatchDownloadType.SelectDirectory);
|
||||||
|
}
|
||||||
|
if (supportsStreamingZipDownload()) {
|
||||||
|
types.push(BatchDownloadType.StreamZip);
|
||||||
|
}
|
||||||
|
types.push(BatchDownloadType.PackZip);
|
||||||
|
return types;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { BatchDownloadType } from '~/platform/capabilities';
|
||||||
|
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intersect user batch-download settings with platform `downloadTypes`.
|
||||||
|
* Order matches browser fallback: SelectDirectory → StreamZip → PackZip.
|
||||||
|
* Native direct-disk write is gated by `capabilities.directFsAccess`, not these modes.
|
||||||
|
*/
|
||||||
|
export function buildEnabledDownloadModes(
|
||||||
|
settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
|
||||||
|
downloadTypes: readonly BatchDownloadType[],
|
||||||
|
): BatchDownloadType[] {
|
||||||
|
const available = new Set(downloadTypes);
|
||||||
|
const modes: BatchDownloadType[] = [];
|
||||||
|
|
||||||
|
if (settings.directoryPicker && available.has(BatchDownloadType.SelectDirectory)) {
|
||||||
|
modes.push(BatchDownloadType.SelectDirectory);
|
||||||
|
}
|
||||||
|
if (settings.streamingZip && available.has(BatchDownloadType.StreamZip)) {
|
||||||
|
modes.push(BatchDownloadType.StreamZip);
|
||||||
|
}
|
||||||
|
if (settings.blobZip && available.has(BatchDownloadType.PackZip)) {
|
||||||
|
modes.push(BatchDownloadType.PackZip);
|
||||||
|
}
|
||||||
|
|
||||||
|
return modes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/** Batch download modes a platform may expose via `capabilities.downloadTypes`. */
|
||||||
|
export enum BatchDownloadType {
|
||||||
|
/** Existing File System Access directory picker. */
|
||||||
|
SelectDirectory = 'SelectDirectory',
|
||||||
|
/** Existing streaming ZIP via `showSaveFilePicker`. */
|
||||||
|
StreamZip = 'StreamZip',
|
||||||
|
/** Existing in-memory ZIP blob download. */
|
||||||
|
PackZip = 'PackZip',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Android-side key import path (single value on capabilities). */
|
||||||
|
export enum AndroidImportType {
|
||||||
|
None = 'none',
|
||||||
|
Adb = 'adb',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One-click native client import targets (settings checkboxes). */
|
||||||
|
export enum NativeImportType {
|
||||||
|
QQMusic = 'qqmusic',
|
||||||
|
Kuwo = 'kuwo',
|
||||||
|
Kugou = 'kugou',
|
||||||
|
QingTing = 'qtfm',
|
||||||
|
}
|
||||||
@@ -0,0 +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.
|
||||||
|
* Defaults to Browser; switches to the Tauri stub when the Tauri runtime is detected
|
||||||
|
* (or when `runtime: 'tauri'` is passed explicitly).
|
||||||
|
*/
|
||||||
|
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,48 @@
|
|||||||
|
/**
|
||||||
|
* Thrown when a provider method is declared or expected but not wired yet.
|
||||||
|
* Distinct from {@link NotSupportedMethod} (platform does not support this call).
|
||||||
|
*/
|
||||||
|
export class NotImplementedError extends Error {
|
||||||
|
readonly code = 'NOT_IMPLEMENTED' as const;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly capability: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? `Capability not implemented: ${capability}`);
|
||||||
|
this.name = 'NotImplementedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when `crypto.*` (or other init-gated APIs) is used before `provider.init()` completes.
|
||||||
|
* Distinct from {@link NotImplementedError} (not wired) and {@link NotSupportedMethod} (unsupported).
|
||||||
|
*/
|
||||||
|
export class PlatformNotInitializedError extends Error {
|
||||||
|
readonly code = 'NOT_INITIALIZED' as const;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly capability: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? `Platform not initialized; call init() before using ${capability}`);
|
||||||
|
this.name = 'PlatformNotInitializedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when the current platform explicitly does not support a method / mode
|
||||||
|
* (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 {
|
||||||
|
readonly code = 'NOT_SUPPORTED' as const;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly capability: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? `Capability not supported: ${capability}`);
|
||||||
|
this.name = 'NotSupportedMethod';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import type { PlatformProvider } from './PlatformProvider';
|
||||||
|
|
||||||
|
/** Non-React callers (thunks / modules) after AppRoot finishes `init()` and publishes the singleton. */
|
||||||
|
let platformSingleton: PlatformProvider | null = null;
|
||||||
|
|
||||||
|
export function setPlatform(provider: PlatformProvider): void {
|
||||||
|
platformSingleton = provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPlatform(): PlatformProvider {
|
||||||
|
if (!platformSingleton) {
|
||||||
|
throw new Error('Platform provider is not ready. Call setPlatform() after provider.init() completes.');
|
||||||
|
}
|
||||||
|
return platformSingleton;
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { StagingKugouKey } from '~/features/kugou/types';
|
||||||
|
import type { StagingKWMv2Key } from '~/features/kwm/types';
|
||||||
|
import type { StagingQMCv2Key } from '~/features/qmc/types';
|
||||||
|
import type { StagingQtfmSettings } from '~/features/qtfm/types';
|
||||||
|
import type { AndroidImportType, BatchDownloadType, NativeImportType } from './capabilities';
|
||||||
|
|
||||||
|
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). */
|
||||||
|
nativeKeyAccess: readonly NativeImportType[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadOneInput {
|
||||||
|
/** Object URL of the decrypted content. */
|
||||||
|
url: string;
|
||||||
|
/** Suggested download file name (including extension). */
|
||||||
|
fileName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadManyFile {
|
||||||
|
url: string;
|
||||||
|
fileName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadManyInput {
|
||||||
|
files: readonly DownloadManyFile[];
|
||||||
|
/** Remember FS Access directory handle when using SelectDirectory. */
|
||||||
|
rememberDirectory?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DownloadManyResult = 'ok' | 'cancelled';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Native / ADB import payload shaped for existing Redux `*ImportKeys` / qtfm staging updates.
|
||||||
|
* Rows omit `id` (reducers assign ids).
|
||||||
|
*/
|
||||||
|
export interface NativeImportResult {
|
||||||
|
qmc2?: Omit<StagingQMCv2Key, 'id'>[];
|
||||||
|
kwm2?: Omit<StagingKWMv2Key, 'id'>[];
|
||||||
|
kugou?: Omit<StagingKugouKey, 'id'>[];
|
||||||
|
qtfm?: Partial<StagingQtfmSettings>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AndroidAdbImportOptions {
|
||||||
|
/** Optional subset of formats to pull; omit = all declared android targets. */
|
||||||
|
targets?: readonly NativeImportType[];
|
||||||
|
}
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
import { RenderOptions, render } from '@testing-library/react';
|
import { RenderOptions, render } from '@testing-library/react';
|
||||||
import { PropsWithChildren } from 'react';
|
import { PropsWithChildren } from 'react';
|
||||||
import { Provider } from 'react-redux';
|
import { Provider } from 'react-redux';
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
|
||||||
|
import { PlatformProviderHost } from '~/platform/PlatformContext';
|
||||||
|
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||||
|
import { setPlatform } from '~/platform/platformSingleton';
|
||||||
import { AppStore, RootState, setupStore } from '~/store';
|
import { AppStore, RootState, setupStore } from '~/store';
|
||||||
|
|
||||||
// Adapted from: https://redux.js.org/usage/writing-tests
|
// Adapted from: https://redux.js.org/usage/writing-tests
|
||||||
@@ -8,18 +13,40 @@ import { AppStore, RootState, setupStore } from '~/store';
|
|||||||
// eslint-disable-next-line react-refresh/only-export-components
|
// eslint-disable-next-line react-refresh/only-export-components
|
||||||
export * from '@testing-library/react';
|
export * from '@testing-library/react';
|
||||||
|
|
||||||
|
/** Default test crypto: no dynamic import of decrypt-worker (avoids teardown races). */
|
||||||
|
const defaultTestCrypto: BrowserCrypto = {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('default test crypto: enqueueDecrypt not configured')),
|
||||||
|
};
|
||||||
|
|
||||||
export interface ExtendedRenderOptions extends RenderOptions {
|
export interface ExtendedRenderOptions extends RenderOptions {
|
||||||
preloadedState?: Partial<RootState>;
|
preloadedState?: Partial<RootState>;
|
||||||
store?: AppStore;
|
store?: AppStore;
|
||||||
|
/** Override platform backend (defaults to BrowserProvider with stub crypto). */
|
||||||
|
platform?: PlatformProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderWithProviders(
|
export function renderWithProviders(
|
||||||
ui: React.ReactElement,
|
ui: React.ReactElement,
|
||||||
{ preloadedState = {}, store = setupStore(preloadedState), ...renderOptions }: ExtendedRenderOptions = {},
|
{
|
||||||
|
preloadedState = {},
|
||||||
|
store = setupStore(preloadedState),
|
||||||
|
platform = createBrowserProvider({ crypto: defaultTestCrypto }),
|
||||||
|
...renderOptions
|
||||||
|
}: ExtendedRenderOptions = {},
|
||||||
) {
|
) {
|
||||||
|
// Publish singleton only after init (matches AppRoot). Stub crypto resolves immediately.
|
||||||
|
void platform.init().then(() => {
|
||||||
|
setPlatform(platform);
|
||||||
|
});
|
||||||
|
|
||||||
function Wrapper({ children }: PropsWithChildren<unknown>): React.JSX.Element {
|
function Wrapper({ children }: PropsWithChildren<unknown>): React.JSX.Element {
|
||||||
return <Provider store={store}>{children}</Provider>;
|
return (
|
||||||
|
<Provider store={store}>
|
||||||
|
<PlatformProviderHost provider={platform}>{children}</PlatformProviderHost>
|
||||||
|
</Provider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
|
return { store, platform, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
|
||||||
}
|
}
|
||||||
Vendored
+6
-4
@@ -1,5 +1,11 @@
|
|||||||
/// <reference types="vite/client" />
|
/// <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' {
|
module 'virtual:pwa-register' {
|
||||||
/**
|
/**
|
||||||
* See: {@link https://vite-pwa-org.netlify.app/guide/prompt-for-update.html}
|
* See: {@link https://vite-pwa-org.netlify.app/guide/prompt-for-update.html}
|
||||||
@@ -17,7 +23,3 @@ declare module '*&mac-command' {
|
|||||||
export const commandName: string;
|
export const commandName: string;
|
||||||
export const tarName: string;
|
export const tarName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
declare interface Window {
|
|
||||||
BASE_URL: string;
|
|
||||||
}
|
|
||||||
+2
-1
@@ -22,7 +22,7 @@ const version = `${pkg.version} (${shortCommit})`;
|
|||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
base: './',
|
base: '/',
|
||||||
worker: {
|
worker: {
|
||||||
format: 'es',
|
format: 'es',
|
||||||
},
|
},
|
||||||
@@ -97,6 +97,7 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
build: {
|
build: {
|
||||||
|
assetsDir: 'um-react.assets',
|
||||||
minify: true,
|
minify: true,
|
||||||
rolldownOptions: {
|
rolldownOptions: {
|
||||||
output: {
|
output: {
|
||||||
|
|||||||
Reference in new issue
Block a user