mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-27 23:56:59 +00:00
Compare commits
15
Commits
75d786c747
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8bb7d4430 | ||
|
|
6571dc5344 | ||
|
|
4d688af4ca | ||
|
|
b9c8d5b3cd | ||
|
|
79e5b45e6b | ||
|
|
ef4cd9c21e | ||
|
|
94eab8ecf6 | ||
|
|
d424837e66 | ||
|
|
b5fdc8ebbe | ||
|
|
cb5531e9e4 | ||
|
|
cc688b85bd | ||
|
|
d86323e38a | ||
|
|
4a7994df96 | ||
|
|
7a11d4f941 | ||
|
|
a9a937bc5e |
No files matched your search
@@ -0,0 +1,156 @@
|
||||
# AGENTS.md — Unlock Music (um-react)
|
||||
|
||||
Browser SPA that decrypts locally selected encrypted music files (no upload). React rewrite of Unlock Music.
|
||||
|
||||
Hosted at [git.um-react.app/um/um-react](https://git.um-react.app/um/um-react). Crypto algorithms live in `@unlock-music/crypto` (WASM), **not** in this repo.
|
||||
|
||||
## Quick start
|
||||
|
||||
```sh
|
||||
corepack prepare [email protected] --activate
|
||||
pnpm i --frozen-lockfile
|
||||
pnpm start # http://localhost:5173/
|
||||
pnpm test # vitest run (also pre-push)
|
||||
pnpm lint
|
||||
pnpm build # tsc -p tsconfig.prod.json && vite build && write-version
|
||||
```
|
||||
|
||||
- **Package manager:** pnpm `@12.14.0` (`engineStrict`)
|
||||
- **Node:** `24.22.0` (`devEngines`)
|
||||
- **TypeScript:** stay on **6.x** (do not bump to 7)
|
||||
- **Registry:** `@unlock-music/*` from `git.um-react.app` (see `.npmrc`)
|
||||
- App **does not support subdirectory deploy**
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Main thread (UI / Redux / key import)
|
||||
SelectFile → blob URL → fileListingSlice.processFile
|
||||
→ keyLookup(production settings) → DecryptCommandOptions
|
||||
→ DecryptionQueue → WorkerClientBus
|
||||
Web Worker (decrypt-worker)
|
||||
fetch(blobURI) → try Deciphers in order → blob URL result
|
||||
```
|
||||
|
||||
- Blob URIs are passed via `postMessage`; worker loads bytes with `fetch`.
|
||||
- Single worker today (`decrypt-worker/client.ts`); concurrency via `ConcurrentQueue` (default 5).
|
||||
- Key DB / MMKV parsing runs on the **main thread** (`util/sqlite.ts`, `util/mmkv/`, `util/DatabaseKeyExtractor.ts`).
|
||||
|
||||
### Entry points
|
||||
|
||||
| Concern | Path |
|
||||
| ---------------------- | ----------------------------------------------------- |
|
||||
| Bootstrap | `src/main.tsx` → `src/components/AppRoot.tsx` |
|
||||
| Redux store | `src/store.ts` (`fileListing` + `settings` only) |
|
||||
| Typed hooks | `src/hooks.ts` |
|
||||
| Decrypt queue UI | `src/features/file-listing/` |
|
||||
| Settings + persist | `src/features/settings/` |
|
||||
| Worker client / server | `src/decrypt-worker/client.ts`, `worker.ts` |
|
||||
| Decipher registry | `src/decrypt-worker/Deciphers.ts` (**order matters**) |
|
||||
| Path alias | `~/*` → `src/*` |
|
||||
|
||||
### Routes (`AppRoot`)
|
||||
|
||||
| Path | Tab |
|
||||
| -------------- | -------------------------- |
|
||||
| `/` | Main unlock UI |
|
||||
| `/settings/*` | Settings (`SETTINGS_TABS`) |
|
||||
| `/questions/*` | FAQ (`FAQ_PAGES`) |
|
||||
|
||||
## `src/` layout
|
||||
|
||||
| Dir | Role |
|
||||
| ----------------- | --------------------------------------------------------------------- |
|
||||
| `components/` | Shared UI (AppRoot, Dialog, key import, downloads) — **no `App.tsx`** |
|
||||
| `tabs/` | Top-level route shells |
|
||||
| `features/` | Domain modules (see below) |
|
||||
| `decrypt-worker/` | Worker + `decipher/*` + worker parsers |
|
||||
| `faq/` | FAQ pages + registry |
|
||||
| `util/` | Queues, worker bus, SQLite/MMKV, downloads, helpers |
|
||||
| `test-utils/` | Vitest setup + `renderWithProviders` |
|
||||
|
||||
### Features
|
||||
|
||||
| Folder | Purpose |
|
||||
| --------------- | ------------------------------------------------------------------ |
|
||||
| `settings/` | Staging/production slice, persistence, general panel, tab registry |
|
||||
| `file-listing/` | Decrypt queue + `processFile` thunk |
|
||||
| `nav/` | Settings/FAQ nested nav |
|
||||
| `qmc/` | QQ Music QMCv2 keys |
|
||||
| `kwm/` | Kuwo KWMv2 keys |
|
||||
| `kugou/` | Kugou KGG/KGM keys |
|
||||
| `qtfm/` | QingTing FM device key |
|
||||
|
||||
Provider features typically contain: `types.ts`, `importKeys.ts`, `keyLookup.ts`, `panel/`, `instructions/`, `__tests__/`. They do **not** own Redux slices — they plug into `settingsSlice`.
|
||||
|
||||
## Settings model (critical)
|
||||
|
||||
- **`staging`**: editable UI state (key rows with `id`).
|
||||
- **`production`**: committed shape used for decrypt + `localStorage` (`um-react-settings`).
|
||||
- Decrypt **`keyLookup` selectors always read `production`**. Dirty settings must be committed (保存) before decrypt sees them.
|
||||
- Persist: `features/settings/persistSettings.ts` (debounced save; `mergeSettings` on load).
|
||||
- Key-list CRUD: `createKeyListReducers.ts` for `qmc2` / `kwm2` / `kugou`.
|
||||
|
||||
**Route id ≠ Redux key** (do not “fix” rename persist keys):
|
||||
|
||||
| Route | Redux / persist |
|
||||
| ------ | --------------- |
|
||||
| `qmc` | `qmc2` |
|
||||
| `kwm` | `kwm2` |
|
||||
| `kgg` | `kugou` |
|
||||
| `qtfm` | `qtfm` |
|
||||
|
||||
## Adding / changing a music format
|
||||
|
||||
1. Prefer implementing crypto in `@unlock-music/crypto` / `lib_um_crypto_rust` (see `docs/develop-with-um_crypto.zh.md`).
|
||||
2. Add `src/decrypt-worker/decipher/YourFormat.ts` implementing `DecipherInstance`.
|
||||
3. Register factory in `Deciphers.ts` at the right priority (fixed header → footer → expensive full-file last).
|
||||
4. If user keys needed: extend `DecryptCommandOptions`; add `features/<name>/` + wire `settingsSlice`, `persistSettings.mergeSettings`, `settingsTabs.tsx`.
|
||||
5. If header parse needed before decrypt: worker action in `actions.ts` / `worker.ts` / `worker/*`, call from `fileListingSlice.processFile`.
|
||||
6. Tests + README supported-formats / FAQ as appropriate.
|
||||
|
||||
## UI & copy
|
||||
|
||||
- Tailwind CSS 4 + **DaisyUI 5** (`src/App.css`). Prefer existing patterns (`btn`, `modal`, `list`, `alert`, …).
|
||||
- Shared: `Dialog`, `KeyListContainer`, `ImportSecretModal`, `HelpText/*`, `react-icons`.
|
||||
- **No i18n library** — user-facing strings are hard-coded Simplified Chinese (some Traditional phrasing exists; match nearby copy).
|
||||
- Import from `react-router` (v8), not `react-router-dom`.
|
||||
|
||||
## Testing
|
||||
|
||||
- Vitest + jsdom; `globals: true`; setup `src/test-utils/setup-jest.ts` (mocks `Worker`, `matchMedia`).
|
||||
- Colocate under `__tests__/` as `*.test.ts(x)`.
|
||||
- Components: `renderWithProviders` from `src/test-utils/test-helper.tsx`.
|
||||
- Selectors/converters: mini-store or `setupStore({ preloadedState })`.
|
||||
- Contribution rule: coverage must not drop below main branch; Prettier + ESLint clean before PR.
|
||||
- Hooks: `pre-commit` → lint-staged; `pre-push` → `pnpm test`.
|
||||
|
||||
## Tooling gotchas
|
||||
|
||||
| Topic | Note |
|
||||
| ----------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| WASM | `vite-plugin-wasm`; exclude `@unlock-music/crypto` from `optimizeDeps`; worker awaits crypto `ready` |
|
||||
| Local crypto link | `LIB_UM_WASM_LOADER_DIR` / pnpm link; Vite `server.fs.allow` |
|
||||
| sql.js | Patched via `pnpm-workspace.yaml` → `patches/sql.js.patch`; alias `@sql-wasm` |
|
||||
| PWA | `vite-plugin-pwa`; `src/dummy.mjs` aliases `module` for Workbox |
|
||||
| Prettier | singleQuote, printWidth 120 |
|
||||
| Unused vars | prefix with `_` (ESLint) |
|
||||
| CI | `.gitea/workflows/build.yaml` (build, zip, win64, Netlify deploy) |
|
||||
|
||||
## Docs to read first
|
||||
|
||||
| Doc | When |
|
||||
| ------------------------------------------ | ------------------------------------------- |
|
||||
| `README.MD` | Formats, architecture summary, contribution |
|
||||
| `docs/getting-started.zh.md` | Install / build / pack |
|
||||
| `docs/develop-with-um_crypto.zh.md` | Crypto SDK local development |
|
||||
| `docs/faq_zh-hans.md` / `docs/adb_dump.md` | User FAQ / ADB key dump |
|
||||
|
||||
## Agent working rules for this repo
|
||||
|
||||
- Prefer **surgical edits**; match existing DaisyUI/Tailwind and feature folder patterns.
|
||||
- Do not rename `kugou` persist key or casually change staging↔production semantics.
|
||||
- Do not move heavy crypto into the main thread; keep decryption in the worker.
|
||||
- Do not invent an i18n framework for one-off strings.
|
||||
- Run `pnpm test` / `pnpm lint` after behavioral changes when practical.
|
||||
- Crypto algorithm work usually belongs upstream in `@unlock-music/crypto`, not duplicated here.
|
||||
@@ -92,8 +92,21 @@ docker run -d -p 8080:80 --name um-react um-react
|
||||
|
||||
然后访问 `http://localhost:8080` 即可。
|
||||
|
||||
## 部署到子目录
|
||||
|
||||
> [!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="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
|
||||
<meta name="theme-color" content="#4DBA87" />
|
||||
<script>
|
||||
// 设置基础路径,如果希望部署在/music-unlock/,则改为 '/music-unlock/',默认部署在根路径
|
||||
window.BASE_URL = '/';
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { minify } from 'terser';
|
||||
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)) {
|
||||
continue;
|
||||
}
|
||||
@@ -9,11 +11,11 @@ for (const file of readdirSync('dist/assets')) {
|
||||
console.log(`minifying ${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,
|
||||
mangle: true,
|
||||
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';
|
||||
|
||||
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 {
|
||||
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 () => {
|
||||
renderWithProviders(<AppRoot />);
|
||||
await act(async () => {
|
||||
renderWithProviders(<AppRoot />);
|
||||
// Flush Suspense retry after platform.init() (dynamic import) settles.
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Should eventually load sdk version
|
||||
await waitFor(() => screen.getByTestId('sdk-version'));
|
||||
// Platform Suspense gate + SDK version fetch
|
||||
expect(await screen.findByTestId('sdk-version')).toBeInTheDocument();
|
||||
|
||||
// Quick sanity check of known strings.
|
||||
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 { BrowserRouter, NavLink, Route, Routes } from 'react-router';
|
||||
import { MdSettings, MdHome, MdQuestionAnswer } from 'react-icons/md';
|
||||
|
||||
import { MainTab } from '~/tabs/MainTab';
|
||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
||||
|
||||
import { Suspense } from 'react';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { Provider } from 'react-redux';
|
||||
|
||||
import { AppLayout } from '~/components/AppLayout';
|
||||
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 { 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.
|
||||
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() {
|
||||
useEffect(() => persistSettings(store), []);
|
||||
|
||||
return (
|
||||
<BrowserRouter basename={window.BASE_URL || '/'}>
|
||||
<BrowserRouter basename={import.meta.env.BASE_URL}>
|
||||
<Provider store={store}>
|
||||
<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(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 />
|
||||
<PlatformProviderHost provider={platform}>
|
||||
<Suspense fallback={<AppBootFallback />}>
|
||||
<PlatformLoadGuard ready={platformReady}>
|
||||
<AppLayout />
|
||||
</PlatformLoadGuard>
|
||||
</Suspense>
|
||||
</PlatformProviderHost>
|
||||
</Provider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
|
||||
+22
-123
@@ -2,17 +2,18 @@ import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-l
|
||||
import { FaDownload } from 'react-icons/fa';
|
||||
import { useAppSelector } from '~/hooks';
|
||||
import { toast } from 'react-toastify';
|
||||
import { SimpleQueue } from '~/util/SimpleQueue';
|
||||
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
|
||||
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
|
||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
||||
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
|
||||
import { downloadZipAsBlob, downloadZipViaSavePicker, ZipSourceFile } from '~/util/streamZip';
|
||||
import { triggerAnchorDownload } from '~/util/triggerDownload';
|
||||
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
export function DownloadAll() {
|
||||
const files = useAppSelector(selectFiles);
|
||||
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
|
||||
const { download, capabilities } = usePlatform();
|
||||
|
||||
if (capabilities.downloadTypes.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const downloadAllAsync = async () => {
|
||||
const fileList = Object.values(files);
|
||||
@@ -36,12 +37,16 @@ export function DownloadAll() {
|
||||
|
||||
// Single file: direct blob download, no ZIP / directory picker.
|
||||
if (completeFiles.length === 1) {
|
||||
downloadSingleBlob(completeFiles[0]);
|
||||
const file = completeFiles[0];
|
||||
await download.saveOne({
|
||||
url: file.decrypted,
|
||||
fileName: decryptedDownloadName(file),
|
||||
});
|
||||
toast.success('已开始下载');
|
||||
return;
|
||||
}
|
||||
|
||||
const modes = buildEnabledModes(batchSettings);
|
||||
const modes = buildEnabledDownloadModes(batchSettings, capabilities.downloadTypes);
|
||||
if (modes.length === 0) {
|
||||
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
|
||||
return;
|
||||
@@ -49,9 +54,17 @@ export function DownloadAll() {
|
||||
|
||||
toast.warning('开始下载,请稍候');
|
||||
|
||||
const manyInput = {
|
||||
files: completeFiles.map((file) => ({
|
||||
url: file.decrypted,
|
||||
fileName: decryptedDownloadName(file),
|
||||
})),
|
||||
rememberDirectory: batchSettings.rememberDirectory,
|
||||
};
|
||||
|
||||
for (const mode of modes) {
|
||||
try {
|
||||
const result = await runMode(mode, completeFiles, batchSettings.rememberDirectory);
|
||||
const result = await download.saveMany(mode, manyInput);
|
||||
if (result === 'ok') {
|
||||
return;
|
||||
}
|
||||
@@ -79,120 +92,6 @@ export function DownloadAll() {
|
||||
);
|
||||
}
|
||||
|
||||
type BatchMode = 'directory' | 'streamingZip' | 'blobZip';
|
||||
|
||||
function buildEnabledModes(
|
||||
settings: Pick<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 {
|
||||
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 { workerClientBus } from '~/decrypt-worker/client';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
const getSDKVersion = async (): Promise<string> => {
|
||||
return workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
|
||||
};
|
||||
|
||||
export function SDKVersion() {
|
||||
const { crypto } = usePlatform();
|
||||
const refDialog = useRef<HTMLDialogElement>(null);
|
||||
const [sdkVersion, setSdkVersion] = useState('...');
|
||||
useEffect(() => {
|
||||
getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
|
||||
}, []);
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null).then(setSdkVersion, () => setSdkVersion('N/A'));
|
||||
}, [crypto]);
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { DecryptionResult } from './constants';
|
||||
import type {
|
||||
DecryptCommandPayload,
|
||||
FetchMusicExNamePayload,
|
||||
GetQingTingFMDeviceKeyPayload,
|
||||
ParseKugouHeaderPayload,
|
||||
ParseKugouHeaderResponse,
|
||||
ParseKuwoHeaderPayload,
|
||||
ParseKuwoHeaderResponse,
|
||||
} from './types';
|
||||
|
||||
export type WorkerActionMap = {
|
||||
DECRYPT: { req: DecryptCommandPayload; res: DecryptionResult };
|
||||
FIND_QMC_MUSICEX_NAME: { req: FetchMusicExNamePayload; res: string | null };
|
||||
KUWO_PARSE_HEADER: { req: ParseKuwoHeaderPayload; res: ParseKuwoHeaderResponse };
|
||||
KUGOU_PARSE_HEADER: { req: ParseKugouHeaderPayload; res: ParseKugouHeaderResponse };
|
||||
QINGTING_FM_GET_DEVICE_KEY: { req: GetQingTingFMDeviceKeyPayload; res: string };
|
||||
VERSION: { req: null; res: string };
|
||||
};
|
||||
|
||||
export type WorkerActionName = keyof WorkerActionMap;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { WorkerClientBus } from '~/util/WorkerEventBus';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
|
||||
import type { WorkerActionMap } from './actions';
|
||||
import { DecryptionQueue } from '~/util/DecryptionQueue';
|
||||
|
||||
// TODO: Worker pool?
|
||||
@@ -8,5 +8,5 @@ export const workerClient = new Worker(new URL('./worker', import.meta.url), { t
|
||||
// FIXME: report the error so is obvious to the user.
|
||||
workerClient.addEventListener('error', console.error);
|
||||
|
||||
export const workerClientBus = new WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>(workerClient);
|
||||
export const workerClientBus = new WorkerClientBus<WorkerActionMap>(workerClient);
|
||||
export const decryptionQueue = new DecryptionQueue(workerClientBus);
|
||||
@@ -12,7 +12,7 @@ export class KuwoMusicDecipher implements DecipherInstance {
|
||||
|
||||
try {
|
||||
header = KuwoHeader.parse(buffer.subarray(0, 0x400));
|
||||
kwm = new KWMDecipher(header, options.kwm2key);
|
||||
kwm = new KWMDecipher(header, options.kwm2Key);
|
||||
|
||||
const audioBuffer = new Uint8Array(buffer.subarray(0x400));
|
||||
for (const [block, offset] of chunkBuffer(audioBuffer)) {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
export interface DecryptCommandOptions {
|
||||
fileName: string;
|
||||
qmc2Key?: string;
|
||||
kwm2key?: string;
|
||||
kwm2Key?: string;
|
||||
kugouKey?: string;
|
||||
qingTingAndroidKey?: string;
|
||||
}
|
||||
|
||||
export interface DecryptCommandPayload {
|
||||
id: string;
|
||||
fileId: string;
|
||||
blobURI: string;
|
||||
options: DecryptCommandOptions;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WorkerServerBus } from '~/util/WorkerEventBus';
|
||||
import type { WorkerActionMap } from './actions';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
|
||||
import { getUmcVersion } from '@unlock-music/crypto';
|
||||
|
||||
@@ -8,7 +9,7 @@ import { workerGetQtfmDeviceKey } from '~/decrypt-worker/worker/qtfm_device_key.
|
||||
import { workerParseKuwoHeader } from '~/decrypt-worker/worker/kuwo_header_parse.ts';
|
||||
import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts';
|
||||
|
||||
const bus = new WorkerServerBus();
|
||||
const bus = new WorkerServerBus<WorkerActionMap>();
|
||||
onmessage = bus.onmessage;
|
||||
|
||||
bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler);
|
||||
|
||||
@@ -80,13 +80,12 @@ class DecryptCommandHandler {
|
||||
}
|
||||
}
|
||||
|
||||
export const workerDecryptHandler = async ({ id: payloadId, blobURI, options }: DecryptCommandPayload) => {
|
||||
export const workerDecryptHandler = async ({ fileId, blobURI, options }: DecryptCommandPayload) => {
|
||||
await umCryptoReady;
|
||||
const id = payloadId.replace('://', ':');
|
||||
const label = `decrypt(${id})`;
|
||||
const label = `decrypt(${fileId})`;
|
||||
return withTimeGroupedLogs(label, async () => {
|
||||
const buffer = await fetch(blobURI).then((r) => r.arrayBuffer());
|
||||
const handler = new DecryptCommandHandler(id, new Uint8Array(buffer), options);
|
||||
const handler = new DecryptCommandHandler(fileId, new Uint8Array(buffer), options);
|
||||
return handler.decrypt(allCryptoFactories);
|
||||
});
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Header2, Header3 } from '~/components/HelpText/Headers';
|
||||
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
|
||||
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx';
|
||||
import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
|
||||
import { RiErrorWarningLine } from 'react-icons/ri';
|
||||
|
||||
export function KugouFAQ() {
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { Header2, Header3 } from '~/components/HelpText/Headers';
|
||||
import { VQuote } from '~/components/HelpText/VQuote';
|
||||
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
|
||||
import { HiWord } from '~/components/HelpText/HiWord';
|
||||
import { KWMv2AllInstructions } from '~/features/settings/panels/KWMv2/KWMv2AllInstructions';
|
||||
import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
|
||||
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
|
||||
import { RiErrorWarningLine } from 'react-icons/ri';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Header2, Header3 } from '~/components/HelpText/Headers';
|
||||
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
|
||||
import { QMCv2QQMusicAllInstructions } from '~/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions';
|
||||
import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
|
||||
|
||||
export function QQMusicFAQ() {
|
||||
return (
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DecryptedAudioFile, deleteFile, ProcessState } from './fileListingSlice
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { FileError } from './FileError';
|
||||
import classNames from 'classnames';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
interface FileRowProps {
|
||||
id: string;
|
||||
@@ -10,7 +11,9 @@ interface FileRowProps {
|
||||
|
||||
export function FileRow({ id, file }: FileRowProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
const { capabilities } = usePlatform();
|
||||
const isDecrypted = file.state === ProcessState.COMPLETE;
|
||||
const showDownload = capabilities.downloadTypes.length > 0;
|
||||
|
||||
const decryptedName = file.cleanName + '.' + file.ext;
|
||||
|
||||
@@ -32,18 +35,20 @@ export function FileRow({ id, file }: FileRowProps) {
|
||||
</div>
|
||||
|
||||
<div className="card-actions justify-end">
|
||||
<a
|
||||
href={file.decrypted}
|
||||
download={decryptedName}
|
||||
title={`下载: ${decryptedName}`}
|
||||
className={classNames('btn', {
|
||||
'btn-primary': file.decrypted,
|
||||
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
||||
})}
|
||||
data-testid="audio-download"
|
||||
>
|
||||
下载
|
||||
</a>
|
||||
{showDownload && (
|
||||
<a
|
||||
href={file.decrypted}
|
||||
download={decryptedName}
|
||||
title={`下载: ${decryptedName}`}
|
||||
className={classNames('btn', {
|
||||
'btn-primary': file.decrypted,
|
||||
'cursor-not-allowed pointer-events-none': !file.decrypted,
|
||||
})}
|
||||
data-testid="audio-download"
|
||||
>
|
||||
下载
|
||||
</a>
|
||||
)}
|
||||
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
|
||||
删除
|
||||
</button>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import { renderWithProviders, screen } from '~/test-utils/test-helper';
|
||||
import { untouchedFile } from './__fixture__/file-list';
|
||||
import { FileRow } from '../FileRow';
|
||||
@@ -14,4 +15,19 @@ test('should render basic title (done)', () => {
|
||||
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -3,22 +3,13 @@ import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
|
||||
import type { RootState } from '~/store';
|
||||
|
||||
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
||||
import type {
|
||||
DecryptCommandOptions,
|
||||
FetchMusicExNamePayload,
|
||||
ParseKugouHeaderPayload,
|
||||
ParseKugouHeaderResponse,
|
||||
ParseKuwoHeaderPayload,
|
||||
ParseKuwoHeaderResponse,
|
||||
} from '~/decrypt-worker/types';
|
||||
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
|
||||
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
||||
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
||||
import {
|
||||
selectKugouKey,
|
||||
selectKWMv2Key,
|
||||
selectQMCv2KeyByFileName,
|
||||
selectQtfmAndroidKey,
|
||||
} from '../settings/settingsSelector';
|
||||
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
||||
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
|
||||
import { selectKugouKey } from '~/features/kugou/keyLookup';
|
||||
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||
import { getPlatform } from '~/platform/platformSingleton';
|
||||
import { cleanFilename } from '~/util/cleanFilename';
|
||||
|
||||
export enum ProcessState {
|
||||
@@ -79,28 +70,27 @@ export const processFile = createAsyncThunk<
|
||||
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
|
||||
};
|
||||
|
||||
const { crypto } = getPlatform();
|
||||
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
|
||||
workerClientBus.request<string, FetchMusicExNamePayload>(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
workerClientBus.request<ParseKuwoHeaderResponse, ParseKuwoHeaderPayload>(
|
||||
DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER,
|
||||
{ blobURI: file.raw },
|
||||
),
|
||||
workerClientBus.request<ParseKugouHeaderResponse, ParseKugouHeaderPayload>(
|
||||
DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER,
|
||||
{ blobURI: file.raw },
|
||||
),
|
||||
]);
|
||||
|
||||
const options: DecryptCommandOptions = {
|
||||
fileName: file.fileName,
|
||||
qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName),
|
||||
kwm2key: selectKWMv2Key(state, kuwoHdr),
|
||||
kwm2Key: selectKWMv2Key(state, kuwoHdr),
|
||||
kugouKey: selectKugouKey(state, kugouHdr),
|
||||
qingTingAndroidKey: selectQtfmAndroidKey(state),
|
||||
};
|
||||
return decryptionQueue.add({ id: fileId, blobURI: file.raw, options }, onPreProcess);
|
||||
return crypto.enqueueDecrypt({ fileId, blobURI: file.raw, options }, onPreProcess);
|
||||
});
|
||||
|
||||
export const fileListingSlice = createSlice({
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
|
||||
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
|
||||
import type { RootState } from '~/store';
|
||||
import { selectKugouKey } from '../keyLookup';
|
||||
|
||||
function storeWithKugouKeys(keys: Record<string, string>) {
|
||||
const base = settingsSlice.getInitialState();
|
||||
return configureStore({
|
||||
reducer: { settings: settingsReducer },
|
||||
preloadedState: {
|
||||
settings: {
|
||||
...base,
|
||||
production: {
|
||||
...base.production,
|
||||
kugou: { keys },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('selectKugouKey', () => {
|
||||
test('returns key for matching audioHash', () => {
|
||||
const hash = 'a'.repeat(32);
|
||||
const store = storeWithKugouKeys({ [hash]: 'ek' });
|
||||
expect(selectKugouKey(store.getState() as RootState, { audioHash: hash } as never)).toBe('ek');
|
||||
});
|
||||
|
||||
test('returns undefined for unknown hash or null header', () => {
|
||||
const store = storeWithKugouKeys({ ['b'.repeat(32)]: 'ek' });
|
||||
expect(selectKugouKey(store.getState() as RootState, { audioHash: 'c'.repeat(32) } as never)).toBeUndefined();
|
||||
expect(selectKugouKey(store.getState() as RootState, null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
|
||||
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou';
|
||||
import type { StagingKugouKey } from './types';
|
||||
|
||||
/** Parse a Kugou MMKV / encrypted DB dump into staging key rows (without `id`). */
|
||||
export async function importKugouKeysFromFile(file: File): Promise<null | Omit<StagingKugouKey, 'id'>[]> {
|
||||
if (/mggkey_multi_process/i.test(file.name)) {
|
||||
return parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
|
||||
}
|
||||
if (/^KGMusicV3\.db$/.test(file.name)) {
|
||||
const extractor = await DatabaseKeyExtractor.getInstance();
|
||||
return extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,19 @@
|
||||
import type { RootState } from '~/store';
|
||||
import type { ParseKugouHeaderResponse } from '~/decrypt-worker/types.ts';
|
||||
import { hasOwn } from '~/util/objects';
|
||||
|
||||
/** Staging KuGou/KGG keys (`state.settings.staging.kugou`; UI tab `kgg`). */
|
||||
export const selectStagingKugouV5Keys = (state: RootState) => state.settings.staging.kugou.keys;
|
||||
/** Production KuGou/KGG keys (`state.settings.production.kugou`; persist key `kugou`). */
|
||||
export const selectFinalKugouV5Keys = (state: RootState) => state.settings.production.kugou.keys;
|
||||
|
||||
export const selectKugouKey = (state: RootState, hdr: ParseKugouHeaderResponse): string | undefined => {
|
||||
if (!hdr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = selectFinalKugouV5Keys(state);
|
||||
const lookupKey = hdr.audioHash;
|
||||
|
||||
return hasOwn(keys, lookupKey) ? keys[lookupKey] : undefined;
|
||||
};
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { kugouDeleteKey, kugouUpdateKey } from '../../settingsSlice';
|
||||
import { kugouDeleteKey, kugouUpdateKey } from '~/features/settings/settingsSlice';
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { memo } from 'react';
|
||||
import { StagingKugouKey } from '../../keyFormats';
|
||||
import type { StagingKugouKey } from '~/features/kugou/types';
|
||||
import { KeyInput } from '~/components/KeyInput';
|
||||
|
||||
export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => {
|
||||
+6
-15
@@ -2,15 +2,12 @@ import { useRef, useState } from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
|
||||
import { ImportSecretModal } from '~/components/ImportSecretModal';
|
||||
|
||||
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '../settingsSlice';
|
||||
import { selectStagingKugouV5Keys } from '../settingsSelector';
|
||||
import type { StagingKugouKey } from '../keyFormats';
|
||||
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '~/features/settings/settingsSlice';
|
||||
import { selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
|
||||
import { AddKey } from '~/components/AddKey.tsx';
|
||||
import { KugouEKeyItem } from '~/features/settings/panels/Kugou/KugouEKeyItem.tsx';
|
||||
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx';
|
||||
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou.ts';
|
||||
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor.ts';
|
||||
import { KugouEKeyItem } from './KugouEKeyItem';
|
||||
import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
|
||||
import { importKugouKeysFromFile } from '~/features/kugou/importKeys';
|
||||
import { KeyListContainer } from '~/components/KeyListContainer';
|
||||
import { toastImportResult } from '~/util/toastImportResult';
|
||||
|
||||
@@ -22,13 +19,7 @@ export function PanelKGGKey() {
|
||||
const addKey = () => dispatch(kugouAddKey());
|
||||
const clearAll = () => dispatch(kugouClearKeys());
|
||||
const handleSecretImport = async (file: File) => {
|
||||
let keys: Omit<StagingKugouKey, 'id'>[] | null = null;
|
||||
if (/mggkey_multi_process/i.test(file.name)) {
|
||||
keys = parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
|
||||
} else if (/^KGMusicV3\.db$/.test(file.name)) {
|
||||
const extractor = await DatabaseKeyExtractor.getInstance();
|
||||
keys = extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
|
||||
}
|
||||
const keys = await importKugouKeysFromFile(file);
|
||||
|
||||
if (keys && keys.length > 0) {
|
||||
dispatch(kugouImportKeys(keys));
|
||||
@@ -0,0 +1,22 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
/**
|
||||
* KuGou / KGG (kgm v5).
|
||||
* UI settings tab route: `kgg`. Redux + localStorage production field: `kugou`.
|
||||
*/
|
||||
export interface StagingKugouKey {
|
||||
id: string;
|
||||
audioHash: string;
|
||||
ekey: string;
|
||||
}
|
||||
|
||||
export type ProductionKugouKey = Record<string /* audioHash */, string /* ekey */>;
|
||||
export const kugouStagingToProductionKey = (key: StagingKugouKey) => key.audioHash.normalize();
|
||||
export const kugouStagingToProductionValue = (key: StagingKugouKey) => key.ekey.normalize();
|
||||
export const kugouProductionToStaging = (
|
||||
key: keyof ProductionKugouKey,
|
||||
value: ProductionKugouKey[keyof ProductionKugouKey],
|
||||
): null | StagingKugouKey => {
|
||||
if (typeof value !== 'string') return null;
|
||||
return { id: nanoid(), audioHash: key.normalize(), ekey: value };
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { importKWMv2KeysFromFile } from '../importKeys';
|
||||
|
||||
const fixtureDir = join(dirname(fileURLToPath(import.meta.url)), '../../../util/mmkv/__tests__/__fixture__');
|
||||
|
||||
function fileFromFixture(name: string, path: string): File {
|
||||
const buff = readFileSync(path);
|
||||
return new File([buff], name);
|
||||
}
|
||||
|
||||
describe('importKWMv2KeysFromFile', () => {
|
||||
test('parses Android Kuwo MMKV by filename', async () => {
|
||||
const file = fileFromFixture('cn.kuwo.player.mmkv.defaultconfig', join(fixtureDir, 'kuwo_android.mmkv'));
|
||||
await expect(importKWMv2KeysFromFile(file)).resolves.toEqual([
|
||||
{ rid: '1234567', quality: '20201kmflac', ekey: 'xyz123' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('parses iOS Kuwo ekey dump by filename', async () => {
|
||||
const file = fileFromFixture('kw_ekey', join(fixtureDir, 'kuwo_ios.mmkv'));
|
||||
await expect(importKWMv2KeysFromFile(file)).resolves.toEqual([
|
||||
{ rid: '1234567', quality: '20201', ekey: 'xyz123' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('returns null for unrecognized filenames', async () => {
|
||||
await expect(importKWMv2KeysFromFile(new File([], 'notes.txt'))).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo';
|
||||
import type { StagingKWMv2Key } from './types';
|
||||
|
||||
/** Parse a Kuwo MMKV / iOS ekey dump into staging key rows (without `id`). */
|
||||
export async function importKWMv2KeysFromFile(file: File): Promise<null | Omit<StagingKWMv2Key, 'id'>[]> {
|
||||
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
|
||||
return parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
|
||||
}
|
||||
if (/kw_ekey/.test(file.name)) {
|
||||
return parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,26 @@
|
||||
import type { RootState } from '~/store';
|
||||
import type { ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
|
||||
import { hasOwn } from '~/util/objects';
|
||||
import { kwm2StagingToProductionKey } from './types';
|
||||
|
||||
export const selectStagingKWMv2Keys = (state: RootState) => state.settings.staging.kwm2.keys;
|
||||
export const selectFinalKWMv2Keys = (state: RootState) => state.settings.production.kwm2.keys;
|
||||
|
||||
export const selectKWMv2Key = (state: RootState, hdr: ParseKuwoHeaderResponse): string | undefined => {
|
||||
if (!hdr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const quality = String(hdr.qualityId);
|
||||
const rid = String(hdr.resourceId);
|
||||
|
||||
const keys = selectFinalKWMv2Keys(state);
|
||||
const lookupKey = kwm2StagingToProductionKey({ id: '', ekey: '', quality, rid });
|
||||
|
||||
let ekey: string | undefined;
|
||||
if (hasOwn(keys, lookupKey)) {
|
||||
ekey = keys[lookupKey];
|
||||
}
|
||||
|
||||
return ekey;
|
||||
};
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import { PiFileAudio, PiHash } from 'react-icons/pi';
|
||||
import { kwm2DeleteKey, kwm2UpdateKey } from '../../settingsSlice';
|
||||
import { kwm2DeleteKey, kwm2UpdateKey } from '~/features/settings/settingsSlice';
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { memo } from 'react';
|
||||
import { StagingKWMv2Key } from '../../keyFormats';
|
||||
import type { StagingKWMv2Key } from '~/features/kwm/types';
|
||||
import { KeyInput } from '~/components/KeyInput';
|
||||
|
||||
export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => {
|
||||
+6
-13
@@ -2,13 +2,11 @@ import { useRef, useState } from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
|
||||
import { ImportSecretModal } from '~/components/ImportSecretModal';
|
||||
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo';
|
||||
|
||||
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '../settingsSlice';
|
||||
import { selectStagingKWMv2Keys } from '../settingsSelector';
|
||||
import { KWMv2EKeyItem } from './KWMv2/KWMv2EKeyItem';
|
||||
import type { StagingKWMv2Key } from '../keyFormats';
|
||||
import { KWMv2AllInstructions } from './KWMv2/KWMv2AllInstructions';
|
||||
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '~/features/settings/settingsSlice';
|
||||
import { selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
|
||||
import { KWMv2EKeyItem } from './KWMv2EKeyItem';
|
||||
import { importKWMv2KeysFromFile } from '~/features/kwm/importKeys';
|
||||
import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
|
||||
import { AddKey } from '~/components/AddKey';
|
||||
import { KeyListContainer } from '~/components/KeyListContainer';
|
||||
import { toastImportResult } from '~/util/toastImportResult';
|
||||
@@ -21,12 +19,7 @@ export function PanelKWMv2Key() {
|
||||
const addKey = () => dispatch(kwm2AddKey());
|
||||
const clearAll = () => dispatch(kwm2ClearKeys());
|
||||
const handleSecretImport = async (file: File) => {
|
||||
let keys: Omit<StagingKWMv2Key, 'id'>[] | null = null;
|
||||
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
|
||||
keys = parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
|
||||
} else if (/kw_ekey/.test(file.name)) {
|
||||
keys = parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
|
||||
}
|
||||
const keys = await importKWMv2KeysFromFile(file);
|
||||
|
||||
if (keys && keys.length > 0) {
|
||||
dispatch(kwm2ImportKeys(keys));
|
||||
@@ -0,0 +1,39 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
/** KWMv2 staging key row (Kuwo). */
|
||||
export interface StagingKWMv2Key {
|
||||
id: string;
|
||||
/**
|
||||
* Resource ID
|
||||
*/
|
||||
rid: string;
|
||||
/**
|
||||
* Quality String
|
||||
*/
|
||||
quality: string;
|
||||
ekey: string;
|
||||
}
|
||||
|
||||
export type ProductionKWMv2Keys = Record<string /* `${rid}-${quality}` */, string /* ekey */>;
|
||||
|
||||
export const parseKwm2ProductionKey = (key: string): null | { rid: string; quality: string } => {
|
||||
const m = key.match(/^(\d+)-(\w+)$/);
|
||||
if (!m) return null;
|
||||
const [_, rid, quality] = m;
|
||||
|
||||
return { rid, quality };
|
||||
};
|
||||
export const kwm2StagingToProductionKey = (key: StagingKWMv2Key) => `${key.rid}-${key.quality.replace(/\D/g, '')}`;
|
||||
export const kwm2StagingToProductionValue = (key: StagingKWMv2Key) => key.ekey;
|
||||
export const kwm2ProductionToStaging = (
|
||||
key: keyof ProductionKWMv2Keys,
|
||||
value: ProductionKWMv2Keys[keyof ProductionKWMv2Keys],
|
||||
): null | StagingKWMv2Key => {
|
||||
if (typeof value !== 'string') return null;
|
||||
|
||||
const parsed = parseKwm2ProductionKey(key);
|
||||
if (!parsed) return null;
|
||||
const { quality, rid } = parsed;
|
||||
|
||||
return { id: nanoid(), rid, quality, ekey: value };
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
|
||||
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
|
||||
import type { RootState } from '~/store';
|
||||
import { selectQMCv2KeyByFileName } from '../keyLookup';
|
||||
|
||||
function storeWithQmcKeys(keys: Record<string, string>, allowFuzzyNameSearch = true) {
|
||||
const base = settingsSlice.getInitialState();
|
||||
return configureStore({
|
||||
reducer: { settings: settingsReducer },
|
||||
preloadedState: {
|
||||
settings: {
|
||||
...base,
|
||||
production: {
|
||||
...base.production,
|
||||
qmc2: { allowFuzzyNameSearch, keys },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('selectQMCv2KeyByFileName', () => {
|
||||
test('returns exact match', () => {
|
||||
const store = storeWithQmcKeys({ 'song.mflac': 'ek-exact' });
|
||||
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'song.mflac')).toBe('ek-exact');
|
||||
});
|
||||
|
||||
test('falls back to closest name when fuzzy search is enabled', () => {
|
||||
const store = storeWithQmcKeys({ 'song.mflac': 'ek-fuzzy' });
|
||||
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'songg.mflac')).toBe('ek-fuzzy');
|
||||
});
|
||||
|
||||
test('returns undefined when fuzzy search is disabled and name misses', () => {
|
||||
const store = storeWithQmcKeys({ 'song.mflac': 'ek' }, false);
|
||||
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'other.mflac')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
|
||||
import { parseAndroidQmEKey } from '~/util/mmkv/qm';
|
||||
import { getFileName } from '~/util/pathHelper';
|
||||
import type { StagingQMCv2Key } from './types';
|
||||
|
||||
/** Parse a QMCv2 key database / MMKV dump into staging key rows (without `id`). */
|
||||
export async function importQMCv2KeysFromFile(file: File): Promise<null | Omit<StagingQMCv2Key, 'id'>[]> {
|
||||
const fileBuffer = await file.arrayBuffer();
|
||||
|
||||
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
|
||||
const extractor = await DatabaseKeyExtractor.getInstance();
|
||||
return extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
|
||||
}
|
||||
|
||||
if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
|
||||
const map = parseAndroidQmEKey(new DataView(fileBuffer));
|
||||
return Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
|
Before Width: | Height: | Size: 5.1 KiB After Width: | Height: | Size: 5.1 KiB |
@@ -0,0 +1,25 @@
|
||||
import type { RootState } from '~/store';
|
||||
import { closestByLevenshtein } from '~/util/levenshtein';
|
||||
import { hasOwn } from '~/util/objects';
|
||||
|
||||
export const selectStagingQMCv2Settings = (state: RootState) => state.settings.staging.qmc2;
|
||||
export const selectFinalQMCv2Settings = (state: RootState) => state.settings.production.qmc2;
|
||||
|
||||
export const selectQMCv2KeyByFileName = (state: RootState, name: string): string | undefined => {
|
||||
const normalizedName = name.normalize();
|
||||
|
||||
let ekey: string | undefined;
|
||||
const { keys, allowFuzzyNameSearch } = selectFinalQMCv2Settings(state);
|
||||
if (hasOwn(keys, normalizedName)) {
|
||||
ekey = keys[normalizedName];
|
||||
} else if (allowFuzzyNameSearch) {
|
||||
const qmc2KeyStoreNames = Object.keys(keys);
|
||||
if (qmc2KeyStoreNames.length > 0) {
|
||||
const closestName = closestByLevenshtein(normalizedName, qmc2KeyStoreNames);
|
||||
console.debug('qmc2: key db could not find %o, using closest %o instead.', normalizedName, closestName);
|
||||
ekey = keys[closestName];
|
||||
}
|
||||
}
|
||||
|
||||
return ekey;
|
||||
};
|
||||
+7
-21
@@ -1,15 +1,12 @@
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '../settingsSlice';
|
||||
import { selectStagingQMCv2Settings } from '../settingsSelector';
|
||||
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '~/features/settings/settingsSlice';
|
||||
import { selectStagingQMCv2Settings } from '~/features/qmc/keyLookup';
|
||||
import React, { useRef, useState } from 'react';
|
||||
import { QMCv2EKeyItem } from './QMCv2/QMCv2EKeyItem';
|
||||
import { QMCv2EKeyItem } from './QMCv2EKeyItem';
|
||||
import { ImportSecretModal } from '~/components/ImportSecretModal';
|
||||
import { StagingQMCv2Key } from '../keyFormats';
|
||||
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
|
||||
import { parseAndroidQmEKey } from '~/util/mmkv/qm';
|
||||
import { getFileName } from '~/util/pathHelper';
|
||||
import { QMCv2QQMusicAllInstructions } from './QMCv2/QMCv2QQMusicAllInstructions';
|
||||
import { QMCv2DoubanAllInstructions } from './QMCv2/QMCv2DoubanAllInstructions';
|
||||
import { importQMCv2KeysFromFile } from '~/features/qmc/importKeys';
|
||||
import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
|
||||
import { QMCv2DoubanAllInstructions } from '~/features/qmc/instructions/QMCv2DoubanAllInstructions';
|
||||
import { AddKey } from '~/components/AddKey';
|
||||
import { InfoModal } from '~/components/InfoModal.tsx';
|
||||
import { Ruby } from '~/components/Ruby.tsx';
|
||||
@@ -32,18 +29,7 @@ export function PanelQMCv2Key() {
|
||||
|
||||
const handleSecretImport = async (file: File) => {
|
||||
try {
|
||||
const fileBuffer = await file.arrayBuffer();
|
||||
|
||||
let keys: null | Omit<StagingQMCv2Key, 'id'>[] = null;
|
||||
|
||||
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
|
||||
const extractor = await DatabaseKeyExtractor.getInstance();
|
||||
keys = extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
|
||||
} else if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
|
||||
const fileBuffer = await file.arrayBuffer();
|
||||
const map = parseAndroidQmEKey(new DataView(fileBuffer));
|
||||
keys = Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
|
||||
}
|
||||
const keys = await importQMCv2KeysFromFile(file);
|
||||
|
||||
if (keys && keys.length > 0) {
|
||||
dispatch(qmc2ImportKeys(keys));
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { qmc2DeleteKey, qmc2UpdateKey } from '../../settingsSlice';
|
||||
import { qmc2DeleteKey, qmc2UpdateKey } from '~/features/settings/settingsSlice';
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { memo } from 'react';
|
||||
import { KeyInput } from '~/components/KeyInput.tsx';
|
||||
@@ -0,0 +1,23 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
/** QMCv2 staging key row (QQ Music / Douban FM). */
|
||||
export interface StagingQMCv2Key {
|
||||
id: string;
|
||||
name: string;
|
||||
ekey: string;
|
||||
}
|
||||
|
||||
export type ProductionQMCv2Keys = Record<string /* filename */, string /* ekey */>;
|
||||
|
||||
export const qmc2StagingToProductionKey = (key: StagingQMCv2Key) => key.name.normalize();
|
||||
export const qmc2StagingToProductionValue = (key: StagingQMCv2Key) => key.ekey.trim();
|
||||
export const qmc2ProductionToStaging = (
|
||||
key: keyof ProductionQMCv2Keys,
|
||||
value: ProductionQMCv2Keys[keyof ProductionQMCv2Keys],
|
||||
): StagingQMCv2Key => {
|
||||
return {
|
||||
id: nanoid(),
|
||||
name: key.normalize(),
|
||||
ekey: value.trim(),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '../importKeys';
|
||||
import { sanitizeQtfmAndroidKey } from '../types';
|
||||
|
||||
describe('qtfm import / sanitize', () => {
|
||||
test('parseQtfmDeviceSecretFromText extracts DEVICE_SECRET line', () => {
|
||||
const text = 'foo\nDEVICE_SECRET: aBcD1234\nbar';
|
||||
expect(parseQtfmDeviceSecretFromText(text)).toBe('aBcD1234');
|
||||
expect(parseQtfmDeviceSecretFromText('no secret here')).toBeNull();
|
||||
});
|
||||
|
||||
test('parseQtfmDeviceInfoFromText requires all fields', () => {
|
||||
const full = ['PRODUCT: p', 'DEVICE: d', 'MANUFACTURER: m', 'BRAND: b', 'BOARD: board', 'MODEL: model'].join('\n');
|
||||
expect(parseQtfmDeviceInfoFromText(full)).toEqual({
|
||||
product: 'p',
|
||||
device: 'd',
|
||||
manufacturer: 'm',
|
||||
brand: 'b',
|
||||
board: 'board',
|
||||
model: 'model',
|
||||
});
|
||||
expect(parseQtfmDeviceInfoFromText('PRODUCT: p\nDEVICE: d')).toBeNull();
|
||||
});
|
||||
|
||||
test('sanitizeQtfmAndroidKey strips non-hex', () => {
|
||||
expect(sanitizeQtfmAndroidKey('de-ad_be ef!!')).toBe('deadbeef');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { GetQingTingFMDeviceKeyPayload } from '~/decrypt-worker/types.ts';
|
||||
|
||||
/**
|
||||
* Extract a hex device secret from clipboard / dump text.
|
||||
* Matches lines like `DEVICE_SECRET: deadbeef…` (from qtfm-device-id).
|
||||
*/
|
||||
export function parseQtfmDeviceSecretFromText(text: string): string | null {
|
||||
const match = text.match(/^DEVICE_SECRET: ([0-9a-fA-F]+)/m);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract build.prop-style device fields for worker-side key derivation.
|
||||
* Returns null unless all required fields are present.
|
||||
*/
|
||||
export function parseQtfmDeviceInfoFromText(text: string): GetQingTingFMDeviceKeyPayload | null {
|
||||
const dataMap = Object.create(null) as GetQingTingFMDeviceKeyPayload;
|
||||
for (const [, key, value] of text.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) {
|
||||
dataMap[key.toLowerCase() as keyof GetQingTingFMDeviceKeyPayload] = value;
|
||||
}
|
||||
const { product, device, manufacturer, brand, board, model } = dataMap;
|
||||
if (product && device && manufacturer && brand && board && model) {
|
||||
return dataMap;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { VQuote } from '~/components/HelpText/VQuote';
|
||||
import { HiWord } from '~/components/HelpText/HiWord';
|
||||
import { Ruby } from '~/components/Ruby';
|
||||
|
||||
/** File-location / naming notes for QingTing FM Android downloads. */
|
||||
export function QingTingNotes() {
|
||||
return (
|
||||
<>
|
||||
<h3 className="text-xl font-bold my-2">注意事项</h3>
|
||||
<ul className="list-disc pl-6">
|
||||
<li>
|
||||
<p>
|
||||
下载的文件位于
|
||||
<VQuote>
|
||||
<code className="break-words">
|
||||
<HiWord>[内部储存]</HiWord>/<wbr />
|
||||
Android/
|
||||
<wbr />
|
||||
data/
|
||||
<wbr />
|
||||
fm.qingting.qtradio/
|
||||
<wbr />
|
||||
files/Music/
|
||||
</code>
|
||||
</VQuote>
|
||||
</p>
|
||||
<ul className="list-disc pl-6">
|
||||
<li>
|
||||
<p>
|
||||
你可能需要使用有
|
||||
<Ruby caption="root">特权</Ruby>
|
||||
的文件浏览器访问。
|
||||
</p>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>
|
||||
音频文件文件名为「<code>.p~!</code>」后缀。
|
||||
</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>因为解密密钥与文件名相关,因此解密前请不要更改文件名。</p>
|
||||
</li>
|
||||
</ul>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { RootState } from '~/store';
|
||||
|
||||
export const selectStagingQtfmAndroidKey = (state: RootState) => state.settings.staging.qtfm.android;
|
||||
export const selectQtfmAndroidKey = (state: RootState) => state.settings.production.qtfm.android;
|
||||
+14
-58
@@ -2,19 +2,19 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||
import { ExtLink } from '~/components/ExtLink';
|
||||
import { ChangeEvent, ClipboardEvent, useId } from 'react';
|
||||
import { VQuote } from '~/components/HelpText/VQuote';
|
||||
import { selectStagingQtfmAndroidKey } from '../settingsSelector';
|
||||
import { qtfmAndroidUpdateKey } from '../settingsSlice';
|
||||
import { workerClientBus } from '~/decrypt-worker/client.ts';
|
||||
import { GetQingTingFMDeviceKeyPayload } from '~/decrypt-worker/types.ts';
|
||||
import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
|
||||
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
|
||||
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
|
||||
import { Ruby } from '~/components/Ruby';
|
||||
import { HiWord } from '~/components/HelpText/HiWord';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
|
||||
|
||||
export function PanelQingTing() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { crypto } = usePlatform();
|
||||
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
|
||||
const setSecretKey = (secretKey: string) => {
|
||||
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
|
||||
@@ -22,26 +22,18 @@ export function PanelQingTing() {
|
||||
|
||||
const handleDataPaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
||||
const plainText = e.clipboardData.getData('text/plain');
|
||||
const matchDeviceSecret = plainText.match(/^DEVICE_SECRET: ([0-9a-fA-F]+)/m);
|
||||
if (matchDeviceSecret) {
|
||||
const deviceSecret = parseQtfmDeviceSecretFromText(plainText);
|
||||
if (deviceSecret) {
|
||||
e.preventDefault();
|
||||
setSecretKey(matchDeviceSecret[1]);
|
||||
setSecretKey(deviceSecret);
|
||||
return;
|
||||
}
|
||||
|
||||
const dataMap = Object.create(null) as GetQingTingFMDeviceKeyPayload;
|
||||
for (const [, key, value] of plainText.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) {
|
||||
dataMap[key.toLowerCase() as keyof GetQingTingFMDeviceKeyPayload] = value;
|
||||
}
|
||||
const { product, device, manufacturer, brand, board, model } = dataMap;
|
||||
|
||||
if (product && device && manufacturer && brand && board && model) {
|
||||
const dataMap = parseQtfmDeviceInfoFromText(plainText);
|
||||
if (dataMap) {
|
||||
e.preventDefault();
|
||||
workerClientBus
|
||||
.request<
|
||||
string,
|
||||
GetQingTingFMDeviceKeyPayload
|
||||
>(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
||||
crypto
|
||||
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
|
||||
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
|
||||
}
|
||||
};
|
||||
@@ -83,43 +75,7 @@ export function PanelQingTing() {
|
||||
</fieldset>
|
||||
</div>
|
||||
|
||||
<h3 className="text-xl font-bold my-2">注意事项</h3>
|
||||
<ul className="list-disc pl-6">
|
||||
<li>
|
||||
<p>
|
||||
下载的文件位于
|
||||
<VQuote>
|
||||
<code className="break-words">
|
||||
<HiWord>[内部储存]</HiWord>/<wbr />
|
||||
Android/
|
||||
<wbr />
|
||||
data/
|
||||
<wbr />
|
||||
fm.qingting.qtradio/
|
||||
<wbr />
|
||||
files/Music/
|
||||
</code>
|
||||
</VQuote>
|
||||
</p>
|
||||
<ul className="list-disc pl-6">
|
||||
<li>
|
||||
<p>
|
||||
你可能需要使用有
|
||||
<Ruby caption="root">特权</Ruby>
|
||||
的文件浏览器访问。
|
||||
</p>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>
|
||||
音频文件文件名为「<code>.p~!</code>」前缀。
|
||||
</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>因为解密密钥与文件名相关,因此解密前请不要更改文件名。</p>
|
||||
</li>
|
||||
</ul>
|
||||
<QingTingNotes />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/** QingTing FM staging settings (`state.settings.staging.qtfm`). */
|
||||
export interface StagingQtfmSettings {
|
||||
/** Android device key (hex). */
|
||||
android: string;
|
||||
}
|
||||
|
||||
/** QingTing FM production settings (`state.settings.production.qtfm`; persist key `qtfm`). */
|
||||
export type ProductionQtfmSettings = StagingQtfmSettings;
|
||||
|
||||
export const EMPTY_QTFM_SETTINGS: StagingQtfmSettings = { android: '' };
|
||||
|
||||
/** Strip non-hex characters from a pasted / typed device key. */
|
||||
export function sanitizeQtfmAndroidKey(key: string): string {
|
||||
return key.replace(/[^0-9a-fA-F]/g, '');
|
||||
}
|
||||
@@ -2,14 +2,17 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||
import { commitStagingChange, discardStagingChanges } from './settingsSlice';
|
||||
import { selectIsSettingsNotSaved } from './settingsSelector';
|
||||
import { Outlet } from 'react-router';
|
||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs.tsx';
|
||||
import { getSettingsTabs } from '~/features/settings/settingsTabs.tsx';
|
||||
import { MdOutlineSettingsBackupRestore } from 'react-icons/md';
|
||||
import { toast } from 'react-toastify';
|
||||
import { ResponsiveNav } from '../nav/ResponsiveNav';
|
||||
import { TabNavLink } from '../nav/TabNavLink';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
export function Settings() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { capabilities } = usePlatform();
|
||||
const settingsTabs = getSettingsTabs(capabilities);
|
||||
|
||||
const handleResetSettings = () => {
|
||||
dispatch(discardStagingChanges());
|
||||
@@ -35,7 +38,7 @@ export function Settings() {
|
||||
navigationClassName="overflow-x-auto pb-[2px] md:pb-0 h-full items-start [&]:md:flex"
|
||||
navigation={
|
||||
<div role="tablist" className="tabs gap-1 flex-nowrap md:flex-col grow items-center">
|
||||
{Object.entries(SETTINGS_TABS).map(([id, { name }]) => (
|
||||
{Object.entries(settingsTabs).map(([id, { name }]) => (
|
||||
<TabNavLink key={id} to={`/settings/${id}`}>
|
||||
{name}
|
||||
</TabNavLink>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,259 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
|
||||
import {
|
||||
commitStagingChange,
|
||||
discardStagingChanges,
|
||||
productionToStaging,
|
||||
qmc2AddKey,
|
||||
qmc2ImportKeys,
|
||||
qmc2UpdateKey,
|
||||
settingsSlice,
|
||||
stagingToProduction,
|
||||
type ProductionSettings,
|
||||
type StagingSettings,
|
||||
} from '../settingsSlice';
|
||||
import { mergeSettings } from '../persistSettings';
|
||||
import { productionKeyToStaging, stagingKeyToProduction } from '../keyFormats';
|
||||
import {
|
||||
qmc2ProductionToStaging,
|
||||
qmc2StagingToProductionKey,
|
||||
qmc2StagingToProductionValue,
|
||||
} from '~/features/qmc/types';
|
||||
import { kwm2StagingToProductionKey } from '~/features/kwm/types';
|
||||
|
||||
function createSettingsStore(preloaded?: ReturnType<typeof settingsSlice.getInitialState>) {
|
||||
return configureStore({
|
||||
reducer: { settings: settingsSlice.reducer },
|
||||
preloadedState: preloaded ? { settings: preloaded } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
describe('stagingToProduction / productionToStaging', () => {
|
||||
test('stagingToProduction maps qmc2/kwm2/kugou keys and copies scalars', () => {
|
||||
const staging: StagingSettings = {
|
||||
general: {
|
||||
batchDownload: {
|
||||
directoryPicker: false,
|
||||
rememberDirectory: false,
|
||||
streamingZip: true,
|
||||
blobZip: false,
|
||||
},
|
||||
directWrite: {
|
||||
outputMode: 'fixedDirectory',
|
||||
fixedDirectoryPath: '/out',
|
||||
deleteSourceAfterDecrypt: true,
|
||||
},
|
||||
},
|
||||
qmc2: {
|
||||
allowFuzzyNameSearch: false,
|
||||
keys: [{ id: 'q1', name: 'a.mflac', ekey: ' ek1 ' }],
|
||||
},
|
||||
kwm2: {
|
||||
keys: [{ id: 'k1', rid: '123', quality: '2000k', ekey: 'kw' }],
|
||||
},
|
||||
kugou: {
|
||||
keys: [{ id: 'g1', audioHash: 'hash1', ekey: 'kg' }],
|
||||
},
|
||||
qtfm: { android: 'abcd' },
|
||||
};
|
||||
|
||||
expect(stagingToProduction(staging)).toEqual({
|
||||
general: {
|
||||
batchDownload: {
|
||||
directoryPicker: false,
|
||||
rememberDirectory: false,
|
||||
streamingZip: true,
|
||||
blobZip: false,
|
||||
},
|
||||
directWrite: {
|
||||
outputMode: 'fixedDirectory',
|
||||
fixedDirectoryPath: '/out',
|
||||
deleteSourceAfterDecrypt: true,
|
||||
},
|
||||
},
|
||||
qmc2: {
|
||||
allowFuzzyNameSearch: false,
|
||||
keys: { 'a.mflac': 'ek1' },
|
||||
},
|
||||
kwm2: {
|
||||
keys: { [kwm2StagingToProductionKey(staging.kwm2.keys[0])]: 'kw' },
|
||||
},
|
||||
kugou: {
|
||||
keys: { hash1: 'kg' },
|
||||
},
|
||||
qtfm: { android: 'abcd' },
|
||||
});
|
||||
});
|
||||
|
||||
test('productionToStaging round-trips values via keyFormats helpers', () => {
|
||||
const production: ProductionSettings = {
|
||||
general: settingsSlice.getInitialState().production.general,
|
||||
qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } },
|
||||
kwm2: { keys: { '42-2000': 'kw' } },
|
||||
kugou: { keys: { abcd: 'kg' } },
|
||||
qtfm: { android: 'ff00' },
|
||||
};
|
||||
|
||||
const staging = productionToStaging(production);
|
||||
expect(staging.qmc2.allowFuzzyNameSearch).toBe(true);
|
||||
expect(staging.qmc2.keys).toHaveLength(1);
|
||||
expect(staging.qmc2.keys[0]).toMatchObject({ name: 'song.mflac', ekey: 'ek' });
|
||||
expect(staging.qmc2.keys[0].id).toEqual(expect.any(String));
|
||||
|
||||
expect(staging.kwm2.keys).toEqual([expect.objectContaining({ rid: '42', quality: '2000', ekey: 'kw' })]);
|
||||
expect(staging.kugou.keys).toEqual([expect.objectContaining({ audioHash: 'abcd', ekey: 'kg' })]);
|
||||
expect(staging.qtfm.android).toBe('ff00');
|
||||
|
||||
// Same mapping as productionKeyToStaging for qmc2
|
||||
expect(staging.qmc2.keys.map(({ name, ekey }) => ({ name, ekey }))).toEqual(
|
||||
productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging).map(({ name, ekey }) => ({ name, ekey })),
|
||||
);
|
||||
});
|
||||
|
||||
test('stagingKeyToProduction matches stagingToProduction for qmc2 keys', () => {
|
||||
const keys = [{ id: '1', name: 'x.mflac', ekey: ' e ' }];
|
||||
expect(stagingKeyToProduction(keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue)).toEqual(
|
||||
stagingToProduction({
|
||||
...settingsSlice.getInitialState().staging,
|
||||
qmc2: { allowFuzzyNameSearch: true, keys },
|
||||
}).qmc2.keys,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('commitStagingChange', () => {
|
||||
test('does not regenerate staging key ids', () => {
|
||||
const store = createSettingsStore();
|
||||
store.dispatch(qmc2AddKey());
|
||||
const id = store.getState().settings.staging.qmc2.keys[0].id;
|
||||
|
||||
store.dispatch(qmc2UpdateKey({ id, field: 'name', value: 'track.mflac' }));
|
||||
store.dispatch(qmc2UpdateKey({ id, field: 'ekey', value: 'secret' }));
|
||||
store.dispatch(commitStagingChange());
|
||||
|
||||
const { dirty, staging, production } = store.getState().settings;
|
||||
expect(dirty).toBe(false);
|
||||
expect(staging.qmc2.keys[0].id).toBe(id);
|
||||
expect(production.qmc2.keys).toEqual({ 'track.mflac': 'secret' });
|
||||
});
|
||||
|
||||
test('keeps ids stable across multiple commits', () => {
|
||||
const store = createSettingsStore();
|
||||
store.dispatch(qmc2ImportKeys([{ name: 'a.mflac', ekey: '1' }]));
|
||||
const id = store.getState().settings.staging.qmc2.keys[0].id;
|
||||
|
||||
store.dispatch(commitStagingChange());
|
||||
store.dispatch(qmc2UpdateKey({ id, field: 'ekey', value: '2' }));
|
||||
store.dispatch(commitStagingChange());
|
||||
|
||||
expect(store.getState().settings.staging.qmc2.keys[0].id).toBe(id);
|
||||
expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': '2' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('discardStagingChanges', () => {
|
||||
test('restores staging from production (ids may change)', () => {
|
||||
const store = createSettingsStore();
|
||||
store.dispatch(qmc2ImportKeys([{ name: 'a.mflac', ekey: '1' }]));
|
||||
store.dispatch(commitStagingChange());
|
||||
|
||||
store.dispatch(
|
||||
qmc2UpdateKey({ id: store.getState().settings.staging.qmc2.keys[0].id, field: 'ekey', value: 'dirty' }),
|
||||
);
|
||||
expect(store.getState().settings.dirty).toBe(true);
|
||||
|
||||
store.dispatch(discardStagingChanges());
|
||||
|
||||
expect(store.getState().settings.dirty).toBe(false);
|
||||
expect(store.getState().settings.staging.qmc2.keys).toEqual([
|
||||
expect.objectContaining({ name: 'a.mflac', ekey: '1' }),
|
||||
]);
|
||||
expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': '1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeSettings', () => {
|
||||
test('fills defaults and keeps valid production keys', () => {
|
||||
const merged = mergeSettings({
|
||||
qmc2: { allowFuzzyNameSearch: false, keys: { 'a.mflac': 'ek' } },
|
||||
kwm2: { keys: { '1-2000': 'kw', bad: 'x', '2-hi': 'y' } },
|
||||
kugou: { keys: { hash: 'kg', nested: { nope: true } } },
|
||||
qtfm: { android: 'zz11!!aa' },
|
||||
} as unknown as ProductionSettings);
|
||||
|
||||
expect(merged.general.batchDownload).toEqual(settingsSlice.getInitialState().production.general.batchDownload);
|
||||
expect(merged.general.directWrite).toEqual(settingsSlice.getInitialState().production.general.directWrite);
|
||||
expect(merged.qmc2).toEqual({ allowFuzzyNameSearch: false, keys: { 'a.mflac': 'ek' } });
|
||||
// only keys matching /^(\d+)-(\w+)$/
|
||||
expect(merged.kwm2.keys).toEqual({ '1-2000': 'kw', '2-hi': 'y' });
|
||||
expect(merged.kugou.keys).toEqual({ hash: 'kg' });
|
||||
// non-hex stripped (`z` is not hex)
|
||||
expect(merged.qtfm.android).toBe('11aa');
|
||||
});
|
||||
|
||||
test('merged production round-trips through productionToStaging → stagingToProduction', () => {
|
||||
const merged = mergeSettings({
|
||||
general: {
|
||||
batchDownload: {
|
||||
directoryPicker: false,
|
||||
rememberDirectory: true,
|
||||
streamingZip: false,
|
||||
blobZip: true,
|
||||
},
|
||||
directWrite: {
|
||||
outputMode: 'fixedDirectory',
|
||||
fixedDirectoryPath: '/music/out',
|
||||
deleteSourceAfterDecrypt: true,
|
||||
},
|
||||
},
|
||||
qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } },
|
||||
kwm2: { keys: { '9-1000': 'kw' } },
|
||||
kugou: { keys: { h1: 'kg' } },
|
||||
qtfm: { android: 'abc' },
|
||||
});
|
||||
|
||||
const roundTrip = stagingToProduction(productionToStaging(merged));
|
||||
expect(roundTrip.general).toEqual(merged.general);
|
||||
expect(roundTrip.qmc2).toEqual(merged.qmc2);
|
||||
expect(roundTrip.kwm2).toEqual(merged.kwm2);
|
||||
expect(roundTrip.kugou).toEqual(merged.kugou);
|
||||
expect(roundTrip.qtfm).toEqual(merged.qtfm);
|
||||
});
|
||||
|
||||
test('mergeSettings fills directWrite defaults and ignores invalid fields', () => {
|
||||
const merged = mergeSettings({
|
||||
general: {
|
||||
directWrite: {
|
||||
outputMode: 'nope',
|
||||
fixedDirectoryPath: 42,
|
||||
deleteSourceAfterDecrypt: 'yes',
|
||||
},
|
||||
},
|
||||
} as unknown as ProductionSettings);
|
||||
|
||||
expect(merged.general.directWrite).toEqual({
|
||||
outputMode: 'besideSource',
|
||||
fixedDirectoryPath: null,
|
||||
deleteSourceAfterDecrypt: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('mergeSettings keeps valid directWrite values when batchDownload omitted', () => {
|
||||
const merged = mergeSettings({
|
||||
general: {
|
||||
directWrite: {
|
||||
outputMode: 'fixedDirectory',
|
||||
fixedDirectoryPath: null,
|
||||
deleteSourceAfterDecrypt: true,
|
||||
},
|
||||
},
|
||||
} as unknown as ProductionSettings);
|
||||
|
||||
expect(merged.general.directWrite).toEqual({
|
||||
outputMode: 'fixedDirectory',
|
||||
fixedDirectoryPath: null,
|
||||
deleteSourceAfterDecrypt: true,
|
||||
});
|
||||
expect(merged.general.batchDownload).toEqual(settingsSlice.getInitialState().production.general.batchDownload);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||
import type { PlatformCapabilities } from '~/platform/types';
|
||||
import { getSettingsTabs, hasOneClickImportCapability, ONE_CLICK_TAB_ID } from '../settingsTabs';
|
||||
|
||||
const baseCaps = (overrides: Partial<PlatformCapabilities> = {}): PlatformCapabilities => ({
|
||||
downloadTypes: [BatchDownloadType.PackZip],
|
||||
directFsAccess: false,
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('settingsTabs', () => {
|
||||
test('hasOneClickImportCapability is false for browser defaults', () => {
|
||||
expect(hasOneClickImportCapability(baseCaps())).toBe(false);
|
||||
});
|
||||
|
||||
test('hasOneClickImportCapability is true with nativeKeyAccess', () => {
|
||||
expect(hasOneClickImportCapability(baseCaps({ nativeKeyAccess: [NativeImportType.QQMusic] }))).toBe(true);
|
||||
});
|
||||
|
||||
test('hasOneClickImportCapability is true with Adb', () => {
|
||||
expect(hasOneClickImportCapability(baseCaps({ androidKeyAccess: AndroidImportType.Adb }))).toBe(true);
|
||||
});
|
||||
|
||||
test('getSettingsTabs omits one-click without capability', () => {
|
||||
const tabs = getSettingsTabs(baseCaps());
|
||||
expect(Object.keys(tabs)).toEqual(['general', 'qmc', 'kwm', 'kgg', 'qtfm']);
|
||||
expect(tabs[ONE_CLICK_TAB_ID]).toBeUndefined();
|
||||
});
|
||||
|
||||
test('getSettingsTabs inserts one-click after general when capable', () => {
|
||||
const tabs = getSettingsTabs(baseCaps({ nativeKeyAccess: [NativeImportType.Kugou] }));
|
||||
expect(Object.keys(tabs)).toEqual(['general', ONE_CLICK_TAB_ID, 'qmc', 'kwm', 'kgg', 'qtfm']);
|
||||
expect(tabs[ONE_CLICK_TAB_ID]?.name).toBe('一键导入');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
kugouImportKeys,
|
||||
kwm2ImportKeys,
|
||||
qmc2ImportKeys,
|
||||
qtfmAndroidUpdateKey,
|
||||
} from '~/features/settings/settingsSlice';
|
||||
import type { NativeImportResult } from '~/platform/types';
|
||||
import type { AppDispatch } from '~/store';
|
||||
|
||||
/** Apply native/ADB import payload into staging. Caller may commit immediately (one-click import). */
|
||||
export function applyNativeImportResult(dispatch: AppDispatch, result: NativeImportResult): number {
|
||||
let count = 0;
|
||||
if (result.qmc2?.length) {
|
||||
dispatch(qmc2ImportKeys(result.qmc2));
|
||||
count += result.qmc2.length;
|
||||
}
|
||||
if (result.kwm2?.length) {
|
||||
dispatch(kwm2ImportKeys(result.kwm2));
|
||||
count += result.kwm2.length;
|
||||
}
|
||||
if (result.kugou?.length) {
|
||||
dispatch(kugouImportKeys(result.kugou));
|
||||
count += result.kugou.length;
|
||||
}
|
||||
if (result.qtfm?.android !== undefined) {
|
||||
dispatch(qtfmAndroidUpdateKey({ deviceKey: result.qtfm.android }));
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { PayloadAction, WritableDraft } from '@reduxjs/toolkit';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
import type { StagingQMCv2Key } from '~/features/qmc/types';
|
||||
import type { StagingKWMv2Key } from '~/features/kwm/types';
|
||||
import type { StagingKugouKey } from '~/features/kugou/types';
|
||||
|
||||
/** Formats that store keys as a staging list (array with stable `id`). */
|
||||
export type KeyListFormat = 'qmc2' | 'kwm2' | 'kugou';
|
||||
|
||||
type StagingKeyByFormat = {
|
||||
qmc2: StagingQMCv2Key;
|
||||
kwm2: StagingKWMv2Key;
|
||||
kugou: StagingKugouKey;
|
||||
};
|
||||
|
||||
/** Minimal state shape so this module does not import settingsSlice (avoids cycles). */
|
||||
type KeyListSettingsState = {
|
||||
dirty: boolean;
|
||||
staging: {
|
||||
qmc2: { keys: StagingQMCv2Key[] };
|
||||
kwm2: { keys: StagingKWMv2Key[] };
|
||||
kugou: { keys: StagingKugouKey[] };
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Shared Add / Import / Delete / Update / Clear reducers for staging key lists.
|
||||
* Action names are wired by the caller (`qmc2AddKey`, `kwm2AddKey`, …).
|
||||
*
|
||||
* Returns arrow-function reducers so they can be assigned into `createSlice` without
|
||||
* unbound-method lint issues.
|
||||
*/
|
||||
export function createKeyListReducers<F extends KeyListFormat>(
|
||||
path: F,
|
||||
emptyItem: () => Omit<StagingKeyByFormat[F], 'id'>,
|
||||
) {
|
||||
type T = StagingKeyByFormat[F];
|
||||
type Field = Exclude<keyof T, 'id'>;
|
||||
type DraftState = WritableDraft<KeyListSettingsState>;
|
||||
|
||||
const getKeys = (state: DraftState): T[] => state.staging[path].keys as T[];
|
||||
|
||||
const setKeys = (state: DraftState, keys: T[]) => {
|
||||
// Generic path makes TS widen the union; cast is safe for a fixed `path`.
|
||||
(state.staging[path] as { keys: T[] }).keys = keys;
|
||||
};
|
||||
|
||||
return {
|
||||
addKey: (state: DraftState) => {
|
||||
getKeys(state).push({ id: nanoid(), ...emptyItem() } as T);
|
||||
state.dirty = true;
|
||||
},
|
||||
importKeys: (state: DraftState, { payload }: PayloadAction<Omit<T, 'id'>[]>) => {
|
||||
getKeys(state).push(...payload.map((item) => ({ id: nanoid(), ...item }) as T));
|
||||
state.dirty = true;
|
||||
},
|
||||
deleteKey: (state: DraftState, { payload: { id } }: PayloadAction<{ id: string }>) => {
|
||||
setKeys(
|
||||
state,
|
||||
getKeys(state).filter((item) => item.id !== id),
|
||||
);
|
||||
state.dirty = true;
|
||||
},
|
||||
updateKey: (
|
||||
state: DraftState,
|
||||
{ payload: { id, field, value } }: PayloadAction<{ id: string; field: Field; value: string }>,
|
||||
) => {
|
||||
const keyItem = getKeys(state).find((item) => item.id === id);
|
||||
if (keyItem) {
|
||||
(keyItem as Record<Field, string>)[field] = value;
|
||||
state.dirty = true;
|
||||
}
|
||||
},
|
||||
clearKeys: (state: DraftState) => {
|
||||
setKeys(state, []);
|
||||
state.dirty = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
import { objectify } from 'radash';
|
||||
|
||||
/** Generic map↔list helpers shared by format feature types. */
|
||||
export function productionKeyToStaging<S, P extends Record<string, unknown>>(
|
||||
src: P,
|
||||
make: (k: keyof P, v: P[keyof P]) => null | S,
|
||||
@@ -18,81 +18,3 @@ export function productionKeyToStaging<S, P extends Record<string, unknown>>(
|
||||
export function stagingKeyToProduction<S, P>(src: S[], toKey: (s: S) => keyof P, toValue: (s: S) => P[keyof P]): P {
|
||||
return objectify(src, toKey, toValue) as P;
|
||||
}
|
||||
|
||||
// QMCv2 (QQ)
|
||||
export interface StagingQMCv2Key {
|
||||
id: string;
|
||||
name: string;
|
||||
ekey: string;
|
||||
}
|
||||
|
||||
export type ProductionQMCv2Keys = Record<string /* filename */, string /* ekey */>;
|
||||
|
||||
export const qmc2StagingToProductionKey = (key: StagingQMCv2Key) => key.name.normalize();
|
||||
export const qmc2StagingToProductionValue = (key: StagingQMCv2Key) => key.ekey.trim();
|
||||
export const qmc2ProductionToStaging = (
|
||||
key: keyof ProductionQMCv2Keys,
|
||||
value: ProductionQMCv2Keys[keyof ProductionQMCv2Keys],
|
||||
): StagingQMCv2Key => {
|
||||
return {
|
||||
id: nanoid(),
|
||||
name: key.normalize(),
|
||||
ekey: value.trim(),
|
||||
};
|
||||
};
|
||||
|
||||
// KWMv2 (KuWo)
|
||||
export interface StagingKWMv2Key {
|
||||
id: string;
|
||||
/**
|
||||
* Resource ID
|
||||
*/
|
||||
rid: string;
|
||||
/**
|
||||
* Quality String
|
||||
*/
|
||||
quality: string;
|
||||
ekey: string;
|
||||
}
|
||||
|
||||
export type ProductionKWMv2Keys = Record<string /* `${rid}-${quality}` */, string /* ekey */>;
|
||||
|
||||
export const parseKwm2ProductionKey = (key: string): null | { rid: string; quality: string } => {
|
||||
const m = key.match(/^(\d+)-(\w+)$/);
|
||||
if (!m) return null;
|
||||
const [_, rid, quality] = m;
|
||||
|
||||
return { rid, quality };
|
||||
};
|
||||
export const kwm2StagingToProductionKey = (key: StagingKWMv2Key) => `${key.rid}-${key.quality.replace(/\D/g, '')}`;
|
||||
export const kwm2StagingToProductionValue = (key: StagingKWMv2Key) => key.ekey;
|
||||
export const kwm2ProductionToStaging = (
|
||||
key: keyof ProductionKWMv2Keys,
|
||||
value: ProductionKWMv2Keys[keyof ProductionKWMv2Keys],
|
||||
): null | StagingKWMv2Key => {
|
||||
if (typeof value !== 'string') return null;
|
||||
|
||||
const parsed = parseKwm2ProductionKey(key);
|
||||
if (!parsed) return null;
|
||||
const { quality, rid } = parsed;
|
||||
|
||||
return { id: nanoid(), rid, quality, ekey: value };
|
||||
};
|
||||
|
||||
// KuGou (kgg, kgm v5)
|
||||
export interface StagingKugouKey {
|
||||
id: string;
|
||||
audioHash: string;
|
||||
ekey: string;
|
||||
}
|
||||
|
||||
export type ProductionKugouKey = Record<string /* audioHash */, string /* ekey */>;
|
||||
export const kugouStagingToProductionKey = (key: StagingKugouKey) => key.audioHash.normalize();
|
||||
export const kugouStagingToProductionValue = (key: StagingKugouKey) => key.ekey.normalize();
|
||||
export const kugouProductionToStaging = (
|
||||
key: keyof ProductionKugouKey,
|
||||
value: ProductionKugouKey[keyof ProductionKugouKey],
|
||||
): null | StagingKugouKey => {
|
||||
if (typeof value !== 'string') return null;
|
||||
return { id: nanoid(), audioHash: key.normalize(), ekey: value };
|
||||
};
|
||||
@@ -1,17 +1,30 @@
|
||||
import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '~/hooks';
|
||||
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
|
||||
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
|
||||
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
|
||||
import { selectStagingBatchDownloadSettings, selectStagingDirectWriteSettings } from '../settingsSelector';
|
||||
import {
|
||||
BatchDownloadSettings,
|
||||
DirectWriteOutputMode,
|
||||
updateBatchDownloadSetting,
|
||||
updateDirectWriteSetting,
|
||||
} from '../settingsSlice';
|
||||
import { BatchDownloadType } from '~/platform/capabilities';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
export function PanelGeneral() {
|
||||
const dispatch = useAppDispatch();
|
||||
const batch = useAppSelector(selectStagingBatchDownloadSettings);
|
||||
const canDirectoryPicker = supportsDirectoryPicker();
|
||||
const canStreamingZip = supportsStreamingZipDownload();
|
||||
const directWrite = useAppSelector(selectStagingDirectWriteSettings);
|
||||
const { capabilities, download } = usePlatform();
|
||||
const downloadTypes = new Set(capabilities.downloadTypes);
|
||||
const canDirectoryPicker = downloadTypes.has(BatchDownloadType.SelectDirectory);
|
||||
const canStreamingZip = downloadTypes.has(BatchDownloadType.StreamZip);
|
||||
const canBlobZip = downloadTypes.has(BatchDownloadType.PackZip);
|
||||
const showBatchDownload = downloadTypes.size > 0;
|
||||
const canDirectWrite = capabilities.directFsAccess;
|
||||
const [hasRememberedDir, setHasRememberedDir] = useState(false);
|
||||
const [pickingDirectory, setPickingDirectory] = useState(false);
|
||||
|
||||
const refreshRemembered = useCallback(() => {
|
||||
hasRememberedDirectoryHandle()
|
||||
@@ -33,84 +46,171 @@ export function PanelGeneral() {
|
||||
toast.info('已清除记住的输出目录');
|
||||
};
|
||||
|
||||
const handlePickDirectory = async () => {
|
||||
setPickingDirectory(true);
|
||||
try {
|
||||
const path = await download.pickDirectory();
|
||||
if (path) {
|
||||
dispatch(updateDirectWriteSetting({ fixedDirectoryPath: path, outputMode: 'fixedDirectory' }));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`无法选择文件夹: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setPickingDirectory(false);
|
||||
}
|
||||
};
|
||||
|
||||
const idDir = useId();
|
||||
const idRemember = useId();
|
||||
const idStreamZip = useId();
|
||||
const idBlobZip = useId();
|
||||
const idOutputMode = useId();
|
||||
const idFixedPath = useId();
|
||||
const idDeleteSource = useId();
|
||||
|
||||
return (
|
||||
<div className="min-h-0 flex-col grow px-1">
|
||||
<h2 className="text-2xl font-bold mb-4">通用设置</h2>
|
||||
|
||||
<h3 className="text-xl font-semibold mb-2">批量下载</h3>
|
||||
<p className="text-sm text-base-content/80 mb-4">
|
||||
点击「下载全部」时,将按下方勾选项的顺序依次尝试。若选中的模式均不可用或全部失败,会弹出提示。
|
||||
</p>
|
||||
{showBatchDownload && (
|
||||
<>
|
||||
<h3 className="text-xl font-semibold mb-2">批量下载</h3>
|
||||
<p className="text-sm text-base-content/80 mb-4">
|
||||
点击「下载全部」时,将按下方勾选项的顺序依次尝试。若选中的模式均不可用或全部失败,会弹出提示。
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<BatchOption
|
||||
id={idDir}
|
||||
checked={batch.directoryPicker && canDirectoryPicker}
|
||||
disabled={!canDirectoryPicker}
|
||||
dimmed={!canDirectoryPicker}
|
||||
title="使用选择目录批量下载"
|
||||
description={
|
||||
canDirectoryPicker
|
||||
? '通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。'
|
||||
: '当前浏览器不支持 showDirectoryPicker。'
|
||||
}
|
||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||
/>
|
||||
<div className="flex flex-col gap-3">
|
||||
{canDirectoryPicker && (
|
||||
<>
|
||||
<BatchOption
|
||||
id={idDir}
|
||||
checked={batch.directoryPicker}
|
||||
title="使用选择目录批量下载"
|
||||
description="通过 showDirectoryPicker 将解密文件直接写入所选目录(推荐,Chrome / Edge)。"
|
||||
onChange={(checked) => setBatch('directoryPicker', checked)}
|
||||
/>
|
||||
|
||||
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker && canDirectoryPicker ? '' : 'opacity-50'}`}>
|
||||
<BatchOption
|
||||
id={idRemember}
|
||||
checked={batch.rememberDirectory}
|
||||
disabled={!batch.directoryPicker || !canDirectoryPicker}
|
||||
title="记住输出目录"
|
||||
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
|
||||
onChange={(checked) => setBatch('rememberDirectory', checked)}
|
||||
/>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-base-content/70">{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-xs btn-ghost"
|
||||
disabled={!hasRememberedDir}
|
||||
onClick={() => void handleClearDirectory()}
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker ? '' : 'opacity-50'}`}>
|
||||
<BatchOption
|
||||
id={idRemember}
|
||||
checked={batch.rememberDirectory}
|
||||
disabled={!batch.directoryPicker}
|
||||
title="记住输出目录"
|
||||
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
|
||||
onChange={(checked) => setBatch('rememberDirectory', checked)}
|
||||
/>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-base-content/70">
|
||||
{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-xs btn-ghost"
|
||||
disabled={!hasRememberedDir}
|
||||
onClick={() => void handleClearDirectory()}
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{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>
|
||||
</>
|
||||
)}
|
||||
|
||||
<BatchOption
|
||||
id={idStreamZip}
|
||||
checked={batch.streamingZip && canStreamingZip}
|
||||
disabled={!canStreamingZip}
|
||||
dimmed={!canStreamingZip}
|
||||
title="流式生成 ZIP"
|
||||
description={
|
||||
canStreamingZip
|
||||
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
|
||||
: '当前浏览器不支持 showSaveFilePicker,无法流式写出 ZIP。'
|
||||
}
|
||||
onChange={(checked) => setBatch('streamingZip', checked)}
|
||||
/>
|
||||
{canDirectWrite && (
|
||||
<>
|
||||
<h3 className={`text-xl font-semibold mb-2 ${showBatchDownload ? 'mt-8' : ''}`}>解密后自动保存</h3>
|
||||
<p className="text-sm text-base-content/80 mb-4">解密完成后直接保存到本机,无需再手动下载。</p>
|
||||
|
||||
<BatchOption
|
||||
id={idBlobZip}
|
||||
checked={batch.blobZip}
|
||||
title="生成单个 ZIP 并触发下载"
|
||||
description={
|
||||
<>
|
||||
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
|
||||
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
|
||||
</>
|
||||
}
|
||||
onChange={(checked) => setBatch('blobZip', checked)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor={idOutputMode} className="font-medium">
|
||||
保存位置
|
||||
</label>
|
||||
<select
|
||||
id={idOutputMode}
|
||||
className="select select-bordered select-sm w-full max-w-md"
|
||||
value={directWrite.outputMode}
|
||||
onChange={(e) =>
|
||||
dispatch(updateDirectWriteSetting({ outputMode: e.target.value as DirectWriteOutputMode }))
|
||||
}
|
||||
>
|
||||
<option value="besideSource">原文件所在文件夹</option>
|
||||
<option value="fixedDirectory">指定文件夹</option>
|
||||
</select>
|
||||
<span className="text-sm text-base-content/70">
|
||||
{directWrite.outputMode === 'besideSource'
|
||||
? '解密后的文件保存在加密文件旁边。'
|
||||
: '解密后的文件保存到下方指定的文件夹。'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor={idFixedPath} className="font-medium">
|
||||
文件夹路径
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-2 max-w-xl">
|
||||
<input
|
||||
id={idFixedPath}
|
||||
type="text"
|
||||
className="input input-bordered input-sm min-w-0 flex-1"
|
||||
placeholder="/path/to/output"
|
||||
value={directWrite.fixedDirectoryPath ?? ''}
|
||||
disabled={directWrite.outputMode !== 'fixedDirectory'}
|
||||
onChange={(e) =>
|
||||
dispatch(
|
||||
updateDirectWriteSetting({ fixedDirectoryPath: e.target.value === '' ? null : e.target.value }),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-outline"
|
||||
disabled={pickingDirectory}
|
||||
onClick={() => void handlePickDirectory()}
|
||||
>
|
||||
{pickingDirectory ? '选择中…' : '选择文件夹'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BatchOption
|
||||
id={idDeleteSource}
|
||||
checked={directWrite.deleteSourceAfterDecrypt}
|
||||
title="保存成功后删除加密文件"
|
||||
description="仅在写出成功后删除;请先确认已有备份。"
|
||||
onChange={(checked) => dispatch(updateDirectWriteSetting({ deleteSourceAfterDecrypt: checked }))}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -119,15 +219,14 @@ type BatchOptionProps = {
|
||||
id: string;
|
||||
checked: boolean;
|
||||
disabled?: boolean;
|
||||
dimmed?: boolean;
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
onChange: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
function BatchOption({ id, checked, disabled, dimmed, title, description, onChange }: BatchOptionProps) {
|
||||
function BatchOption({ id, checked, disabled, title, description, onChange }: BatchOptionProps) {
|
||||
return (
|
||||
<label className={`flex items-start gap-2 ${dimmed ? 'opacity-50' : ''}`}>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { useId, useMemo, useState } from 'react';
|
||||
import { Navigate } from 'react-router';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
import { useAppDispatch } from '~/hooks';
|
||||
import { applyNativeImportResult } from '~/features/settings/applyNativeImportResult';
|
||||
import { commitStagingChange } from '~/features/settings/settingsSlice';
|
||||
import { hasOneClickImportCapability } from '~/features/settings/settingsTabs';
|
||||
import { AndroidImportType, NativeImportType } from '~/platform/capabilities';
|
||||
import { usePlatform } from '~/platform/PlatformContext';
|
||||
|
||||
const NATIVE_IMPORT_LABELS: Record<NativeImportType, string> = {
|
||||
[NativeImportType.QQMusic]: 'QQ 音乐',
|
||||
[NativeImportType.Kuwo]: '酷我音乐',
|
||||
[NativeImportType.Kugou]: '酷狗音乐',
|
||||
[NativeImportType.QingTing]: '蜻蜓 FM',
|
||||
};
|
||||
|
||||
function selectedFromCaps(types: readonly NativeImportType[]): Record<NativeImportType, boolean> {
|
||||
return {
|
||||
[NativeImportType.QQMusic]: types.includes(NativeImportType.QQMusic),
|
||||
[NativeImportType.Kuwo]: types.includes(NativeImportType.Kuwo),
|
||||
[NativeImportType.Kugou]: types.includes(NativeImportType.Kugou),
|
||||
[NativeImportType.QingTing]: types.includes(NativeImportType.QingTing),
|
||||
};
|
||||
}
|
||||
|
||||
export function PanelOneClick() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { capabilities, keys } = usePlatform();
|
||||
const nativeTypes = capabilities.nativeKeyAccess;
|
||||
const canAdb = capabilities.androidKeyAccess === AndroidImportType.Adb;
|
||||
const canShow = hasOneClickImportCapability(capabilities);
|
||||
|
||||
const [selected, setSelected] = useState(() => selectedFromCaps(nativeTypes));
|
||||
const [importingNative, setImportingNative] = useState(false);
|
||||
const [importingAdb, setImportingAdb] = useState(false);
|
||||
|
||||
const nativeTargets = useMemo(() => nativeTypes.filter((type) => selected[type]), [nativeTypes, selected]);
|
||||
|
||||
const idNative = useId();
|
||||
const idAdb = useId();
|
||||
|
||||
if (!canShow) {
|
||||
return <Navigate to="/settings/general" replace />;
|
||||
}
|
||||
|
||||
const finishImport = (count: number, emptyMessage: string) => {
|
||||
if (count === 0) {
|
||||
toast.info(emptyMessage);
|
||||
return;
|
||||
}
|
||||
dispatch(commitStagingChange());
|
||||
toast.success(`成功导入 ${count} 项密钥`);
|
||||
};
|
||||
|
||||
const handleImportNative = async () => {
|
||||
if (nativeTargets.length === 0) {
|
||||
toast.warning('请至少勾选一个客户端');
|
||||
return;
|
||||
}
|
||||
setImportingNative(true);
|
||||
try {
|
||||
const result = await keys.importNative(nativeTargets);
|
||||
finishImport(applyNativeImportResult(dispatch, result), '未导入到新密钥');
|
||||
} catch (e) {
|
||||
toast.error(`一键导入失败: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setImportingNative(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportAdb = async () => {
|
||||
setImportingAdb(true);
|
||||
try {
|
||||
const targets = nativeTargets.length > 0 ? nativeTargets : undefined;
|
||||
const result = await keys.importAndroidAdb({ targets });
|
||||
finishImport(applyNativeImportResult(dispatch, result), 'ADB 未导入到新密钥');
|
||||
} catch (e) {
|
||||
toast.error(`ADB 导入失败: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setImportingAdb(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-0 flex-col grow px-1">
|
||||
<h2 className="text-2xl font-bold mb-4">一键导入</h2>
|
||||
<p className="text-sm text-base-content/80 mb-4">
|
||||
从本机已安装的客户端读取密钥并立即保存生效。各格式页的「导入数据库…」仍可单独使用。
|
||||
</p>
|
||||
|
||||
{nativeTypes.length > 0 && (
|
||||
<section className="mb-8" aria-labelledby={idNative}>
|
||||
<h3 id={idNative} className="text-xl font-semibold mb-2">
|
||||
本机客户端
|
||||
</h3>
|
||||
<div className="flex flex-col gap-3 mb-4">
|
||||
{nativeTypes.map((type) => {
|
||||
const checkboxId = `${idNative}-${type}`;
|
||||
return (
|
||||
<label key={type} className="flex items-start gap-2" htmlFor={checkboxId}>
|
||||
<input
|
||||
id={checkboxId}
|
||||
type="checkbox"
|
||||
className="checkbox checkbox-sm mt-0.5"
|
||||
checked={selected[type]}
|
||||
onChange={(e) => setSelected((prev) => ({ ...prev, [type]: e.target.checked }))}
|
||||
/>
|
||||
<span className="font-medium">{NATIVE_IMPORT_LABELS[type]}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={importingNative || nativeTargets.length === 0}
|
||||
onClick={() => void handleImportNative()}
|
||||
>
|
||||
{importingNative ? '导入中…' : '开始导入'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{canAdb && (
|
||||
<section aria-labelledby={idAdb}>
|
||||
<h3 id={idAdb} className="text-xl font-semibold mb-2">
|
||||
Android ADB
|
||||
</h3>
|
||||
<p className="text-sm text-base-content/70 mb-4">
|
||||
通过 ADB 从已连接设备拉取密钥。若上方已勾选客户端,将仅导入对应格式;未勾选时导入全部支持项。
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-outline btn-sm"
|
||||
disabled={importingAdb}
|
||||
onClick={() => void handleImportAdb()}
|
||||
>
|
||||
{importingAdb ? '导入中…' : '从 ADB 导入'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
// TODO: Popup dialog for QingTing instructions
|
||||
@@ -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,14 +6,16 @@ import {
|
||||
setProductionChanges,
|
||||
ProductionSettings,
|
||||
DEFAULT_BATCH_DOWNLOAD_SETTINGS,
|
||||
DEFAULT_DIRECT_WRITE_SETTINGS,
|
||||
BatchDownloadSettings,
|
||||
DirectWriteSettings,
|
||||
} from './settingsSlice';
|
||||
import { enumObject } from '~/util/objects';
|
||||
import { getLogger } from '~/util/logUtils';
|
||||
import { parseKwm2ProductionKey } from './keyFormats';
|
||||
import { parseKwm2ProductionKey } from '~/features/kwm/types';
|
||||
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
|
||||
import { deepClone } from '~/util/deepClone';
|
||||
|
||||
const DEFAULT_STORAGE_KEY = 'um-react-settings';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
|
||||
function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
|
||||
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
|
||||
@@ -28,10 +30,29 @@ function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined):
|
||||
return result;
|
||||
}
|
||||
|
||||
function mergeSettings(settings: ProductionSettings): ProductionSettings {
|
||||
function mergeDirectWrite(source: Partial<DirectWriteSettings> | undefined): DirectWriteSettings {
|
||||
const result = { ...DEFAULT_DIRECT_WRITE_SETTINGS };
|
||||
if (!source) {
|
||||
return result;
|
||||
}
|
||||
if (source.outputMode === 'besideSource' || source.outputMode === 'fixedDirectory') {
|
||||
result.outputMode = source.outputMode;
|
||||
}
|
||||
if (source.fixedDirectoryPath === null || typeof source.fixedDirectoryPath === 'string') {
|
||||
result.fixedDirectoryPath = source.fixedDirectoryPath;
|
||||
}
|
||||
if (typeof source.deleteSourceAfterDecrypt === 'boolean') {
|
||||
result.deleteSourceAfterDecrypt = source.deleteSourceAfterDecrypt;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Normalize / sanitize loaded production settings against defaults. Exported for tests. */
|
||||
export function mergeSettings(settings: ProductionSettings): ProductionSettings {
|
||||
const draft = deepClone(settingsSlice.getInitialState().production);
|
||||
|
||||
draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload);
|
||||
draft.general.directWrite = mergeDirectWrite(settings?.general?.directWrite);
|
||||
|
||||
if (settings?.qmc2) {
|
||||
const { allowFuzzyNameSearch, keys } = settings.qmc2;
|
||||
@@ -67,34 +88,53 @@ function mergeSettings(settings: ProductionSettings): ProductionSettings {
|
||||
}
|
||||
|
||||
if (typeof settings?.qtfm?.android === 'string') {
|
||||
draft.qtfm.android = settings.qtfm.android.replace(/[^0-9a-fA-F]/g, '');
|
||||
draft.qtfm.android = sanitizeQtfmAndroidKey(settings.qtfm.android);
|
||||
}
|
||||
|
||||
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 cancelled = false;
|
||||
|
||||
try {
|
||||
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(
|
||||
const unsubscribe = store.subscribe(
|
||||
debounce({ delay: 150 }, () => {
|
||||
const currentSettings = store.getState().settings.production;
|
||||
if (lastSettings !== currentSettings) {
|
||||
lastSettings = currentSettings;
|
||||
localStorage.setItem(storageKey, JSON.stringify(currentSettings));
|
||||
getLogger().debug('settings saved');
|
||||
void provider.settings.save(currentSettings).then(
|
||||
() => 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();
|
||||
};
|
||||
}
|
||||
@@ -1,71 +1,19 @@
|
||||
import type { RootState } from '~/store';
|
||||
import { closestByLevenshtein } from '~/util/levenshtein';
|
||||
import { hasOwn } from '~/util/objects';
|
||||
import { kwm2StagingToProductionKey } from './keyFormats';
|
||||
import type { ParseKugouHeaderResponse, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
|
||||
|
||||
/** Re-exports format key lookups so callers can keep a single settings import if desired. */
|
||||
export {
|
||||
selectFinalQMCv2Settings,
|
||||
selectQMCv2KeyByFileName,
|
||||
selectStagingQMCv2Settings,
|
||||
} from '~/features/qmc/keyLookup';
|
||||
export { selectFinalKWMv2Keys, selectKWMv2Key, selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
|
||||
export { selectFinalKugouV5Keys, selectKugouKey, selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
|
||||
export { selectQtfmAndroidKey, selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
|
||||
|
||||
export const selectIsSettingsNotSaved = (state: RootState) => state.settings.dirty;
|
||||
|
||||
export const selectStagingQMCv2Settings = (state: RootState) => state.settings.staging.qmc2;
|
||||
export const selectFinalQMCv2Settings = (state: RootState) => state.settings.production.qmc2;
|
||||
|
||||
export const selectStagingKWMv2Keys = (state: RootState) => state.settings.staging.kwm2.keys;
|
||||
export const selectFinalKWMv2Keys = (state: RootState) => state.settings.production.kwm2.keys;
|
||||
|
||||
export const selectStagingKugouV5Keys = (state: RootState) => state.settings.staging.kugou.keys;
|
||||
export const selectFinalKugouV5Keys = (state: RootState) => state.settings.production.kugou.keys;
|
||||
|
||||
export const selectQMCv2KeyByFileName = (state: RootState, name: string): string | undefined => {
|
||||
const normalizedName = name.normalize();
|
||||
|
||||
let ekey: string | undefined;
|
||||
const { keys, allowFuzzyNameSearch } = selectFinalQMCv2Settings(state);
|
||||
if (hasOwn(keys, normalizedName)) {
|
||||
ekey = keys[normalizedName];
|
||||
} else if (allowFuzzyNameSearch) {
|
||||
const qmc2KeyStoreNames = Object.keys(keys);
|
||||
if (qmc2KeyStoreNames.length > 0) {
|
||||
const closestName = closestByLevenshtein(normalizedName, qmc2KeyStoreNames);
|
||||
console.debug('qmc2: key db could not find %o, using closest %o instead.', normalizedName, closestName);
|
||||
ekey = keys[closestName];
|
||||
}
|
||||
}
|
||||
|
||||
return ekey;
|
||||
};
|
||||
|
||||
export const selectKWMv2Key = (state: RootState, hdr: ParseKuwoHeaderResponse): string | undefined => {
|
||||
if (!hdr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const quality = String(hdr.qualityId);
|
||||
const rid = String(hdr.resourceId);
|
||||
|
||||
const keys = selectFinalKWMv2Keys(state);
|
||||
const lookupKey = kwm2StagingToProductionKey({ id: '', ekey: '', quality, rid });
|
||||
|
||||
let ekey: string | undefined;
|
||||
if (hasOwn(keys, lookupKey)) {
|
||||
ekey = keys[lookupKey];
|
||||
}
|
||||
|
||||
return ekey;
|
||||
};
|
||||
|
||||
export const selectKugouKey = (state: RootState, hdr: ParseKugouHeaderResponse): string | undefined => {
|
||||
if (!hdr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = selectFinalKugouV5Keys(state);
|
||||
const lookupKey = hdr.audioHash;
|
||||
|
||||
return hasOwn(keys, lookupKey) ? keys[lookupKey] : undefined;
|
||||
};
|
||||
|
||||
export const selectStagingQtfmAndroidKey = (state: RootState) => state.settings.staging.qtfm.android;
|
||||
export const selectQtfmAndroidKey = (state: RootState) => state.settings.production.qtfm.android;
|
||||
|
||||
export const selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
|
||||
export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.general.batchDownload;
|
||||
|
||||
export const selectStagingDirectWriteSettings = (state: RootState) => state.settings.staging.general.directWrite;
|
||||
export const selectFinalDirectWriteSettings = (state: RootState) => state.settings.production.general.directWrite;
|
||||
@@ -1,25 +1,29 @@
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
import type { PayloadAction } from '@reduxjs/toolkit';
|
||||
import { nanoid } from 'nanoid';
|
||||
import {
|
||||
ProductionKWMv2Keys,
|
||||
ProductionQMCv2Keys,
|
||||
StagingKWMv2Key,
|
||||
StagingQMCv2Key,
|
||||
kwm2ProductionToStaging,
|
||||
kwm2StagingToProductionKey,
|
||||
kwm2StagingToProductionValue,
|
||||
productionKeyToStaging,
|
||||
type ProductionQMCv2Keys,
|
||||
type StagingQMCv2Key,
|
||||
qmc2ProductionToStaging,
|
||||
qmc2StagingToProductionKey,
|
||||
qmc2StagingToProductionValue,
|
||||
stagingKeyToProduction,
|
||||
ProductionKugouKey,
|
||||
} from '~/features/qmc/types';
|
||||
import {
|
||||
type ProductionKWMv2Keys,
|
||||
type StagingKWMv2Key,
|
||||
kwm2ProductionToStaging,
|
||||
kwm2StagingToProductionKey,
|
||||
kwm2StagingToProductionValue,
|
||||
} from '~/features/kwm/types';
|
||||
import {
|
||||
type ProductionKugouKey,
|
||||
type StagingKugouKey,
|
||||
kugouProductionToStaging,
|
||||
kugouStagingToProductionKey,
|
||||
kugouStagingToProductionValue,
|
||||
StagingKugouKey,
|
||||
} from './keyFormats';
|
||||
} from '~/features/kugou/types';
|
||||
import { EMPTY_QTFM_SETTINGS, type ProductionQtfmSettings, type StagingQtfmSettings } from '~/features/qtfm/types';
|
||||
import { productionKeyToStaging, stagingKeyToProduction } from './keyFormats';
|
||||
import { createKeyListReducers } from './createKeyListReducers';
|
||||
|
||||
export interface BatchDownloadSettings {
|
||||
directoryPicker: boolean;
|
||||
@@ -28,9 +32,20 @@ export interface BatchDownloadSettings {
|
||||
blobZip: boolean;
|
||||
}
|
||||
|
||||
/** Where native clients write decrypted files (gated by `capabilities.directFsAccess`). */
|
||||
export type DirectWriteOutputMode = 'besideSource' | 'fixedDirectory';
|
||||
|
||||
export interface DirectWriteSettings {
|
||||
outputMode: DirectWriteOutputMode;
|
||||
/** Absolute path when `outputMode` is `fixedDirectory`; unused in the browser UI. */
|
||||
fixedDirectoryPath: string | null;
|
||||
deleteSourceAfterDecrypt: boolean;
|
||||
}
|
||||
|
||||
export interface StagingSettings {
|
||||
general: {
|
||||
batchDownload: BatchDownloadSettings;
|
||||
directWrite: DirectWriteSettings;
|
||||
};
|
||||
qmc2: {
|
||||
keys: StagingQMCv2Key[];
|
||||
@@ -39,17 +54,20 @@ export interface StagingSettings {
|
||||
kwm2: {
|
||||
keys: StagingKWMv2Key[];
|
||||
};
|
||||
/**
|
||||
* KuGou / KGG keys.
|
||||
* UI route tab id is `kgg`; Redux / production persist key remains `kugou`.
|
||||
*/
|
||||
kugou: {
|
||||
keys: StagingKugouKey[];
|
||||
};
|
||||
qtfm: {
|
||||
android: string;
|
||||
};
|
||||
qtfm: StagingQtfmSettings;
|
||||
}
|
||||
|
||||
export interface ProductionSettings {
|
||||
general: {
|
||||
batchDownload: BatchDownloadSettings;
|
||||
directWrite: DirectWriteSettings;
|
||||
};
|
||||
qmc2: {
|
||||
keys: ProductionQMCv2Keys; // { [fileName]: ekey }
|
||||
@@ -58,12 +76,14 @@ export interface ProductionSettings {
|
||||
kwm2: {
|
||||
keys: ProductionKWMv2Keys; // { [`${rid}-${quality}`]: ekey }
|
||||
};
|
||||
/**
|
||||
* KuGou / KGG keys.
|
||||
* UI route tab id is `kgg`; localStorage production shape key remains `kugou` (do not rename).
|
||||
*/
|
||||
kugou: {
|
||||
keys: ProductionKugouKey; // { [fileName]: ekey }
|
||||
};
|
||||
qtfm: {
|
||||
android: string;
|
||||
};
|
||||
qtfm: ProductionQtfmSettings;
|
||||
}
|
||||
|
||||
export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = {
|
||||
@@ -73,6 +93,12 @@ export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = {
|
||||
blobZip: true,
|
||||
};
|
||||
|
||||
export const DEFAULT_DIRECT_WRITE_SETTINGS: DirectWriteSettings = {
|
||||
outputMode: 'besideSource',
|
||||
fixedDirectoryPath: null,
|
||||
deleteSourceAfterDecrypt: false,
|
||||
};
|
||||
|
||||
export interface SettingsState {
|
||||
dirty: boolean;
|
||||
staging: StagingSettings;
|
||||
@@ -82,24 +108,31 @@ export interface SettingsState {
|
||||
const initialState: SettingsState = {
|
||||
dirty: false,
|
||||
staging: {
|
||||
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
|
||||
general: {
|
||||
batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS },
|
||||
directWrite: { ...DEFAULT_DIRECT_WRITE_SETTINGS },
|
||||
},
|
||||
qmc2: { allowFuzzyNameSearch: true, keys: [] },
|
||||
kwm2: { keys: [] },
|
||||
qtfm: { android: '' },
|
||||
qtfm: { ...EMPTY_QTFM_SETTINGS },
|
||||
kugou: { keys: [] },
|
||||
},
|
||||
production: {
|
||||
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
|
||||
general: {
|
||||
batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS },
|
||||
directWrite: { ...DEFAULT_DIRECT_WRITE_SETTINGS },
|
||||
},
|
||||
qmc2: { allowFuzzyNameSearch: true, keys: {} },
|
||||
kwm2: { keys: {} },
|
||||
kugou: { keys: {} },
|
||||
qtfm: { android: '' },
|
||||
qtfm: { ...EMPTY_QTFM_SETTINGS },
|
||||
},
|
||||
};
|
||||
|
||||
const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
|
||||
export const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
|
||||
general: {
|
||||
batchDownload: { ...staging.general.batchDownload },
|
||||
directWrite: { ...staging.general.directWrite },
|
||||
},
|
||||
qmc2: {
|
||||
keys: stagingKeyToProduction(staging.qmc2.keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue),
|
||||
@@ -114,9 +147,10 @@ const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
|
||||
qtfm: staging.qtfm,
|
||||
});
|
||||
|
||||
const productionToStaging = (production: ProductionSettings): StagingSettings => ({
|
||||
export const productionToStaging = (production: ProductionSettings): StagingSettings => ({
|
||||
general: {
|
||||
batchDownload: { ...production.general.batchDownload },
|
||||
directWrite: { ...production.general.directWrite },
|
||||
},
|
||||
qmc2: {
|
||||
keys: productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging),
|
||||
@@ -131,6 +165,10 @@ const productionToStaging = (production: ProductionSettings): StagingSettings =>
|
||||
qtfm: production.qtfm,
|
||||
});
|
||||
|
||||
const qmc2KeyList = createKeyListReducers('qmc2', () => ({ name: '', ekey: '' }));
|
||||
const kwm2KeyList = createKeyListReducers('kwm2', () => ({ ekey: '', quality: '', rid: '' }));
|
||||
const kugouKeyList = createKeyListReducers('kugou', () => ({ audioHash: '', ekey: '' }));
|
||||
|
||||
export const settingsSlice = createSlice({
|
||||
name: 'settings',
|
||||
initialState,
|
||||
@@ -142,96 +180,25 @@ export const settingsSlice = createSlice({
|
||||
staging: productionToStaging(payload),
|
||||
};
|
||||
},
|
||||
//
|
||||
qmc2AddKey(state) {
|
||||
state.staging.qmc2.keys.push({ id: nanoid(), name: '', ekey: '' });
|
||||
state.dirty = true;
|
||||
},
|
||||
qmc2ImportKeys(state, { payload }: PayloadAction<Omit<StagingQMCv2Key, 'id'>[]>) {
|
||||
const newItems = payload.map((item) => ({ id: nanoid(), ...item }));
|
||||
state.staging.qmc2.keys.push(...newItems);
|
||||
state.dirty = true;
|
||||
},
|
||||
qmc2DeleteKey(state, { payload: { id } }: PayloadAction<{ id: string }>) {
|
||||
const qmc2 = state.staging.qmc2;
|
||||
qmc2.keys = qmc2.keys.filter((item) => item.id !== id);
|
||||
state.dirty = true;
|
||||
},
|
||||
qmc2UpdateKey(
|
||||
state,
|
||||
{ payload: { id, field, value } }: PayloadAction<{ id: string; field: keyof StagingQMCv2Key; value: string }>,
|
||||
) {
|
||||
const keyItem = state.staging.qmc2.keys.find((item) => item.id === id);
|
||||
if (keyItem) {
|
||||
keyItem[field] = value;
|
||||
state.dirty = true;
|
||||
}
|
||||
},
|
||||
qmc2ClearKeys(state) {
|
||||
state.staging.qmc2.keys = [];
|
||||
state.dirty = true;
|
||||
},
|
||||
qmc2AddKey: qmc2KeyList.addKey,
|
||||
qmc2ImportKeys: qmc2KeyList.importKeys,
|
||||
qmc2DeleteKey: qmc2KeyList.deleteKey,
|
||||
qmc2UpdateKey: qmc2KeyList.updateKey,
|
||||
qmc2ClearKeys: qmc2KeyList.clearKeys,
|
||||
qmc2AllowFuzzyNameSearch(state, { payload: { enable } }: PayloadAction<{ enable: boolean }>) {
|
||||
state.staging.qmc2.allowFuzzyNameSearch = enable;
|
||||
state.dirty = true;
|
||||
},
|
||||
// TODO: reuse the logic somehow?
|
||||
kwm2AddKey(state) {
|
||||
state.staging.kwm2.keys.push({ id: nanoid(), ekey: '', quality: '', rid: '' });
|
||||
state.dirty = true;
|
||||
},
|
||||
kwm2ImportKeys(state, { payload }: PayloadAction<Omit<StagingKWMv2Key, 'id'>[]>) {
|
||||
const newItems = payload.map((item) => ({ id: nanoid(), ...item }));
|
||||
state.staging.kwm2.keys.push(...newItems);
|
||||
state.dirty = true;
|
||||
},
|
||||
kwm2DeleteKey(state, { payload: { id } }: PayloadAction<{ id: string }>) {
|
||||
const kwm2 = state.staging.kwm2;
|
||||
kwm2.keys = kwm2.keys.filter((item) => item.id !== id);
|
||||
state.dirty = true;
|
||||
},
|
||||
kwm2UpdateKey(
|
||||
state,
|
||||
{ payload: { id, field, value } }: PayloadAction<{ id: string; field: keyof StagingKWMv2Key; value: string }>,
|
||||
) {
|
||||
const keyItem = state.staging.kwm2.keys.find((item) => item.id === id);
|
||||
if (keyItem) {
|
||||
keyItem[field] = value;
|
||||
state.dirty = true;
|
||||
}
|
||||
},
|
||||
kwm2ClearKeys(state) {
|
||||
state.staging.kwm2.keys = [];
|
||||
state.dirty = true;
|
||||
},
|
||||
kugouAddKey(state) {
|
||||
state.staging.kugou.keys.push({ id: nanoid(), audioHash: '', ekey: '' });
|
||||
state.dirty = true;
|
||||
},
|
||||
kugouImportKeys(state, { payload }: PayloadAction<Omit<StagingKugouKey, 'id'>[]>) {
|
||||
const newItems = payload.map((item) => ({ id: nanoid(), ...item }));
|
||||
state.staging.kugou.keys.push(...newItems);
|
||||
state.dirty = true;
|
||||
},
|
||||
kugouDeleteKey(state, { payload: { id } }: PayloadAction<{ id: string }>) {
|
||||
const kugou = state.staging.kugou;
|
||||
kugou.keys = kugou.keys.filter((item) => item.id !== id);
|
||||
state.dirty = true;
|
||||
},
|
||||
kugouUpdateKey(
|
||||
state,
|
||||
{ payload: { id, field, value } }: PayloadAction<{ id: string; field: keyof StagingKugouKey; value: string }>,
|
||||
) {
|
||||
const keyItem = state.staging.kugou.keys.find((item) => item.id === id);
|
||||
if (keyItem) {
|
||||
keyItem[field] = value;
|
||||
state.dirty = true;
|
||||
}
|
||||
},
|
||||
kugouClearKeys(state) {
|
||||
state.staging.kugou.keys = [];
|
||||
state.dirty = true;
|
||||
},
|
||||
kwm2AddKey: kwm2KeyList.addKey,
|
||||
kwm2ImportKeys: kwm2KeyList.importKeys,
|
||||
kwm2DeleteKey: kwm2KeyList.deleteKey,
|
||||
kwm2UpdateKey: kwm2KeyList.updateKey,
|
||||
kwm2ClearKeys: kwm2KeyList.clearKeys,
|
||||
kugouAddKey: kugouKeyList.addKey,
|
||||
kugouImportKeys: kugouKeyList.importKeys,
|
||||
kugouDeleteKey: kugouKeyList.deleteKey,
|
||||
kugouUpdateKey: kugouKeyList.updateKey,
|
||||
kugouClearKeys: kugouKeyList.clearKeys,
|
||||
qtfmAndroidUpdateKey(state, { payload: { deviceKey } }: PayloadAction<{ deviceKey: string }>) {
|
||||
state.staging.qtfm.android = deviceKey;
|
||||
state.dirty = true;
|
||||
@@ -243,19 +210,21 @@ export const settingsSlice = createSlice({
|
||||
state.staging.general.batchDownload[key] = value;
|
||||
state.dirty = true;
|
||||
},
|
||||
//
|
||||
updateDirectWriteSetting(state, { payload }: PayloadAction<Partial<DirectWriteSettings>>) {
|
||||
state.staging.general.directWrite = {
|
||||
...state.staging.general.directWrite,
|
||||
...payload,
|
||||
};
|
||||
state.dirty = true;
|
||||
},
|
||||
discardStagingChanges: (state) => {
|
||||
state.dirty = false;
|
||||
state.staging = productionToStaging(state.production);
|
||||
},
|
||||
/** Apply staging → production. Staging list row `id`s are kept (no productionToStaging round-trip). */
|
||||
commitStagingChange: (state) => {
|
||||
const production = stagingToProduction(state.staging);
|
||||
return {
|
||||
dirty: false,
|
||||
// Sync back to staging
|
||||
staging: productionToStaging(production),
|
||||
production,
|
||||
};
|
||||
state.production = stagingToProduction(state.staging);
|
||||
state.dirty = false;
|
||||
},
|
||||
resetConfig: () => {
|
||||
return initialState;
|
||||
@@ -288,6 +257,7 @@ export const {
|
||||
|
||||
qtfmAndroidUpdateKey,
|
||||
updateBatchDownloadSetting,
|
||||
updateDirectWriteSetting,
|
||||
|
||||
commitStagingChange,
|
||||
discardStagingChanges,
|
||||
|
||||
@@ -1,14 +1,55 @@
|
||||
import type { FC } from 'react';
|
||||
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
|
||||
import { PanelQMCv2Key } from '~/features/settings/panels/PanelQMCv2Key.tsx';
|
||||
import { PanelKWMv2Key } from '~/features/settings/panels/PanelKWMv2Key.tsx';
|
||||
import { PanelKGGKey } from '~/features/settings/panels/PanelKGGKey.tsx';
|
||||
import { PanelQingTing } from '~/features/settings/panels/PanelQingTing.tsx';
|
||||
import { PanelOneClick } from '~/features/settings/panels/PanelOneClick.tsx';
|
||||
import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
|
||||
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
|
||||
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
|
||||
import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
||||
import { AndroidImportType } from '~/platform/capabilities';
|
||||
import type { PlatformCapabilities } from '~/platform/types';
|
||||
|
||||
export const SETTINGS_TABS: Record<string, { name: string; Tab: FC }> = {
|
||||
export type SettingsTabDef = { name: string; Tab: FC };
|
||||
|
||||
/**
|
||||
* Settings UI route ids → panels.
|
||||
*
|
||||
* Naming aliases (route vs Redux / persist):
|
||||
* - `qmc` ↔ state `qmc2`
|
||||
* - `kwm` ↔ state `kwm2`
|
||||
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
|
||||
* - `qtfm` ↔ state `qtfm`
|
||||
* - `one-click` ↔ platform native / ADB key import (only when capable)
|
||||
*/
|
||||
export const ONE_CLICK_TAB_ID = 'one-click';
|
||||
|
||||
const CORE_SETTINGS_TABS: Record<string, SettingsTabDef> = {
|
||||
general: { name: '通用设置', Tab: PanelGeneral },
|
||||
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
|
||||
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
|
||||
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
|
||||
qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing },
|
||||
} as const;
|
||||
};
|
||||
|
||||
const ONE_CLICK_TAB: SettingsTabDef = { name: '一键导入', Tab: PanelOneClick };
|
||||
|
||||
/** True when the platform can show the one-click import settings tab. */
|
||||
export function hasOneClickImportCapability(capabilities: PlatformCapabilities): boolean {
|
||||
return capabilities.nativeKeyAccess.length > 0 || capabilities.androidKeyAccess === AndroidImportType.Adb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings tabs for the current platform.
|
||||
* Registers `one-click` only when `nativeKeyAccess` or ADB import is available.
|
||||
*/
|
||||
export function getSettingsTabs(capabilities: PlatformCapabilities): Record<string, SettingsTabDef> {
|
||||
if (!hasOneClickImportCapability(capabilities)) {
|
||||
return CORE_SETTINGS_TABS;
|
||||
}
|
||||
|
||||
const { general, ...rest } = CORE_SETTINGS_TABS;
|
||||
return {
|
||||
general,
|
||||
[ONE_CLICK_TAB_ID]: ONE_CLICK_TAB,
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
+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 { RootState, AppDispatch } from './store';
|
||||
import type { RootState, AppDispatch, AppStore } from './store';
|
||||
|
||||
export const useAppDispatch: () => AppDispatch = useDispatch;
|
||||
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',
|
||||
}
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user