5 Commits
Author SHA1 Message Date
鲁树人 d86323e38a docs: add AGENTS.md for Unlock Music project overview and setup instructions
- Introduced a new AGENTS.md file detailing the architecture, quick start guide, and directory layout for the Unlock Music project.
- Included comprehensive sections on features, settings model, and guidelines for adding or changing music formats.
- Documented tooling considerations and testing practices to aid developers in contributing to the project.
2026-11-01 02:58:09 +09:00
鲁树人 4a7994df96 feat: introduce worker action types and refactor decryption handling
- Added a new `actions.ts` file defining `WorkerActionMap` for better type management of worker actions.
- Updated `client.ts`, `worker.ts`, and `decrypt.ts` to utilize the new action types, enhancing type safety.
- Refactored `DecryptCommandPayload` to rename `id` to `fileId` for clarity and consistency.
- Adjusted various components to align with the new payload structure and improved error handling in the worker event bus.
- Enhanced tests to ensure compatibility with the new action type definitions and payload structures.
2026-11-01 02:55:30 +09:00
鲁树人 7a11d4f941 refactor: reorganize Kugou and Kuwo imports, add key management features
- Updated import paths for Kugou and Kuwo instructions to reflect new directory structure.
- Introduced new key management functionalities for Kugou, including key import and selection logic.
- Added comprehensive instructions for both Kugou and Kuwo key handling across various platforms.
- Implemented Redux selectors for managing staging and production keys for Kugou and Kuwo.
- Enhanced documentation and tests for new features and key management processes.
2026-11-01 02:42:13 +09:00
鲁树人 a9a937bc5e docs: enhance comments and documentation for KuGou/KGG settings
- Added detailed comments and documentation for KuGou/KGG key formats and settings in keyFormats.ts, persistSettings.ts, settingsSelector.ts, settingsSlice.ts, and settingsTabs.tsx.
- Improved clarity on UI route identifiers and Redux persist keys for better understanding and maintenance.
2026-10-31 23:37:55 +09:00
鲁树人 75d786c747 fix: clamp payload length in MMKVParser to prevent overflow
- Updated the MMKVParser to ensure the calculated length does not exceed the DataView's byte length.
- Added tests to verify behavior at the payload boundary, including cases for oversized payloads and exact matches.
2026-10-27 09:01:42 +09:00
70 changed files with 1152 additions and 467 deletions

No files matched your search

+156
View File
@@ -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.
+21
View File
@@ -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;
+2 -2
View File
@@ -1,5 +1,5 @@
import { WorkerClientBus } from '~/util/WorkerEventBus'; import { WorkerClientBus } from '~/util/WorkerEventBus';
import { DECRYPTION_WORKER_ACTION_NAME } from './constants'; import type { WorkerActionMap } from './actions';
import { DecryptionQueue } from '~/util/DecryptionQueue'; import { DecryptionQueue } from '~/util/DecryptionQueue';
// TODO: Worker pool? // 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. // FIXME: report the error so is obvious to the user.
workerClient.addEventListener('error', console.error); 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); export const decryptionQueue = new DecryptionQueue(workerClientBus);
+1 -1
View File
@@ -12,7 +12,7 @@ export class KuwoMusicDecipher implements DecipherInstance {
try { try {
header = KuwoHeader.parse(buffer.subarray(0, 0x400)); 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)); const audioBuffer = new Uint8Array(buffer.subarray(0x400));
for (const [block, offset] of chunkBuffer(audioBuffer)) { for (const [block, offset] of chunkBuffer(audioBuffer)) {
+2 -2
View File
@@ -1,13 +1,13 @@
export interface DecryptCommandOptions { export interface DecryptCommandOptions {
fileName: string; fileName: string;
qmc2Key?: string; qmc2Key?: string;
kwm2key?: string; kwm2Key?: string;
kugouKey?: string; kugouKey?: string;
qingTingAndroidKey?: string; qingTingAndroidKey?: string;
} }
export interface DecryptCommandPayload { export interface DecryptCommandPayload {
id: string; fileId: string;
blobURI: string; blobURI: string;
options: DecryptCommandOptions; options: DecryptCommandOptions;
} }
+2 -1
View File
@@ -1,4 +1,5 @@
import { WorkerServerBus } from '~/util/WorkerEventBus'; import { WorkerServerBus } from '~/util/WorkerEventBus';
import type { WorkerActionMap } from './actions';
import { DECRYPTION_WORKER_ACTION_NAME } from './constants'; import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
import { getUmcVersion } from '@unlock-music/crypto'; 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 { workerParseKuwoHeader } from '~/decrypt-worker/worker/kuwo_header_parse.ts';
import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts'; import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts';
const bus = new WorkerServerBus(); const bus = new WorkerServerBus<WorkerActionMap>();
onmessage = bus.onmessage; onmessage = bus.onmessage;
bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler); bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler);
+3 -4
View File
@@ -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; await umCryptoReady;
const id = payloadId.replace('://', ':'); const label = `decrypt(${fileId})`;
const label = `decrypt(${id})`;
return withTimeGroupedLogs(label, async () => { return withTimeGroupedLogs(label, async () => {
const buffer = await fetch(blobURI).then((r) => r.arrayBuffer()); 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); return handler.decrypt(allCryptoFactories);
}); });
}; };
+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers'; import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions'; 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'; import { RiErrorWarningLine } from 'react-icons/ri';
export function KugouFAQ() { export function KugouFAQ() {
+1 -1
View File
@@ -2,7 +2,7 @@ import { Header2, Header3 } from '~/components/HelpText/Headers';
import { VQuote } from '~/components/HelpText/VQuote'; import { VQuote } from '~/components/HelpText/VQuote';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer'; import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { HiWord } from '~/components/HelpText/HiWord'; 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 { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { RiErrorWarningLine } from 'react-icons/ri'; import { RiErrorWarningLine } from 'react-icons/ri';
+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers'; import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer'; import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { QMCv2QQMusicAllInstructions } from '~/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions'; import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
export function QQMusicFAQ() { export function QQMusicFAQ() {
return ( return (
+14 -25
View File
@@ -3,22 +3,13 @@ import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import type { RootState } from '~/store'; import type { RootState } from '~/store';
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants'; import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
import type { import type { DecryptCommandOptions } from '~/decrypt-worker/types';
DecryptCommandOptions,
FetchMusicExNamePayload,
ParseKugouHeaderPayload,
ParseKugouHeaderResponse,
ParseKuwoHeaderPayload,
ParseKuwoHeaderResponse,
} from '~/decrypt-worker/types';
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client'; import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError'; import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
import { import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
selectKugouKey, import { selectKWMv2Key } from '~/features/kwm/keyLookup';
selectKWMv2Key, import { selectKugouKey } from '~/features/kugou/keyLookup';
selectQMCv2KeyByFileName, import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
selectQtfmAndroidKey,
} from '../settings/settingsSelector';
import { cleanFilename } from '~/util/cleanFilename'; import { cleanFilename } from '~/util/cleanFilename';
export enum ProcessState { export enum ProcessState {
@@ -80,27 +71,25 @@ export const processFile = createAsyncThunk<
}; };
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([ const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
workerClientBus.request<string, FetchMusicExNamePayload>(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, { workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
blobURI: file.raw,
}),
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
blobURI: file.raw,
}),
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
blobURI: file.raw, 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 = { const options: DecryptCommandOptions = {
fileName: file.fileName, fileName: file.fileName,
qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName), qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName),
kwm2key: selectKWMv2Key(state, kuwoHdr), kwm2Key: selectKWMv2Key(state, kuwoHdr),
kugouKey: selectKugouKey(state, kugouHdr), kugouKey: selectKugouKey(state, kugouHdr),
qingTingAndroidKey: selectQtfmAndroidKey(state), qingTingAndroidKey: selectQtfmAndroidKey(state),
}; };
return decryptionQueue.add({ id: fileId, blobURI: file.raw, options }, onPreProcess); return decryptionQueue.add({ fileId, blobURI: file.raw, options }, onPreProcess);
}); });
export const fileListingSlice = createSlice({ 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();
});
});
+15
View File
@@ -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;
}
+19
View File
@@ -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;
};
@@ -1,7 +1,7 @@
import { kugouDeleteKey, kugouUpdateKey } from '../../settingsSlice'; import { kugouDeleteKey, kugouUpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks'; import { useAppDispatch } from '~/hooks';
import { memo } from 'react'; import { memo } from 'react';
import { StagingKugouKey } from '../../keyFormats'; import type { StagingKugouKey } from '~/features/kugou/types';
import { KeyInput } from '~/components/KeyInput'; import { KeyInput } from '~/components/KeyInput';
export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => { export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => {
@@ -2,15 +2,12 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal'; import { ImportSecretModal } from '~/components/ImportSecretModal';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '~/features/settings/settingsSlice';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '../settingsSlice'; import { selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
import { selectStagingKugouV5Keys } from '../settingsSelector';
import type { StagingKugouKey } from '../keyFormats';
import { AddKey } from '~/components/AddKey.tsx'; import { AddKey } from '~/components/AddKey.tsx';
import { KugouEKeyItem } from '~/features/settings/panels/Kugou/KugouEKeyItem.tsx'; import { KugouEKeyItem } from './KugouEKeyItem';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx'; import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou.ts'; import { importKugouKeysFromFile } from '~/features/kugou/importKeys';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor.ts';
import { KeyListContainer } from '~/components/KeyListContainer'; import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult'; import { toastImportResult } from '~/util/toastImportResult';
@@ -22,13 +19,7 @@ export function PanelKGGKey() {
const addKey = () => dispatch(kugouAddKey()); const addKey = () => dispatch(kugouAddKey());
const clearAll = () => dispatch(kugouClearKeys()); const clearAll = () => dispatch(kugouClearKeys());
const handleSecretImport = async (file: File) => { const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKugouKey, 'id'>[] | null = null; const keys = await importKugouKeysFromFile(file);
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());
}
if (keys && keys.length > 0) { if (keys && keys.length > 0) {
dispatch(kugouImportKeys(keys)); dispatch(kugouImportKeys(keys));
+22
View File
@@ -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();
});
});
+13
View File
@@ -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;
}
+26
View File
@@ -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;
};
@@ -1,8 +1,8 @@
import { PiFileAudio, PiHash } from 'react-icons/pi'; import { PiFileAudio, PiHash } from 'react-icons/pi';
import { kwm2DeleteKey, kwm2UpdateKey } from '../../settingsSlice'; import { kwm2DeleteKey, kwm2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks'; import { useAppDispatch } from '~/hooks';
import { memo } from 'react'; import { memo } from 'react';
import { StagingKWMv2Key } from '../../keyFormats'; import type { StagingKWMv2Key } from '~/features/kwm/types';
import { KeyInput } from '~/components/KeyInput'; import { KeyInput } from '~/components/KeyInput';
export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => { export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => {
@@ -2,13 +2,11 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal'; import { ImportSecretModal } from '~/components/ImportSecretModal';
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo'; import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '../settingsSlice'; import { KWMv2EKeyItem } from './KWMv2EKeyItem';
import { selectStagingKWMv2Keys } from '../settingsSelector'; import { importKWMv2KeysFromFile } from '~/features/kwm/importKeys';
import { KWMv2EKeyItem } from './KWMv2/KWMv2EKeyItem'; import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import type { StagingKWMv2Key } from '../keyFormats';
import { KWMv2AllInstructions } from './KWMv2/KWMv2AllInstructions';
import { AddKey } from '~/components/AddKey'; import { AddKey } from '~/components/AddKey';
import { KeyListContainer } from '~/components/KeyListContainer'; import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult'; import { toastImportResult } from '~/util/toastImportResult';
@@ -21,12 +19,7 @@ export function PanelKWMv2Key() {
const addKey = () => dispatch(kwm2AddKey()); const addKey = () => dispatch(kwm2AddKey());
const clearAll = () => dispatch(kwm2ClearKeys()); const clearAll = () => dispatch(kwm2ClearKeys());
const handleSecretImport = async (file: File) => { const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKWMv2Key, 'id'>[] | null = null; const keys = await importKWMv2KeysFromFile(file);
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()));
}
if (keys && keys.length > 0) { if (keys && keys.length > 0) {
dispatch(kwm2ImportKeys(keys)); dispatch(kwm2ImportKeys(keys));
+39
View File
@@ -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();
});
});
+21
View File
@@ -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.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

+25
View File
@@ -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;
};
@@ -1,15 +1,12 @@
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '../settingsSlice'; import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingQMCv2Settings } from '../settingsSelector'; import { selectStagingQMCv2Settings } from '~/features/qmc/keyLookup';
import React, { useRef, useState } from 'react'; import React, { useRef, useState } from 'react';
import { QMCv2EKeyItem } from './QMCv2/QMCv2EKeyItem'; import { QMCv2EKeyItem } from './QMCv2EKeyItem';
import { ImportSecretModal } from '~/components/ImportSecretModal'; import { ImportSecretModal } from '~/components/ImportSecretModal';
import { StagingQMCv2Key } from '../keyFormats'; import { importQMCv2KeysFromFile } from '~/features/qmc/importKeys';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor'; import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
import { parseAndroidQmEKey } from '~/util/mmkv/qm'; import { QMCv2DoubanAllInstructions } from '~/features/qmc/instructions/QMCv2DoubanAllInstructions';
import { getFileName } from '~/util/pathHelper';
import { QMCv2QQMusicAllInstructions } from './QMCv2/QMCv2QQMusicAllInstructions';
import { QMCv2DoubanAllInstructions } from './QMCv2/QMCv2DoubanAllInstructions';
import { AddKey } from '~/components/AddKey'; import { AddKey } from '~/components/AddKey';
import { InfoModal } from '~/components/InfoModal.tsx'; import { InfoModal } from '~/components/InfoModal.tsx';
import { Ruby } from '~/components/Ruby.tsx'; import { Ruby } from '~/components/Ruby.tsx';
@@ -32,18 +29,7 @@ export function PanelQMCv2Key() {
const handleSecretImport = async (file: File) => { const handleSecretImport = async (file: File) => {
try { try {
const fileBuffer = await file.arrayBuffer(); const keys = await importQMCv2KeysFromFile(file);
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 }));
}
if (keys && keys.length > 0) { if (keys && keys.length > 0) {
dispatch(qmc2ImportKeys(keys)); dispatch(qmc2ImportKeys(keys));
@@ -1,4 +1,4 @@
import { qmc2DeleteKey, qmc2UpdateKey } from '../../settingsSlice'; import { qmc2DeleteKey, qmc2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks'; import { useAppDispatch } from '~/hooks';
import { memo } from 'react'; import { memo } from 'react';
import { KeyInput } from '~/components/KeyInput.tsx'; import { KeyInput } from '~/components/KeyInput.tsx';
+23
View File
@@ -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');
});
});
+26
View File
@@ -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>
</>
);
}
+4
View File
@@ -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;
@@ -2,13 +2,12 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
import { ExtLink } from '~/components/ExtLink'; import { ExtLink } from '~/components/ExtLink';
import { ChangeEvent, ClipboardEvent, useId } from 'react'; import { ChangeEvent, ClipboardEvent, useId } from 'react';
import { VQuote } from '~/components/HelpText/VQuote'; import { VQuote } from '~/components/HelpText/VQuote';
import { selectStagingQtfmAndroidKey } from '../settingsSelector'; import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
import { qtfmAndroidUpdateKey } from '../settingsSlice'; import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
import { workerClientBus } from '~/decrypt-worker/client.ts'; import { workerClientBus } from '~/decrypt-worker/client.ts';
import { GetQingTingFMDeviceKeyPayload } from '~/decrypt-worker/types.ts';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts'; import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
import { Ruby } from '~/components/Ruby';
import { HiWord } from '~/components/HelpText/HiWord';
import { toast } from 'react-toastify'; import { toast } from 'react-toastify';
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest'; const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
@@ -22,26 +21,18 @@ export function PanelQingTing() {
const handleDataPaste = (e: ClipboardEvent<HTMLInputElement>) => { const handleDataPaste = (e: ClipboardEvent<HTMLInputElement>) => {
const plainText = e.clipboardData.getData('text/plain'); const plainText = e.clipboardData.getData('text/plain');
const matchDeviceSecret = plainText.match(/^DEVICE_SECRET: ([0-9a-fA-F]+)/m); const deviceSecret = parseQtfmDeviceSecretFromText(plainText);
if (matchDeviceSecret) { if (deviceSecret) {
e.preventDefault(); e.preventDefault();
setSecretKey(matchDeviceSecret[1]); setSecretKey(deviceSecret);
return; return;
} }
const dataMap = Object.create(null) as GetQingTingFMDeviceKeyPayload; const dataMap = parseQtfmDeviceInfoFromText(plainText);
for (const [, key, value] of plainText.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) { if (dataMap) {
dataMap[key.toLowerCase() as keyof GetQingTingFMDeviceKeyPayload] = value;
}
const { product, device, manufacturer, brand, board, model } = dataMap;
if (product && device && manufacturer && brand && board && model) {
e.preventDefault(); e.preventDefault();
workerClientBus workerClientBus
.request< .request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
string,
GetQingTingFMDeviceKeyPayload
>(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`)); .then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
} }
}; };
@@ -83,43 +74,7 @@ export function PanelQingTing() {
</fieldset> </fieldset>
</div> </div>
<h3 className="text-xl font-bold my-2">注意事项</h3> <QingTingNotes />
<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>
</div> </div>
); );
} }
+15
View File
@@ -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, '');
}
@@ -0,0 +1,206 @@
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,
},
},
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,
},
},
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.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,
},
},
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);
});
});
@@ -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 -79
View File
@@ -1,6 +1,6 @@
import { nanoid } from 'nanoid';
import { objectify } from 'radash'; import { objectify } from 'radash';
/** Generic map↔list helpers shared by format feature types. */
export function productionKeyToStaging<S, P extends Record<string, unknown>>( export function productionKeyToStaging<S, P extends Record<string, unknown>>(
src: P, src: P,
make: (k: keyof P, v: P[keyof P]) => null | S, 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 { 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; 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 +0,0 @@
// TODO: Popup dialog for QingTing instructions
+5 -3
View File
@@ -10,7 +10,8 @@ import {
} from './settingsSlice'; } from './settingsSlice';
import { enumObject } from '~/util/objects'; import { enumObject } from '~/util/objects';
import { getLogger } from '~/util/logUtils'; import { getLogger } from '~/util/logUtils';
import { parseKwm2ProductionKey } from './keyFormats'; import { parseKwm2ProductionKey } from '~/features/kwm/types';
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
import { deepClone } from '~/util/deepClone'; import { deepClone } from '~/util/deepClone';
const DEFAULT_STORAGE_KEY = 'um-react-settings'; const DEFAULT_STORAGE_KEY = 'um-react-settings';
@@ -28,7 +29,8 @@ function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined):
return result; return result;
} }
function mergeSettings(settings: ProductionSettings): ProductionSettings { /** Normalize / sanitize loaded production settings against defaults. Exported for tests. */
export function mergeSettings(settings: ProductionSettings): ProductionSettings {
const draft = deepClone(settingsSlice.getInitialState().production); const draft = deepClone(settingsSlice.getInitialState().production);
draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload); draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload);
@@ -67,7 +69,7 @@ function mergeSettings(settings: ProductionSettings): ProductionSettings {
} }
if (typeof settings?.qtfm?.android === 'string') { 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; return draft;
+10 -65
View File
@@ -1,71 +1,16 @@
import type { RootState } from '~/store'; import type { RootState } from '~/store';
import { closestByLevenshtein } from '~/util/levenshtein';
import { hasOwn } from '~/util/objects'; /** Re-exports format key lookups so callers can keep a single settings import if desired. */
import { kwm2StagingToProductionKey } from './keyFormats'; export {
import type { ParseKugouHeaderResponse, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts'; 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 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 selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.general.batchDownload; export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.general.batchDownload;
+53 -117
View File
@@ -1,25 +1,29 @@
import { createSlice } from '@reduxjs/toolkit'; import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit'; import type { PayloadAction } from '@reduxjs/toolkit';
import { nanoid } from 'nanoid';
import { import {
ProductionKWMv2Keys, type ProductionQMCv2Keys,
ProductionQMCv2Keys, type StagingQMCv2Key,
StagingKWMv2Key,
StagingQMCv2Key,
kwm2ProductionToStaging,
kwm2StagingToProductionKey,
kwm2StagingToProductionValue,
productionKeyToStaging,
qmc2ProductionToStaging, qmc2ProductionToStaging,
qmc2StagingToProductionKey, qmc2StagingToProductionKey,
qmc2StagingToProductionValue, qmc2StagingToProductionValue,
stagingKeyToProduction, } from '~/features/qmc/types';
ProductionKugouKey, import {
type ProductionKWMv2Keys,
type StagingKWMv2Key,
kwm2ProductionToStaging,
kwm2StagingToProductionKey,
kwm2StagingToProductionValue,
} from '~/features/kwm/types';
import {
type ProductionKugouKey,
type StagingKugouKey,
kugouProductionToStaging, kugouProductionToStaging,
kugouStagingToProductionKey, kugouStagingToProductionKey,
kugouStagingToProductionValue, kugouStagingToProductionValue,
StagingKugouKey, } from '~/features/kugou/types';
} from './keyFormats'; import { EMPTY_QTFM_SETTINGS, type ProductionQtfmSettings, type StagingQtfmSettings } from '~/features/qtfm/types';
import { productionKeyToStaging, stagingKeyToProduction } from './keyFormats';
import { createKeyListReducers } from './createKeyListReducers';
export interface BatchDownloadSettings { export interface BatchDownloadSettings {
directoryPicker: boolean; directoryPicker: boolean;
@@ -39,12 +43,14 @@ export interface StagingSettings {
kwm2: { kwm2: {
keys: StagingKWMv2Key[]; keys: StagingKWMv2Key[];
}; };
/**
* KuGou / KGG keys.
* UI route tab id is `kgg`; Redux / production persist key remains `kugou`.
*/
kugou: { kugou: {
keys: StagingKugouKey[]; keys: StagingKugouKey[];
}; };
qtfm: { qtfm: StagingQtfmSettings;
android: string;
};
} }
export interface ProductionSettings { export interface ProductionSettings {
@@ -58,12 +64,14 @@ export interface ProductionSettings {
kwm2: { kwm2: {
keys: ProductionKWMv2Keys; // { [`${rid}-${quality}`]: ekey } keys: ProductionKWMv2Keys; // { [`${rid}-${quality}`]: ekey }
}; };
/**
* KuGou / KGG keys.
* UI route tab id is `kgg`; localStorage production shape key remains `kugou` (do not rename).
*/
kugou: { kugou: {
keys: ProductionKugouKey; // { [fileName]: ekey } keys: ProductionKugouKey; // { [fileName]: ekey }
}; };
qtfm: { qtfm: ProductionQtfmSettings;
android: string;
};
} }
export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = { export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = {
@@ -85,7 +93,7 @@ const initialState: SettingsState = {
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } }, general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
qmc2: { allowFuzzyNameSearch: true, keys: [] }, qmc2: { allowFuzzyNameSearch: true, keys: [] },
kwm2: { keys: [] }, kwm2: { keys: [] },
qtfm: { android: '' }, qtfm: { ...EMPTY_QTFM_SETTINGS },
kugou: { keys: [] }, kugou: { keys: [] },
}, },
production: { production: {
@@ -93,11 +101,11 @@ const initialState: SettingsState = {
qmc2: { allowFuzzyNameSearch: true, keys: {} }, qmc2: { allowFuzzyNameSearch: true, keys: {} },
kwm2: { keys: {} }, kwm2: { keys: {} },
kugou: { keys: {} }, kugou: { keys: {} },
qtfm: { android: '' }, qtfm: { ...EMPTY_QTFM_SETTINGS },
}, },
}; };
const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({ export const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
general: { general: {
batchDownload: { ...staging.general.batchDownload }, batchDownload: { ...staging.general.batchDownload },
}, },
@@ -114,7 +122,7 @@ const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
qtfm: staging.qtfm, qtfm: staging.qtfm,
}); });
const productionToStaging = (production: ProductionSettings): StagingSettings => ({ export const productionToStaging = (production: ProductionSettings): StagingSettings => ({
general: { general: {
batchDownload: { ...production.general.batchDownload }, batchDownload: { ...production.general.batchDownload },
}, },
@@ -131,6 +139,10 @@ const productionToStaging = (production: ProductionSettings): StagingSettings =>
qtfm: production.qtfm, 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({ export const settingsSlice = createSlice({
name: 'settings', name: 'settings',
initialState, initialState,
@@ -142,96 +154,25 @@ export const settingsSlice = createSlice({
staging: productionToStaging(payload), staging: productionToStaging(payload),
}; };
}, },
// qmc2AddKey: qmc2KeyList.addKey,
qmc2AddKey(state) { qmc2ImportKeys: qmc2KeyList.importKeys,
state.staging.qmc2.keys.push({ id: nanoid(), name: '', ekey: '' }); qmc2DeleteKey: qmc2KeyList.deleteKey,
state.dirty = true; qmc2UpdateKey: qmc2KeyList.updateKey,
}, qmc2ClearKeys: qmc2KeyList.clearKeys,
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;
},
qmc2AllowFuzzyNameSearch(state, { payload: { enable } }: PayloadAction<{ enable: boolean }>) { qmc2AllowFuzzyNameSearch(state, { payload: { enable } }: PayloadAction<{ enable: boolean }>) {
state.staging.qmc2.allowFuzzyNameSearch = enable; state.staging.qmc2.allowFuzzyNameSearch = enable;
state.dirty = true; state.dirty = true;
}, },
// TODO: reuse the logic somehow? kwm2AddKey: kwm2KeyList.addKey,
kwm2AddKey(state) { kwm2ImportKeys: kwm2KeyList.importKeys,
state.staging.kwm2.keys.push({ id: nanoid(), ekey: '', quality: '', rid: '' }); kwm2DeleteKey: kwm2KeyList.deleteKey,
state.dirty = true; kwm2UpdateKey: kwm2KeyList.updateKey,
}, kwm2ClearKeys: kwm2KeyList.clearKeys,
kwm2ImportKeys(state, { payload }: PayloadAction<Omit<StagingKWMv2Key, 'id'>[]>) { kugouAddKey: kugouKeyList.addKey,
const newItems = payload.map((item) => ({ id: nanoid(), ...item })); kugouImportKeys: kugouKeyList.importKeys,
state.staging.kwm2.keys.push(...newItems); kugouDeleteKey: kugouKeyList.deleteKey,
state.dirty = true; kugouUpdateKey: kugouKeyList.updateKey,
}, kugouClearKeys: kugouKeyList.clearKeys,
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;
},
qtfmAndroidUpdateKey(state, { payload: { deviceKey } }: PayloadAction<{ deviceKey: string }>) { qtfmAndroidUpdateKey(state, { payload: { deviceKey } }: PayloadAction<{ deviceKey: string }>) {
state.staging.qtfm.android = deviceKey; state.staging.qtfm.android = deviceKey;
state.dirty = true; state.dirty = true;
@@ -243,19 +184,14 @@ export const settingsSlice = createSlice({
state.staging.general.batchDownload[key] = value; state.staging.general.batchDownload[key] = value;
state.dirty = true; state.dirty = true;
}, },
//
discardStagingChanges: (state) => { discardStagingChanges: (state) => {
state.dirty = false; state.dirty = false;
state.staging = productionToStaging(state.production); state.staging = productionToStaging(state.production);
}, },
/** Apply staging → production. Staging list row `id`s are kept (no productionToStaging round-trip). */
commitStagingChange: (state) => { commitStagingChange: (state) => {
const production = stagingToProduction(state.staging); state.production = stagingToProduction(state.staging);
return { state.dirty = false;
dirty: false,
// Sync back to staging
staging: productionToStaging(production),
production,
};
}, },
resetConfig: () => { resetConfig: () => {
return initialState; return initialState;
+13 -4
View File
@@ -1,10 +1,19 @@
import type { FC } from 'react'; import type { FC } from 'react';
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx'; import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
import { PanelQMCv2Key } from '~/features/settings/panels/PanelQMCv2Key.tsx'; import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
import { PanelKWMv2Key } from '~/features/settings/panels/PanelKWMv2Key.tsx'; import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
import { PanelKGGKey } from '~/features/settings/panels/PanelKGGKey.tsx'; import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
import { PanelQingTing } from '~/features/settings/panels/PanelQingTing.tsx'; import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
/**
* 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`
*/
export const SETTINGS_TABS: Record<string, { name: string; Tab: FC }> = { export const SETTINGS_TABS: Record<string, { name: string; Tab: FC }> = {
general: { name: '通用设置', Tab: PanelGeneral }, general: { name: '通用设置', Tab: PanelGeneral },
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key }, qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
+4 -9
View File
@@ -1,16 +1,11 @@
import { getFileName } from './pathHelper'; import { getFileName } from './pathHelper';
import { SQLDatabase, SQLStatic, loadSQL } from './sqlite'; import { SQLDatabase, SQLStatic, loadSQL } from './sqlite';
import { KuGou } from '@unlock-music/crypto'; import { KuGou } from '@unlock-music/crypto';
import type { StagingQMCv2Key } from '~/features/qmc/types';
import type { StagingKugouKey } from '~/features/kugou/types';
export interface QMAndroidKeyEntry { export type QMAndroidKeyEntry = Omit<StagingQMCv2Key, 'id'>;
name: string; export type KugouKeyEntry = Omit<StagingKugouKey, 'id'>;
ekey: string;
}
export type KugouKeyEntry = {
audioHash: string;
ekey: string;
};
export class DatabaseKeyExtractor { export class DatabaseKeyExtractor {
private static _instance: DatabaseKeyExtractor; private static _instance: DatabaseKeyExtractor;
+3 -2
View File
@@ -1,12 +1,13 @@
import type { WorkerActionMap } from '~/decrypt-worker/actions';
import type { DecryptCommandPayload } from '~/decrypt-worker/types'; import type { DecryptCommandPayload } from '~/decrypt-worker/types';
import { DECRYPTION_WORKER_ACTION_NAME, DecryptionResult } from '~/decrypt-worker/constants'; import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
import { ConcurrentQueue } from './ConcurrentQueue'; import { ConcurrentQueue } from './ConcurrentQueue';
import { WorkerClientBus } from './WorkerEventBus'; import { WorkerClientBus } from './WorkerEventBus';
export class DecryptionQueue extends ConcurrentQueue<DecryptCommandPayload, DecryptionResult> { export class DecryptionQueue extends ConcurrentQueue<DecryptCommandPayload, DecryptionResult> {
constructor( constructor(
private workerClientBus: WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>, private workerClientBus: WorkerClientBus<WorkerActionMap>,
maxQueue?: number, maxQueue?: number,
) { ) {
super(maxQueue); super(maxQueue);
+1 -1
View File
@@ -7,7 +7,7 @@ export class MMKVParser {
constructor(private view: DataView<ArrayBuffer>) { constructor(private view: DataView<ArrayBuffer>) {
const payloadLength = view.getUint32(0, true); const payloadLength = view.getUint32(0, true);
this.length = 4 + payloadLength; this.length = Math.min(4 + payloadLength, view.byteLength);
// skip unused str // skip unused str
this.readInt(); this.readInt();
+45 -28
View File
@@ -1,27 +1,45 @@
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
import { DecryptError } from '~/decrypt-worker/util/DecryptError'; import { DecryptError } from '~/decrypt-worker/util/DecryptError';
type WorkerActionEntry = { req: unknown; res: unknown };
type WorkerServerHandler<P, R> = (payload: P) => R | Promise<R>; type WorkerServerHandler<P, R> = (payload: P) => R | Promise<R>;
interface SerializedError { export interface SerializedError {
message: string; message: string;
stack?: string; stack?: string;
code?: string; code?: string;
name?: string;
} }
interface WorkerClientRequestPayload<P = unknown> { interface WorkerClientRequestPayload<P = unknown> {
id: string; requestId: string;
action: string; action: string;
payload: P; payload: P;
} }
interface WorkerServerResponsePayload<R = unknown> { interface WorkerServerResponsePayload<R = unknown> {
id: string; requestId: string;
result: R; result: R | null;
error: SerializedError; error: SerializedError | null;
} }
export class WorkerClientBus<T = string> { export function serializeError(err: unknown): SerializedError {
if (err instanceof DecryptError) {
return err.toJSON();
}
if (err instanceof Error) {
const withCode = err as Error & { code?: string };
return {
name: err.name,
message: err.message,
stack: err.stack,
code: withCode.code,
};
}
return { message: String(err) };
}
export class WorkerClientBus<TMap extends Record<string, WorkerActionEntry>> {
private idPromiseMap = new Map<string, [(data: never) => void, (error: Error) => void]>(); private idPromiseMap = new Map<string, [(data: never) => void, (error: Error) => void]>();
constructor(private worker: Worker) { constructor(private worker: Worker) {
@@ -29,13 +47,13 @@ export class WorkerClientBus<T = string> {
} }
eventHandler = (e: MessageEvent<WorkerServerResponsePayload>) => { eventHandler = (e: MessageEvent<WorkerServerResponsePayload>) => {
const { id, result, error } = e.data; const { requestId, result, error } = e.data;
const actionPromise = this.idPromiseMap.get(id); const actionPromise = this.idPromiseMap.get(requestId);
if (!actionPromise) { if (!actionPromise) {
console.error('cound not fetch worker promise for action: %s', id); console.error('could not fetch worker promise for request: %s', requestId);
return; return;
} }
this.idPromiseMap.delete(id); this.idPromiseMap.delete(requestId);
const [resolve, reject] = actionPromise; const [resolve, reject] = actionPromise;
if (error) { if (error) {
@@ -48,47 +66,46 @@ export class WorkerClientBus<T = string> {
} }
}; };
async request<R, P>(actionName: T, payload: P): Promise<R> { async request<K extends keyof TMap & string>(actionName: K, payload: TMap[K]['req']): Promise<TMap[K]['res']> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const id = `request://${actionName as string}/${nanoid()}`; const requestId = `request://${actionName}/${nanoid()}`;
this.idPromiseMap.set(id, [resolve, reject]); this.idPromiseMap.set(requestId, [resolve, reject]);
this.worker.postMessage({ this.worker.postMessage({
id, requestId,
action: actionName, action: actionName,
payload, payload,
}); } satisfies WorkerClientRequestPayload);
}); });
} }
} }
export class WorkerServerBus { export class WorkerServerBus<TMap extends Record<string, WorkerActionEntry> = Record<string, WorkerActionEntry>> {
private handlers = new Map<string, WorkerServerHandler<unknown, unknown>>(); private handlers = new Map<string, WorkerServerHandler<unknown, unknown>>();
addEventHandler<R, P>(actionName: string, handler: WorkerServerHandler<P, R>) { addEventHandler<K extends keyof TMap & string>(
this.handlers.set(actionName, handler as WorkerServerHandler<unknown, unknown>); actionName: K,
handler: WorkerServerHandler<TMap[K]['req'], TMap[K]['res']>,
) {
this.handlers.set(actionName, handler);
} }
onmessage = async (e: MessageEvent<WorkerClientRequestPayload>) => { onmessage = async (e: MessageEvent<WorkerClientRequestPayload>) => {
const { id, action, payload } = e.data; const { requestId, action, payload } = e.data;
const handler = this.handlers.get(action); const handler = this.handlers.get(action);
let result = null; let result: unknown = null;
let error = null; let error: SerializedError | null = null;
if (!handler) { if (!handler) {
error = new Error('Handler missing for action ' + action); error = serializeError(new Error('Handler missing for action ' + action));
} else { } else {
try { try {
result = await handler(payload); result = await handler(payload);
} catch (err: unknown) { } catch (err: unknown) {
if (err instanceof DecryptError) { error = serializeError(err);
error = err.toJSON();
} else {
error = err;
}
} }
} }
postMessage({ id, result, error }); postMessage({ requestId, result, error } satisfies WorkerServerResponsePayload);
}; };
} }
+7 -8
View File
@@ -1,3 +1,4 @@
import type { WorkerActionMap } from '~/decrypt-worker/actions';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants'; import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
import { WorkerClientBus } from '../WorkerEventBus'; import { WorkerClientBus } from '../WorkerEventBus';
import { DecryptionQueue } from '../DecryptionQueue'; import { DecryptionQueue } from '../DecryptionQueue';
@@ -14,21 +15,19 @@ vi.mock('../WorkerEventBus', () => {
test('should be able to forward request to worker client bus', async () => { test('should be able to forward request to worker client bus', async () => {
// This class is mocked // This class is mocked
const bus = new WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>(null as never); const bus = new WorkerClientBus<WorkerActionMap>(null as never);
vi.spyOn(bus, 'request').mockImplementation( vi.spyOn(bus, 'request').mockImplementation((actionName, payload) => {
async (actionName: DECRYPTION_WORKER_ACTION_NAME, payload: unknown): Promise<unknown> => { return Promise.resolve({ actionName, payload } as never);
return Promise.resolve({ actionName, payload }); });
},
);
const queue = new DecryptionQueue(bus, 1); const queue = new DecryptionQueue(bus, 1);
await expect( await expect(
queue.add({ id: 'file://1', blobURI: 'blob://mock-file', options: { fileName: 'test.bin' } }), queue.add({ fileId: 'file://1', blobURI: 'blob://mock-file', options: { fileName: 'test.bin' } }),
).resolves.toEqual({ ).resolves.toEqual({
actionName: DECRYPTION_WORKER_ACTION_NAME.DECRYPT, actionName: DECRYPTION_WORKER_ACTION_NAME.DECRYPT,
payload: { payload: {
blobURI: 'blob://mock-file', blobURI: 'blob://mock-file',
id: 'file://1', fileId: 'file://1',
options: { fileName: 'test.bin' }, options: { fileName: 'test.bin' },
}, },
}); });
+55
View File
@@ -26,3 +26,58 @@ test('able to handle empty value', () => {
expect(parser.readKey()).toEqual('1'); expect(parser.readKey()).toEqual('1');
expect(parser.readStringValue()).toEqual('2'); expect(parser.readStringValue()).toEqual('2');
}); });
describe('eof payload boundary', () => {
// Small string records: "a" -> "one" and "b" -> "two".
const firstRecord = Buffer.from([0x01, 0x61, 0x04, 0x03, 0x6f, 0x6e, 0x65]);
const secondRecord = Buffer.from([0x01, 0x62, 0x04, 0x03, 0x74, 0x77, 0x6f]);
const payload = Buffer.concat([Buffer.from([0x7f]), firstRecord, secondRecord]);
const allEntries = [
['a', 'one'],
['b', 'two'],
];
const makeView = (payloadLength: number) => {
const header = Buffer.alloc(4);
header.writeUInt32LE(payloadLength);
return makeViewFromBuffer(Buffer.concat([header, payload]));
};
const readEntries = (parser: MMKVParser) => {
const entries: [string, string | null][] = [];
while (!parser.eof) {
entries.push([parser.readKey(), parser.readStringValue()]);
}
return entries;
};
test.each([payload.byteLength + 4, 0xffffffff])('clamps oversized payload length %i to the view', (payloadLength) => {
const parser = new MMKVParser(makeView(payloadLength));
expect(readEntries(parser)).toEqual(allEntries);
expect(parser.eof).toBe(true);
});
test('reads all records when the payload length is exact', () => {
const parser = new MMKVParser(makeView(payload.byteLength));
expect(readEntries(parser)).toEqual(allEntries);
expect(parser.eof).toBe(true);
});
test('stops at the declared payload boundary with another valid record remaining', () => {
const parser = new MMKVParser(makeView(1 + firstRecord.byteLength));
expect(readEntries(parser)).toEqual([allEntries[0]]);
expect(parser.eof).toBe(true);
});
test('clamps to the DataView length with another valid record outside the view', () => {
const fullView = makeView(payload.byteLength + 4);
const view = new DataView(fullView.buffer, 0, 4 + 1 + firstRecord.byteLength);
const parser = new MMKVParser(view);
expect(readEntries(parser)).toEqual([allEntries[0]]);
expect(parser.eof).toBe(true);
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StagingKugouKey } from '~/features/settings/keyFormats'; import type { StagingKugouKey } from '~/features/kugou/types';
import { MMKVParser } from '../MMKVParser'; import { MMKVParser } from '../MMKVParser';
export function parseAndroidKugouMMKV(view: DataView<ArrayBuffer>): Omit<StagingKugouKey, 'id'>[] { export function parseAndroidKugouMMKV(view: DataView<ArrayBuffer>): Omit<StagingKugouKey, 'id'>[] {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StagingKWMv2Key } from '~/features/settings/keyFormats'; import type { StagingKWMv2Key } from '~/features/kwm/types';
import { MMKVParser } from '../MMKVParser'; import { MMKVParser } from '../MMKVParser';
export function parseAndroidKuwoEKey(view: DataView<ArrayBuffer>): Omit<StagingKWMv2Key, 'id'>[] { export function parseAndroidKuwoEKey(view: DataView<ArrayBuffer>): Omit<StagingKWMv2Key, 'id'>[] {