28 Commits
Author SHA1 Message Date
鲁树人 79e5b45e6b refactor: update HTML structure and improve deployment instructions
- Cleaned up the HTML structure in `index.html` for better readability.
- Updated `README.md` to clarify deployment instructions for subdirectory setups.
- Removed unused `BASE_URL` declaration from `vite-env.d.ts` and adjusted `AppRoot` to use `import.meta.env.BASE_URL` for improved environment variable handling.
2026-11-05 20:47:16 +09:00
鲁树人 ef4cd9c21e feat: update asset directory structure
- Changed the asset directory in Vite configuration to 'um-react.assets' for better organization.
- Updated the minification script to read from and write to the new asset directory, ensuring consistency in asset handling.
2026-11-05 20:36:16 +09:00
鲁树人 94eab8ecf6 fix: update base path in Vite configuration for correct asset resolution 2026-11-05 20:34:26 +09:00
鲁树人 d424837e66 feat: integrate platform capabilities for enhanced download management
- Refactored `DownloadAll` component to utilize platform capabilities for download types, improving flexibility in handling various download methods.
- Introduced `buildEnabledDownloadModes` function to determine available download modes based on user settings and platform capabilities.
- Updated `FileRow` and `PanelGeneral` components to conditionally render download options based on platform capabilities.
- Added tests for new functionalities in `DownloadAll`, `FileRow`, and `PanelGeneral` to ensure correct behavior under different platform conditions.
- Enhanced error handling for unsupported download methods, providing clearer feedback to users.
2026-11-01 11:32:04 +09:00
鲁树人 b5fdc8ebbe feat: integrate platform provider with enhanced crypto handling and new AppLayout component
- Added a new `AppLayout` component to manage navigation and routing within the application.
- Refactored `AppRoot` to utilize `PlatformLoadGuard` for ensuring platform readiness before rendering.
- Introduced `useAppStore` hook for accessing the Redux store directly.
- Updated `SDKVersion` and `PanelQingTing` components to leverage the new platform provider for crypto operations.
- Enhanced error handling with `PlatformNotInitializedError` for better user feedback on uninitialized platform states.
- Added tests for new functionalities and ensured compatibility with the updated platform architecture.
2026-11-01 11:18:24 +09:00
鲁树人 cb5531e9e4 feat: enhance settings persistence with platform provider integration
- Updated `persistSettings` to accept a `PlatformProvider`, enabling dynamic loading and saving of production settings.
- Refactored settings loading to handle null cases and invalid JSON gracefully.
- Introduced a new `browserSettingsIo` module for managing settings storage in the browser.
- Added comprehensive tests for `persistSettings` and `browserSettingsIo` to ensure correct functionality and error handling.
- Integrated the updated settings persistence into `AppRoot` for improved platform-specific behavior.
2026-11-01 10:54:13 +09:00
鲁树人 cc688b85bd feat: implement platform provider architecture and integrate into AppRoot
- Introduced a new platform provider architecture to manage platform-specific functionalities.
- Created `PlatformProvider`, `PlatformContext`, and related capabilities for handling downloads and key imports.
- Integrated the platform provider into `AppRoot`, allowing for dynamic platform management.
- Added error handling classes for unsupported and unimplemented methods.
- Updated tests to validate the new platform provider functionalities and capabilities.
2026-11-01 10:46:52 +09:00
鲁树人 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
157 changed files with 7135 additions and 4675 deletions

No files matched your search

+3 -1
View File
@@ -7,7 +7,9 @@ body:
value: |
### 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)
* [通过 Telegram 下载](https://t.me/um_lsr_ch/24)
-3
View File
@@ -4,8 +4,6 @@ on: [push]
jobs:
build:
runs-on: ubuntu-latest
env:
npm_config_registry: https://registry.npmmirror.com
steps:
- name: Check out repository code
uses: actions/checkout@v4
@@ -40,7 +38,6 @@ jobs:
draft: true
files: |
release/um-react-*.zip
release/um-react-win64-*.zip
body: |
上个版本:[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/
+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 PATH="$PNPM_HOME:$PATH"
WORKDIR /app
@@ -9,7 +9,7 @@ RUN corepack enable pnpm \
&& apt-get clean \
&& 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
COPY . .
RUN pnpm install --frozen-lockfile
+35 -12
View File
@@ -10,7 +10,7 @@
- CI 自动构建已经部署,可以在 [Actions][um-react-actions] 寻找对应的<ruby>构建产物<rp>(</rp><rt>Artifact</rt><rp>)</rp> </ruby>下载。
- [常见问题参考](./docs/faq_zh-hans.md)
> **WARNING**
> [!WARNING]
> 在本站 fork 不会起到备份的作用,只会浪费服务器储存空间。如无必要请勿 fork 该仓库。
[授权协议]: 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
[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]
- [x] 网易云音乐 (`.ncm`)
- [x] 虾米音乐 (`.xm`)
- [x] 酷我音乐 (`.kwm`)
- [x] 酷我音乐 (`.kwm` / `.mflac`) [^kuwo-key-android]
- [x] 酷狗音乐 (`.kgm` / `.vpr` / `.kgg`)
- PC / 安卓客户端的 `kgg` 文件需要提供密钥数据库。
- PC / 安卓客户端[^kgg-android]的 `kgg` 文件需要提供密钥数据库。
- [x] 喜马拉雅 (`.x2m` / `.x3m` / `.xm`)
- [x] 咪咕音乐格式 (`.mg3d`)
- [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]。
⚠️ 如果文件太大,请上传到不需要登入下载的网盘,如 [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
## 使用 Docker 构建、部署 (Linux)
## 使用 Docker 构建、部署
首先克隆仓库并进入目录:
@@ -86,13 +92,30 @@ docker run -d -p 8080:80 --name um-react um-react
然后访问 `http://localhost:8080` 即可。
## 部署到子目录
> [!NOTE]
> 官方 Docker 镜像与默认构建产物按站点**根路径**(`/`)部署,不支持部署到子目录下。
若要部署到子目录(例如 `https://example.com/um-react/`),你需要重新使用 Vite 进行构建,并指定 `--base` 参数(路径以 `/` 开头、以 `/` 结尾)。
以部署到 `https://example.com/um-react/` 为例:
```sh
pnpm exec vite build --base=/um-react/
pnpm build:finalize
```
部署时,服务器还需把该子目录下的所有前端路由回退到对应的 `index.html`(SPA)。
## 开发相关
从源码运行或编译生产版本,请参考文档「[新手上路](./docs/getting-started.zh.md)」。
### 解密库开发
⚠️ 如果只是进行前端方面的更改,你可以跳过该节。
> [!TIP]
> 如果只是进行前端方面的更改,你可以跳过该节。
请参考文档「[面向 `@unlock-music/crypto` 开发](./docs/develop-with-um_crypto.zh.md)」。
+13 -1
View File
@@ -10,7 +10,7 @@
#### 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,也建议用电脑操作。
@@ -71,6 +71,18 @@
- 雷电模拟器可以在「模拟器设置」 → 「其他设置」中启用 root 特权。
![雷电模拟器 其他设置](../src/faq/assets/[email protected])
### 批量下载约十首后失败 / 无法全部下载
Chromium 系浏览器会限制页面在短时间内通过程序触发的**多个**文件下载(常见表现为大约十个文件后静默中断,或提示「此网站正在尝试下载多个文件」)。
本站的「下载全部」会按「设定 → 通用设置 → 批量下载」中勾选的顺序尝试:
1. 选择输出目录,直接写入文件(推荐,Chrome / Edge)
2. 流式生成单个 ZIP 并保存
3. 在内存中生成 ZIP 后触发一次下载(兼容性最好)
若全部失败会弹出提示。大批量转换也可使用 [命令行版本](https://git.um-react.app/um/cli)。
### Via 等浏览器无法正常解密/下载
⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。
+6 -2
View File
@@ -4,8 +4,8 @@
## 安装依赖
- 安装 Node v16.17 或更高,推荐当前最新的 Node LTS 版本。
- 安装/激活 `pnpm` [^1]:`corepack prepare pnpm@latest --activate`
- 安装 Node 24.22.0;pnpm 也会根据 `package.json` 中的 `devEngines.runtime` 自动获取该版本。
- 安装/激活项目指定的 `pnpm` [^1]:`corepack prepare pnpm@12.14.0 --activate`
- 安装软件依赖:`pnpm i --frozen-lockfile`
[^1]: 参考 pnpm 说明「[使用 Corepack 安装](https://pnpm.io/zh/installation#使用-corepack-安装)」。
@@ -34,6 +34,10 @@ pnpm build
[vite-preview-url]: http://localhost:4173/
### TypeScript 工具链
编译和 ESLint 统一使用 TypeScript 6.x,暂不升级到 TypeScript 7。
## 打包 `.zip`
建议在 Linux 环境下执行,可参考 `.drone.yml` CI 文件。
+14 -3
View File
@@ -1,15 +1,16 @@
import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';
import reactRefresh from 'eslint-plugin-react-refresh';
import reactHooks from 'eslint-plugin-react-hooks';
import eslintConfigPrettier from 'eslint-config-prettier/flat';
import globals from 'globals';
export default tseslint.config(
export default defineConfig(
eslint.configs.recommended,
tseslint.configs.recommended,
tseslint.configs.recommendedTypeChecked,
reactRefresh.configs.recommended,
reactHooks.configs['recommended-latest'],
reactHooks.configs.flat.recommended,
eslintConfigPrettier,
{
@@ -40,4 +41,14 @@ export default tseslint.config(
},
},
},
{
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.mjs', 'src/*.mjs', 'scripts/*.mjs'],
},
},
},
},
);
+60 -66
View File
@@ -1,7 +1,7 @@
{
"name": "um-react",
"private": true,
"version": "0.6.0",
"version": "0.6.2",
"type": "module",
"scripts": {
"start": "vite",
@@ -17,65 +17,66 @@
"prepare": "simple-git-hooks"
},
"dependencies": {
"@reduxjs/toolkit": "^2.9.0",
"@reduxjs/toolkit": "^2.13.0",
"@unlock-music/crypto": "^0.1.12",
"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",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-dropzone": "^14.3.8",
"react-icons": "^5.5.0",
"react-redux": "^9.2.0",
"react-router": "^7.8.2",
"react-syntax-highlighter": "^15.6.6",
"react-toastify": "^11.0.5",
"sql.js": "^1.13.0"
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-icons": "^5.7.0",
"react-redux": "^9.3.0",
"react-router": "^8.5.0",
"react-syntax-highlighter": "^16.1.2",
"react-toastify": "^11.1.0",
"sql.js": "^1.15.1"
},
"devDependencies": {
"@eslint/js": "^9.35.0",
"@rollup/plugin-replace": "^6.0.2",
"@tailwindcss/vite": "^4.1.13",
"@testing-library/jest-dom": "^6.8.0",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^24.3.1",
"@types/react": "^19.1.12",
"@types/react-dom": "^19.1.9",
"@eslint/js": "^10.0.1",
"@rollup/plugin-replace": "^6.0.3",
"@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.8",
"@types/node": "^26.6.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/sql.js": "^1.4.9",
"@types/tar-stream": "^3.1.4",
"@types/wicg-file-system-access": "^2023.10.6",
"@typescript-eslint/eslint-plugin": "^8.42.0",
"@typescript-eslint/parser": "^8.42.0",
"@vitejs/plugin-react": "^5.0.2",
"@vitest/coverage-v8": "^3.2.4",
"@vitest/ui": "^3.2.4",
"daisyui": "^5.1.8",
"eslint": "^9.35.0",
"@types/sql.js": "^1.4.11",
"@types/tar-stream": "^3.1.5",
"@types/wicg-file-system-access": "^2023.10.7",
"@typescript-eslint/eslint-plugin": "^8.72.0",
"@typescript-eslint/parser": "^8.72.0",
"@vitejs/plugin-react": "^6.1.2",
"@vitest/coverage-v8": "^5.0.5",
"@vitest/ui": "^5.0.5",
"daisyui": "^5.7.50",
"eslint": "^10.13.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"globals": "^17.13.0",
"husky": "^9.1.7",
"jsdom": "^26.1.0",
"lint-staged": "^16.1.6",
"prettier": "^3.6.2",
"rollup": "^4.50.1",
"sass": "^1.92.1",
"simple-git-hooks": "^2.13.1",
"tailwindcss": "^4.1.13",
"tar-stream": "^3.1.7",
"terser": "^5.44.0",
"typescript": "^5.9.2",
"typescript-eslint": "^8.42.0",
"vite": "^7.1.5",
"vite-plugin-pwa": "^1.0.3",
"vite-plugin-top-level-await": "^1.6.0",
"vite-plugin-wasm": "^3.5.0",
"vitest": "^3.2.4",
"workbox-build": "^7.3.0",
"workbox-window": "^7.3.0"
"jsdom": "^30.1.3",
"lint-staged": "^17.6.0",
"prettier": "^3.9.10",
"rollup": "^4.64.12",
"sass": "^1.105.2",
"simple-git-hooks": "^2.14.0",
"tailwindcss": "^4.3.3",
"tar-stream": "^3.2.2",
"terser": "^5.51.2",
"typescript": "^6.0.3",
"typescript-eslint": "^8.72.0",
"vite": "^8.3.4",
"vite-plugin-pwa": "^2.0.0",
"vite-plugin-wasm": "^3.6.0",
"vitest": "^5.0.5",
"workbox-build": "^7.4.1",
"workbox-window": "^7.4.1"
},
"lint-staged": {
"*": "prettier --write --ignore-unknown",
@@ -90,19 +91,12 @@
"printWidth": 120,
"tabWidth": 2
},
"pnpm": {
"patchedDependencies": {
"sql.js": "patches/sql.js.patch"
},
"overrides": {
"sourcemap-codec": "npm:@jridgewell/[email protected]"
},
"onlyBuiltDependencies": [
"@swc/core",
"@tailwindcss/oxide",
"esbuild",
"simple-git-hooks"
]
"devEngines": {
"runtime": {
"name": "node",
"version": "24.22.0",
"onFail": "download"
}
},
"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
+5 -3
View File
@@ -1,7 +1,9 @@
import { minify } from 'terser';
import { readFileSync, writeFileSync, readdirSync } from 'fs';
for (const file of readdirSync('dist/assets')) {
const assetsDir = 'dist/um-react.assets';
for (const file of readdirSync(assetsDir)) {
if (!/\.(mjs|js)$/.test(file)) {
continue;
}
@@ -9,11 +11,11 @@ for (const file of readdirSync('dist/assets')) {
console.log(`minifying ${file}...`);
const isModule = /\.mjs$/.test(file);
const output = await minify(readFileSync(`dist/assets/${file}`, 'utf-8'), {
const output = await minify(readFileSync(`${assetsDir}/${file}`, 'utf-8'), {
compress: true,
mangle: true,
module: isModule,
});
writeFileSync(`dist/assets/${file}`, output.code);
writeFileSync(`${assetsDir}/${file}`, output.code);
}
+15 -6
View File
@@ -1,19 +1,28 @@
import { renderWithProviders, screen, waitFor } from '~/test-utils/test-helper';
import { act, renderWithProviders, screen } from '~/test-utils/test-helper';
import { AppRoot } from '~/components/AppRoot';
vi.mock('../decrypt-worker/client', () => {
// Must match the dynamic import specifier used by browserCrypto (`~/decrypt-worker/client`).
// Plain functions: vitest `mockReset` clears vi.fn mockResolvedValue between tests.
vi.mock('~/decrypt-worker/client', () => {
return {
workerClientBus: {
request: vi.fn().mockResolvedValue('dummy'),
request: () => Promise.resolve('dummy'),
},
decryptionQueue: {
add: () => Promise.resolve({ decrypted: 'blob://dummy', ext: 'flac' }),
},
};
});
test('should be able to render App', async () => {
renderWithProviders(<AppRoot />);
await act(async () => {
renderWithProviders(<AppRoot />);
// Flush Suspense retry after platform.init() (dynamic import) settles.
await Promise.resolve();
});
// Should eventually load sdk version
await waitFor(() => screen.getByTestId('sdk-version'));
// Platform Suspense gate + SDK version fetch
expect(await screen.findByTestId('sdk-version')).toBeInTheDocument();
// Quick sanity check of known strings.
expect(screen.getByText(/音乐解锁/i)).toBeInTheDocument();
+67
View File
@@ -0,0 +1,67 @@
import { NavLink, Route, Routes } from 'react-router';
import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
import { Bounce, ToastContainer } from 'react-toastify';
import { Footer } from '~/components/Footer';
import { FaqHome } from '~/faq/FaqHome';
import { FAQ_PAGES } from '~/faq/FAQPages';
import { SettingsHome } from '~/features/settings/SettingsHome';
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
import { FaqTab } from '~/tabs/FaqTab';
import { MainTab } from '~/tabs/MainTab';
import { SettingsTab } from '~/tabs/SettingsTab';
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
/** Main chrome (nav / routes / toast / footer). Render only after platform `init()` resolves. */
export function AppLayout() {
return (
<>
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
<NavLink to="/" role="tab" className={tabClassNames}>
<MdHome />
应用
</NavLink>
<NavLink to="/settings" role="tab" className={tabClassNames}>
<MdSettings />
设置
</NavLink>
<NavLink to="/questions" role="tab" className={tabClassNames}>
<MdQuestionAnswer />
答疑
</NavLink>
</div>
<main className="flex-1 flex justify-center min-h-0 overflow-auto">
<Routes>
<Route path="/" Component={MainTab} />
<Route path="/settings" Component={SettingsTab}>
<Route index Component={SettingsHome} />
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
<Route key={key} path={key} Component={Tab} />
))}
</Route>
<Route path="/questions" Component={FaqTab}>
<Route index Component={FaqHome} />
{FAQ_PAGES.map(({ id, Component }) => (
<Route key={id} path={id} Component={Component} />
))}
</Route>
</Routes>
</main>
<ToastContainer
position="bottom-center"
autoClose={5000}
newestOnTop
closeOnClick={false}
pauseOnFocusLoss
draggable
theme="colored"
transition={Bounce}
/>
<Footer />
</>
);
}
+30 -63
View File
@@ -1,77 +1,44 @@
import { useEffect } from 'react';
import { BrowserRouter, NavLink, Route, Routes } from 'react-router';
import { MdSettings, MdHome, MdQuestionAnswer } from 'react-icons/md';
import { MainTab } from '~/tabs/MainTab';
import { SettingsTab } from '~/tabs/SettingsTab';
import { Suspense } from 'react';
import { BrowserRouter } from 'react-router';
import { Provider } from 'react-redux';
import { AppLayout } from '~/components/AppLayout';
import { persistSettings } from '~/features/settings/persistSettings';
import { createPlatformProvider } from '~/platform/createPlatformProvider';
import { PlatformLoadGuard } from '~/platform/PlatformLoadGuard';
import { PlatformProviderHost } from '~/platform/PlatformContext';
import { setPlatform } from '~/platform/platformSingleton';
import { setupStore } from '~/store';
import { Footer } from '~/components/Footer';
import { FaqTab } from '~/tabs/FaqTab';
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
import { Bounce, ToastContainer } from 'react-toastify';
import { SettingsHome } from '~/features/settings/SettingsHome';
import { FAQ_PAGES } from '~/faq/FAQPages';
import { FaqHome } from '~/faq/FaqHome';
// Private to this file only.
const store = setupStore();
const platform = createPlatformProvider();
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
const platformReady = platform.init().then(() => {
setPlatform(platform);
persistSettings(store, platform);
});
function AppBootFallback() {
return (
<div className="flex flex-1 items-center justify-center min-h-0" role="status" aria-live="polite">
<span className="loading loading-spinner loading-lg text-primary" />
<span className="sr-only">加载中</span>
</div>
);
}
export function AppRoot() {
useEffect(() => persistSettings(store), []);
return (
<BrowserRouter>
<BrowserRouter basename={import.meta.env.BASE_URL}>
<Provider store={store}>
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
<NavLink to="/" role="tab" className={tabClassNames}>
<MdHome />
应用
</NavLink>
<NavLink to="/settings" role="tab" className={tabClassNames}>
<MdSettings />
设置
</NavLink>
<NavLink to="/questions" role="tab" className={tabClassNames}>
<MdQuestionAnswer />
答疑
</NavLink>
</div>
<main className="flex-1 flex justify-center min-h-0 overflow-auto">
<Routes>
<Route path="/" Component={MainTab} />
<Route path="/settings" Component={SettingsTab}>
<Route index Component={SettingsHome} />
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
<Route key={key} path={key} Component={Tab} />
))}
</Route>
<Route path="/questions" Component={FaqTab}>
<Route index Component={FaqHome} />
{FAQ_PAGES.map(({ id, Component }) => (
<Route key={id} path={id} Component={Component} />
))}
</Route>
</Routes>
</main>
<ToastContainer
position="bottom-center"
autoClose={5000}
newestOnTop
closeOnClick={false}
pauseOnFocusLoss
draggable
theme="colored"
transition={Bounce}
/>
<Footer />
<PlatformProviderHost provider={platform}>
<Suspense fallback={<AppBootFallback />}>
<PlatformLoadGuard ready={platformReady}>
<AppLayout />
</PlatformLoadGuard>
</Suspense>
</PlatformProviderHost>
</Provider>
</BrowserRouter>
);
+64 -51
View File
@@ -2,83 +2,96 @@ import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-l
import { FaDownload } from 'react-icons/fa';
import { useAppSelector } from '~/hooks';
import { toast } from 'react-toastify';
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
import { buildEnabledDownloadModes } from '~/platform/buildEnabledDownloadModes';
import { usePlatform } from '~/platform/PlatformContext';
export function DownloadAll() {
const files = useAppSelector(selectFiles);
const onClickDownloadAll = async () => {
console.time('DownloadAll'); //开始计时
const fileCount = Object.keys(files).length;
const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
const { download, capabilities } = usePlatform();
if (capabilities.downloadTypes.length === 0) {
return null;
}
const downloadAllAsync = async () => {
const fileList = Object.values(files);
const fileCount = fileList.length;
if (fileCount === 0) {
toast.warning('未添加文件');
return;
}
//判断所有文件是否处理完成
const allComplete = Object.values(files).every((file) => file.state !== ProcessState.PROCESSING);
const allComplete = fileList.every((file) => file.state !== ProcessState.PROCESSING);
if (!allComplete) {
toast.warning('请等待所有文件解密完成');
return;
}
//过滤处理失败的文件
const completeFiles = Object.values(files).filter((file) => file.state === ProcessState.COMPLETE);
//开始下载
let dir: FileSystemDirectoryHandle | undefined;
try {
dir = await window.showDirectoryPicker({ mode: 'readwrite' });
} catch (e) {
console.error(e);
if (e instanceof Error && e.name === 'AbortError') {
return;
}
const completeFiles = fileList.filter((file) => file.state === ProcessState.COMPLETE);
if (completeFiles.length === 0) {
toast.warning('没有可下载的已解密文件');
return;
}
// Single file: direct blob download, no ZIP / directory picker.
if (completeFiles.length === 1) {
const file = completeFiles[0];
await download.saveOne({
url: file.decrypted,
fileName: decryptedDownloadName(file),
});
toast.success('已开始下载');
return;
}
const modes = buildEnabledDownloadModes(batchSettings, capabilities.downloadTypes);
if (modes.length === 0) {
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
return;
}
toast.warning('开始下载,请稍候');
const promises = Object.values(completeFiles).map(async (file) => {
console.log(`开始下载: ${file.fileName}`);
const manyInput = {
files: completeFiles.map((file) => ({
url: file.decrypted,
fileName: decryptedDownloadName(file),
})),
rememberDirectory: batchSettings.rememberDirectory,
};
for (const mode of modes) {
try {
if (dir) {
await DownloadNew(dir, file);
} else {
await DownloadOld(file);
const result = await download.saveMany(mode, manyInput);
if (result === 'ok') {
return;
}
console.log(`成功下载: ${file.fileName}`);
// cancelled / skipped → try next mode
} catch (e) {
console.error(`下载失败: ${file.fileName}`, e);
toast.error(`出现错误: ${e}`);
throw e;
console.error(`批量下载模式 ${mode} 失败`, e);
toast.error(`下载方式失败,尝试下一种: ${e instanceof Error ? e.message : String(e)}`);
}
});
await Promise.allSettled(promises).then((f) => {
const success = f.filter((result) => result.status === 'fulfilled').length;
if (success === fileCount) {
toast.success(`成功下载: ${success}/${fileCount}首`);
} else {
toast.warning(`成功下载: ${success}/${fileCount}首`);
}
});
console.timeEnd('DownloadAll'); //停止计时
}
toast.error('批量下载失败:当前浏览器不支持或您取消了所有可用方式。可在「设定 → 通用设置」调整选项。');
};
function onDownloadAll() {
downloadAllAsync().catch((e) => {
console.error('下载全部出现错误', e);
toast.error(`批量下载出现错误: ${e instanceof Error ? e.message : String(e)}`);
});
}
return (
<button className="btn btn-primary" id="downloadAll" onClick={onClickDownloadAll} title="下载全部">
<button className="btn btn-primary" id="downloadAll" onClick={onDownloadAll} title="下载全部">
<FaDownload />
</button>
);
}
async function DownloadNew(dir: FileSystemDirectoryHandle, file: DecryptedAudioFile) {
const fileHandle = await dir.getFileHandle(file.cleanName + '.' + file.ext, { create: true });
const writable = await fileHandle.createWritable();
await fetch(file.decrypted).then((res) => res.body?.pipeTo(writable));
}
async function DownloadOld(file: DecryptedAudioFile) {
const a = document.createElement('a');
a.href = file.decrypted;
a.download = file.cleanName + '.' + file.ext;
document.body.append(a);
a.click();
a.remove();
function decryptedDownloadName(file: DecryptedAudioFile): string {
return `${file.cleanName}.${file.ext}`;
}
+1 -1
View File
@@ -7,7 +7,7 @@ export type DownloadBase64Props = {
filename: string;
mimetype?: string;
className?: string;
icon?: boolean | ReactNode;
icon?: ReactNode | true | false;
children?: ReactNode;
};
+1 -1
View File
@@ -2,7 +2,7 @@ import type { AnchorHTMLAttributes, ReactNode } from 'react';
import { FiExternalLink } from 'react-icons/fi';
export type ExtLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
icon?: boolean | ReactNode;
icon?: ReactNode | true | false;
};
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) {
const handleFileReceived = (files: File[]) => {
const promise = onImport(files[0]);
if (promise instanceof Promise) {
promise.catch((err) => {
const importResult = onImport(files[0]);
if (importResult instanceof Promise) {
importResult.catch((err) => {
console.error('could not import: ', err);
});
}
return promise;
};
const refModel = useRef<HTMLDialogElement>(null);
+4 -7
View File
@@ -1,18 +1,15 @@
import { MdInfoOutline } from 'react-icons/md';
import { workerClientBus } from '~/decrypt-worker/client';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
import { usePlatform } from '~/platform/PlatformContext';
import { useEffect, useRef, useState } from 'react';
const getSDKVersion = async (): Promise<string> => {
return workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
};
export function SDKVersion() {
const { crypto } = usePlatform();
const refDialog = useRef<HTMLDialogElement>(null);
const [sdkVersion, setSdkVersion] = useState('...');
useEffect(() => {
getSDKVersion().then(setSdkVersion);
}, []);
crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null).then(setSdkVersion, () => setSdkVersion('N/A'));
}, [crypto]);
return (
<>
+4 -1
View File
@@ -27,7 +27,10 @@ export function SelectFile() {
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,25 @@
import { DownloadAll } from '~/components/DownloadAll';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
import { renderWithProviders, screen } from '~/test-utils/test-helper';
test('hides download-all control when platform has no downloadTypes', () => {
const platform = createBrowserProvider({
crypto: {
request: () => Promise.resolve(null as never),
enqueueDecrypt: () => Promise.reject(new Error('unused')),
},
downloadTypes: [],
});
renderWithProviders(<DownloadAll />, { platform });
expect(screen.queryByTitle('下载全部')).not.toBeInTheDocument();
expect(document.getElementById('downloadAll')).toBeNull();
});
test('renders download-all control when PackZip is available', () => {
renderWithProviders(<DownloadAll />);
expect(screen.getByTitle('下载全部')).toBeInTheDocument();
expect(document.getElementById('downloadAll')).not.toBeNull();
});
@@ -0,0 +1,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 { DECRYPTION_WORKER_ACTION_NAME } from './constants';
import type { WorkerActionMap } from './actions';
import { DecryptionQueue } from '~/util/DecryptionQueue';
// TODO: Worker pool?
@@ -8,5 +8,5 @@ export const workerClient = new Worker(new URL('./worker', import.meta.url), { t
// FIXME: report the error so is obvious to the user.
workerClient.addEventListener('error', console.error);
export const workerClientBus = new WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>(workerClient);
export const workerClientBus = new WorkerClientBus<WorkerActionMap>(workerClient);
export const decryptionQueue = new DecryptionQueue(workerClientBus);
+3 -3
View File
@@ -19,18 +19,18 @@ export class KugouMusicDecipher implements DecipherInstance {
kgm.decrypt(block, offset);
}
return {
return Promise.resolve({
status: Status.OK,
cipherName: this.cipherName,
data: audioBuffer,
};
});
} finally {
kgmHdr?.free();
kgm?.free();
}
}
public static make() {
public static make(this: void) {
return new KugouMusicDecipher();
}
}
+4 -4
View File
@@ -12,24 +12,24 @@ export class KuwoMusicDecipher implements DecipherInstance {
try {
header = KuwoHeader.parse(buffer.subarray(0, 0x400));
kwm = new KWMDecipher(header, options.kwm2key);
kwm = new KWMDecipher(header, options.kwm2Key);
const audioBuffer = new Uint8Array(buffer.subarray(0x400));
for (const [block, offset] of chunkBuffer(audioBuffer)) {
kwm.decrypt(block, offset);
}
return {
return Promise.resolve({
status: Status.OK,
cipherName: this.cipherName,
data: audioBuffer,
};
});
} finally {
kwm?.free();
header?.free();
}
}
public static make() {
public static make(this: void) {
return new KuwoMusicDecipher();
}
}
+10 -7
View File
@@ -6,22 +6,25 @@ export class Migu3DKeylessDecipher implements DecipherInstance {
cipherName = 'Migu3D (Keyless)';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> {
const mg3d = Migu3D.fromHeader(buffer.subarray(0, 0x100));
const audioBuffer = new Uint8Array(buffer);
const mg3d = Migu3D.fromHeader(buffer.subarray(0, 0x100));
for (const [block, i] of chunkBuffer(audioBuffer)) {
mg3d.decrypt(block, i);
try {
for (const [block, i] of chunkBuffer(audioBuffer)) {
mg3d.decrypt(block, i);
}
} finally {
mg3d.free();
}
mg3d.free();
return {
return Promise.resolve({
cipherName: this.cipherName,
status: Status.OK,
data: audioBuffer,
};
});
}
public static make() {
public static make(this: void) {
return new Migu3DKeylessDecipher();
}
}
@@ -26,17 +26,17 @@ export class NetEaseCloudMusicDecipher implements DecipherInstance {
for (const [block, offset] of chunkBuffer(audioBuffer)) {
ncm.decrypt(block, offset);
}
return {
return Promise.resolve({
status: Status.OK,
cipherName: this.cipherName,
data: audioBuffer,
};
});
} finally {
ncm.free();
}
}
public static make() {
public static make(this: void) {
return new NetEaseCloudMusicDecipher();
}
}
+14 -11
View File
@@ -19,14 +19,14 @@ export class QQMusicV1Decipher implements DecipherInstance {
for (const [block, offset] of chunkBuffer(audioBuffer)) {
decryptQMC1(block, offset);
}
return {
return Promise.resolve({
status: Status.OK,
cipherName: this.cipherName,
data: audioBuffer,
};
});
}
public static create() {
public static create(this: void) {
return new QQMusicV1Decipher();
}
}
@@ -62,25 +62,28 @@ export class QQMusicV2Decipher implements DecipherInstance {
throw new Error('EKey required');
}
const qmc2 = new QMC2(ekey);
const audioBuffer = buffer.slice(0, buffer.byteLength - footer.size);
for (const [block, offset] of chunkBuffer(audioBuffer)) {
qmc2.decrypt(block, offset);
const qmc2 = new QMC2(ekey);
try {
for (const [block, offset] of chunkBuffer(audioBuffer)) {
qmc2.decrypt(block, offset);
}
} finally {
qmc2.free();
}
qmc2.free();
return {
return Promise.resolve({
status: Status.OK,
cipherName: this.cipherName,
data: audioBuffer,
};
});
}
public static createWithUserKey() {
public static createWithUserKey(this: void) {
return new QQMusicV2Decipher(true);
}
public static createWithEmbeddedEKey() {
public static createWithEmbeddedEKey(this: void) {
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);
for (const [block, i] of chunkBuffer(audioBuffer)) {
qtfm.decrypt(block, i);
const qtfm = new QingTingFM(key, iv);
try {
for (const [block, i] of chunkBuffer(audioBuffer)) {
qtfm.decrypt(block, i);
}
} finally {
qtfm.free();
}
return {
return Promise.resolve({
cipherName: this.cipherName,
status: Status.OK,
data: audioBuffer,
};
});
}
public static make() {
public static make(this: void) {
return new QignTingFMDecipher();
}
}
+3 -3
View File
@@ -4,15 +4,15 @@ export class TransparentDecipher implements DecipherInstance {
cipherName = 'none';
async decrypt(buffer: Uint8Array<ArrayBuffer>): Promise<DecipherResult | DecipherOK> {
return {
return Promise.resolve({
cipherName: 'None',
status: Status.OK,
data: buffer,
message: 'No decipher applied',
};
});
}
public static make() {
public static make(this: void) {
return new TransparentDecipher();
}
}
+11 -8
View File
@@ -6,23 +6,26 @@ export class XiamiDecipher implements DecipherInstance {
cipherName = 'Xiami (XM)';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> {
const xm = Xiami.from_header(buffer.subarray(0, 0x10));
const { copyPlainLength } = xm;
const audioBuffer = buffer.slice(0x10);
for (const [block] of chunkBuffer(audioBuffer.subarray(copyPlainLength))) {
xm.decrypt(block);
const xm = Xiami.from_header(buffer.subarray(0, 0x10));
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,
status: Status.OK,
data: audioBuffer,
};
});
}
public static make() {
public static make(this: void) {
return new XiamiDecipher();
}
}
+26 -22
View File
@@ -23,18 +23,18 @@ export class XimalayaAndroidDecipher implements DecipherInstance {
}
const result = new Uint8Array(buffer);
result.set(slice, 0);
return {
return Promise.resolve({
cipherName: this.cipherName,
status: Status.OK,
data: result,
};
});
}
public static makeX2M() {
public static makeX2M(this: void) {
return new XimalayaAndroidDecipher(decryptX2MHeader, 'X2M');
}
public static makeX3M() {
public static makeX3M(this: void) {
return new XimalayaAndroidDecipher(decryptX3MHeader, 'X3M');
}
}
@@ -45,27 +45,31 @@ export class XimalayaPCDecipher implements DecipherInstance {
async decrypt(buffer: Uint8Array, _options: DecryptCommandOptions): Promise<DecipherResult | DecipherOK> {
// Detect with first 0x400 bytes
const headerSize = XmlyPC.getHeaderSize(buffer.subarray(0, 1024));
const xm = 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 xmly = new XmlyPC(buffer.subarray(0, headerSize));
const result = new Uint8Array(audioSize);
result.set(audioHeader);
result.set(encryptedAudioPart, audioHeader.byteLength);
result.set(buffer.subarray(plainAudioDataOffset), audioHeader.byteLength + encryptedAudioPartLen);
return {
status: Status.OK,
data: result,
cipherName: this.cipherName,
};
try {
const { audioHeader, encryptedHeaderOffset, encryptedHeaderSize } = xmly;
const plainAudioDataOffset = encryptedHeaderOffset + encryptedHeaderSize;
const plainAudioDataLength = buffer.byteLength - plainAudioDataOffset;
const encryptedAudioPart = buffer.slice(encryptedHeaderOffset, plainAudioDataOffset);
const encryptedAudioPartLen = xmly.decrypt(encryptedAudioPart);
const audioSize = audioHeader.byteLength + encryptedAudioPartLen + plainAudioDataLength;
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();
}
}
+2 -2
View File
@@ -1,13 +1,13 @@
export interface DecryptCommandOptions {
fileName: string;
qmc2Key?: string;
kwm2key?: string;
kwm2Key?: string;
kugouKey?: string;
qingTingAndroidKey?: string;
}
export interface DecryptCommandPayload {
id: string;
fileId: string;
blobURI: string;
options: DecryptCommandOptions;
}
+1 -1
View File
@@ -6,7 +6,7 @@ export function withWasmClass<T extends { free: () => void }, R>(instance: T, cb
const resp = cb(instance);
if (resp && isPromise(resp)) {
isAsync = true;
resp.finally(() => instance.free());
resp.finally(() => instance.free()).catch(() => {});
}
return resp;
} finally {
+2 -1
View File
@@ -1,4 +1,5 @@
import { WorkerServerBus } from '~/util/WorkerEventBus';
import type { WorkerActionMap } from './actions';
import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
import { getUmcVersion } from '@unlock-music/crypto';
@@ -8,7 +9,7 @@ import { workerGetQtfmDeviceKey } from '~/decrypt-worker/worker/qtfm_device_key.
import { workerParseKuwoHeader } from '~/decrypt-worker/worker/kuwo_header_parse.ts';
import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts';
const bus = new WorkerServerBus();
const bus = new WorkerServerBus<WorkerActionMap>();
onmessage = bus.onmessage;
bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler);
+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;
const id = payloadId.replace('://', ':');
const label = `decrypt(${id})`;
const label = `decrypt(${fileId})`;
return withTimeGroupedLogs(label, async () => {
const buffer = await fetch(blobURI).then((r) => r.arrayBuffer());
const handler = new DecryptCommandHandler(id, new Uint8Array(buffer), options);
const handler = new DecryptCommandHandler(fileId, new Uint8Array(buffer), options);
return handler.decrypt(allCryptoFactories);
});
};
@@ -1,15 +1,14 @@
import {
ParseKugouHeaderPayload, ParseKugouHeaderResponse,
} from '~/decrypt-worker/types.ts';
import { ParseKugouHeaderPayload, ParseKugouHeaderResponse } from '~/decrypt-worker/types.ts';
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 arrayBuffer = await blob.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer.slice(0, 0x400));
let kwm : KuGouHeader | undefined;
let kwm: KuGouHeader | undefined;
try {
kwm = new KuGouHeader(buffer);
@@ -20,4 +19,4 @@ export const workerParseKugouHeader = async ({ blobURI }: ParseKugouHeaderPayloa
} finally {
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';
export const workerParseKuwoHeader = async ({ blobURI }: ParseKuwoHeaderPayload): Promise<ParseKuwoHeaderResponse> => {
+1 -1
View File
@@ -11,5 +11,5 @@ export async function workerGetQtfmDeviceKey({
board,
}: GetQingTingFMDeviceKeyPayload) {
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.
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');
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx';
import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { RiErrorWarningLine } from 'react-icons/ri';
export function KugouFAQ() {
+1 -1
View File
@@ -2,7 +2,7 @@ import { Header2, Header3 } from '~/components/HelpText/Headers';
import { VQuote } from '~/components/HelpText/VQuote';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { HiWord } from '~/components/HelpText/HiWord';
import { KWMv2AllInstructions } from '~/features/settings/panels/KWMv2/KWMv2AllInstructions';
import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { RiErrorWarningLine } from 'react-icons/ri';
+16
View File
@@ -11,6 +11,22 @@ export function OtherFAQ() {
<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>
<p>⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。</p>
<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 { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { QMCv2QQMusicAllInstructions } from '~/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions';
import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
export function QQMusicFAQ() {
return (
+4 -8
View File
@@ -26,14 +26,10 @@ export function FileError({ error, code }: FileErrorProps) {
const copyError = () => {
if (error) {
navigator.clipboard
.writeText(applyTemplate(ERROR_TEMPLATE, { summary, error }))
.then(() => {
toast.success('错误信息已复制到剪贴板');
})
.catch((e) => {
toast.error(`复制错误信息失败: ${e}`);
});
navigator.clipboard.writeText(applyTemplate(ERROR_TEMPLATE, { summary, error })).then(
() => toast.success('错误信息已复制到剪贴板'),
(e) => toast.error(`复制错误信息失败: ${e as Error}`),
);
}
};
+17 -12
View File
@@ -2,6 +2,7 @@ import { DecryptedAudioFile, deleteFile, ProcessState } from './fileListingSlice
import { useAppDispatch } from '~/hooks';
import { FileError } from './FileError';
import classNames from 'classnames';
import { usePlatform } from '~/platform/PlatformContext';
interface FileRowProps {
id: string;
@@ -10,7 +11,9 @@ interface FileRowProps {
export function FileRow({ id, file }: FileRowProps) {
const dispatch = useAppDispatch();
const { capabilities } = usePlatform();
const isDecrypted = file.state === ProcessState.COMPLETE;
const showDownload = capabilities.downloadTypes.length > 0;
const decryptedName = file.cleanName + '.' + file.ext;
@@ -32,18 +35,20 @@ export function FileRow({ id, file }: FileRowProps) {
</div>
<div className="card-actions justify-end">
<a
href={file.decrypted}
download={decryptedName}
title={`下载: ${decryptedName}`}
className={classNames('btn', {
'btn-primary': file.decrypted,
'cursor-not-allowed pointer-events-none': !file.decrypted,
})}
data-testid="audio-download"
>
下载
</a>
{showDownload && (
<a
href={file.decrypted}
download={decryptedName}
title={`下载: ${decryptedName}`}
className={classNames('btn', {
'btn-primary': file.decrypted,
'cursor-not-allowed pointer-events-none': !file.decrypted,
})}
data-testid="audio-download"
>
下载
</a>
)}
<button type="button" className="btn btn-error" onClick={() => dispatch(deleteFile({ id }))}>
删除
</button>
@@ -1,3 +1,4 @@
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
import { renderWithProviders, screen } from '~/test-utils/test-helper';
import { untouchedFile } from './__fixture__/file-list';
import { FileRow } from '../FileRow';
@@ -14,4 +15,19 @@ test('should render basic title (done)', () => {
renderWithProviders(<FileRow id="file://done" file={completedFile} />);
expect(screen.getAllByTestId('file-row')).toHaveLength(1);
expect(screen.getByTestId('audio-download')).toBeInTheDocument();
});
test('hides single-file download when platform has no downloadTypes', () => {
const platform = createBrowserProvider({
crypto: {
request: () => Promise.resolve(null as never),
enqueueDecrypt: () => Promise.reject(new Error('unused')),
},
downloadTypes: [],
});
renderWithProviders(<FileRow id="file://done" file={completedFile} />, { platform });
expect(screen.queryByTestId('audio-download')).not.toBeInTheDocument();
});
@@ -0,0 +1,76 @@
import type { WorkerActionName } from '~/decrypt-worker/actions';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
import { setPlatform } from '~/platform/platformSingleton';
import { setupStore } from '~/store';
import { ListingMode, ProcessState, processFile, selectFiles } from '../fileListingSlice';
import { untouchedFile } from './__fixture__/file-list';
describe('processFile', () => {
test('parses headers via platform.crypto then enqueueDecrypts', async () => {
const request = vi.fn((action: WorkerActionName) => {
if (action === 'FIND_QMC_MUSICEX_NAME') {
return Promise.resolve('track.mflac');
}
return Promise.resolve(null);
});
const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
const crypto: BrowserCrypto = { request, enqueueDecrypt };
setPlatform(createBrowserProvider({ crypto }));
const fileId = 'file://untouched';
const store = setupStore({
fileListing: {
files: { [fileId]: { ...untouchedFile } },
displayMode: ListingMode.LIST,
},
});
const result = await store.dispatch(processFile({ fileId }));
expect(result.type).toBe(processFile.fulfilled.type);
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
blobURI: untouchedFile.raw,
});
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
blobURI: untouchedFile.raw,
});
expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
blobURI: untouchedFile.raw,
});
expect(enqueueDecrypt).toHaveBeenCalledTimes(1);
const [decryptPayload, onPreProcess] = enqueueDecrypt.mock.calls[0] as [
{ fileId: string; blobURI: string; options: { fileName: string } },
() => void,
];
expect(decryptPayload).toMatchObject({
fileId,
blobURI: untouchedFile.raw,
options: { fileName: untouchedFile.fileName },
});
expect(typeof onPreProcess).toBe('function');
const file = selectFiles(store.getState())[fileId];
expect(file.state).toBe(ProcessState.COMPLETE);
expect(file.decrypted).toBe('blob://out');
expect(file.ext).toBe('flac');
});
test('rejects when file id is missing', async () => {
const crypto: BrowserCrypto = {
request: vi.fn(),
enqueueDecrypt: vi.fn(),
};
setPlatform(createBrowserProvider({ crypto }));
const store = setupStore({
fileListing: {
files: {},
displayMode: ListingMode.LIST,
},
});
const result = await store.dispatch(processFile({ fileId: 'missing' }));
expect(result.type).toBe(processFile.rejected.type);
});
});
+16 -26
View File
@@ -3,22 +3,13 @@ import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import type { RootState } from '~/store';
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
import type {
DecryptCommandOptions,
FetchMusicExNamePayload,
ParseKugouHeaderPayload,
ParseKugouHeaderResponse,
ParseKuwoHeaderPayload,
ParseKuwoHeaderResponse,
} from '~/decrypt-worker/types';
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
import {
selectKugouKey,
selectKWMv2Key,
selectQMCv2KeyByFileName,
selectQtfmAndroidKey,
} from '../settings/settingsSelector';
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
import { selectKugouKey } from '~/features/kugou/keyLookup';
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
import { getPlatform } from '~/platform/platformSingleton';
import { cleanFilename } from '~/util/cleanFilename';
export enum ProcessState {
@@ -79,28 +70,27 @@ export const processFile = createAsyncThunk<
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
};
const { crypto } = getPlatform();
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
workerClientBus.request<string, FetchMusicExNamePayload>(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
crypto.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
blobURI: file.raw,
}),
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
blobURI: file.raw,
}),
crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
blobURI: file.raw,
}),
workerClientBus.request<ParseKuwoHeaderResponse, ParseKuwoHeaderPayload>(
DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER,
{ blobURI: file.raw },
),
workerClientBus.request<ParseKugouHeaderResponse, ParseKugouHeaderPayload>(
DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER,
{ blobURI: file.raw },
),
]);
const options: DecryptCommandOptions = {
fileName: file.fileName,
qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName),
kwm2key: selectKWMv2Key(state, kuwoHdr),
kwm2Key: selectKWMv2Key(state, kuwoHdr),
kugouKey: selectKugouKey(state, kugouHdr),
qingTingAndroidKey: selectQtfmAndroidKey(state),
};
return decryptionQueue.add({ id: fileId, blobURI: file.raw, options }, onPreProcess);
return crypto.enqueueDecrypt({ fileId, blobURI: file.raw, options }, onPreProcess);
});
export const fileListingSlice = createSlice({
@@ -0,0 +1,35 @@
import { configureStore } from '@reduxjs/toolkit';
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
import type { RootState } from '~/store';
import { selectKugouKey } from '../keyLookup';
function storeWithKugouKeys(keys: Record<string, string>) {
const base = settingsSlice.getInitialState();
return configureStore({
reducer: { settings: settingsReducer },
preloadedState: {
settings: {
...base,
production: {
...base.production,
kugou: { keys },
},
},
},
});
}
describe('selectKugouKey', () => {
test('returns key for matching audioHash', () => {
const hash = 'a'.repeat(32);
const store = storeWithKugouKeys({ [hash]: 'ek' });
expect(selectKugouKey(store.getState() as RootState, { audioHash: hash } as never)).toBe('ek');
});
test('returns undefined for unknown hash or null header', () => {
const store = storeWithKugouKeys({ ['b'.repeat(32)]: 'ek' });
expect(selectKugouKey(store.getState() as RootState, { audioHash: 'c'.repeat(32) } as never)).toBeUndefined();
expect(selectKugouKey(store.getState() as RootState, null)).toBeUndefined();
});
});
+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 { toast } from 'react-toastify';
import { ExtLink } from '~/components/ExtLink';
import { FilePathBlock } from '~/components/FilePathBlock.tsx';
import { copyToClipboard } from '~/util/clipboard';
const DB_PATH = '%APPDATA%\\KuGou8\\KGMusicV3.db';
export function InstructionsPC() {
const DB_PATH = '%APPDATA%\\KuGou8\\KGMusicV3.db';
const copyDbPathToClipboard = () => {
navigator.clipboard
.writeText(DB_PATH)
.then(() => {
toast.success('已复制到剪贴板');
})
.catch((err) => {
toast.error(`复制失败,请手动复制\n${err}`);
});
};
const copyDbPathToClipboard = () => copyToClipboard(DB_PATH);
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 { memo } from 'react';
import { StagingKugouKey } from '../../keyFormats';
import type { StagingKugouKey } from '~/features/kugou/types';
import { KeyInput } from '~/components/KeyInput';
export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => {
@@ -2,15 +2,12 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '../settingsSlice';
import { selectStagingKugouV5Keys } from '../settingsSelector';
import type { StagingKugouKey } from '../keyFormats';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
import { AddKey } from '~/components/AddKey.tsx';
import { KugouEKeyItem } from '~/features/settings/panels/Kugou/KugouEKeyItem.tsx';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx';
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou.ts';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor.ts';
import { KugouEKeyItem } from './KugouEKeyItem';
import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { importKugouKeysFromFile } from '~/features/kugou/importKeys';
import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult';
@@ -22,13 +19,7 @@ export function PanelKGGKey() {
const addKey = () => dispatch(kugouAddKey());
const clearAll = () => dispatch(kugouClearKeys());
const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKugouKey, 'id'>[] | null = null;
if (/mggkey_multi_process/i.test(file.name)) {
keys = parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
} else if (/^KGMusicV3\.db$/.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
keys = extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
}
const keys = await importKugouKeysFromFile(file);
if (keys && keys.length > 0) {
dispatch(kugouImportKeys(keys));
+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 { kwm2DeleteKey, kwm2UpdateKey } from '../../settingsSlice';
import { kwm2DeleteKey, kwm2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks';
import { memo } from 'react';
import { StagingKWMv2Key } from '../../keyFormats';
import type { StagingKWMv2Key } from '~/features/kwm/types';
import { KeyInput } from '~/components/KeyInput';
export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => {
@@ -2,13 +2,11 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal';
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo';
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '../settingsSlice';
import { selectStagingKWMv2Keys } from '../settingsSelector';
import { KWMv2EKeyItem } from './KWMv2/KWMv2EKeyItem';
import type { StagingKWMv2Key } from '../keyFormats';
import { KWMv2AllInstructions } from './KWMv2/KWMv2AllInstructions';
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
import { KWMv2EKeyItem } from './KWMv2EKeyItem';
import { importKWMv2KeysFromFile } from '~/features/kwm/importKeys';
import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import { AddKey } from '~/components/AddKey';
import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult';
@@ -21,12 +19,7 @@ export function PanelKWMv2Key() {
const addKey = () => dispatch(kwm2AddKey());
const clearAll = () => dispatch(kwm2ClearKeys());
const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKWMv2Key, 'id'>[] | null = null;
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
keys = parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
} else if (/kw_ekey/.test(file.name)) {
keys = parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
}
const keys = await importKWMv2KeysFromFile(file);
if (keys && keys.length > 0) {
dispatch(kwm2ImportKeys(keys));
+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 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_TG_URL = 'https://t.me/um_lsr_ch/24';
@@ -10,14 +11,20 @@ export function InstructionsPC() {
return (
<>
<p className="mt-2">
使用 <span className="text-error">19.57 或更高版本</span>下载的歌曲文件
使用 <span className="text-primary">19.57 至 22.76</span>下载的歌曲文件
<HiWord>需要导入密钥</HiWord>。
<br />
目前未公开密钥获取方式,因此不支持。
</p>
<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>。
</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 { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '../settingsSlice';
import { selectStagingQMCv2Settings } from '../settingsSelector';
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingQMCv2Settings } from '~/features/qmc/keyLookup';
import React, { useRef, useState } from 'react';
import { QMCv2EKeyItem } from './QMCv2/QMCv2EKeyItem';
import { QMCv2EKeyItem } from './QMCv2EKeyItem';
import { ImportSecretModal } from '~/components/ImportSecretModal';
import { StagingQMCv2Key } from '../keyFormats';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
import { parseAndroidQmEKey } from '~/util/mmkv/qm';
import { getFileName } from '~/util/pathHelper';
import { QMCv2QQMusicAllInstructions } from './QMCv2/QMCv2QQMusicAllInstructions';
import { QMCv2DoubanAllInstructions } from './QMCv2/QMCv2DoubanAllInstructions';
import { importQMCv2KeysFromFile } from '~/features/qmc/importKeys';
import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
import { QMCv2DoubanAllInstructions } from '~/features/qmc/instructions/QMCv2DoubanAllInstructions';
import { AddKey } from '~/components/AddKey';
import { InfoModal } from '~/components/InfoModal.tsx';
import { Ruby } from '~/components/Ruby.tsx';
@@ -32,18 +29,7 @@ export function PanelQMCv2Key() {
const handleSecretImport = async (file: File) => {
try {
const fileBuffer = await file.arrayBuffer();
let keys: null | Omit<StagingQMCv2Key, 'id'>[] = null;
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
keys = extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
} else if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
const fileBuffer = await file.arrayBuffer();
const map = parseAndroidQmEKey(new DataView(fileBuffer));
keys = Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
}
const keys = await importQMCv2KeysFromFile(file);
if (keys && keys.length > 0) {
dispatch(qmc2ImportKeys(keys));
@@ -53,7 +39,7 @@ export function PanelQMCv2Key() {
toastImportResult(file.name, keys);
} catch (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 { memo } from 'react';
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;
+81
View File
@@ -0,0 +1,81 @@
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 { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
import { usePlatform } from '~/platform/PlatformContext';
import { toast } from 'react-toastify';
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
export function PanelQingTing() {
const dispatch = useAppDispatch();
const { crypto } = usePlatform();
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
const setSecretKey = (secretKey: string) => {
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
};
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();
crypto
.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,90 @@
import { configureStore } from '@reduxjs/toolkit';
import { afterEach, vi } from 'vitest';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
import type { SettingsStorage } from '~/platform/browser/browserSettingsIo';
import { persistSettings, mergeSettings } from '../persistSettings';
import { settingsSlice, setProductionChanges, type ProductionSettings } from '../settingsSlice';
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
const data = { ...initial };
return {
data,
getItem(key: string) {
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
},
setItem(key: string, value: string) {
data[key] = value;
},
};
}
function createStore() {
return configureStore({
reducer: { settings: settingsSlice.reducer },
});
}
describe('persistSettings', () => {
afterEach(() => {
vi.useRealTimers();
});
test('loads via provider, merges, and dispatches production', async () => {
const stored: ProductionSettings = {
...settingsSlice.getInitialState().production,
qmc2: {
allowFuzzyNameSearch: false,
keys: { 'a.mflac': 'ek' },
},
};
const storage = createMemoryStorage({ 'um-react-settings': JSON.stringify(stored) });
const provider = createBrowserProvider({ settingsStorage: storage });
const store = createStore();
const unsubscribe = persistSettings(store, provider);
await vi.waitFor(() => {
expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': 'ek' });
expect(store.getState().settings.production.qmc2.allowFuzzyNameSearch).toBe(false);
});
unsubscribe();
});
test('ignores failed loads and keeps defaults', async () => {
const storage = createMemoryStorage({ 'um-react-settings': '{bad' });
const provider = createBrowserProvider({ settingsStorage: storage });
const store = createStore();
const defaults = settingsSlice.getInitialState().production;
const unsubscribe = persistSettings(store, provider);
// Give the rejected load a turn to settle.
await Promise.resolve();
await Promise.resolve();
expect(store.getState().settings.production).toEqual(defaults);
unsubscribe();
});
test('debounced save writes production through provider', async () => {
vi.useFakeTimers();
const storage = createMemoryStorage();
const provider = createBrowserProvider({ settingsStorage: storage });
const store = createStore();
const unsubscribe = persistSettings(store, provider);
await Promise.resolve();
const next = mergeSettings({
...settingsSlice.getInitialState().production,
qmc2: { allowFuzzyNameSearch: true, keys: { 'b.mflac': 'x' } },
});
store.dispatch(setProductionChanges(next));
await vi.advanceTimersByTimeAsync(150);
await Promise.resolve();
expect(JSON.parse(storage.data['um-react-settings'])).toEqual(next);
unsubscribe();
});
});
@@ -0,0 +1,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';
/** Generic map↔list helpers shared by format feature types. */
export function productionKeyToStaging<S, P extends Record<string, unknown>>(
src: P,
make: (k: keyof P, v: P[keyof P]) => null | S,
@@ -18,81 +18,3 @@ export function productionKeyToStaging<S, P extends Record<string, unknown>>(
export function stagingKeyToProduction<S, P>(src: S[], toKey: (s: S) => keyof P, toValue: (s: S) => P[keyof P]): P {
return objectify(src, toKey, toValue) as P;
}
// QMCv2 (QQ)
export interface StagingQMCv2Key {
id: string;
name: string;
ekey: string;
}
export type ProductionQMCv2Keys = Record<string /* filename */, string /* ekey */>;
export const qmc2StagingToProductionKey = (key: StagingQMCv2Key) => key.name.normalize();
export const qmc2StagingToProductionValue = (key: StagingQMCv2Key) => key.ekey.trim();
export const qmc2ProductionToStaging = (
key: keyof ProductionQMCv2Keys,
value: ProductionQMCv2Keys[keyof ProductionQMCv2Keys],
): StagingQMCv2Key => {
return {
id: nanoid(),
name: key.normalize(),
ekey: value.trim(),
};
};
// KWMv2 (KuWo)
export interface StagingKWMv2Key {
id: string;
/**
* Resource ID
*/
rid: string;
/**
* Quality String
*/
quality: string;
ekey: string;
}
export type ProductionKWMv2Keys = Record<string /* `${rid}-${quality}` */, string /* ekey */>;
export const parseKwm2ProductionKey = (key: string): null | { rid: string; quality: string } => {
const m = key.match(/^(\d+)-(\w+)$/);
if (!m) return null;
const [_, rid, quality] = m;
return { rid, quality };
};
export const kwm2StagingToProductionKey = (key: StagingKWMv2Key) => `${key.rid}-${key.quality.replace(/\D/g, '')}`;
export const kwm2StagingToProductionValue = (key: StagingKWMv2Key) => key.ekey;
export const kwm2ProductionToStaging = (
key: keyof ProductionKWMv2Keys,
value: ProductionKWMv2Keys[keyof ProductionKWMv2Keys],
): null | StagingKWMv2Key => {
if (typeof value !== 'string') return null;
const parsed = parseKwm2ProductionKey(key);
if (!parsed) return null;
const { quality, rid } = parsed;
return { id: nanoid(), rid, quality, ekey: value };
};
// KuGou (kgg, kgm v5)
export interface StagingKugouKey {
id: string;
audioHash: string;
ekey: string;
}
export type ProductionKugouKey = Record<string /* audioHash */, string /* ekey */>;
export const kugouStagingToProductionKey = (key: StagingKugouKey) => key.audioHash.normalize();
export const kugouStagingToProductionValue = (key: StagingKugouKey) => key.ekey.normalize();
export const kugouProductionToStaging = (
key: keyof ProductionKugouKey,
value: ProductionKugouKey[keyof ProductionKugouKey],
): null | StagingKugouKey => {
if (typeof value !== 'string') return null;
return { id: nanoid(), audioHash: key.normalize(), ekey: value };
};
@@ -0,0 +1,155 @@
import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
import { BatchDownloadType } from '~/platform/capabilities';
import { usePlatform } from '~/platform/PlatformContext';
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
import { toast } from 'react-toastify';
export function PanelGeneral() {
const dispatch = useAppDispatch();
const batch = useAppSelector(selectStagingBatchDownloadSettings);
const { capabilities } = usePlatform();
const downloadTypes = new Set(capabilities.downloadTypes);
const canDirectoryPicker = downloadTypes.has(BatchDownloadType.SelectDirectory);
const canStreamingZip = downloadTypes.has(BatchDownloadType.StreamZip);
const canBlobZip = downloadTypes.has(BatchDownloadType.PackZip);
const [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)。'
: '当前环境不支持选择目录批量下载。'
}
onChange={(checked) => setBatch('directoryPicker', checked)}
/>
<div className={`ml-6 flex flex-col gap-2 ${batch.directoryPicker && canDirectoryPicker ? '' : 'opacity-50'}`}>
<BatchOption
id={idRemember}
checked={batch.rememberDirectory}
disabled={!batch.directoryPicker || !canDirectoryPicker}
title="记住输出目录"
description="将目录句柄保存在本机;下次下载时可能仍需确认写入权限。"
onChange={(checked) => setBatch('rememberDirectory', checked)}
/>
<div className="flex items-center gap-2 text-sm">
<span className="text-base-content/70">{hasRememberedDir ? '已记住一个输出目录' : '尚未记住输出目录'}</span>
<button
type="button"
className="btn btn-xs btn-ghost"
disabled={!hasRememberedDir}
onClick={() => void handleClearDirectory()}
>
清除
</button>
</div>
</div>
<BatchOption
id={idStreamZip}
checked={batch.streamingZip && canStreamingZip}
disabled={!canStreamingZip}
dimmed={!canStreamingZip}
title="流式生成 ZIP"
description={
canStreamingZip
? '边打包边写入单个 ZIP 文件(showSaveFilePicker),内存占用较低。'
: '当前环境不支持流式写出 ZIP。'
}
onChange={(checked) => setBatch('streamingZip', checked)}
/>
<BatchOption
id={idBlobZip}
checked={batch.blobZip && canBlobZip}
disabled={!canBlobZip}
dimmed={!canBlobZip}
title="生成单个 ZIP 并触发下载"
description={
canBlobZip ? (
<>
在内存中生成 ZIP 后触发一次浏览器下载。兼容性最好;ZIP 需整包驻留内存,建议合计不超过约
500MB~1GB(视设备可用内存而定,过大可能失败或卡顿)。
</>
) : (
'当前环境不支持打包 ZIP 下载。'
)
}
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>
);
}
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more