21 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
鲁树人 10e857a903 0.6.2 2026-10-22 02:23:47 +09:00
鲁树人 537391ed03 docs: update README and FAQ for QQ Music client key requirements
- Revised README to clarify that QQ Music PC client versions 19.57 to 22.76 require importing a key file extracted using qmpc-mmkv-cli.
- Updated issue template to reflect the same changes regarding key file requirements for Windows clients.
- Modified FAQ to specify that only versions 19.51 or lower do not require a key, while versions 19.57 to 22.76 do.
- Enhanced instructions for obtaining the key file in the PC instructions panel.
2026-10-21 11:40:55 +09:00
鲁树人 881aa5e44c chore: remove unused environment variable from build workflow 2026-10-21 10:55:35 +09:00
鲁树人 757bbd2172 0.6.1 2026-10-21 10:53:12 +09:00
鲁树人 3f14a3acff chore: update Vite configuration to use vmThreads pool 2026-10-21 10:52:44 +09:00
鲁树人 b142c1ba34 chore: dep pkg upgrade
- Updated Node version in Dockerfile and .npmrc.
- Upgraded various dependencies in package.json, including react-dropzone, react-router, and eslint.
- Added pnpm-workspace.yaml for workspace management.
- Adjusted TypeScript configurations and test utilities for compatibility.
- Enhanced documentation for installation instructions and TypeScript toolchain.
2026-10-21 10:51:06 +09:00
鲁树人 4df197ac4d chore: minor pkg updates 2026-10-21 10:25:22 +09:00
鲁树人 07d160c547 feat(#10): add batch download settings and capabilities
- Introduced new batch download settings in the settings slice, allowing users to configure options for directory picking, streaming ZIP downloads, and blob ZIP downloads.
- Implemented a new general settings panel for managing batch download preferences.
- Added utility functions to handle directory selection and ZIP file creation.
- Updated the download logic to support multiple download modes based on user preferences.
- Enhanced documentation to reflect changes in batch download functionality.
2026-10-21 10:24:21 +09:00
鲁树人 3059f495ab Merge pull request 'feat: allow deployment on subpaths' (#11) from Charles/um-react:main into main
Reviewed-on: https://git.um-react.app/um/um-react/pulls/11
2026-07-15 10:30:44 +01:00
Charles 024847a45a feat: allow deployment on subpaths 2026-01-30 16:28:39 +08:00
鲁树人 a11caaae92 refactor: major package updates 2025-10-16 01:00:38 +09:00
鲁树人 2e52c67533 chore: minor package updates 2025-10-15 23:15:00 +09:00
鲁树人 56bb94b90c docs: update highlight styling 2025-10-15 23:12:47 +09:00
鲁树人 c1a5c6bde6 chore: reformat project 2025-10-15 23:10:19 +09:00
鲁树人 009804cbbd docs: update notes regarding supported formats 2025-10-15 23:10:12 +09:00
鲁树人 ff6fc467ae ci: only include artifact file once. 2025-10-15 22:52:59 +09:00
128 changed files with 5735 additions and 4562 deletions

No files matched your search

+3 -1
View File
@@ -7,7 +7,9 @@ body:
value: | value: |
### Windows 客户端 ### Windows 客户端
目前 Windows 客户端仅支持 19.51 或更低版本下载的歌曲文件。 目前 Windows 客户端支持 19.57 至 22.76(目前最新版)下载的歌曲文件,但需要导入由 [qmpc-mmkv-cli](https://git.um-react.app/um/qmpc-mmkv/releases) 提取的密钥文件 `qmpc-mmkv-v1.mmkv`。
使用 19.51 或更低版本下载的歌曲文件无需密钥。
* [web.archive.org 镜像](https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe) * [web.archive.org 镜像](https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe)
* [通过 Telegram 下载](https://t.me/um_lsr_ch/24) * [通过 Telegram 下载](https://t.me/um_lsr_ch/24)
-3
View File
@@ -4,8 +4,6 @@ on: [push]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
npm_config_registry: https://registry.npmmirror.com
steps: steps:
- name: Check out repository code - name: Check out repository code
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -40,7 +38,6 @@ jobs:
draft: true draft: true
files: | files: |
release/um-react-*.zip release/um-react-*.zip
release/um-react-win64-*.zip
body: | body: |
上个版本:[v0.0.0](https://git.um-react.app/um/um-react/releases/tag/v0.0.0) 上个版本:[v0.0.0](https://git.um-react.app/um/um-react/releases/tag/v0.0.0)
-2
View File
@@ -1,3 +1 @@
use-node-version=24.7.0
engine-strict=true
@unlock-music:registry=https://git.um-react.app/api/packages/um/npm/ @unlock-music:registry=https://git.um-react.app/api/packages/um/npm/
+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.
+2 -2
View File
@@ -1,4 +1,4 @@
FROM node:22-slim AS build FROM node:24.22.0-slim AS build
ENV PNPM_HOME="/p" ENV PNPM_HOME="/p"
ENV PATH="$PNPM_HOME:$PATH" ENV PATH="$PNPM_HOME:$PATH"
WORKDIR /app WORKDIR /app
@@ -9,7 +9,7 @@ RUN corepack enable pnpm \
&& apt-get clean \ && apt-get clean \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
COPY package.json pnpm-lock.yaml .npmrc ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
RUN pnpm exec true RUN pnpm exec true
COPY . . COPY . .
RUN pnpm install --frozen-lockfile RUN pnpm install --frozen-lockfile
+22 -12
View File
@@ -10,7 +10,7 @@
- CI 自动构建已经部署,可以在 [Actions][um-react-actions] 寻找对应的<ruby>构建产物<rp>(</rp><rt>Artifact</rt><rp>)</rp> </ruby>下载。 - CI 自动构建已经部署,可以在 [Actions][um-react-actions] 寻找对应的<ruby>构建产物<rp>(</rp><rt>Artifact</rt><rp>)</rp> </ruby>下载。
- [常见问题参考](./docs/faq_zh-hans.md) - [常见问题参考](./docs/faq_zh-hans.md)
> **WARNING** > [!WARNING]
> 在本站 fork 不会起到备份的作用,只会浪费服务器储存空间。如无必要请勿 fork 该仓库。 > 在本站 fork 不会起到备份的作用,只会浪费服务器储存空间。如无必要请勿 fork 该仓库。
[授权协议]: https://git.um-react.app/um/um-react/src/branch/main/LICENSE [授权协议]: https://git.um-react.app/um/um-react/src/branch/main/LICENSE
@@ -19,7 +19,8 @@
[`@unlock_music_chat`]: https://t.me/unlock_music_chat [`@unlock_music_chat`]: https://t.me/unlock_music_chat
[um-react-actions]: https://git.um-react.app/um/um-react/actions?workflow=build.yaml [um-react-actions]: https://git.um-react.app/um/um-react/actions?workflow=build.yaml
⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。 > [!TIP]
> 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。
## 支持的格式 ## 支持的格式
@@ -31,27 +32,32 @@
- Mac 客户端 (`.mflach` 等) [^qm-key-mac] - Mac 客户端 (`.mflach` 等) [^qm-key-mac]
- [x] 网易云音乐 (`.ncm`) - [x] 网易云音乐 (`.ncm`)
- [x] 虾米音乐 (`.xm`) - [x] 虾米音乐 (`.xm`)
- [x] 酷我音乐 (`.kwm`) - [x] 酷我音乐 (`.kwm` / `.mflac`) [^kuwo-key-android]
- [x] 酷狗音乐 (`.kgm` / `.vpr` / `.kgg`) - [x] 酷狗音乐 (`.kgm` / `.vpr` / `.kgg`)
- PC / 安卓客户端的 `kgg` 文件需要提供密钥数据库。 - PC / 安卓客户端[^kgg-android]的 `kgg` 文件需要提供密钥数据库。
- [x] 喜马拉雅 (`.x2m` / `.x3m` / `.xm`) - [x] 喜马拉雅 (`.x2m` / `.x3m` / `.xm`)
- [x] 咪咕音乐格式 (`.mg3d`) - [x] 咪咕音乐格式 (`.mg3d`)
- [x] 蜻蜓 FM (`.qta`) - [x] 蜻蜓 FM (`.qta`)
- [ ] ~~<ruby>QQ 音乐海外版<rt>JOOX Music</rt></ruby> (`.ofl_en`)~~ - 需要提取设备 ID。
[^qm-key-pc]: PC 客户端仅支持 v19.43 或更低版本。 [^qm-key-pc]: QQ 音乐的 PC 客户端(v19.57 至 v22.76)需要导入由 [qmpc-mmkv-cli](https://git.um-react.app/um/qmpc-mmkv/releases) 提取的密钥文件 `qmpc-mmkv-v1.mmkv`。
[^qm-key-android]: 需要获取超级管理员权限后提取密钥数据库,并导入后使用。 [^qm-key-android]: QQ 音乐的安卓客户端支持需要获取超级管理员权限后提取密钥数据库并导入后使用。
[^qm-key-ios]: 需要越狱获取密钥数据库,或对设备进行完整备份后提取密钥数据库,并导入后使用。 [^qm-key-ios]: QQ 音乐 iOS 客户端支持需要越狱获取密钥数据库,或对设备进行完整备份后提取密钥数据库并导入后使用。
[^qm-key-mac]: 需要导入密钥数据库。 [^qm-key-mac]: QQ 音乐 Mac 客户端支持需要导入密钥数据库,目前支持 v8.8.0 及 v10.7.1。
[^kgg-android]: 酷狗音乐的安卓客户端支持需要获取超级管理员权限后提取密钥数据库并导入后使用。
[^kuwo-key-android]: 酷我音乐的安卓客户端下载的 AI 升频文件需要获取超级管理员权限后提取密钥数据库并导入后使用。
## 错误报告 ## 错误报告
有不支持的格式?请提交样本(加密文件)与客户端信息版本信息(如系统版本、下载渠道),或一并上传其安装包到[仓库的问题追踪区][project-issues]。 有不支持的格式?请提交样本(加密文件)与客户端信息版本信息(如系统版本、下载渠道),或一并上传其安装包到[仓库的问题追踪区][project-issues]。
⚠️ 如果文件太大,请上传到不需要登入下载的网盘,如 [mega.nz](https://mega.nz)、[OneDrive](https://www.onedrive.com/) 等。 > [!NOTE]
> 如果文件太大,请上传到不需要登入下载的网盘,如 [mega.nz](https://mega.nz)、[OneDrive](https://www.onedrive.com/) 等。
遇到解密出错的情况,请一并携带错误信息(诊断信息)并简单描述错误的重现过程。 遇到解密出错的情况,请一并携带错误信息(诊断信息)并简单描述错误的重现过程。
@@ -59,7 +65,7 @@
[project-issues]: https://git.um-react.app/um/um-react/issues/new [project-issues]: https://git.um-react.app/um/um-react/issues/new
## 使用 Docker 构建、部署 (Linux) ## 使用 Docker 构建、部署
首先克隆仓库并进入目录: 首先克隆仓库并进入目录:
@@ -86,13 +92,17 @@ docker run -d -p 8080:80 --name um-react um-react
然后访问 `http://localhost:8080` 即可。 然后访问 `http://localhost:8080` 即可。
> [!NOTE]
> 项目不支持运行在子目录下。
## 开发相关 ## 开发相关
从源码运行或编译生产版本,请参考文档「[新手上路](./docs/getting-started.zh.md)」。 从源码运行或编译生产版本,请参考文档「[新手上路](./docs/getting-started.zh.md)」。
### 解密库开发 ### 解密库开发
⚠️ 如果只是进行前端方面的更改,你可以跳过该节。 > [!TIP]
> 如果只是进行前端方面的更改,你可以跳过该节。
请参考文档「[面向 `@unlock-music/crypto` 开发](./docs/develop-with-um_crypto.zh.md)」。 请参考文档「[面向 `@unlock-music/crypto` 开发](./docs/develop-with-um_crypto.zh.md)」。
+13 -1
View File
@@ -10,7 +10,7 @@
#### 2、检查您的平台。 #### 2、检查您的平台。
日前,<mark>仅 Windows 客户端 v19.43 或以下版本</mark>下载的歌曲无需密钥,其余平台的官方正式版本均需要提取密钥。 日前,Windows 客户端 <mark>v19.57 至 v22.76</mark>(目前最新版)下载的歌曲需要导入由 [qmpc-mmkv-cli](https://git.um-react.app/um/qmpc-mmkv/releases) 提取的密钥文件 `qmpc-mmkv-v1.mmkv`;<mark>v19.51 或更低版本</mark>下载的歌曲无需密钥。其余平台的官方正式版本均需要提取密钥。
> iOS 用户提取歌曲困难,建议换用电脑操作;Android 用户提取密钥需要 root,也建议用电脑操作。 > iOS 用户提取歌曲困难,建议换用电脑操作;Android 用户提取密钥需要 root,也建议用电脑操作。
@@ -71,6 +71,18 @@
- 雷电模拟器可以在「模拟器设置」 → 「其他设置」中启用 root 特权。 - 雷电模拟器可以在「模拟器设置」 → 「其他设置」中启用 root 特权。
![雷电模拟器 其他设置](../src/faq/assets/[email protected]) ![雷电模拟器 其他设置](../src/faq/assets/[email protected])
### 批量下载约十首后失败 / 无法全部下载
Chromium 系浏览器会限制页面在短时间内通过程序触发的**多个**文件下载(常见表现为大约十个文件后静默中断,或提示「此网站正在尝试下载多个文件」)。
本站的「下载全部」会按「设定 → 通用设置 → 批量下载」中勾选的顺序尝试:
1. 选择输出目录,直接写入文件(推荐,Chrome / Edge)
2. 流式生成单个 ZIP 并保存
3. 在内存中生成 ZIP 后触发一次下载(兼容性最好)
若全部失败会弹出提示。大批量转换也可使用 [命令行版本](https://git.um-react.app/um/cli)。
### Via 等浏览器无法正常解密/下载 ### Via 等浏览器无法正常解密/下载
⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。 ⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。
+6 -2
View File
@@ -4,8 +4,8 @@
## 安装依赖 ## 安装依赖
- 安装 Node v16.17 或更高,推荐当前最新的 Node LTS 版本。 - 安装 Node 24.22.0;pnpm 也会根据 `package.json` 中的 `devEngines.runtime` 自动获取该版本。
- 安装/激活 `pnpm` [^1]:`corepack prepare pnpm@latest --activate` - 安装/激活项目指定的 `pnpm` [^1]:`corepack prepare pnpm@12.14.0 --activate`
- 安装软件依赖:`pnpm i --frozen-lockfile` - 安装软件依赖:`pnpm i --frozen-lockfile`
[^1]: 参考 pnpm 说明「[使用 Corepack 安装](https://pnpm.io/zh/installation#使用-corepack-安装)」。 [^1]: 参考 pnpm 说明「[使用 Corepack 安装](https://pnpm.io/zh/installation#使用-corepack-安装)」。
@@ -34,6 +34,10 @@ pnpm build
[vite-preview-url]: http://localhost:4173/ [vite-preview-url]: http://localhost:4173/
### TypeScript 工具链
编译和 ESLint 统一使用 TypeScript 6.x,暂不升级到 TypeScript 7。
## 打包 `.zip` ## 打包 `.zip`
建议在 Linux 环境下执行,可参考 `.drone.yml` CI 文件。 建议在 Linux 环境下执行,可参考 `.drone.yml` CI 文件。
+14 -3
View File
@@ -1,15 +1,16 @@
import eslint from '@eslint/js'; import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint'; import tseslint from 'typescript-eslint';
import reactRefresh from 'eslint-plugin-react-refresh'; import reactRefresh from 'eslint-plugin-react-refresh';
import reactHooks from 'eslint-plugin-react-hooks'; import reactHooks from 'eslint-plugin-react-hooks';
import eslintConfigPrettier from 'eslint-config-prettier/flat'; import eslintConfigPrettier from 'eslint-config-prettier/flat';
import globals from 'globals'; import globals from 'globals';
export default tseslint.config( export default defineConfig(
eslint.configs.recommended, eslint.configs.recommended,
tseslint.configs.recommended, tseslint.configs.recommendedTypeChecked,
reactRefresh.configs.recommended, reactRefresh.configs.recommended,
reactHooks.configs['recommended-latest'], reactHooks.configs.flat.recommended,
eslintConfigPrettier, eslintConfigPrettier,
{ {
@@ -40,4 +41,14 @@ export default tseslint.config(
}, },
}, },
}, },
{
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.mjs', 'src/*.mjs', 'scripts/*.mjs'],
},
},
},
},
); );
+4
View File
@@ -9,6 +9,10 @@
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" /> <link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
<meta name="theme-color" content="#4DBA87" /> <meta name="theme-color" content="#4DBA87" />
<script>
// 设置基础路径,如果希望部署在/music-unlock/,则改为 '/music-unlock/',默认部署在根路径
window.BASE_URL = '/';
</script>
</head> </head>
<body> <body>
+60 -66
View File
@@ -1,7 +1,7 @@
{ {
"name": "um-react", "name": "um-react",
"private": true, "private": true,
"version": "0.6.0", "version": "0.6.2",
"type": "module", "type": "module",
"scripts": { "scripts": {
"start": "vite", "start": "vite",
@@ -17,65 +17,66 @@
"prepare": "simple-git-hooks" "prepare": "simple-git-hooks"
}, },
"dependencies": { "dependencies": {
"@reduxjs/toolkit": "^2.9.0", "@reduxjs/toolkit": "^2.13.0",
"@unlock-music/crypto": "^0.1.12", "@unlock-music/crypto": "^0.1.12",
"classnames": "^2.5.1", "classnames": "^2.5.1",
"nanoid": "^5.1.5", "fflate": "^0.8.3",
"idb-keyval": "^6.3.0",
"nanoid": "^6.0.2",
"radash": "^12.1.1", "radash": "^12.1.1",
"react": "^19.1.1", "react": "^19.3.1",
"react-dom": "^19.1.1", "react-dom": "^19.3.1",
"react-dropzone": "^14.3.8", "react-dropzone": "^20.1.4",
"react-icons": "^5.5.0", "react-icons": "^5.7.0",
"react-redux": "^9.2.0", "react-redux": "^9.3.0",
"react-router": "^7.8.2", "react-router": "^8.5.0",
"react-syntax-highlighter": "^15.6.6", "react-syntax-highlighter": "^16.1.2",
"react-toastify": "^11.0.5", "react-toastify": "^11.1.0",
"sql.js": "^1.13.0" "sql.js": "^1.15.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.35.0", "@eslint/js": "^10.0.1",
"@rollup/plugin-replace": "^6.0.2", "@rollup/plugin-replace": "^6.0.3",
"@tailwindcss/vite": "^4.1.13", "@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^6.8.0", "@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.0", "@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.1", "@testing-library/user-event": "^14.6.8",
"@types/node": "^24.3.1", "@types/node": "^26.6.5",
"@types/react": "^19.1.12", "@types/react": "^19.3.0",
"@types/react-dom": "^19.1.9", "@types/react-dom": "^19.3.0",
"@types/react-syntax-highlighter": "^15.5.13", "@types/react-syntax-highlighter": "^15.5.13",
"@types/sql.js": "^1.4.9", "@types/sql.js": "^1.4.11",
"@types/tar-stream": "^3.1.4", "@types/tar-stream": "^3.1.5",
"@types/wicg-file-system-access": "^2023.10.6", "@types/wicg-file-system-access": "^2023.10.7",
"@typescript-eslint/eslint-plugin": "^8.42.0", "@typescript-eslint/eslint-plugin": "^8.72.0",
"@typescript-eslint/parser": "^8.42.0", "@typescript-eslint/parser": "^8.72.0",
"@vitejs/plugin-react": "^5.0.2", "@vitejs/plugin-react": "^6.1.2",
"@vitest/coverage-v8": "^3.2.4", "@vitest/coverage-v8": "^5.0.5",
"@vitest/ui": "^3.2.4", "@vitest/ui": "^5.0.5",
"daisyui": "^5.1.8", "daisyui": "^5.7.50",
"eslint": "^9.35.0", "eslint": "^10.13.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.4.20", "eslint-plugin-react-refresh": "^0.5.7",
"globals": "^16.3.0", "globals": "^17.13.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"jsdom": "^26.1.0", "jsdom": "^30.1.3",
"lint-staged": "^16.1.6", "lint-staged": "^17.6.0",
"prettier": "^3.6.2", "prettier": "^3.9.10",
"rollup": "^4.50.1", "rollup": "^4.64.12",
"sass": "^1.92.1", "sass": "^1.105.2",
"simple-git-hooks": "^2.13.1", "simple-git-hooks": "^2.14.0",
"tailwindcss": "^4.1.13", "tailwindcss": "^4.3.3",
"tar-stream": "^3.1.7", "tar-stream": "^3.2.2",
"terser": "^5.44.0", "terser": "^5.51.2",
"typescript": "^5.9.2", "typescript": "^6.0.3",
"typescript-eslint": "^8.42.0", "typescript-eslint": "^8.72.0",
"vite": "^7.1.5", "vite": "^8.3.4",
"vite-plugin-pwa": "^1.0.3", "vite-plugin-pwa": "^2.0.0",
"vite-plugin-top-level-await": "^1.6.0", "vite-plugin-wasm": "^3.6.0",
"vite-plugin-wasm": "^3.5.0", "vitest": "^5.0.5",
"vitest": "^3.2.4", "workbox-build": "^7.4.1",
"workbox-build": "^7.3.0", "workbox-window": "^7.4.1"
"workbox-window": "^7.3.0"
}, },
"lint-staged": { "lint-staged": {
"*": "prettier --write --ignore-unknown", "*": "prettier --write --ignore-unknown",
@@ -90,19 +91,12 @@
"printWidth": 120, "printWidth": 120,
"tabWidth": 2 "tabWidth": 2
}, },
"pnpm": { "devEngines": {
"patchedDependencies": { "runtime": {
"sql.js": "patches/sql.js.patch" "name": "node",
}, "version": "24.22.0",
"overrides": { "onFail": "download"
"sourcemap-codec": "npm:@jridgewell/[email protected]" }
},
"onlyBuiltDependencies": [
"@swc/core",
"@tailwindcss/oxide",
"esbuild",
"simple-git-hooks"
]
}, },
"packageManager": "pnpm@10.15.1" "packageManager": "pnpm@12.14.0"
} }
+3505 -3728
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
engineStrict: true
patchedDependencies:
sql.js: patches/sql.js.patch
overrides:
sourcemap-codec: npm:@jridgewell/[email protected]
allowBuilds:
'@parcel/watcher': false
'@swc/core': true
'@tailwindcss/oxide': true
esbuild: true
simple-git-hooks: true
minimumReleaseAge: 0
+1 -1
View File
@@ -25,7 +25,7 @@ export function AppRoot() {
useEffect(() => persistSettings(store), []); useEffect(() => persistSettings(store), []);
return ( return (
<BrowserRouter> <BrowserRouter basename={window.BASE_URL || '/'}>
<Provider store={store}> <Provider store={store}>
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content"> <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}> <NavLink to="/" role="tab" className={tabClassNames}>
+163 -49
View File
@@ -2,83 +2,197 @@ import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-l
import { FaDownload } from 'react-icons/fa'; import { FaDownload } from 'react-icons/fa';
import { useAppSelector } from '~/hooks'; import { useAppSelector } from '~/hooks';
import { toast } from 'react-toastify'; import { toast } from 'react-toastify';
import { SimpleQueue } from '~/util/SimpleQueue';
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
import 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';
export function DownloadAll() { export function DownloadAll() {
const files = useAppSelector(selectFiles); const files = useAppSelector(selectFiles);
const onClickDownloadAll = async () => { const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
console.time('DownloadAll'); //开始计时
const fileCount = Object.keys(files).length; const downloadAllAsync = async () => {
const fileList = Object.values(files);
const fileCount = fileList.length;
if (fileCount === 0) { if (fileCount === 0) {
toast.warning('未添加文件'); toast.warning('未添加文件');
return; return;
} }
//判断所有文件是否处理完成 const allComplete = fileList.every((file) => file.state !== ProcessState.PROCESSING);
const allComplete = Object.values(files).every((file) => file.state !== ProcessState.PROCESSING);
if (!allComplete) { if (!allComplete) {
toast.warning('请等待所有文件解密完成'); toast.warning('请等待所有文件解密完成');
return; return;
} }
//过滤处理失败的文件 const completeFiles = fileList.filter((file) => file.state === ProcessState.COMPLETE);
const completeFiles = Object.values(files).filter((file) => file.state === ProcessState.COMPLETE); if (completeFiles.length === 0) {
toast.warning('没有可下载的已解密文件');
//开始下载 return;
let dir: FileSystemDirectoryHandle | undefined;
try {
dir = await window.showDirectoryPicker({ mode: 'readwrite' });
} catch (e) {
console.error(e);
if (e instanceof Error && e.name === 'AbortError') {
return;
}
} }
// Single file: direct blob download, no ZIP / directory picker.
if (completeFiles.length === 1) {
downloadSingleBlob(completeFiles[0]);
toast.success('已开始下载');
return;
}
const modes = buildEnabledModes(batchSettings);
if (modes.length === 0) {
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
return;
}
toast.warning('开始下载,请稍候'); toast.warning('开始下载,请稍候');
const promises = Object.values(completeFiles).map(async (file) => { for (const mode of modes) {
console.log(`开始下载: ${file.fileName}`);
try { try {
if (dir) { const result = await runMode(mode, completeFiles, batchSettings.rememberDirectory);
await DownloadNew(dir, file); if (result === 'ok') {
} else { return;
await DownloadOld(file);
} }
console.log(`成功下载: ${file.fileName}`); // cancelled / skipped → try next mode
} catch (e) { } catch (e) {
console.error(`下载失败: ${file.fileName}`, e); console.error(`批量下载模式 ${mode} 失败`, e);
toast.error(`出现错误: ${e}`); toast.error(`下载方式失败,尝试下一种: ${e instanceof Error ? e.message : String(e)}`);
throw e;
} }
}); }
await Promise.allSettled(promises).then((f) => {
const success = f.filter((result) => result.status === 'fulfilled').length; toast.error('批量下载失败:当前浏览器不支持或您取消了所有可用方式。可在「设定 → 通用设置」调整选项。');
if (success === fileCount) {
toast.success(`成功下载: ${success}/${fileCount}首`);
} else {
toast.warning(`成功下载: ${success}/${fileCount}首`);
}
});
console.timeEnd('DownloadAll'); //停止计时
}; };
function onDownloadAll() {
downloadAllAsync().catch((e) => {
console.error('下载全部出现错误', e);
toast.error(`批量下载出现错误: ${e instanceof Error ? e.message : String(e)}`);
});
}
return ( return (
<button className="btn btn-primary" id="downloadAll" onClick={onClickDownloadAll} title="下载全部"> <button className="btn btn-primary" id="downloadAll" onClick={onDownloadAll} title="下载全部">
<FaDownload /> <FaDownload />
</button> </button>
); );
} }
async function DownloadNew(dir: FileSystemDirectoryHandle, file: DecryptedAudioFile) { type BatchMode = 'directory' | 'streamingZip' | 'blobZip';
const fileHandle = await dir.getFileHandle(file.cleanName + '.' + file.ext, { create: true });
const writable = await fileHandle.createWritable(); function buildEnabledModes(
await fetch(file.decrypted).then((res) => res.body?.pipeTo(writable)); 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 DownloadOld(file: DecryptedAudioFile) { async function runMode(
const a = document.createElement('a'); mode: BatchMode,
a.href = file.decrypted; completeFiles: DecryptedAudioFile[],
a.download = file.cleanName + '.' + file.ext; rememberDirectory: boolean,
document.body.append(a); ): Promise<'ok' | 'cancelled'> {
a.click(); switch (mode) {
a.remove(); 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 -1
View File
@@ -7,7 +7,7 @@ export type DownloadBase64Props = {
filename: string; filename: string;
mimetype?: string; mimetype?: string;
className?: string; className?: string;
icon?: boolean | ReactNode; icon?: ReactNode | true | false;
children?: ReactNode; children?: ReactNode;
}; };
+1 -1
View File
@@ -2,7 +2,7 @@ import type { AnchorHTMLAttributes, ReactNode } from 'react';
import { FiExternalLink } from 'react-icons/fi'; import { FiExternalLink } from 'react-icons/fi';
export type ExtLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & { export type ExtLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
icon?: boolean | ReactNode; icon?: ReactNode | true | false;
}; };
export function ExtLink({ className, icon = true, children, ...props }: ExtLinkProps) { export function ExtLink({ className, icon = true, children, ...props }: ExtLinkProps) {
+3 -4
View File
@@ -13,13 +13,12 @@ export interface ImportSecretModalProps {
export function ImportSecretModal({ clientName, children, show, onClose, onImport }: ImportSecretModalProps) { export function ImportSecretModal({ clientName, children, show, onClose, onImport }: ImportSecretModalProps) {
const handleFileReceived = (files: File[]) => { const handleFileReceived = (files: File[]) => {
const promise = onImport(files[0]); const importResult = onImport(files[0]);
if (promise instanceof Promise) { if (importResult instanceof Promise) {
promise.catch((err) => { importResult.catch((err) => {
console.error('could not import: ', err); console.error('could not import: ', err);
}); });
} }
return promise;
}; };
const refModel = useRef<HTMLDialogElement>(null); const refModel = useRef<HTMLDialogElement>(null);
+1 -1
View File
@@ -11,7 +11,7 @@ export function SDKVersion() {
const refDialog = useRef<HTMLDialogElement>(null); const refDialog = useRef<HTMLDialogElement>(null);
const [sdkVersion, setSdkVersion] = useState('...'); const [sdkVersion, setSdkVersion] = useState('...');
useEffect(() => { useEffect(() => {
getSDKVersion().then(setSdkVersion); getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
}, []); }, []);
return ( return (
+4 -1
View File
@@ -27,7 +27,10 @@ export function SelectFile() {
fileName, fileName,
}), }),
); );
dispatch(processFile({ fileId }));
dispatch(processFile({ fileId })).catch((err) => {
console.log(`failed to add file (id=${fileId}, name=${fileName}, err=${err as Error})`);
});
} }
}; };
@@ -0,0 +1,33 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { FileInput } from '../FileInput';
test('receives multiple files from the file picker', async () => {
const onReceiveFiles = vi.fn();
const files = [new File(['first'], 'first.qmc3'), new File(['second'], 'second.mflac')];
const { container } = render(<FileInput onReceiveFiles={onReceiveFiles}>Choose files</FileInput>);
const input = container.querySelector('input');
if (!input) throw new Error('File input is missing');
await userEvent.upload(input, files);
await waitFor(() => expect(onReceiveFiles).toHaveBeenCalledOnce());
expect(onReceiveFiles.mock.calls[0][0]).toEqual(files);
});
test('receives multiple dropped files', async () => {
const onReceiveFiles = vi.fn();
const files = [new File(['first'], 'first.kgm'), new File(['second'], 'second.ncm')];
render(<FileInput onReceiveFiles={onReceiveFiles}>Drop files</FileInput>);
fireEvent.drop(screen.getByText('Drop files'), {
dataTransfer: {
files,
items: files.map((file) => ({ kind: 'file', type: file.type, getAsFile: () => file })),
types: ['Files'],
},
});
await waitFor(() => expect(onReceiveFiles).toHaveBeenCalledOnce());
expect(onReceiveFiles.mock.calls[0][0]).toEqual(files);
});
+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);
+3 -3
View File
@@ -19,18 +19,18 @@ export class KugouMusicDecipher implements DecipherInstance {
kgm.decrypt(block, offset); kgm.decrypt(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} finally { } finally {
kgmHdr?.free(); kgmHdr?.free();
kgm?.free(); kgm?.free();
} }
} }
public static make() { public static make(this: void) {
return new KugouMusicDecipher(); return new KugouMusicDecipher();
} }
} }
+4 -4
View File
@@ -12,24 +12,24 @@ 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)) {
kwm.decrypt(block, offset); kwm.decrypt(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} finally { } finally {
kwm?.free(); kwm?.free();
header?.free(); header?.free();
} }
} }
public static make() { public static make(this: void) {
return new KuwoMusicDecipher(); return new KuwoMusicDecipher();
} }
} }
+10 -7
View File
@@ -6,22 +6,25 @@ export class Migu3DKeylessDecipher implements DecipherInstance {
cipherName = 'Migu3D (Keyless)'; cipherName = 'Migu3D (Keyless)';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> {
const mg3d = Migu3D.fromHeader(buffer.subarray(0, 0x100));
const audioBuffer = new Uint8Array(buffer); const audioBuffer = new Uint8Array(buffer);
const mg3d = Migu3D.fromHeader(buffer.subarray(0, 0x100));
for (const [block, i] of chunkBuffer(audioBuffer)) { try {
mg3d.decrypt(block, i); for (const [block, i] of chunkBuffer(audioBuffer)) {
mg3d.decrypt(block, i);
}
} finally {
mg3d.free();
} }
mg3d.free();
return { return Promise.resolve({
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static make() { public static make(this: void) {
return new Migu3DKeylessDecipher(); return new Migu3DKeylessDecipher();
} }
} }
@@ -26,17 +26,17 @@ export class NetEaseCloudMusicDecipher implements DecipherInstance {
for (const [block, offset] of chunkBuffer(audioBuffer)) { for (const [block, offset] of chunkBuffer(audioBuffer)) {
ncm.decrypt(block, offset); ncm.decrypt(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} finally { } finally {
ncm.free(); ncm.free();
} }
} }
public static make() { public static make(this: void) {
return new NetEaseCloudMusicDecipher(); return new NetEaseCloudMusicDecipher();
} }
} }
+14 -11
View File
@@ -19,14 +19,14 @@ export class QQMusicV1Decipher implements DecipherInstance {
for (const [block, offset] of chunkBuffer(audioBuffer)) { for (const [block, offset] of chunkBuffer(audioBuffer)) {
decryptQMC1(block, offset); decryptQMC1(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static create() { public static create(this: void) {
return new QQMusicV1Decipher(); return new QQMusicV1Decipher();
} }
} }
@@ -62,25 +62,28 @@ export class QQMusicV2Decipher implements DecipherInstance {
throw new Error('EKey required'); throw new Error('EKey required');
} }
const qmc2 = new QMC2(ekey);
const audioBuffer = buffer.slice(0, buffer.byteLength - footer.size); const audioBuffer = buffer.slice(0, buffer.byteLength - footer.size);
for (const [block, offset] of chunkBuffer(audioBuffer)) { const qmc2 = new QMC2(ekey);
qmc2.decrypt(block, offset); try {
for (const [block, offset] of chunkBuffer(audioBuffer)) {
qmc2.decrypt(block, offset);
}
} finally {
qmc2.free();
} }
qmc2.free();
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static createWithUserKey() { public static createWithUserKey(this: void) {
return new QQMusicV2Decipher(true); return new QQMusicV2Decipher(true);
} }
public static createWithEmbeddedEKey() { public static createWithEmbeddedEKey(this: void) {
return new QQMusicV2Decipher(false); return new QQMusicV2Decipher(false);
} }
} }
+10 -7
View File
@@ -18,20 +18,23 @@ export class QignTingFMDecipher implements DecipherInstance {
}; };
} }
const qtfm = new QingTingFM(key, iv);
const audioBuffer = new Uint8Array(buffer); const audioBuffer = new Uint8Array(buffer);
for (const [block, i] of chunkBuffer(audioBuffer)) { const qtfm = new QingTingFM(key, iv);
qtfm.decrypt(block, i); try {
for (const [block, i] of chunkBuffer(audioBuffer)) {
qtfm.decrypt(block, i);
}
} finally {
qtfm.free();
} }
return Promise.resolve({
return {
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static make() { public static make(this: void) {
return new QignTingFMDecipher(); return new QignTingFMDecipher();
} }
} }
+3 -3
View File
@@ -4,15 +4,15 @@ export class TransparentDecipher implements DecipherInstance {
cipherName = 'none'; cipherName = 'none';
async decrypt(buffer: Uint8Array<ArrayBuffer>): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array<ArrayBuffer>): Promise<DecipherResult | DecipherOK> {
return { return Promise.resolve({
cipherName: 'None', cipherName: 'None',
status: Status.OK, status: Status.OK,
data: buffer, data: buffer,
message: 'No decipher applied', message: 'No decipher applied',
}; });
} }
public static make() { public static make(this: void) {
return new TransparentDecipher(); return new TransparentDecipher();
} }
} }
+11 -8
View File
@@ -6,23 +6,26 @@ export class XiamiDecipher implements DecipherInstance {
cipherName = 'Xiami (XM)'; cipherName = 'Xiami (XM)';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> {
const xm = Xiami.from_header(buffer.subarray(0, 0x10));
const { copyPlainLength } = xm;
const audioBuffer = buffer.slice(0x10); const audioBuffer = buffer.slice(0x10);
for (const [block] of chunkBuffer(audioBuffer.subarray(copyPlainLength))) { const xm = Xiami.from_header(buffer.subarray(0, 0x10));
xm.decrypt(block); try {
const { copyPlainLength } = xm;
for (const [block] of chunkBuffer(audioBuffer.subarray(copyPlainLength))) {
xm.decrypt(block);
}
} finally {
xm.free();
} }
xm.free();
return { return Promise.resolve({
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static make() { public static make(this: void) {
return new XiamiDecipher(); return new XiamiDecipher();
} }
} }
+26 -22
View File
@@ -23,18 +23,18 @@ export class XimalayaAndroidDecipher implements DecipherInstance {
} }
const result = new Uint8Array(buffer); const result = new Uint8Array(buffer);
result.set(slice, 0); result.set(slice, 0);
return { return Promise.resolve({
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: result, data: result,
}; });
} }
public static makeX2M() { public static makeX2M(this: void) {
return new XimalayaAndroidDecipher(decryptX2MHeader, 'X2M'); return new XimalayaAndroidDecipher(decryptX2MHeader, 'X2M');
} }
public static makeX3M() { public static makeX3M(this: void) {
return new XimalayaAndroidDecipher(decryptX3MHeader, 'X3M'); return new XimalayaAndroidDecipher(decryptX3MHeader, 'X3M');
} }
} }
@@ -45,27 +45,31 @@ export class XimalayaPCDecipher implements DecipherInstance {
async decrypt(buffer: Uint8Array, _options: DecryptCommandOptions): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array, _options: DecryptCommandOptions): Promise<DecipherResult | DecipherOK> {
// Detect with first 0x400 bytes // Detect with first 0x400 bytes
const headerSize = XmlyPC.getHeaderSize(buffer.subarray(0, 1024)); const headerSize = XmlyPC.getHeaderSize(buffer.subarray(0, 1024));
const xm = new XmlyPC(buffer.subarray(0, headerSize)); const xmly = new XmlyPC(buffer.subarray(0, headerSize));
const { audioHeader, encryptedHeaderOffset, encryptedHeaderSize } = xm;
const plainAudioDataOffset = encryptedHeaderOffset + encryptedHeaderSize;
const plainAudioDataLength = buffer.byteLength - plainAudioDataOffset;
const encryptedAudioPart = buffer.slice(encryptedHeaderOffset, plainAudioDataOffset);
const encryptedAudioPartLen = xm.decrypt(encryptedAudioPart);
const audioSize = audioHeader.byteLength + encryptedAudioPartLen + plainAudioDataLength;
xm.free();
const result = new Uint8Array(audioSize); try {
result.set(audioHeader); const { audioHeader, encryptedHeaderOffset, encryptedHeaderSize } = xmly;
result.set(encryptedAudioPart, audioHeader.byteLength); const plainAudioDataOffset = encryptedHeaderOffset + encryptedHeaderSize;
result.set(buffer.subarray(plainAudioDataOffset), audioHeader.byteLength + encryptedAudioPartLen); const plainAudioDataLength = buffer.byteLength - plainAudioDataOffset;
return { const encryptedAudioPart = buffer.slice(encryptedHeaderOffset, plainAudioDataOffset);
status: Status.OK, const encryptedAudioPartLen = xmly.decrypt(encryptedAudioPart);
data: result, const audioSize = audioHeader.byteLength + encryptedAudioPartLen + plainAudioDataLength;
cipherName: this.cipherName,
}; const result = new Uint8Array(audioSize);
result.set(audioHeader);
result.set(encryptedAudioPart, audioHeader.byteLength);
result.set(buffer.subarray(plainAudioDataOffset), audioHeader.byteLength + encryptedAudioPartLen);
return Promise.resolve({
status: Status.OK,
data: result,
cipherName: this.cipherName,
});
} finally {
xmly.free();
}
} }
public static make() { public static make(this: void) {
return new XimalayaPCDecipher(); return new XimalayaPCDecipher();
} }
} }
+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;
} }
+1 -1
View File
@@ -6,7 +6,7 @@ export function withWasmClass<T extends { free: () => void }, R>(instance: T, cb
const resp = cb(instance); const resp = cb(instance);
if (resp && isPromise(resp)) { if (resp && isPromise(resp)) {
isAsync = true; isAsync = true;
resp.finally(() => instance.free()); resp.finally(() => instance.free()).catch(() => {});
} }
return resp; return resp;
} finally { } finally {
+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,15 +1,14 @@
import { import { ParseKugouHeaderPayload, ParseKugouHeaderResponse } from '~/decrypt-worker/types.ts';
ParseKugouHeaderPayload, ParseKugouHeaderResponse,
} from '~/decrypt-worker/types.ts';
import { KuGouHeader } from '@unlock-music/crypto'; import { KuGouHeader } from '@unlock-music/crypto';
export const workerParseKugouHeader = async ({ blobURI }: ParseKugouHeaderPayload): Promise<ParseKugouHeaderResponse> => { export const workerParseKugouHeader = async ({
blobURI,
}: ParseKugouHeaderPayload): Promise<ParseKugouHeaderResponse> => {
const blob = await fetch(blobURI, { headers: { Range: 'bytes=0-1023' } }).then((r) => r.blob()); const blob = await fetch(blobURI, { headers: { Range: 'bytes=0-1023' } }).then((r) => r.blob());
const arrayBuffer = await blob.arrayBuffer(); const arrayBuffer = await blob.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer.slice(0, 0x400)); const buffer = new Uint8Array(arrayBuffer.slice(0, 0x400));
let kwm : KuGouHeader | undefined; let kwm: KuGouHeader | undefined;
try { try {
kwm = new KuGouHeader(buffer); kwm = new KuGouHeader(buffer);
@@ -20,4 +19,4 @@ export const workerParseKugouHeader = async ({ blobURI }: ParseKugouHeaderPayloa
} finally { } finally {
kwm?.free(); kwm?.free();
} }
} };
@@ -1,4 +1,4 @@
import { ParseKuwoHeaderPayload, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts'; import { ParseKuwoHeaderPayload, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
import { KuwoHeader } from '@unlock-music/crypto'; import { KuwoHeader } from '@unlock-music/crypto';
export const workerParseKuwoHeader = async ({ blobURI }: ParseKuwoHeaderPayload): Promise<ParseKuwoHeaderResponse> => { export const workerParseKuwoHeader = async ({ blobURI }: ParseKuwoHeaderPayload): Promise<ParseKuwoHeaderResponse> => {
+1 -1
View File
@@ -11,5 +11,5 @@ export async function workerGetQtfmDeviceKey({
board, board,
}: GetQingTingFMDeviceKeyPayload) { }: GetQingTingFMDeviceKeyPayload) {
const buffer = QingTingFM.getDeviceKey(device, brand, model, product, manufacturer, board); const buffer = QingTingFM.getDeviceKey(device, brand, model, product, manufacturer, board);
return hex(buffer); return Promise.resolve(hex(buffer));
} }
+1 -1
View File
@@ -1,5 +1,5 @@
// This is a dummy module for vite/rollup to resolve. // This is a dummy module for vite/rollup to resolve.
export function createRequire() { export function createRequire() {
import('radash'); // we need to import something, so vite don't complain on build const _ = import('radash'); // we need to import something, so vite don't complain on build
throw new Error('this is a dummy module. Do not use'); throw new Error('this is a dummy module. Do not use');
} }
+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';
+16
View File
@@ -11,6 +11,22 @@ export function OtherFAQ() {
<p>该项目进行解密处理。如果加密前的资源没有内嵌元信息或封面,解密的文件也没有。</p> <p>该项目进行解密处理。如果加密前的资源没有内嵌元信息或封面,解密的文件也没有。</p>
<p>请使用第三方工具进行编辑或管理元信息。</p> <p>请使用第三方工具进行编辑或管理元信息。</p>
<Header3 id="batch-download">批量下载约十首后失败 / 无法全部下载</Header3>
<p>
Chromium 系浏览器会限制页面在短时间内通过程序触发的<strong>多个</strong>
文件下载(常见表现为大约十个文件后静默中断,或提示「此网站正在尝试下载多个文件」)。
</p>
<p className="my-2">本站的「下载全部」会按「设定 → 通用设置 → 批量下载」中勾选的顺序尝试:</p>
<ol className="list-decimal pl-8 my-2">
<li>选择输出目录,直接写入文件(推荐,Chrome / Edge)</li>
<li>流式生成单个 ZIP 并保存</li>
<li>在内存中生成 ZIP 后触发一次下载(兼容性最好)</li>
</ol>
<p>
若全部失败会弹出提示。大批量转换也可使用
<ExtLink href="https://git.um-react.app/um/cli">命令行版本</ExtLink>。
</p>
<Header3 id="android-browsers">安卓: 浏览器支持说明</Header3> <Header3 id="android-browsers">安卓: 浏览器支持说明</Header3>
<p>⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。</p> <p>⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。</p>
<div className="flex flex-col md:flex-row gap-2 md:gap-8"> <div className="flex flex-col md:flex-row gap-2 md:gap-8">
+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 (
+4 -8
View File
@@ -26,14 +26,10 @@ export function FileError({ error, code }: FileErrorProps) {
const copyError = () => { const copyError = () => {
if (error) { if (error) {
navigator.clipboard navigator.clipboard.writeText(applyTemplate(ERROR_TEMPLATE, { summary, error })).then(
.writeText(applyTemplate(ERROR_TEMPLATE, { summary, error })) () => toast.success('错误信息已复制到剪贴板'),
.then(() => { (e) => toast.error(`复制错误信息失败: ${e as Error}`),
toast.success('错误信息已复制到剪贴板'); );
})
.catch((e) => {
toast.error(`复制错误信息失败: ${e}`);
});
} }
}; };
+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;
}
@@ -1,20 +1,11 @@
import { RiFileCopyLine } from 'react-icons/ri'; import { RiFileCopyLine } from 'react-icons/ri';
import { toast } from 'react-toastify';
import { ExtLink } from '~/components/ExtLink'; import { ExtLink } from '~/components/ExtLink';
import { FilePathBlock } from '~/components/FilePathBlock.tsx'; import { FilePathBlock } from '~/components/FilePathBlock.tsx';
import { copyToClipboard } from '~/util/clipboard';
const DB_PATH = '%APPDATA%\\KuGou8\\KGMusicV3.db';
export function InstructionsPC() { export function InstructionsPC() {
const DB_PATH = '%APPDATA%\\KuGou8\\KGMusicV3.db'; const copyDbPathToClipboard = () => copyToClipboard(DB_PATH);
const copyDbPathToClipboard = () => {
navigator.clipboard
.writeText(DB_PATH)
.then(() => {
toast.success('已复制到剪贴板');
})
.catch((err) => {
toast.error(`复制失败,请手动复制\n${err}`);
});
};
return ( return (
<> <>
+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;
}
@@ -3,6 +3,7 @@ import { HiWord } from '~/components/HelpText/HiWord';
import NoopExecutable from './assets/noop.exe?base64'; import NoopExecutable from './assets/noop.exe?base64';
import NoopExecutableSource from './assets/noop.asm.txt?base64'; import NoopExecutableSource from './assets/noop.asm.txt?base64';
const QMPC_MMKV_RELEASES_URL = 'https://git.um-react.app/um/qmpc-mmkv/releases';
const PC_CLIENT_URL = 'https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe'; const PC_CLIENT_URL = 'https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe';
const PC_CLIENT_TG_URL = 'https://t.me/um_lsr_ch/24'; const PC_CLIENT_TG_URL = 'https://t.me/um_lsr_ch/24';
@@ -10,14 +11,20 @@ export function InstructionsPC() {
return ( return (
<> <>
<p className="mt-2"> <p className="mt-2">
使用 <span className="text-error">19.57 或更高版本</span>下载的歌曲文件 使用 <span className="text-primary">19.57 至 22.76</span>下载的歌曲文件
<HiWord>需要导入密钥</HiWord>。 <HiWord>需要导入密钥</HiWord>。
<br />
目前未公开密钥获取方式,因此不支持。
</p> </p>
<p className="mt-4"> <p className="mt-4">
使用 <span className="text-primary">19.51 或更低版本</span>下载的歌曲文件 请从{' '}
<ExtLink className="link-info" href={QMPC_MMKV_RELEASES_URL}>
qmpc-mmkv-cli
</ExtLink>{' '}
获取工具,提取密钥文件 <code>qmpc-mmkv-v1.mmkv</code> 后在本页导入。
</p>
<p className="mt-4">
使用 <span className="text-base-content/70">19.51 或更低版本</span>下载的歌曲文件
<HiWord>无需密钥</HiWord>。 <HiWord>无需密钥</HiWord>。
</p> </p>
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));
@@ -53,7 +39,7 @@ export function PanelQMCv2Key() {
toastImportResult(file.name, keys); toastImportResult(file.name, keys);
} catch (e) { } catch (e) {
console.error('error during import: ', e); console.error('error during import: ', e);
alert(`导入数据库时发生错误:${e}`); alert(`导入数据库时发生错误:${e as Error}`);
} }
}; };
@@ -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;
+80
View File
@@ -0,0 +1,80 @@
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 '~/features/qtfm/keyLookup';
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 { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
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 secretKey = useAppSelector(selectStagingQtfmAndroidKey);
const setSecretKey = (secretKey: string) => {
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
};
const handleDataPaste = (e: ClipboardEvent<HTMLInputElement>) => {
const plainText = e.clipboardData.getData('text/plain');
const deviceSecret = parseQtfmDeviceSecretFromText(plainText);
if (deviceSecret) {
e.preventDefault();
setSecretKey(deviceSecret);
return;
}
const dataMap = parseQtfmDeviceInfoFromText(plainText);
if (dataMap) {
e.preventDefault();
workerClientBus
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
}
};
const handleDataInput = (e: ChangeEvent<HTMLInputElement>) => {
setSecretKey(e.target.value);
};
const idSecretKey = useId();
return (
<div className="min-h-0 flex-col grow px-1">
<h2 className="text-2xl font-bold mb-4">蜻蜓 FM</h2>
<p>
<VQuote>蜻蜓 FM</VQuote>的安卓版本需要获取设备密钥,并以此来生成解密密钥。
</p>
<div className="my-4">
<fieldset className="fieldset">
<legend className="fieldset-legend text-lg">
<label htmlFor={idSecretKey}>设备密钥</label>
</legend>
<input
id={idSecretKey}
type="text"
className="input font-mono"
onPaste={handleDataPaste}
value={secretKey}
onChange={handleDataInput}
/>
<p className="label flex-wrap">
粘贴含有设备密钥的信息的内容时将自动提取密钥(如通过
<ExtLink href={QTFM_DEVICE_ID_URL}>
<code>qtfm-device-id</code>
</ExtLink>
获取的设备信息),不需要 root。
</p>
</fieldset>
</div>
<QingTingNotes />
</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 };
};
@@ -0,0 +1,145 @@
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 { 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 [hasRememberedDir, setHasRememberedDir] = useState(false);
const refreshRemembered = useCallback(() => {
hasRememberedDirectoryHandle()
.then(setHasRememberedDir)
.catch(() => setHasRememberedDir(false));
}, []);
useEffect(() => {
refreshRemembered();
}, [refreshRemembered]);
const setBatch = (key: keyof BatchDownloadSettings, value: boolean) => {
dispatch(updateBatchDownloadSetting({ key, value }));
};
const handleClearDirectory = async () => {
await clearRememberedDirectoryHandle();
refreshRemembered();
toast.info('已清除记住的输出目录');
};
const idDir = useId();
const idRemember = useId();
const idStreamZip = useId();
const idBlobZip = 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>
<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={`ml-6 flex flex-col gap-2 ${batch.directoryPicker && canDirectoryPicker ? '' : 'opacity-50'}`}>
<BatchOption
id={idRemember}
checked={batch.rememberDirectory}
disabled={!batch.directoryPicker || !canDirectoryPicker}
title="记住输出目录"
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
onChange={(checked) => setBatch('rememberDirectory', checked)}
/>
<div className="flex items-center gap-2 text-sm">
<span className="text-base-content/70">{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}</span>
<button
type="button"
className="btn btn-xs btn-ghost"
disabled={!hasRememberedDir}
onClick={() => void handleClearDirectory()}
>
清除
</button>
</div>
</div>
<BatchOption
id={idStreamZip}
checked={batch.streamingZip && canStreamingZip}
disabled={!canStreamingZip}
dimmed={!canStreamingZip}
title="流式生成 ZIP"
description={
canStreamingZip
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
: '当前浏览器不支持 showSaveFilePicker,无法流式写出 ZIP。'
}
onChange={(checked) => setBatch('streamingZip', checked)}
/>
<BatchOption
id={idBlobZip}
checked={batch.blobZip}
title="生成单个 ZIP 并触发下载"
description={
<>
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
</>
}
onChange={(checked) => setBatch('blobZip', checked)}
/>
</div>
</div>
);
}
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) {
return (
<label className={`flex items-start gap-2 ${dimmed ? 'opacity-50' : ''}`}>
<input
id={id}
type="checkbox"
className="checkbox checkbox-sm mt-0.5"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
/>
<span>
<span className="font-medium">{title}</span>
<span className="block text-sm text-base-content/70">{description}</span>
</span>
</label>
);
}
@@ -1,127 +0,0 @@
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 { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
import { Ruby } from '~/components/Ruby';
import { HiWord } from '~/components/HelpText/HiWord';
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
export function PanelQingTing() {
const dispatch = useAppDispatch();
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
const setSecretKey = (secretKey: string) => {
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
};
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) {
e.preventDefault();
setSecretKey(matchDeviceSecret[1]);
return;
}
const dataMap = Object.create(null);
for (const [, key, value] of plainText.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) {
dataMap[key.toLowerCase()] = value;
}
const { product, device, manufacturer, brand, board, model } = dataMap;
if (product && device && manufacturer && brand && board && model) {
e.preventDefault();
workerClientBus
.request<string, GetQingTingFMDeviceKeyPayload>(
DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY,
dataMap,
)
.then(setSecretKey)
.catch((err) => {
alert(`生成设备密钥时发生错误: ${err}`);
});
}
};
const handleDataInput = (e: ChangeEvent<HTMLInputElement>) => {
setSecretKey(e.target.value);
};
const idSecretKey = useId();
return (
<div className="min-h-0 flex-col grow px-1">
<h2 className="text-2xl font-bold mb-4">蜻蜓 FM</h2>
<p>
<VQuote>蜻蜓 FM</VQuote>的安卓版本需要获取设备密钥,并以此来生成解密密钥。
</p>
<div className="my-4">
<fieldset className="fieldset">
<legend className="fieldset-legend text-lg">
<label htmlFor={idSecretKey}>设备密钥</label>
</legend>
<input
id={idSecretKey}
type="text"
className="input font-mono"
onPaste={handleDataPaste}
value={secretKey}
onChange={handleDataInput}
/>
<p className="label flex-wrap">
粘贴含有设备密钥的信息的内容时将自动提取密钥(如通过
<ExtLink href={QTFM_DEVICE_ID_URL}>
<code>qtfm-device-id</code>
</ExtLink>
获取的设备信息),不需要 root。
</p>
</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>
</div>
);
}
@@ -1 +0,0 @@
// TODO: Popup dialog for QingTing instructions
+29 -5
View File
@@ -1,16 +1,40 @@
import { debounce } from 'radash'; import { debounce } from 'radash';
import type { AppStore } from '~/store'; import type { AppStore } from '~/store';
import { settingsSlice, setProductionChanges, ProductionSettings } from './settingsSlice'; import {
settingsSlice,
setProductionChanges,
ProductionSettings,
DEFAULT_BATCH_DOWNLOAD_SETTINGS,
BatchDownloadSettings,
} 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';
function mergeSettings(settings: ProductionSettings): ProductionSettings { function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
if (!source) {
return result;
}
for (const key of Object.keys(DEFAULT_BATCH_DOWNLOAD_SETTINGS) as (keyof BatchDownloadSettings)[]) {
if (typeof source[key] === 'boolean') {
result[key] = source[key];
}
}
return result;
}
/** 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);
if (settings?.qmc2) { if (settings?.qmc2) {
const { allowFuzzyNameSearch, keys } = settings.qmc2; const { allowFuzzyNameSearch, keys } = settings.qmc2;
for (const [k, v] of enumObject(keys)) { for (const [k, v] of enumObject(keys)) {
@@ -45,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;
@@ -55,7 +79,7 @@ export function persistSettings(store: AppStore, storageKey = DEFAULT_STORAGE_KE
let lastSettings: unknown; let lastSettings: unknown;
try { try {
const loadedSettings: ProductionSettings = JSON.parse(localStorage.getItem(storageKey) ?? ''); const loadedSettings = JSON.parse(localStorage.getItem(storageKey) ?? '') as ProductionSettings;
if (loadedSettings) { if (loadedSettings) {
const mergedSettings = mergeSettings(loadedSettings); const mergedSettings = mergeSettings(loadedSettings);
store.dispatch(setProductionChanges(mergedSettings)); store.dispatch(setProductionChanges(mergedSettings));
+12 -64
View File
@@ -1,68 +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 selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
export const selectFinalQMCv2Settings = (state: RootState) => state.settings.production.qmc2; export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.general.batchDownload;
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;
+89 -117
View File
@@ -1,27 +1,41 @@
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 {
directoryPicker: boolean;
rememberDirectory: boolean;
streamingZip: boolean;
blobZip: boolean;
}
export interface StagingSettings { export interface StagingSettings {
general: {
batchDownload: BatchDownloadSettings;
};
qmc2: { qmc2: {
keys: StagingQMCv2Key[]; keys: StagingQMCv2Key[];
allowFuzzyNameSearch: boolean; allowFuzzyNameSearch: boolean;
@@ -29,15 +43,20 @@ 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 {
general: {
batchDownload: BatchDownloadSettings;
};
qmc2: { qmc2: {
keys: ProductionQMCv2Keys; // { [fileName]: ekey } keys: ProductionQMCv2Keys; // { [fileName]: ekey }
allowFuzzyNameSearch: boolean; allowFuzzyNameSearch: boolean;
@@ -45,14 +64,23 @@ 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 = {
directoryPicker: true,
rememberDirectory: true,
streamingZip: true,
blobZip: true,
};
export interface SettingsState { export interface SettingsState {
dirty: boolean; dirty: boolean;
staging: StagingSettings; staging: StagingSettings;
@@ -62,20 +90,25 @@ export interface SettingsState {
const initialState: SettingsState = { const initialState: SettingsState = {
dirty: false, dirty: false,
staging: { staging: {
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: {
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
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: {
batchDownload: { ...staging.general.batchDownload },
},
qmc2: { qmc2: {
keys: stagingKeyToProduction(staging.qmc2.keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue), keys: stagingKeyToProduction(staging.qmc2.keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue),
allowFuzzyNameSearch: staging.qmc2.allowFuzzyNameSearch, allowFuzzyNameSearch: staging.qmc2.allowFuzzyNameSearch,
@@ -89,7 +122,10 @@ const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({
qtfm: staging.qtfm, qtfm: staging.qtfm,
}); });
const productionToStaging = (production: ProductionSettings): StagingSettings => ({ export const productionToStaging = (production: ProductionSettings): StagingSettings => ({
general: {
batchDownload: { ...production.general.batchDownload },
},
qmc2: { qmc2: {
keys: productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging), keys: productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging),
allowFuzzyNameSearch: production.qmc2.allowFuzzyNameSearch, allowFuzzyNameSearch: production.qmc2.allowFuzzyNameSearch,
@@ -103,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,
@@ -114,113 +154,44 @@ 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;
}, },
// updateBatchDownloadSetting(
state,
{ payload: { key, value } }: PayloadAction<{ key: keyof BatchDownloadSettings; value: boolean }>,
) {
state.staging.general.batchDownload[key] = value;
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;
@@ -252,6 +223,7 @@ export const {
kugouImportKeys, kugouImportKeys,
qtfmAndroidUpdateKey, qtfmAndroidUpdateKey,
updateBatchDownloadSetting,
commitStagingChange, commitStagingChange,
discardStagingChanges, discardStagingChanges,
+15 -5
View File
@@ -1,13 +1,23 @@
import type { FC } from 'react'; import type { FC } from 'react';
import { PanelQMCv2Key } from '~/features/settings/panels/PanelQMCv2Key.tsx'; import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
import { PanelKWMv2Key } from '~/features/settings/panels/PanelKWMv2Key.tsx'; import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
import { PanelKGGKey } from '~/features/settings/panels/PanelKGGKey.tsx'; import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
import { PanelQingTing } from '~/features/settings/panels/PanelQingTing.tsx'; import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.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 },
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key }, qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key }, kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey }, kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing }, qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing },
// misc: { name: '其它/待定', Tab: () => <p>这里空空如也~</p> },
} as const; } as const;
+3 -2
View File
@@ -1,10 +1,11 @@
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/vitest';
// FIXME: Use something like jsdom-worker? // FIXME: Use something like jsdom-worker?
// see: https://github.com/developit/jsdom-worker // see: https://github.com/developit/jsdom-worker
if (!global.Worker) { if (!global.Worker) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(global as any).Worker = class MockWorker { (global as any).Worker = class MockWorker {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
events: Record<string, (e: unknown) => void> = Object.create(null); events: Record<string, (e: unknown) => void> = Object.create(null);
onmessage = undefined; onmessage = undefined;
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more