49 Commits
Author SHA1 Message Date
鲁树人 d86323e38a docs: add AGENTS.md for Unlock Music project overview and setup instructions
- Introduced a new AGENTS.md file detailing the architecture, quick start guide, and directory layout for the Unlock Music project.
- Included comprehensive sections on features, settings model, and guidelines for adding or changing music formats.
- Documented tooling considerations and testing practices to aid developers in contributing to the project.
2026-11-01 02:58:09 +09:00
鲁树人 4a7994df96 feat: introduce worker action types and refactor decryption handling
- Added a new `actions.ts` file defining `WorkerActionMap` for better type management of worker actions.
- Updated `client.ts`, `worker.ts`, and `decrypt.ts` to utilize the new action types, enhancing type safety.
- Refactored `DecryptCommandPayload` to rename `id` to `fileId` for clarity and consistency.
- Adjusted various components to align with the new payload structure and improved error handling in the worker event bus.
- Enhanced tests to ensure compatibility with the new action type definitions and payload structures.
2026-11-01 02:55:30 +09:00
鲁树人 7a11d4f941 refactor: reorganize Kugou and Kuwo imports, add key management features
- Updated import paths for Kugou and Kuwo instructions to reflect new directory structure.
- Introduced new key management functionalities for Kugou, including key import and selection logic.
- Added comprehensive instructions for both Kugou and Kuwo key handling across various platforms.
- Implemented Redux selectors for managing staging and production keys for Kugou and Kuwo.
- Enhanced documentation and tests for new features and key management processes.
2026-11-01 02:42:13 +09:00
鲁树人 a9a937bc5e docs: enhance comments and documentation for KuGou/KGG settings
- Added detailed comments and documentation for KuGou/KGG key formats and settings in keyFormats.ts, persistSettings.ts, settingsSelector.ts, settingsSlice.ts, and settingsTabs.tsx.
- Improved clarity on UI route identifiers and Redux persist keys for better understanding and maintenance.
2026-10-31 23:37:55 +09:00
鲁树人 75d786c747 fix: clamp payload length in MMKVParser to prevent overflow
- Updated the MMKVParser to ensure the calculated length does not exceed the DataView's byte length.
- Added tests to verify behavior at the payload boundary, including cases for oversized payloads and exact matches.
2026-10-27 09:01:42 +09:00
鲁树人 10e857a903 0.6.2 2026-10-22 02:23:47 +09:00
鲁树人 537391ed03 docs: update README and FAQ for QQ Music client key requirements
- Revised README to clarify that QQ Music PC client versions 19.57 to 22.76 require importing a key file extracted using qmpc-mmkv-cli.
- Updated issue template to reflect the same changes regarding key file requirements for Windows clients.
- Modified FAQ to specify that only versions 19.51 or lower do not require a key, while versions 19.57 to 22.76 do.
- Enhanced instructions for obtaining the key file in the PC instructions panel.
2026-10-21 11:40:55 +09:00
鲁树人 881aa5e44c chore: remove unused environment variable from build workflow 2026-10-21 10:55:35 +09:00
鲁树人 757bbd2172 0.6.1 2026-10-21 10:53:12 +09:00
鲁树人 3f14a3acff chore: update Vite configuration to use vmThreads pool 2026-10-21 10:52:44 +09:00
鲁树人 b142c1ba34 chore: dep pkg upgrade
- Updated Node version in Dockerfile and .npmrc.
- Upgraded various dependencies in package.json, including react-dropzone, react-router, and eslint.
- Added pnpm-workspace.yaml for workspace management.
- Adjusted TypeScript configurations and test utilities for compatibility.
- Enhanced documentation for installation instructions and TypeScript toolchain.
2026-10-21 10:51:06 +09:00
鲁树人 4df197ac4d chore: minor pkg updates 2026-10-21 10:25:22 +09:00
鲁树人 07d160c547 feat(#10): add batch download settings and capabilities
- Introduced new batch download settings in the settings slice, allowing users to configure options for directory picking, streaming ZIP downloads, and blob ZIP downloads.
- Implemented a new general settings panel for managing batch download preferences.
- Added utility functions to handle directory selection and ZIP file creation.
- Updated the download logic to support multiple download modes based on user preferences.
- Enhanced documentation to reflect changes in batch download functionality.
2026-10-21 10:24:21 +09:00
鲁树人 3059f495ab Merge pull request 'feat: allow deployment on subpaths' (#11) from Charles/um-react:main into main
Reviewed-on: https://git.um-react.app/um/um-react/pulls/11
2026-07-15 10:30:44 +01:00
Charles 024847a45a feat: allow deployment on subpaths 2026-01-30 16:28:39 +08:00
鲁树人 a11caaae92 refactor: major package updates 2025-10-16 01:00:38 +09:00
鲁树人 2e52c67533 chore: minor package updates 2025-10-15 23:15:00 +09:00
鲁树人 56bb94b90c docs: update highlight styling 2025-10-15 23:12:47 +09:00
鲁树人 c1a5c6bde6 chore: reformat project 2025-10-15 23:10:19 +09:00
鲁树人 009804cbbd docs: update notes regarding supported formats 2025-10-15 23:10:12 +09:00
鲁树人 ff6fc467ae ci: only include artifact file once. 2025-10-15 22:52:59 +09:00
鲁树人 d514a87198 0.6.0 2025-10-15 22:47:59 +09:00
鲁树人 5c537ab8d9 ci: simplify release 2025-10-15 22:47:59 +09:00
鲁树人 48f10e8e30 fix: layout issue with android instruction in mobile screen 2025-10-15 22:08:51 +09:00
鲁树人 dfac382cbd Merge pull request '添加 Mac QQ 音乐 v10 的说明' (#3) from feat/mac-qqmusic-v10 into main
Reviewed-on: https://git.um-react.app/um/um-react/pulls/3
2025-10-15 12:59:19 +00:00
鲁树人 7b2558c585 feat: update instructions and scripts for QQMusic Mac v10.7 and v8.8.0 2025-10-15 02:08:32 +09:00
鲁树人 fb52b0197c feat: add insturctions on how to dump keys for v10 2025-10-15 00:57:56 +09:00
鲁树人 f49f629917 build: allow vite to access 'index.html' 2025-10-14 07:54:21 +09:00
鲁树人 8093d30579 chore: remove npm package lock file 2025-10-14 07:53:54 +09:00
鲁树人 4fe6efec1f 0.5.2 2025-09-08 21:31:34 +09:00
鲁树人 c4fe9ce938 fix: update dependencies 2025-09-08 21:31:34 +09:00
鲁树人 045bea8084 chore: log which decipher was used 2025-09-08 20:47:13 +09:00
鲁树人 c68195eb9a feat: add instructions to block update for qqmusic mac 8.8.0 2025-09-05 22:15:15 +09:00
鲁树人 b986a2ef99 0.5.1 2025-09-03 21:32:27 +09:00
鲁树人 b48d9b0079 chore: update major versions 2025-09-03 21:32:16 +09:00
鲁树人 62e49804a5 chore: update deps 2025-09-03 21:27:38 +09:00
鲁树人 c41e5ae531 build: sort out deps 2025-09-03 21:21:01 +09:00
鲁树人 27c33a7d20 fix: replace link to new git repo 2025-09-03 21:19:37 +09:00
鲁树人 bbb557eafd Merge pull request 'fix(downloadAll): 一点点修改' (#92) from awalol/um-react:fix-downloadall into main
Reviewed-on: https://git.unlock-music.dev/um/um-react/pulls/92
2025-07-16 10:05:52 +00:00
awalol befe35e5bc ui(DownloadAll): button position 2025-07-15 18:33:37 +00:00
awalol 1fb6526cdb docs: update faq 2025-07-15 18:33:37 +00:00
awalol d122eaecf5 refactor(DownloadAll): 调整按钮位置 2025-07-15 18:33:37 +00:00
awalol 2da766168c refactor(DownloadAll): 并行下载 2025-07-15 18:33:37 +00:00
awalol 17200150dd feat(DownloadAll): 并行下载 2025-07-15 18:33:37 +00:00
awalol 2c461df5fc fix(downloadAll): 防止未解密文件导致的下载失败 优化目录选择框的弹出 优化权限请求 2025-07-15 18:33:37 +00:00
鲁树人 b493391371 Merge pull request '为解密文件添加 MIME 类型' (#95) from awalol/um-react:fix-mime into main
Reviewed-on: https://git.unlock-music.dev/um/um-react/pulls/95
2025-07-14 11:27:00 +00:00
awalol 13b67f40aa refactor(MIME): add getMimeTypeFromExt function 2025-07-14 01:51:28 +08:00
awalol fbe8ef8ba1 fix: add MIME type for the decrypted file 2025-07-11 23:40:31 +08:00
鲁树人 54f784d778 ci: fix wry build 2025-07-05 06:45:43 +09:00
145 changed files with 6494 additions and 16647 deletions

No files matched your search

+8 -1
View File
@@ -7,7 +7,9 @@ body:
value: | value: |
### Windows 客户端 ### Windows 客户端
目前 Windows 客户端仅支持 19.51 或更低版本下载的歌曲文件。 目前 Windows 客户端支持 19.57 至 22.76(目前最新版)下载的歌曲文件,但需要导入由 [qmpc-mmkv-cli](https://git.um-react.app/um/qmpc-mmkv/releases) 提取的密钥文件 `qmpc-mmkv-v1.mmkv`。
使用 19.51 或更低版本下载的歌曲文件无需密钥。
* [web.archive.org 镜像](https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe) * [web.archive.org 镜像](https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe)
* [通过 Telegram 下载](https://t.me/um_lsr_ch/24) * [通过 Telegram 下载](https://t.me/um_lsr_ch/24)
@@ -20,8 +22,13 @@ body:
目前 Mac 客户端仅支持 v8.8.0 或更低版本下载的歌曲文件。 目前 Mac 客户端仅支持 v8.8.0 或更低版本下载的歌曲文件。
* [web.archive.org 镜像](https://web.archive.org/web/20230903/https://dldir1.qq.com/music/clntupate/mac/QQMusicMac_Mgr.dmg)
* [通过 Telegram 下载](https://t.me/um_lsr_ch/21) * [通过 Telegram 下载](https://t.me/um_lsr_ch/21)
安装好客户端后可以加装更新屏蔽更新:
* [屏蔽更新](https://t.me/um_lsr_ch/29)
--- ---
如果你确定你的客户端版本符合上述描述,并遇到了问题,请继续填写下面的表单。 如果你确定你的客户端版本符合上述描述,并遇到了问题,请继续填写下面的表单。
+28 -2
View File
@@ -4,8 +4,6 @@ on: [push]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
npm_config_registry: https://registry.npmmirror.com
steps: steps:
- name: Check out repository code - name: Check out repository code
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -26,6 +24,34 @@ jobs:
with: with:
name: site name: site
path: dist/ path: dist/
- name: Create Release Package
if: startsWith(github.ref, 'refs/tags/')
run: |
VERSION=${GITHUB_REF#refs/tags/v}
mkdir release/
python3 -m zipfile -c "release/um-react-${VERSION}.zip" dist/.
cp win64/dist/*.zip "release/um-react-win64-${VERSION}.zip"
- name: Create Draft Release
if: startsWith(github.ref, 'refs/tags/')
uses: akkuman/gitea-release-action@v1
with:
draft: true
files: |
release/um-react-*.zip
body: |
上个版本:[v0.0.0](https://git.um-react.app/um/um-react/releases/tag/v0.0.0)
## 🐛 修正
- 修正内容
## ✨ 新增
- 新增内容
## 🔧 维护
- 维护内容
- name: Prepare for deployment - name: Prepare for deployment
run: | run: |
cp um-react.zip dist/"release-${GITHUB_SHA}.zip" cp um-react.zip dist/"release-${GITHUB_SHA}.zip"
+1 -3
View File
@@ -1,3 +1 @@
use-node-version=22.12.0 @unlock-music:registry=https://git.um-react.app/api/packages/um/npm/
engine-strict=true
@unlock-music:registry=https://git.unlock-music.dev/api/packages/um/npm/
+156
View File
@@ -0,0 +1,156 @@
# AGENTS.md — Unlock Music (um-react)
Browser SPA that decrypts locally selected encrypted music files (no upload). React rewrite of Unlock Music.
Hosted at [git.um-react.app/um/um-react](https://git.um-react.app/um/um-react). Crypto algorithms live in `@unlock-music/crypto` (WASM), **not** in this repo.
## Quick start
```sh
corepack prepare [email protected] --activate
pnpm i --frozen-lockfile
pnpm start # http://localhost:5173/
pnpm test # vitest run (also pre-push)
pnpm lint
pnpm build # tsc -p tsconfig.prod.json && vite build && write-version
```
- **Package manager:** pnpm `@12.14.0` (`engineStrict`)
- **Node:** `24.22.0` (`devEngines`)
- **TypeScript:** stay on **6.x** (do not bump to 7)
- **Registry:** `@unlock-music/*` from `git.um-react.app` (see `.npmrc`)
- App **does not support subdirectory deploy**
## Architecture
```
Main thread (UI / Redux / key import)
SelectFile → blob URL → fileListingSlice.processFile
→ keyLookup(production settings) → DecryptCommandOptions
→ DecryptionQueue → WorkerClientBus
Web Worker (decrypt-worker)
fetch(blobURI) → try Deciphers in order → blob URL result
```
- Blob URIs are passed via `postMessage`; worker loads bytes with `fetch`.
- Single worker today (`decrypt-worker/client.ts`); concurrency via `ConcurrentQueue` (default 5).
- Key DB / MMKV parsing runs on the **main thread** (`util/sqlite.ts`, `util/mmkv/`, `util/DatabaseKeyExtractor.ts`).
### Entry points
| Concern | Path |
| ---------------------- | ----------------------------------------------------- |
| Bootstrap | `src/main.tsx` → `src/components/AppRoot.tsx` |
| Redux store | `src/store.ts` (`fileListing` + `settings` only) |
| Typed hooks | `src/hooks.ts` |
| Decrypt queue UI | `src/features/file-listing/` |
| Settings + persist | `src/features/settings/` |
| Worker client / server | `src/decrypt-worker/client.ts`, `worker.ts` |
| Decipher registry | `src/decrypt-worker/Deciphers.ts` (**order matters**) |
| Path alias | `~/*` → `src/*` |
### Routes (`AppRoot`)
| Path | Tab |
| -------------- | -------------------------- |
| `/` | Main unlock UI |
| `/settings/*` | Settings (`SETTINGS_TABS`) |
| `/questions/*` | FAQ (`FAQ_PAGES`) |
## `src/` layout
| Dir | Role |
| ----------------- | --------------------------------------------------------------------- |
| `components/` | Shared UI (AppRoot, Dialog, key import, downloads) — **no `App.tsx`** |
| `tabs/` | Top-level route shells |
| `features/` | Domain modules (see below) |
| `decrypt-worker/` | Worker + `decipher/*` + worker parsers |
| `faq/` | FAQ pages + registry |
| `util/` | Queues, worker bus, SQLite/MMKV, downloads, helpers |
| `test-utils/` | Vitest setup + `renderWithProviders` |
### Features
| Folder | Purpose |
| --------------- | ------------------------------------------------------------------ |
| `settings/` | Staging/production slice, persistence, general panel, tab registry |
| `file-listing/` | Decrypt queue + `processFile` thunk |
| `nav/` | Settings/FAQ nested nav |
| `qmc/` | QQ Music QMCv2 keys |
| `kwm/` | Kuwo KWMv2 keys |
| `kugou/` | Kugou KGG/KGM keys |
| `qtfm/` | QingTing FM device key |
Provider features typically contain: `types.ts`, `importKeys.ts`, `keyLookup.ts`, `panel/`, `instructions/`, `__tests__/`. They do **not** own Redux slices — they plug into `settingsSlice`.
## Settings model (critical)
- **`staging`**: editable UI state (key rows with `id`).
- **`production`**: committed shape used for decrypt + `localStorage` (`um-react-settings`).
- Decrypt **`keyLookup` selectors always read `production`**. Dirty settings must be committed (保存) before decrypt sees them.
- Persist: `features/settings/persistSettings.ts` (debounced save; `mergeSettings` on load).
- Key-list CRUD: `createKeyListReducers.ts` for `qmc2` / `kwm2` / `kugou`.
**Route id ≠ Redux key** (do not “fix” rename persist keys):
| Route | Redux / persist |
| ------ | --------------- |
| `qmc` | `qmc2` |
| `kwm` | `kwm2` |
| `kgg` | `kugou` |
| `qtfm` | `qtfm` |
## Adding / changing a music format
1. Prefer implementing crypto in `@unlock-music/crypto` / `lib_um_crypto_rust` (see `docs/develop-with-um_crypto.zh.md`).
2. Add `src/decrypt-worker/decipher/YourFormat.ts` implementing `DecipherInstance`.
3. Register factory in `Deciphers.ts` at the right priority (fixed header → footer → expensive full-file last).
4. If user keys needed: extend `DecryptCommandOptions`; add `features/<name>/` + wire `settingsSlice`, `persistSettings.mergeSettings`, `settingsTabs.tsx`.
5. If header parse needed before decrypt: worker action in `actions.ts` / `worker.ts` / `worker/*`, call from `fileListingSlice.processFile`.
6. Tests + README supported-formats / FAQ as appropriate.
## UI & copy
- Tailwind CSS 4 + **DaisyUI 5** (`src/App.css`). Prefer existing patterns (`btn`, `modal`, `list`, `alert`, …).
- Shared: `Dialog`, `KeyListContainer`, `ImportSecretModal`, `HelpText/*`, `react-icons`.
- **No i18n library** — user-facing strings are hard-coded Simplified Chinese (some Traditional phrasing exists; match nearby copy).
- Import from `react-router` (v8), not `react-router-dom`.
## Testing
- Vitest + jsdom; `globals: true`; setup `src/test-utils/setup-jest.ts` (mocks `Worker`, `matchMedia`).
- Colocate under `__tests__/` as `*.test.ts(x)`.
- Components: `renderWithProviders` from `src/test-utils/test-helper.tsx`.
- Selectors/converters: mini-store or `setupStore({ preloadedState })`.
- Contribution rule: coverage must not drop below main branch; Prettier + ESLint clean before PR.
- Hooks: `pre-commit` → lint-staged; `pre-push` → `pnpm test`.
## Tooling gotchas
| Topic | Note |
| ----------------- | ---------------------------------------------------------------------------------------------------- |
| WASM | `vite-plugin-wasm`; exclude `@unlock-music/crypto` from `optimizeDeps`; worker awaits crypto `ready` |
| Local crypto link | `LIB_UM_WASM_LOADER_DIR` / pnpm link; Vite `server.fs.allow` |
| sql.js | Patched via `pnpm-workspace.yaml` → `patches/sql.js.patch`; alias `@sql-wasm` |
| PWA | `vite-plugin-pwa`; `src/dummy.mjs` aliases `module` for Workbox |
| Prettier | singleQuote, printWidth 120 |
| Unused vars | prefix with `_` (ESLint) |
| CI | `.gitea/workflows/build.yaml` (build, zip, win64, Netlify deploy) |
## Docs to read first
| Doc | When |
| ------------------------------------------ | ------------------------------------------- |
| `README.MD` | Formats, architecture summary, contribution |
| `docs/getting-started.zh.md` | Install / build / pack |
| `docs/develop-with-um_crypto.zh.md` | Crypto SDK local development |
| `docs/faq_zh-hans.md` / `docs/adb_dump.md` | User FAQ / ADB key dump |
## Agent working rules for this repo
- Prefer **surgical edits**; match existing DaisyUI/Tailwind and feature folder patterns.
- Do not rename `kugou` persist key or casually change staging↔production semantics.
- Do not move heavy crypto into the main thread; keep decryption in the worker.
- Do not invent an i18n framework for one-off strings.
- Run `pnpm test` / `pnpm lint` after behavioral changes when practical.
- Crypto algorithm work usually belongs upstream in `@unlock-music/crypto`, not duplicated here.
+2 -2
View File
@@ -1,4 +1,4 @@
FROM node:22-slim AS build FROM node:24.22.0-slim AS build
ENV PNPM_HOME="/p" ENV PNPM_HOME="/p"
ENV PATH="$PNPM_HOME:$PATH" ENV PATH="$PNPM_HOME:$PATH"
WORKDIR /app WORKDIR /app
@@ -9,7 +9,7 @@ RUN corepack enable pnpm \
&& apt-get clean \ && apt-get clean \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
COPY package.json pnpm-lock.yaml .npmrc ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
RUN pnpm exec true RUN pnpm exec true
COPY . . COPY . .
RUN pnpm install --frozen-lockfile RUN pnpm install --frozen-lockfile
+37 -27
View File
@@ -1,6 +1,6 @@
# Unlock Music 音乐解锁 (React) # Unlock Music 音乐解锁 (React)
[![Build Status](https://git.unlock-music.dev/um/um-react/actions/workflows/build.yaml/badge.svg)][um-react-actions] [![Build Status](https://git.um-react.app/um/um-react/actions/workflows/build.yaml/badge.svg)][um-react-actions]
- 在浏览器中解锁加密的音乐文件。 Unlock encrypted music file in the browser. - 在浏览器中解锁加密的音乐文件。 Unlock encrypted music file in the browser.
- 查看[原基于 Vue 的 Unlock Music 项目][um-vue] - 查看[原基于 Vue 的 Unlock Music 项目][um-vue]
@@ -10,16 +10,17 @@
- CI 自动构建已经部署,可以在 [Actions][um-react-actions] 寻找对应的<ruby>构建产物<rp>(</rp><rt>Artifact</rt><rp>)</rp> </ruby>下载。 - CI 自动构建已经部署,可以在 [Actions][um-react-actions] 寻找对应的<ruby>构建产物<rp>(</rp><rt>Artifact</rt><rp>)</rp> </ruby>下载。
- [常见问题参考](./docs/faq_zh-hans.md) - [常见问题参考](./docs/faq_zh-hans.md)
> **WARNING** > [!WARNING]
> 在本站 fork 不会起到备份的作用,只会浪费服务器储存空间。如无必要请勿 fork 该仓库。 > 在本站 fork 不会起到备份的作用,只会浪费服务器储存空间。如无必要请勿 fork 该仓库。
[授权协议]: https://git.unlock-music.dev/um/um-react/src/branch/main/LICENSE [授权协议]: https://git.um-react.app/um/um-react/src/branch/main/LICENSE
[um-vue]: https://git.unlock-music.dev/um/web [um-vue]: https://git.um-react.app/um/web
[unlock-music/cli]: https://git.unlock-music.dev/um/cli [unlock-music/cli]: https://git.um-react.app/um/cli
[`@unlock_music_chat`]: https://t.me/unlock_music_chat [`@unlock_music_chat`]: https://t.me/unlock_music_chat
[um-react-actions]: https://git.unlock-music.dev/um/um-react/actions?workflow=build.yaml [um-react-actions]: https://git.um-react.app/um/um-react/actions?workflow=build.yaml
⚠️ 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。 > [!TIP]
> 手机端浏览器支持有限,请使用最新版本的 Chrome 或 Firefox 官方浏览器。
## 支持的格式 ## 支持的格式
@@ -31,40 +32,45 @@
- Mac 客户端 (`.mflach` 等) [^qm-key-mac] - Mac 客户端 (`.mflach` 等) [^qm-key-mac]
- [x] 网易云音乐 (`.ncm`) - [x] 网易云音乐 (`.ncm`)
- [x] 虾米音乐 (`.xm`) - [x] 虾米音乐 (`.xm`)
- [x] 酷我音乐 (`.kwm`) - [x] 酷我音乐 (`.kwm` / `.mflac`) [^kuwo-key-android]
- [x] 酷狗音乐 (`.kgm` / `.vpr` / `.kgg`) - [x] 酷狗音乐 (`.kgm` / `.vpr` / `.kgg`)
- PC / 安卓客户端的 `kgg` 文件需要提供密钥数据库。 - PC / 安卓客户端[^kgg-android]的 `kgg` 文件需要提供密钥数据库。
- [x] 喜马拉雅 (`.x2m` / `.x3m` / `.xm`) - [x] 喜马拉雅 (`.x2m` / `.x3m` / `.xm`)
- [x] 咪咕音乐格式 (`.mg3d`) - [x] 咪咕音乐格式 (`.mg3d`)
- [x] 蜻蜓 FM (`.qta`) - [x] 蜻蜓 FM (`.qta`)
- [ ] ~~<ruby>QQ 音乐海外版<rt>JOOX Music</rt></ruby> (`.ofl_en`)~~ - 需要提取设备 ID。
[^qm-key-pc]: PC 客户端仅支持 v19.43 或更低版本。 [^qm-key-pc]: QQ 音乐的 PC 客户端(v19.57 至 v22.76)需要导入由 [qmpc-mmkv-cli](https://git.um-react.app/um/qmpc-mmkv/releases) 提取的密钥文件 `qmpc-mmkv-v1.mmkv`。
[^qm-key-android]: 需要获取超级管理员权限后提取密钥数据库,并导入后使用。 [^qm-key-android]: QQ 音乐的安卓客户端支持需要获取超级管理员权限后提取密钥数据库并导入后使用。
[^qm-key-ios]: 需要越狱获取密钥数据库,或对设备进行完整备份后提取密钥数据库,并导入后使用。 [^qm-key-ios]: QQ 音乐 iOS 客户端支持需要越狱获取密钥数据库,或对设备进行完整备份后提取密钥数据库并导入后使用。
[^qm-key-mac]: 需要导入密钥数据库。 [^qm-key-mac]: QQ 音乐 Mac 客户端支持需要导入密钥数据库,目前支持 v8.8.0 及 v10.7.1。
[^kgg-android]: 酷狗音乐的安卓客户端支持需要获取超级管理员权限后提取密钥数据库并导入后使用。
[^kuwo-key-android]: 酷我音乐的安卓客户端下载的 AI 升频文件需要获取超级管理员权限后提取密钥数据库并导入后使用。
## 错误报告 ## 错误报告
有不支持的格式?请提交样本(加密文件)与客户端信息版本信息(如系统版本、下载渠道),或一并上传其安装包到[仓库的问题追踪区][project-issues]。 有不支持的格式?请提交样本(加密文件)与客户端信息版本信息(如系统版本、下载渠道),或一并上传其安装包到[仓库的问题追踪区][project-issues]。
⚠️ 如果文件太大,请上传到不需要登入下载的网盘,如 [mega.nz](https://mega.nz)、[OneDrive](https://www.onedrive.com/) 等。 > [!NOTE]
> 如果文件太大,请上传到不需要登入下载的网盘,如 [mega.nz](https://mega.nz)、[OneDrive](https://www.onedrive.com/) 等。
遇到解密出错的情况,请一并携带错误信息(诊断信息)并简单描述错误的重现过程。 遇到解密出错的情况,请一并携带错误信息(诊断信息)并简单描述错误的重现过程。
待实现的算法支持可[追踪 `crypto` 标签](https://git.unlock-music.dev/um/um-react/issues?labels=67)。 待实现的算法支持可[追踪 `crypto` 标签](https://git.um-react.app/um/um-react/issues?labels=67)。
[project-issues]: https://git.unlock-music.dev/um/um-react/issues/new [project-issues]: https://git.um-react.app/um/um-react/issues/new
## 使用 Docker 构建、部署 (Linux) ## 使用 Docker 构建、部署
首先克隆仓库并进入目录: 首先克隆仓库并进入目录:
```sh ```sh
git clone https://git.unlock-music.dev/um/um-react.git git clone https://git.um-react.app/um/um-react.git
cd um-react cd um-react
``` ```
@@ -86,13 +92,17 @@ docker run -d -p 8080:80 --name um-react um-react
然后访问 `http://localhost:8080` 即可。 然后访问 `http://localhost:8080` 即可。
> [!NOTE]
> 项目不支持运行在子目录下。
## 开发相关 ## 开发相关
从源码运行或编译生产版本,请参考文档「[新手上路](./docs/getting-started.zh.md)」。 从源码运行或编译生产版本,请参考文档「[新手上路](./docs/getting-started.zh.md)」。
### 解密库开发 ### 解密库开发
⚠️ 如果只是进行前端方面的更改,你可以跳过该节。 > [!TIP]
> 如果只是进行前端方面的更改,你可以跳过该节。
请参考文档「[面向 `@unlock-music/crypto` 开发](./docs/develop-with-um_crypto.zh.md)」。 请参考文档「[面向 `@unlock-music/crypto` 开发](./docs/develop-with-um_crypto.zh.md)」。
@@ -115,15 +125,15 @@ docker run -d -p 8080:80 --name um-react um-react
## 相关项目 ## 相关项目
- [Unlock Music (Web)](https://git.unlock-music.dev/um/web) - 原始项目 - [Unlock Music (Web)](https://git.um-react.app/um/web) - 原始项目
- [Unlock Music (Cli)](https://git.unlock-music.dev/um/cli) - 命令行批量处理版 - [Unlock Music (Cli)](https://git.um-react.app/um/cli) - 命令行批量处理版
- [lib_um_crypto_rust](https://git.unlock-music.dev/um/lib_um_crypto_rust) - 项目引入的解密算法实现 - [lib_um_crypto_rust](https://git.um-react.app/um/lib_um_crypto_rust) - 项目引入的解密算法实现
- [NPM 包](https://git.unlock-music.dev/um/-/packages/npm/@unlock-music%2Fcrypto) - [NPM 包](https://git.um-react.app/um/-/packages/npm/@unlock-music%2Fcrypto)
- [um-react (Electron 前端)](https://github.com/CarlGao4/um-react-electron) - 使用 Electron 框架封装的本地可执行文件。 - [um-react (Electron 前端)](https://github.com/CarlGao4/um-react-electron) - 使用 Electron 框架封装的本地可执行文件。
- [GitHub 下载](https://github.com/CarlGao4/um-react-electron/releases/latest) | [仓库镜像](https://git.unlock-music.dev/CarlGao4/um-react-electron) - [GitHub 下载](https://github.com/CarlGao4/um-react-electron/releases/latest)
- [um-react-wry](https://git.unlock-music.dev/um/um-react-wry) - 使用 WRY 框架封装的 Win64 单文件 ( - [um-react-wry](https://git.um-react.app/um/um-react-wry) - 使用 WRY 框架封装的 Win64 单文件 (
需要[安装 Edge WebView2 运行时][webview2_redist],Win10+ 操作系统自带) 需要[安装 Edge WebView2 运行时][webview2_redist],Win10+ 操作系统自带)
- [本地下载](https://git.unlock-music.dev/um/um-react/releases/latest) | 寻找文件名为 `um-react-win64-` 开头的附件 - [本地下载](https://git.um-react.app/um/um-react/releases/latest) | 寻找文件名为 `um-react-win64-` 开头的附件
[webview2_redist]: https://go.microsoft.com/fwlink/p/?LinkId=2124703 [webview2_redist]: https://go.microsoft.com/fwlink/p/?LinkId=2124703
+1 -1
View File
@@ -16,7 +16,7 @@
- 进入上层目录:`cd ..` - 进入上层目录:`cd ..`
- 克隆 `lib_um_crypto_rust` 仓库 - 克隆 `lib_um_crypto_rust` 仓库
- `git clone https://git.unlock-music.dev/um/lib_um_crypto_rust.git` - `git clone https://git.um-react.app/um/lib_um_crypto_rust.git`
- 进入 SDK 目录:`cd lib_um_crypto_rust ; cd um_wasm_loader` - 进入 SDK 目录:`cd lib_um_crypto_rust ; cd um_wasm_loader`
- 安装所有 Node 以来:`pnpm i` - 安装所有 Node 以来:`pnpm i`
- 构建:`pnpm build` - 构建:`pnpm build`
+14 -6
View File
@@ -10,7 +10,7 @@
#### 2、检查您的平台。 #### 2、检查您的平台。
日前,<mark>仅 Windows 客户端 v19.43 或以下版本</mark>下载的歌曲无需密钥,其余平台的官方正式版本均需要提取密钥。 日前,Windows 客户端 <mark>v19.57 至 v22.76</mark>(目前最新版)下载的歌曲需要导入由 [qmpc-mmkv-cli](https://git.um-react.app/um/qmpc-mmkv/releases) 提取的密钥文件 `qmpc-mmkv-v1.mmkv`;<mark>v19.51 或更低版本</mark>下载的歌曲无需密钥。其余平台的官方正式版本均需要提取密钥。
> iOS 用户提取歌曲困难,建议换用电脑操作;Android 用户提取密钥需要 root,也建议用电脑操作。 > iOS 用户提取歌曲困难,建议换用电脑操作;Android 用户提取密钥需要 root,也建议用电脑操作。
@@ -69,7 +69,19 @@
- WSA 可以参考 [MagiskOnWSALocal](https://github.com/LSPosed/MagiskOnWSALocal) 的说明操作。 - WSA 可以参考 [MagiskOnWSALocal](https://github.com/LSPosed/MagiskOnWSALocal) 的说明操作。
- 雷电模拟器可以在「模拟器设置」 → 「其他设置」中启用 root 特权。 - 雷电模拟器可以在「模拟器设置」 → 「其他设置」中启用 root 特权。
![雷电模拟器 其他设置](../src/faq/assets/ld_settings_misc.webp) ![雷电模拟器 其他设置](../src/faq/assets/ld_settings_misc@2x.webp)
### 批量下载约十首后失败 / 无法全部下载
Chromium 系浏览器会限制页面在短时间内通过程序触发的**多个**文件下载(常见表现为大约十个文件后静默中断,或提示「此网站正在尝试下载多个文件」)。
本站的「下载全部」会按「设定 → 通用设置 → 批量下载」中勾选的顺序尝试:
1. 选择输出目录,直接写入文件(推荐,Chrome / Edge)
2. 流式生成单个 ZIP 并保存
3. 在内存中生成 ZIP 后触发一次下载(兼容性最好)
若全部失败会弹出提示。大批量转换也可使用 [命令行版本](https://git.um-react.app/um/cli)。
### Via 等浏览器无法正常解密/下载 ### Via 等浏览器无法正常解密/下载
@@ -87,10 +99,6 @@
- 无法下载解密后内容 - 无法下载解密后内容
- 下载的文件名错误 - 下载的文件名错误
### 新版解锁网站没有批量下载
目前没有做。抱歉。
## 仍有问题? ## 仍有问题?
欢迎进入[Telegram 交流群](https://t.me/unlock_music_chat),一起探讨。 欢迎进入[Telegram 交流群](https://t.me/unlock_music_chat),一起探讨。
+6 -2
View File
@@ -4,8 +4,8 @@
## 安装依赖 ## 安装依赖
- 安装 Node v16.17 或更高,推荐当前最新的 Node LTS 版本。 - 安装 Node 24.22.0;pnpm 也会根据 `package.json` 中的 `devEngines.runtime` 自动获取该版本。
- 安装/激活 `pnpm` [^1]:`corepack prepare pnpm@latest --activate` - 安装/激活项目指定的 `pnpm` [^1]:`corepack prepare pnpm@12.14.0 --activate`
- 安装软件依赖:`pnpm i --frozen-lockfile` - 安装软件依赖:`pnpm i --frozen-lockfile`
[^1]: 参考 pnpm 说明「[使用 Corepack 安装](https://pnpm.io/zh/installation#使用-corepack-安装)」。 [^1]: 参考 pnpm 说明「[使用 Corepack 安装](https://pnpm.io/zh/installation#使用-corepack-安装)」。
@@ -34,6 +34,10 @@ pnpm build
[vite-preview-url]: http://localhost:4173/ [vite-preview-url]: http://localhost:4173/
### TypeScript 工具链
编译和 ESLint 统一使用 TypeScript 6.x,暂不升级到 TypeScript 7。
## 打包 `.zip` ## 打包 `.zip`
建议在 Linux 环境下执行,可参考 `.drone.yml` CI 文件。 建议在 Linux 环境下执行,可参考 `.drone.yml` CI 文件。
+14 -3
View File
@@ -1,15 +1,16 @@
import eslint from '@eslint/js'; import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint'; import tseslint from 'typescript-eslint';
import reactRefresh from 'eslint-plugin-react-refresh'; import reactRefresh from 'eslint-plugin-react-refresh';
import reactHooks from 'eslint-plugin-react-hooks'; import reactHooks from 'eslint-plugin-react-hooks';
import eslintConfigPrettier from 'eslint-config-prettier/flat'; import eslintConfigPrettier from 'eslint-config-prettier/flat';
import globals from 'globals'; import globals from 'globals';
export default tseslint.config( export default defineConfig(
eslint.configs.recommended, eslint.configs.recommended,
tseslint.configs.recommended, tseslint.configs.recommendedTypeChecked,
reactRefresh.configs.recommended, reactRefresh.configs.recommended,
reactHooks.configs['recommended-latest'], reactHooks.configs.flat.recommended,
eslintConfigPrettier, eslintConfigPrettier,
{ {
@@ -40,4 +41,14 @@ export default tseslint.config(
}, },
}, },
}, },
{
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.mjs', 'src/*.mjs', 'scripts/*.mjs'],
},
},
},
},
); );
+4
View File
@@ -9,6 +9,10 @@
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" /> <link rel="apple-touch-icon" href="/pwa-512x512.png" sizes="512x512" />
<meta name="theme-color" content="#4DBA87" /> <meta name="theme-color" content="#4DBA87" />
<script>
// 设置基础路径,如果希望部署在/music-unlock/,则改为 '/music-unlock/',默认部署在根路径
window.BASE_URL = '/';
</script>
</head> </head>
<body> <body>
-11870
View File
File diff suppressed because it is too large. Load diff
+61 -61
View File
@@ -1,7 +1,7 @@
{ {
"name": "um-react", "name": "um-react",
"private": true, "private": true,
"version": "0.5.0", "version": "0.6.2",
"type": "module", "type": "module",
"scripts": { "scripts": {
"start": "vite", "start": "vite",
@@ -17,63 +17,66 @@
"prepare": "simple-git-hooks" "prepare": "simple-git-hooks"
}, },
"dependencies": { "dependencies": {
"@reduxjs/toolkit": "^2.8.2", "@reduxjs/toolkit": "^2.13.0",
"@unlock-music/crypto": "0.1.10", "@unlock-music/crypto": "^0.1.12",
"classnames": "^2.5.1", "classnames": "^2.5.1",
"nanoid": "^5.1.5", "fflate": "^0.8.3",
"idb-keyval": "^6.3.0",
"nanoid": "^6.0.2",
"radash": "^12.1.1", "radash": "^12.1.1",
"react": "^19.1.0", "react": "^19.3.1",
"react-dom": "^19.1.0", "react-dom": "^19.3.1",
"react-dropzone": "^14.3.8", "react-dropzone": "^20.1.4",
"react-icons": "^5.5.0", "react-icons": "^5.7.0",
"react-redux": "^9.2.0", "react-redux": "^9.3.0",
"react-router": "^7.6.3", "react-router": "^8.5.0",
"react-syntax-highlighter": "^15.6.1", "react-syntax-highlighter": "^16.1.2",
"react-toastify": "^11.0.5", "react-toastify": "^11.1.0",
"sql.js": "^1.13.0" "sql.js": "^1.15.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.30.1", "@eslint/js": "^10.0.1",
"@rollup/plugin-replace": "^6.0.2", "@rollup/plugin-replace": "^6.0.3",
"@tailwindcss/vite": "^4.1.11", "@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^6.6.3", "@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.0", "@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.1", "@testing-library/user-event": "^14.6.8",
"@types/node": "^24.0.10", "@types/node": "^26.6.5",
"@types/react": "^19.1.8", "@types/react": "^19.3.0",
"@types/react-dom": "^19.1.6", "@types/react-dom": "^19.3.0",
"@types/react-syntax-highlighter": "^15.5.13", "@types/react-syntax-highlighter": "^15.5.13",
"@types/sql.js": "^1.4.9", "@types/sql.js": "^1.4.11",
"@types/wicg-file-system-access": "^2023.10.6", "@types/tar-stream": "^3.1.5",
"@typescript-eslint/eslint-plugin": "^8.35.1", "@types/wicg-file-system-access": "^2023.10.7",
"@typescript-eslint/parser": "^8.35.1", "@typescript-eslint/eslint-plugin": "^8.72.0",
"@vitejs/plugin-react": "^4.6.0", "@typescript-eslint/parser": "^8.72.0",
"@vitest/coverage-v8": "^3.2.4", "@vitejs/plugin-react": "^6.1.2",
"@vitest/ui": "^3.2.4", "@vitest/coverage-v8": "^5.0.5",
"daisyui": "^5.0.43", "@vitest/ui": "^5.0.5",
"eslint": "^9.30.1", "daisyui": "^5.7.50",
"eslint-config-prettier": "^10.1.5", "eslint": "^10.13.0",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-refresh": "^0.4.20", "eslint-plugin-react-hooks": "^7.1.1",
"globals": "^16.3.0", "eslint-plugin-react-refresh": "^0.5.7",
"globals": "^17.13.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"jsdom": "^26.1.0", "jsdom": "^30.1.3",
"lint-staged": "^16.1.2", "lint-staged": "^17.6.0",
"prettier": "^3.6.2", "prettier": "^3.9.10",
"rollup": "^4.44.2", "rollup": "^4.64.12",
"sass": "^1.89.2", "sass": "^1.105.2",
"simple-git-hooks": "^2.13.0", "simple-git-hooks": "^2.14.0",
"tailwindcss": "^4.1.11", "tailwindcss": "^4.3.3",
"terser": "^5.43.1", "tar-stream": "^3.2.2",
"typescript": "^5.8.3", "terser": "^5.51.2",
"typescript-eslint": "^8.35.1", "typescript": "^6.0.3",
"vite": "^6.3.5", "typescript-eslint": "^8.72.0",
"vite-plugin-pwa": "^1.0.1", "vite": "^8.3.4",
"vite-plugin-top-level-await": "^1.5.0", "vite-plugin-pwa": "^2.0.0",
"vite-plugin-wasm": "^3.4.1", "vite-plugin-wasm": "^3.6.0",
"vitest": "^3.2.4", "vitest": "^5.0.5",
"workbox-build": "^7.3.0", "workbox-build": "^7.4.1",
"workbox-window": "^7.3.0" "workbox-window": "^7.4.1"
}, },
"lint-staged": { "lint-staged": {
"*": "prettier --write --ignore-unknown", "*": "prettier --write --ignore-unknown",
@@ -88,15 +91,12 @@
"printWidth": 120, "printWidth": 120,
"tabWidth": 2 "tabWidth": 2
}, },
"pnpm": { "devEngines": {
"patchedDependencies": { "runtime": {
"@rollup/plugin-terser": "patches/@rollup__plugin-terser.patch", "name": "node",
"sql.js": "patches/sql.js.patch" "version": "24.22.0",
}, "onFail": "download"
"overrides": {
"rollup-plugin-terser": "npm:@rollup/[email protected]",
"sourcemap-codec": "npm:@jridgewell/[email protected]"
} }
}, },
"packageManager": "pnpm@9.12.1+sha512.e5a7e52a4183a02d5931057f7a0dbff9d5e9ce3161e33fa68ae392125b79282a8a8a470a51dfc8a0ed86221442eb2fb57019b0990ed24fab519bf0e1bc5ccfc4" "packageManager": "[email protected]4.0"
} }
+3612 -3812
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
engineStrict: true
patchedDependencies:
sql.js: patches/sql.js.patch
overrides:
sourcemap-codec: npm:@jridgewell/[email protected]
allowBuilds:
'@parcel/watcher': false
'@swc/core': true
'@tailwindcss/oxide': true
esbuild: true
simple-git-hooks: true
minimumReleaseAge: 0
+1 -1
View File
@@ -4,7 +4,7 @@
pushd "$(dirname "${BASH_SOURCE[0]}")/../" pushd "$(dirname "${BASH_SOURCE[0]}")/../"
WRY_VER="0.1.1" WRY_VER="0.1.2"
mkdir -p win64/{deps,dist} mkdir -p win64/{deps,dist}
dl_file() { dl_file() {
+9
View File
@@ -65,3 +65,12 @@ h6 {
opacity: 0.75; opacity: 0.75;
} }
} }
#downloadAll {
position: absolute;
right: 0.5em;
bottom: 72px;
width: 48px;
height: 48px;
margin: 10px;
}
@@ -1,5 +1,4 @@
import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; import { CodeHighlight } from '../CodeHighlight';
import hljsStyleGitHub from 'react-syntax-highlighter/dist/esm/styles/hljs/github';
import { ExtLink } from '../ExtLink'; import { ExtLink } from '../ExtLink';
import PowerShellAdbDumpCommandTemplate from './adb_dump.ps1?raw'; import PowerShellAdbDumpCommandTemplate from './adb_dump.ps1?raw';
import ShellAdbDumpCommandTemplate from './adb_dump.sh?raw'; import ShellAdbDumpCommandTemplate from './adb_dump.sh?raw';
@@ -45,9 +44,7 @@ export function AdbInstructionTemplate({ dir, file, platform }: AdbInstructionTe
<li>将安卓设备连接到电脑。</li> <li>将安卓设备连接到电脑。</li>
<li> <li>
<p>粘贴执行下述代码执行。若设备提示「是否允许 USB 调试」或「超级用户请求」,选择允许:</p> <p>粘贴执行下述代码执行。若设备提示「是否允许 USB 调试」或「超级用户请求」,选择允许:</p>
<SyntaxHighlighter language={language} style={hljsStyleGitHub}> <CodeHighlight language={language}>{command}</CodeHighlight>
{command}
</SyntaxHighlighter>
<br />※ 安卓模拟器可能需要额外操作,如 <br />※ 安卓模拟器可能需要额外操作,如
<ExtLink className="text-nowrap" href="https://g.126.fm/04jewvw"> <ExtLink className="text-nowrap" href="https://g.126.fm/04jewvw">
网易 MuMu 模拟器 网易 MuMu 模拟器
@@ -9,10 +9,10 @@ export function RootExplorerGuide() {
<div className="flex flex-col items-start gap-4 @md:flex-row"> <div className="flex flex-col items-start gap-4 @md:flex-row">
<div> <div>
<Header5 className="[&]:mt-0 [&]:pt-0">Amaze 文件浏览器</Header5> <Header5 className="[&]:mt-0 [&]:pt-0">Amaze 文件浏览器</Header5>
<ul className="ml-2 list-disc list-inside"> <ul className="ml-2 list-disc">
<li> <li>
<div className="inline-flex items-center gap-1"> <div className="inline-flex items-center flex-wrap">
点触主界面左上角的 <FiMenu /> 打开侧边栏 点触主界面左上角的 <FiMenu className="m-1" /> 打开侧边栏
</div> </div>
</li> </li>
<li> <li>
@@ -41,16 +41,16 @@ export function RootExplorerGuide() {
</div> </div>
<div> <div>
<Header5 className="[&]:mt-0 [&]:pt-0">MT 管理器</Header5> <Header5 className="[&]:mt-0 [&]:pt-0">MT 管理器</Header5>
<ul className="ml-2 list-disc list-inside"> <ul className="ml-2 list-disc">
<li> <li>
<div className="inline-flex items-center gap-1"> <div className="inline-flex items-center flex-wrap">
点触主界面左上角的 <FiMenu /> 打开侧边栏 点触主界面左上角的 <FiMenu className="m-1" /> 打开侧边栏
</div> </div>
</li> </li>
<li> <li>
<div className="inline-flex items-center"> <div className="inline-flex items-center flex-wrap">
点触侧边栏右上方的 <FiMoreVertical className="ml-1" /> 点触侧边栏右上方的 <FiMoreVertical className="ml-1" />
,点触<VQuote>设置</VQuote> 弹出菜单,点触<VQuote>设置</VQuote>
</div> </div>
</li> </li>
<li> <li>
+1 -3
View File
@@ -15,7 +15,6 @@ import { Bounce, ToastContainer } from 'react-toastify';
import { SettingsHome } from '~/features/settings/SettingsHome'; import { SettingsHome } from '~/features/settings/SettingsHome';
import { FAQ_PAGES } from '~/faq/FAQPages'; import { FAQ_PAGES } from '~/faq/FAQPages';
import { FaqHome } from '~/faq/FaqHome'; import { FaqHome } from '~/faq/FaqHome';
import { DownloadAll } from '~/components/DownloadAll.tsx';
// Private to this file only. // Private to this file only.
const store = setupStore(); const store = setupStore();
@@ -26,7 +25,7 @@ export function AppRoot() {
useEffect(() => persistSettings(store), []); useEffect(() => persistSettings(store), []);
return ( return (
<BrowserRouter> <BrowserRouter basename={window.BASE_URL || '/'}>
<Provider store={store}> <Provider store={store}>
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content"> <div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
<NavLink to="/" role="tab" className={tabClassNames}> <NavLink to="/" role="tab" className={tabClassNames}>
@@ -72,7 +71,6 @@ export function AppRoot() {
transition={Bounce} transition={Bounce}
/> />
<DownloadAll />
<Footer /> <Footer />
</Provider> </Provider>
</BrowserRouter> </BrowserRouter>
+10
View File
@@ -0,0 +1,10 @@
import { Light as SyntaxHighlighter, type SyntaxHighlighterProps } from 'react-syntax-highlighter';
import hljsStyleGitHub from 'react-syntax-highlighter/dist/esm/styles/hljs/github';
export function CodeHighlight({ children, ...props }: SyntaxHighlighterProps) {
return (
<SyntaxHighlighter style={hljsStyleGitHub} {...props}>
{children}
</SyntaxHighlighter>
);
}
+175 -42
View File
@@ -1,65 +1,198 @@
import { DecryptedAudioFile, selectFiles } from '~/features/file-listing/fileListingSlice'; import { DecryptedAudioFile, ProcessState, selectFiles } from '~/features/file-listing/fileListingSlice';
import { FaDownload } from 'react-icons/fa'; import { FaDownload } from 'react-icons/fa';
import { useAppSelector } from '~/hooks'; import { useAppSelector } from '~/hooks';
import { toast } from 'react-toastify'; import { toast } from 'react-toastify';
import { SimpleQueue } from '~/util/SimpleQueue';
import { selectFinalBatchDownloadSettings } from '~/features/settings/settingsSelector';
import type { BatchDownloadSettings } from '~/features/settings/settingsSlice';
import { supportsDirectoryPicker, supportsStreamingZipDownload } from '~/util/batchDownloadCapabilities';
import { resolveWritableDirectory } from '~/util/downloadDirectoryHandle';
import { downloadZipAsBlob, downloadZipViaSavePicker, ZipSourceFile } from '~/util/streamZip';
import { triggerAnchorDownload } from '~/util/triggerDownload';
export function DownloadAll() { export function DownloadAll() {
const files = useAppSelector(selectFiles); const files = useAppSelector(selectFiles);
const filesLength = Object.keys(files).length; const batchSettings = useAppSelector(selectFinalBatchDownloadSettings);
const onClickDownloadAll = async () => {
let dir: FileSystemDirectoryHandle | undefined; const downloadAllAsync = async () => {
let success = 0; const fileList = Object.values(files);
try { const fileCount = fileList.length;
dir = await window.showDirectoryPicker(); if (fileCount === 0) {
} catch (e) { toast.warning('未添加文件');
console.error(e); return;
if (e instanceof Error && e.name === 'AbortError') {
return;
}
} }
for (const [_, file] of Object.entries(files)) {
const allComplete = fileList.every((file) => file.state !== ProcessState.PROCESSING);
if (!allComplete) {
toast.warning('请等待所有文件解密完成');
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) {
downloadSingleBlob(completeFiles[0]);
toast.success('已开始下载');
return;
}
const modes = buildEnabledModes(batchSettings);
if (modes.length === 0) {
toast.error('批量下载失败:未启用任何可用的下载方式,请在「设定 → 通用设置」中勾选。');
return;
}
toast.warning('开始下载,请稍候');
for (const mode of modes) {
try { try {
if (dir) { const result = await runMode(mode, completeFiles, batchSettings.rememberDirectory);
await DownloadNew(dir, file); if (result === 'ok') {
} else { return;
await DownloadOld(file);
} }
success++; // cancelled / skipped → try next mode
} catch (e) { } catch (e) {
console.error(`下载失败: ${file.fileName}`, e); console.error(`批量下载模式 ${mode} 失败`, e);
toast.error(`出现错误: ${e}`); toast.error(`下载方式失败,尝试下一种: ${e instanceof Error ? e.message : String(e)}`);
} }
} }
if (success === filesLength) {
toast.success(`成功下载: ${success}/${filesLength}首`); toast.error('批量下载失败:当前浏览器不支持或您取消了所有可用方式。可在「设定 → 通用设置」调整选项。');
} else {
toast.error(`成功下载: ${success}/${filesLength}首`);
}
}; };
function onDownloadAll() {
downloadAllAsync().catch((e) => {
console.error('下载全部出现错误', e);
toast.error(`批量下载出现错误: ${e instanceof Error ? e.message : String(e)}`);
});
}
return ( return (
<button <button className="btn btn-primary" id="downloadAll" onClick={onDownloadAll} title="下载全部">
style={{ width: '48px', height: '48px', paddingInline: '0px', margin: '10px', marginLeft: 'auto' }}
className="btn btn-primary"
onClick={onClickDownloadAll}
title="下载全部"
>
<FaDownload /> <FaDownload />
</button> </button>
); );
} }
async function DownloadNew(dir: FileSystemDirectoryHandle, file: DecryptedAudioFile) { type BatchMode = 'directory' | 'streamingZip' | 'blobZip';
const fileHandle = await dir.getFileHandle(file.cleanName + '.' + file.ext, { create: true });
const writable = await fileHandle.createWritable(); function buildEnabledModes(
await fetch(file.decrypted).then((res) => res.body?.pipeTo(writable)); settings: Pick<BatchDownloadSettings, 'directoryPicker' | 'streamingZip' | 'blobZip'>,
): BatchMode[] {
const modes: BatchMode[] = [];
if (settings.directoryPicker && supportsDirectoryPicker()) {
modes.push('directory');
}
if (settings.streamingZip && supportsStreamingZipDownload()) {
modes.push('streamingZip');
}
if (settings.blobZip) {
modes.push('blobZip');
}
return modes;
} }
async function DownloadOld(file: DecryptedAudioFile) { async function runMode(
const a = document.createElement('a'); mode: BatchMode,
a.href = file.decrypted; completeFiles: DecryptedAudioFile[],
a.download = file.cleanName + '.' + file.ext; rememberDirectory: boolean,
document.body.append(a); ): Promise<'ok' | 'cancelled'> {
a.click(); switch (mode) {
a.remove(); case 'directory':
return downloadToDirectory(completeFiles, rememberDirectory);
case 'streamingZip':
return downloadStreamingZip(completeFiles);
case 'blobZip':
await downloadBlobZip(completeFiles);
return 'ok';
}
}
async function downloadToDirectory(
completeFiles: DecryptedAudioFile[],
remember: boolean,
): Promise<'ok' | 'cancelled'> {
const dir = await resolveWritableDirectory(remember);
if (!dir) {
return 'cancelled';
}
const fileCount = completeFiles.length;
const queue = new SimpleQueue(8);
const promises = completeFiles.map(async (file) => {
try {
await queue.enter();
await writeFileToDirectory(file, dir);
} catch (e) {
console.error(`下载失败: ${file.fileName}`, e);
toast.error(`出现错误: ${e instanceof Error ? e.message : String(e)}`);
throw e;
} finally {
queue.leave();
}
});
const promiseResults = await Promise.allSettled(promises);
const success = promiseResults.filter((result) => result.status === 'fulfilled').length;
const level = success === fileCount ? 'success' : success === 0 ? 'error' : 'warning';
toast[level](`成功下载: ${success}/${fileCount}首`);
if (success === 0) {
throw new Error('未能写入任何文件到所选目录');
}
return 'ok';
}
function decryptedDownloadName(file: DecryptedAudioFile): string {
return `${file.cleanName}.${file.ext}`;
}
async function writeFileToDirectory(file: DecryptedAudioFile, dir: FileSystemDirectoryHandle) {
const fileHandle = await dir.getFileHandle(decryptedDownloadName(file), { create: true });
const fileStream = await fileHandle.createWritable();
try {
const res = await fetch(file.decrypted);
if (!res.ok) {
throw new Error(`无法读取文件: ${decryptedDownloadName(file)} (${res.status})`);
}
if (!res.body) {
await fileStream.write(await res.arrayBuffer());
await fileStream.close();
return;
}
await res.body.pipeTo(fileStream);
} catch (e) {
await fileStream.abort();
throw e;
}
}
function toZipSources(files: DecryptedAudioFile[]): ZipSourceFile[] {
return files.map((file) => ({
name: decryptedDownloadName(file),
url: file.decrypted,
}));
}
function downloadSingleBlob(file: DecryptedAudioFile) {
triggerAnchorDownload(file.decrypted, decryptedDownloadName(file));
}
async function downloadStreamingZip(completeFiles: DecryptedAudioFile[]): Promise<'ok' | 'cancelled'> {
const sources = toZipSources(completeFiles);
const result = await downloadZipViaSavePicker(sources);
if (result === 'ok') {
toast.success(`已导出 ZIP(${completeFiles.length} 首)`);
}
return result;
}
async function downloadBlobZip(completeFiles: DecryptedAudioFile[]): Promise<void> {
await downloadZipAsBlob(toZipSources(completeFiles));
toast.success(`已开始下载 ZIP(${completeFiles.length} 首)`);
} }
+32
View File
@@ -0,0 +1,32 @@
import type { ReactNode } from 'react';
import { ExtLink } from './ExtLink';
import { IoMdArchive } from 'react-icons/io';
export type DownloadBase64Props = {
data: string;
filename: string;
mimetype?: string;
className?: string;
icon?: ReactNode | true | false;
children?: ReactNode;
};
export function DownloadBase64({
className,
children,
data,
filename,
icon,
mimetype = 'application/octet-stream',
}: DownloadBase64Props) {
return (
<ExtLink
icon={icon ?? <IoMdArchive className="inline size-sm ml-1" />}
className={className ?? 'link-info mx-1'}
download={filename}
href={`data:${mimetype};base64,${data}`}
>
{children ?? <code>{filename}</code>}
</ExtLink>
);
}
+3 -3
View File
@@ -1,15 +1,15 @@
import type { AnchorHTMLAttributes } from 'react'; import type { AnchorHTMLAttributes, ReactNode } from 'react';
import { FiExternalLink } from 'react-icons/fi'; import { FiExternalLink } from 'react-icons/fi';
export type ExtLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & { export type ExtLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
icon?: boolean; icon?: ReactNode | true | false;
}; };
export function ExtLink({ className, icon = true, children, ...props }: ExtLinkProps) { export function ExtLink({ className, icon = true, children, ...props }: ExtLinkProps) {
return ( return (
<a rel="noreferrer noopener nofollow" target="_blank" className={`link ${className}`} {...props}> <a rel="noreferrer noopener nofollow" target="_blank" className={`link ${className}`} {...props}>
{children} {children}
{icon && <FiExternalLink className="inline size-sm ml-1" />} {icon === true ? <FiExternalLink className="inline size-sm ml-1" /> : icon}
</a> </a>
); );
} }
+5 -5
View File
@@ -5,25 +5,25 @@ export function Footer() {
const appVersionShort = '__APP_VERSION_SHORT__'; const appVersionShort = '__APP_VERSION_SHORT__';
return ( return (
<footer className="flex flex-col text-center p-4 bg-base-200"> <footer className="flex flex-col text-center p-4 bg-base-200">
<p className="flex flex-row justify-center items-center h-[1em]"> <div className="flex flex-row justify-center items-center h-[1em]">
<a className="link link-info mr-1" href="https://git.unlock-music.dev/um/um-react"> <a className="link link-info mr-1" href="https://git.um-react.app/um/um-react">
音乐解锁 音乐解锁
</a> </a>
( (
<a <a
title="使用 MIT 授权协议" title="使用 MIT 授权协议"
className="link link-info" className="link link-info"
href="https://git.unlock-music.dev/um/um-react/src/branch/main/LICENSE" href="https://git.um-react.app/um/um-react/src/branch/main/LICENSE"
> >
MIT MIT
</a> </a>
, v{appVersionShort} , v{appVersionShort}
<SDKVersion />) <SDKVersion />)
</p> </div>
<p> <p>
{'© 2019 - '} {'© 2019 - '}
<CurrentYear /> <CurrentYear />
<a className="ml-1 link link-info" href="https://git.unlock-music.dev/um"> <a className="ml-1 link link-info" href="https://git.um-react.app/um">
Unlock Music Unlock Music
</a> </a>
</p> </p>
+8 -6
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { FileInput } from '~/components/FileInput'; import { FileInput } from '~/components/FileInput';
import { InSecretImportModalContext } from '~/context/InSecretImportModal';
export interface ImportSecretModalProps { export interface ImportSecretModalProps {
clientName?: React.ReactNode; clientName?: React.ReactNode;
@@ -12,13 +13,12 @@ export interface ImportSecretModalProps {
export function ImportSecretModal({ clientName, children, show, onClose, onImport }: ImportSecretModalProps) { export function ImportSecretModal({ clientName, children, show, onClose, onImport }: ImportSecretModalProps) {
const handleFileReceived = (files: File[]) => { const handleFileReceived = (files: File[]) => {
const promise = onImport(files[0]); const importResult = onImport(files[0]);
if (promise instanceof Promise) { if (importResult instanceof Promise) {
promise.catch((err) => { importResult.catch((err) => {
console.error('could not import: ', err); console.error('could not import: ', err);
}); });
} }
return promise;
}; };
const refModel = useRef<HTMLDialogElement>(null); const refModel = useRef<HTMLDialogElement>(null);
@@ -31,7 +31,7 @@ export function ImportSecretModal({ clientName, children, show, onClose, onImpor
}, [show]); }, [show]);
return ( return (
<dialog ref={refModel} className="modal"> <dialog ref={refModel} className="modal" onClose={onClose}>
<div className="modal-box"> <div className="modal-box">
<form method="dialog" onSubmit={() => onClose()}> <form method="dialog" onSubmit={() => onClose()}>
<button className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button> <button className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
@@ -41,7 +41,9 @@ export function ImportSecretModal({ clientName, children, show, onClose, onImpor
<FileInput onReceiveFiles={handleFileReceived}>拖放或点我选择含有密钥的数据库文件</FileInput> <FileInput onReceiveFiles={handleFileReceived}>拖放或点我选择含有密钥的数据库文件</FileInput>
<div className="mt-2">选择你的{clientName && <>「{clientName}」</>}客户端平台以查看对应说明:</div> <div className="mt-2">选择你的{clientName && <>「{clientName}」</>}客户端平台以查看对应说明:</div>
<div>{children}</div> <InSecretImportModalContext.Provider value={true}>
<div>{children}</div>
</InSecretImportModalContext.Provider>
</div> </div>
</div> </div>
</dialog> </dialog>
+1 -1
View File
@@ -7,7 +7,7 @@ export interface ProjectIssueProps {
export function ProjectIssue({ id, title }: ProjectIssueProps) { export function ProjectIssue({ id, title }: ProjectIssueProps) {
return ( return (
<ExtLink target="_blank" href={`https://git.unlock-music.dev/um/um-react/issues/${id}`}> <ExtLink target="_blank" href={`https://git.um-react.app/um/um-react/issues/${id}`}>
{`#${id}`} {`#${id}`}
{title && ` - ${title}`} {title && ` - ${title}`}
</ExtLink> </ExtLink>
+1 -1
View File
@@ -11,7 +11,7 @@ export function SDKVersion() {
const refDialog = useRef<HTMLDialogElement>(null); const refDialog = useRef<HTMLDialogElement>(null);
const [sdkVersion, setSdkVersion] = useState('...'); const [sdkVersion, setSdkVersion] = useState('...');
useEffect(() => { useEffect(() => {
getSDKVersion().then(setSdkVersion); getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
}, []); }, []);
return ( return (
+4 -1
View File
@@ -27,7 +27,10 @@ export function SelectFile() {
fileName, fileName,
}), }),
); );
dispatch(processFile({ fileId }));
dispatch(processFile({ fileId })).catch((err) => {
console.log(`failed to add file (id=${fileId}, name=${fileName}, err=${err as Error})`);
});
} }
}; };
@@ -0,0 +1,33 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { FileInput } from '../FileInput';
test('receives multiple files from the file picker', async () => {
const onReceiveFiles = vi.fn();
const files = [new File(['first'], 'first.qmc3'), new File(['second'], 'second.mflac')];
const { container } = render(<FileInput onReceiveFiles={onReceiveFiles}>Choose files</FileInput>);
const input = container.querySelector('input');
if (!input) throw new Error('File input is missing');
await userEvent.upload(input, files);
await waitFor(() => expect(onReceiveFiles).toHaveBeenCalledOnce());
expect(onReceiveFiles.mock.calls[0][0]).toEqual(files);
});
test('receives multiple dropped files', async () => {
const onReceiveFiles = vi.fn();
const files = [new File(['first'], 'first.kgm'), new File(['second'], 'second.ncm')];
render(<FileInput onReceiveFiles={onReceiveFiles}>Drop files</FileInput>);
fireEvent.drop(screen.getByText('Drop files'), {
dataTransfer: {
files,
items: files.map((file) => ({ kind: 'file', type: file.type, getAsFile: () => file })),
types: ['Files'],
},
});
await waitFor(() => expect(onReceiveFiles).toHaveBeenCalledOnce());
expect(onReceiveFiles.mock.calls[0][0]).toEqual(files);
});
+3
View File
@@ -0,0 +1,3 @@
import { createContext } from 'react';
export const InSecretImportModalContext = createContext<boolean>(false);
+1 -1
View File
@@ -25,7 +25,7 @@ export interface DecipherNotOK {
export interface DecipherOK { export interface DecipherOK {
status: Status.OK; status: Status.OK;
message?: string; message?: string;
data: Uint8Array; data: Uint8Array<ArrayBuffer>;
overrideExtension?: string; overrideExtension?: string;
cipherName: string; cipherName: string;
} }
+21
View File
@@ -0,0 +1,21 @@
import type { DecryptionResult } from './constants';
import type {
DecryptCommandPayload,
FetchMusicExNamePayload,
GetQingTingFMDeviceKeyPayload,
ParseKugouHeaderPayload,
ParseKugouHeaderResponse,
ParseKuwoHeaderPayload,
ParseKuwoHeaderResponse,
} from './types';
export type WorkerActionMap = {
DECRYPT: { req: DecryptCommandPayload; res: DecryptionResult };
FIND_QMC_MUSICEX_NAME: { req: FetchMusicExNamePayload; res: string | null };
KUWO_PARSE_HEADER: { req: ParseKuwoHeaderPayload; res: ParseKuwoHeaderResponse };
KUGOU_PARSE_HEADER: { req: ParseKugouHeaderPayload; res: ParseKugouHeaderResponse };
QINGTING_FM_GET_DEVICE_KEY: { req: GetQingTingFMDeviceKeyPayload; res: string };
VERSION: { req: null; res: string };
};
export type WorkerActionName = keyof WorkerActionMap;
+2 -2
View File
@@ -1,5 +1,5 @@
import { WorkerClientBus } from '~/util/WorkerEventBus'; import { WorkerClientBus } from '~/util/WorkerEventBus';
import { DECRYPTION_WORKER_ACTION_NAME } from './constants'; import type { WorkerActionMap } from './actions';
import { DecryptionQueue } from '~/util/DecryptionQueue'; import { DecryptionQueue } from '~/util/DecryptionQueue';
// TODO: Worker pool? // TODO: Worker pool?
@@ -8,5 +8,5 @@ export const workerClient = new Worker(new URL('./worker', import.meta.url), { t
// FIXME: report the error so is obvious to the user. // FIXME: report the error so is obvious to the user.
workerClient.addEventListener('error', console.error); workerClient.addEventListener('error', console.error);
export const workerClientBus = new WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>(workerClient); export const workerClientBus = new WorkerClientBus<WorkerActionMap>(workerClient);
export const decryptionQueue = new DecryptionQueue(workerClientBus); export const decryptionQueue = new DecryptionQueue(workerClientBus);
+3 -3
View File
@@ -19,18 +19,18 @@ export class KugouMusicDecipher implements DecipherInstance {
kgm.decrypt(block, offset); kgm.decrypt(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} finally { } finally {
kgmHdr?.free(); kgmHdr?.free();
kgm?.free(); kgm?.free();
} }
} }
public static make() { public static make(this: void) {
return new KugouMusicDecipher(); return new KugouMusicDecipher();
} }
} }
+4 -4
View File
@@ -12,24 +12,24 @@ export class KuwoMusicDecipher implements DecipherInstance {
try { try {
header = KuwoHeader.parse(buffer.subarray(0, 0x400)); header = KuwoHeader.parse(buffer.subarray(0, 0x400));
kwm = new KWMDecipher(header, options.kwm2key); kwm = new KWMDecipher(header, options.kwm2Key);
const audioBuffer = new Uint8Array(buffer.subarray(0x400)); const audioBuffer = new Uint8Array(buffer.subarray(0x400));
for (const [block, offset] of chunkBuffer(audioBuffer)) { for (const [block, offset] of chunkBuffer(audioBuffer)) {
kwm.decrypt(block, offset); kwm.decrypt(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} finally { } finally {
kwm?.free(); kwm?.free();
header?.free(); header?.free();
} }
} }
public static make() { public static make(this: void) {
return new KuwoMusicDecipher(); return new KuwoMusicDecipher();
} }
} }
+10 -7
View File
@@ -6,22 +6,25 @@ export class Migu3DKeylessDecipher implements DecipherInstance {
cipherName = 'Migu3D (Keyless)'; cipherName = 'Migu3D (Keyless)';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> {
const mg3d = Migu3D.fromHeader(buffer.subarray(0, 0x100));
const audioBuffer = new Uint8Array(buffer); const audioBuffer = new Uint8Array(buffer);
const mg3d = Migu3D.fromHeader(buffer.subarray(0, 0x100));
for (const [block, i] of chunkBuffer(audioBuffer)) { try {
mg3d.decrypt(block, i); for (const [block, i] of chunkBuffer(audioBuffer)) {
mg3d.decrypt(block, i);
}
} finally {
mg3d.free();
} }
mg3d.free();
return { return Promise.resolve({
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static make() { public static make(this: void) {
return new Migu3DKeylessDecipher(); return new Migu3DKeylessDecipher();
} }
} }
@@ -26,17 +26,17 @@ export class NetEaseCloudMusicDecipher implements DecipherInstance {
for (const [block, offset] of chunkBuffer(audioBuffer)) { for (const [block, offset] of chunkBuffer(audioBuffer)) {
ncm.decrypt(block, offset); ncm.decrypt(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} finally { } finally {
ncm.free(); ncm.free();
} }
} }
public static make() { public static make(this: void) {
return new NetEaseCloudMusicDecipher(); return new NetEaseCloudMusicDecipher();
} }
} }
+14 -11
View File
@@ -19,14 +19,14 @@ export class QQMusicV1Decipher implements DecipherInstance {
for (const [block, offset] of chunkBuffer(audioBuffer)) { for (const [block, offset] of chunkBuffer(audioBuffer)) {
decryptQMC1(block, offset); decryptQMC1(block, offset);
} }
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static create() { public static create(this: void) {
return new QQMusicV1Decipher(); return new QQMusicV1Decipher();
} }
} }
@@ -62,25 +62,28 @@ export class QQMusicV2Decipher implements DecipherInstance {
throw new Error('EKey required'); throw new Error('EKey required');
} }
const qmc2 = new QMC2(ekey);
const audioBuffer = buffer.slice(0, buffer.byteLength - footer.size); const audioBuffer = buffer.slice(0, buffer.byteLength - footer.size);
for (const [block, offset] of chunkBuffer(audioBuffer)) { const qmc2 = new QMC2(ekey);
qmc2.decrypt(block, offset); try {
for (const [block, offset] of chunkBuffer(audioBuffer)) {
qmc2.decrypt(block, offset);
}
} finally {
qmc2.free();
} }
qmc2.free();
return { return Promise.resolve({
status: Status.OK, status: Status.OK,
cipherName: this.cipherName, cipherName: this.cipherName,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static createWithUserKey() { public static createWithUserKey(this: void) {
return new QQMusicV2Decipher(true); return new QQMusicV2Decipher(true);
} }
public static createWithEmbeddedEKey() { public static createWithEmbeddedEKey(this: void) {
return new QQMusicV2Decipher(false); return new QQMusicV2Decipher(false);
} }
} }
+10 -7
View File
@@ -18,20 +18,23 @@ export class QignTingFMDecipher implements DecipherInstance {
}; };
} }
const qtfm = new QingTingFM(key, iv);
const audioBuffer = new Uint8Array(buffer); const audioBuffer = new Uint8Array(buffer);
for (const [block, i] of chunkBuffer(audioBuffer)) { const qtfm = new QingTingFM(key, iv);
qtfm.decrypt(block, i); try {
for (const [block, i] of chunkBuffer(audioBuffer)) {
qtfm.decrypt(block, i);
}
} finally {
qtfm.free();
} }
return Promise.resolve({
return {
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static make() { public static make(this: void) {
return new QignTingFMDecipher(); return new QignTingFMDecipher();
} }
} }
+4 -4
View File
@@ -3,16 +3,16 @@ import { DecipherInstance, DecipherOK, DecipherResult, Status } from '~/decrypt-
export class TransparentDecipher implements DecipherInstance { export class TransparentDecipher implements DecipherInstance {
cipherName = 'none'; cipherName = 'none';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array<ArrayBuffer>): Promise<DecipherResult | DecipherOK> {
return { return Promise.resolve({
cipherName: 'None', cipherName: 'None',
status: Status.OK, status: Status.OK,
data: buffer, data: buffer,
message: 'No decipher applied', message: 'No decipher applied',
}; });
} }
public static make() { public static make(this: void) {
return new TransparentDecipher(); return new TransparentDecipher();
} }
} }
+11 -8
View File
@@ -6,23 +6,26 @@ export class XiamiDecipher implements DecipherInstance {
cipherName = 'Xiami (XM)'; cipherName = 'Xiami (XM)';
async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array): Promise<DecipherResult | DecipherOK> {
const xm = Xiami.from_header(buffer.subarray(0, 0x10));
const { copyPlainLength } = xm;
const audioBuffer = buffer.slice(0x10); const audioBuffer = buffer.slice(0x10);
for (const [block] of chunkBuffer(audioBuffer.subarray(copyPlainLength))) { const xm = Xiami.from_header(buffer.subarray(0, 0x10));
xm.decrypt(block); try {
const { copyPlainLength } = xm;
for (const [block] of chunkBuffer(audioBuffer.subarray(copyPlainLength))) {
xm.decrypt(block);
}
} finally {
xm.free();
} }
xm.free();
return { return Promise.resolve({
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: audioBuffer, data: audioBuffer,
}; });
} }
public static make() { public static make(this: void) {
return new XiamiDecipher(); return new XiamiDecipher();
} }
} }
+26 -22
View File
@@ -23,18 +23,18 @@ export class XimalayaAndroidDecipher implements DecipherInstance {
} }
const result = new Uint8Array(buffer); const result = new Uint8Array(buffer);
result.set(slice, 0); result.set(slice, 0);
return { return Promise.resolve({
cipherName: this.cipherName, cipherName: this.cipherName,
status: Status.OK, status: Status.OK,
data: result, data: result,
}; });
} }
public static makeX2M() { public static makeX2M(this: void) {
return new XimalayaAndroidDecipher(decryptX2MHeader, 'X2M'); return new XimalayaAndroidDecipher(decryptX2MHeader, 'X2M');
} }
public static makeX3M() { public static makeX3M(this: void) {
return new XimalayaAndroidDecipher(decryptX3MHeader, 'X3M'); return new XimalayaAndroidDecipher(decryptX3MHeader, 'X3M');
} }
} }
@@ -45,27 +45,31 @@ export class XimalayaPCDecipher implements DecipherInstance {
async decrypt(buffer: Uint8Array, _options: DecryptCommandOptions): Promise<DecipherResult | DecipherOK> { async decrypt(buffer: Uint8Array, _options: DecryptCommandOptions): Promise<DecipherResult | DecipherOK> {
// Detect with first 0x400 bytes // Detect with first 0x400 bytes
const headerSize = XmlyPC.getHeaderSize(buffer.subarray(0, 1024)); const headerSize = XmlyPC.getHeaderSize(buffer.subarray(0, 1024));
const xm = new XmlyPC(buffer.subarray(0, headerSize)); const xmly = new XmlyPC(buffer.subarray(0, headerSize));
const { audioHeader, encryptedHeaderOffset, encryptedHeaderSize } = xm;
const plainAudioDataOffset = encryptedHeaderOffset + encryptedHeaderSize;
const plainAudioDataLength = buffer.byteLength - plainAudioDataOffset;
const encryptedAudioPart = buffer.slice(encryptedHeaderOffset, plainAudioDataOffset);
const encryptedAudioPartLen = xm.decrypt(encryptedAudioPart);
const audioSize = audioHeader.byteLength + encryptedAudioPartLen + plainAudioDataLength;
xm.free();
const result = new Uint8Array(audioSize); try {
result.set(audioHeader); const { audioHeader, encryptedHeaderOffset, encryptedHeaderSize } = xmly;
result.set(encryptedAudioPart, audioHeader.byteLength); const plainAudioDataOffset = encryptedHeaderOffset + encryptedHeaderSize;
result.set(buffer.subarray(plainAudioDataOffset), audioHeader.byteLength + encryptedAudioPartLen); const plainAudioDataLength = buffer.byteLength - plainAudioDataOffset;
return { const encryptedAudioPart = buffer.slice(encryptedHeaderOffset, plainAudioDataOffset);
status: Status.OK, const encryptedAudioPartLen = xmly.decrypt(encryptedAudioPart);
data: result, const audioSize = audioHeader.byteLength + encryptedAudioPartLen + plainAudioDataLength;
cipherName: this.cipherName,
}; const result = new Uint8Array(audioSize);
result.set(audioHeader);
result.set(encryptedAudioPart, audioHeader.byteLength);
result.set(buffer.subarray(plainAudioDataOffset), audioHeader.byteLength + encryptedAudioPartLen);
return Promise.resolve({
status: Status.OK,
data: result,
cipherName: this.cipherName,
});
} finally {
xmly.free();
}
} }
public static make() { public static make(this: void) {
return new XimalayaPCDecipher(); return new XimalayaPCDecipher();
} }
} }
+2 -2
View File
@@ -1,13 +1,13 @@
export interface DecryptCommandOptions { export interface DecryptCommandOptions {
fileName: string; fileName: string;
qmc2Key?: string; qmc2Key?: string;
kwm2key?: string; kwm2Key?: string;
kugouKey?: string; kugouKey?: string;
qingTingAndroidKey?: string; qingTingAndroidKey?: string;
} }
export interface DecryptCommandPayload { export interface DecryptCommandPayload {
id: string; fileId: string;
blobURI: string; blobURI: string;
options: DecryptCommandOptions; options: DecryptCommandOptions;
} }
+14
View File
@@ -24,3 +24,17 @@ export function isDataLooksLikeAudio(buffer: Uint8Array): boolean {
detectResult.free(); detectResult.free();
return ok; return ok;
} }
const AudioMimeType: Record<string, string> = {
mp3: 'audio/mpeg',
flac: 'audio/flac',
m4a: 'audio/mp4',
ogg: 'audio/ogg',
wma: 'audio/x-ms-wma',
wav: 'audio/x-wav',
dff: 'audio/x-dff',
};
export function getMimeTypeFromExt(ext: string) {
return AudioMimeType[ext] || 'application/octet-stream';
}
+3 -4
View File
@@ -1,7 +1,6 @@
export const toArrayBuffer = async (src: Blob | ArrayBuffer | Uint8Array<ArrayBufferLike>) => export const toArrayBuffer = async (src: Blob | BlobPart) => (src instanceof Blob ? await src.arrayBuffer() : src);
src instanceof Blob ? await src.arrayBuffer() : src; export const toBlob = (src: Blob | BlobPart, mimeType?: string) =>
export const toBlob = (src: Blob | ArrayBuffer | Uint8Array<ArrayBufferLike>) => src instanceof Blob ? src : new Blob([src], { type: mimeType ?? 'application/octet-stream' });
src instanceof Blob ? src : new Blob([src]);
export function* chunkBuffer(buffer: Uint8Array, blockLen = 4096): Generator<[Uint8Array, number], void> { export function* chunkBuffer(buffer: Uint8Array, blockLen = 4096): Generator<[Uint8Array, number], void> {
const len = buffer.byteLength; const len = buffer.byteLength;
+1 -1
View File
@@ -6,7 +6,7 @@ export function withWasmClass<T extends { free: () => void }, R>(instance: T, cb
const resp = cb(instance); const resp = cb(instance);
if (resp && isPromise(resp)) { if (resp && isPromise(resp)) {
isAsync = true; isAsync = true;
resp.finally(() => instance.free()); resp.finally(() => instance.free()).catch(() => {});
} }
return resp; return resp;
} finally { } finally {
+2 -1
View File
@@ -1,4 +1,5 @@
import { WorkerServerBus } from '~/util/WorkerEventBus'; import { WorkerServerBus } from '~/util/WorkerEventBus';
import type { WorkerActionMap } from './actions';
import { DECRYPTION_WORKER_ACTION_NAME } from './constants'; import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
import { getUmcVersion } from '@unlock-music/crypto'; import { getUmcVersion } from '@unlock-music/crypto';
@@ -8,7 +9,7 @@ import { workerGetQtfmDeviceKey } from '~/decrypt-worker/worker/qtfm_device_key.
import { workerParseKuwoHeader } from '~/decrypt-worker/worker/kuwo_header_parse.ts'; import { workerParseKuwoHeader } from '~/decrypt-worker/worker/kuwo_header_parse.ts';
import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts'; import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts';
const bus = new WorkerServerBus(); const bus = new WorkerServerBus<WorkerActionMap>();
onmessage = bus.onmessage; onmessage = bus.onmessage;
bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler); bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler);
+6 -6
View File
@@ -6,7 +6,7 @@ import { DecipherFactory, DecipherInstance, Status } from '~/decrypt-worker/Deci
import { UnsupportedSourceFile } from '~/decrypt-worker/util/DecryptError.ts'; import { UnsupportedSourceFile } from '~/decrypt-worker/util/DecryptError.ts';
import { ready as umCryptoReady } from '@unlock-music/crypto'; import { ready as umCryptoReady } from '@unlock-music/crypto';
import { go } from '~/util/go.ts'; import { go } from '~/util/go.ts';
import { detectAudioExtension } from '~/decrypt-worker/util/audioType.ts'; import { getMimeTypeFromExt, detectAudioExtension } from '~/decrypt-worker/util/audioType.ts';
class DecryptCommandHandler { class DecryptCommandHandler {
private readonly label: string; private readonly label: string;
@@ -31,6 +31,7 @@ class DecryptCommandHandler {
const [result, error] = await go(this.tryDecryptWith(decipher)); const [result, error] = await go(this.tryDecryptWith(decipher));
if (!error) { if (!error) {
if (result) { if (result) {
console.debug(`[${decipher.cipherName}] Decryption OK`);
return result; return result;
} }
errors.push(`${decipher.cipherName}: no response`); errors.push(`${decipher.cipherName}: no response`);
@@ -75,17 +76,16 @@ class DecryptCommandHandler {
audioExt = 'm4a'; audioExt = 'm4a';
} }
return { decrypted: URL.createObjectURL(toBlob(result.data)), ext: audioExt }; return { decrypted: URL.createObjectURL(toBlob(result.data, getMimeTypeFromExt(audioExt))), ext: audioExt };
} }
} }
export const workerDecryptHandler = async ({ id: payloadId, blobURI, options }: DecryptCommandPayload) => { export const workerDecryptHandler = async ({ fileId, blobURI, options }: DecryptCommandPayload) => {
await umCryptoReady; await umCryptoReady;
const id = payloadId.replace('://', ':'); const label = `decrypt(${fileId})`;
const label = `decrypt(${id})`;
return withTimeGroupedLogs(label, async () => { return withTimeGroupedLogs(label, async () => {
const buffer = await fetch(blobURI).then((r) => r.arrayBuffer()); const buffer = await fetch(blobURI).then((r) => r.arrayBuffer());
const handler = new DecryptCommandHandler(id, new Uint8Array(buffer), options); const handler = new DecryptCommandHandler(fileId, new Uint8Array(buffer), options);
return handler.decrypt(allCryptoFactories); return handler.decrypt(allCryptoFactories);
}); });
}; };
@@ -1,15 +1,14 @@
import { import { ParseKugouHeaderPayload, ParseKugouHeaderResponse } from '~/decrypt-worker/types.ts';
ParseKugouHeaderPayload, ParseKugouHeaderResponse,
} from '~/decrypt-worker/types.ts';
import { KuGouHeader } from '@unlock-music/crypto'; import { KuGouHeader } from '@unlock-music/crypto';
export const workerParseKugouHeader = async ({ blobURI }: ParseKugouHeaderPayload): Promise<ParseKugouHeaderResponse> => { export const workerParseKugouHeader = async ({
blobURI,
}: ParseKugouHeaderPayload): Promise<ParseKugouHeaderResponse> => {
const blob = await fetch(blobURI, { headers: { Range: 'bytes=0-1023' } }).then((r) => r.blob()); const blob = await fetch(blobURI, { headers: { Range: 'bytes=0-1023' } }).then((r) => r.blob());
const arrayBuffer = await blob.arrayBuffer(); const arrayBuffer = await blob.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer.slice(0, 0x400)); const buffer = new Uint8Array(arrayBuffer.slice(0, 0x400));
let kwm : KuGouHeader | undefined; let kwm: KuGouHeader | undefined;
try { try {
kwm = new KuGouHeader(buffer); kwm = new KuGouHeader(buffer);
@@ -20,4 +19,4 @@ export const workerParseKugouHeader = async ({ blobURI }: ParseKugouHeaderPayloa
} finally { } finally {
kwm?.free(); kwm?.free();
} }
} };
@@ -1,4 +1,4 @@
import { ParseKuwoHeaderPayload, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts'; import { ParseKuwoHeaderPayload, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
import { KuwoHeader } from '@unlock-music/crypto'; import { KuwoHeader } from '@unlock-music/crypto';
export const workerParseKuwoHeader = async ({ blobURI }: ParseKuwoHeaderPayload): Promise<ParseKuwoHeaderResponse> => { export const workerParseKuwoHeader = async ({ blobURI }: ParseKuwoHeaderPayload): Promise<ParseKuwoHeaderResponse> => {
+1 -1
View File
@@ -11,5 +11,5 @@ export async function workerGetQtfmDeviceKey({
board, board,
}: GetQingTingFMDeviceKeyPayload) { }: GetQingTingFMDeviceKeyPayload) {
const buffer = QingTingFM.getDeviceKey(device, brand, model, product, manufacturer, board); const buffer = QingTingFM.getDeviceKey(device, brand, model, product, manufacturer, board);
return hex(buffer); return Promise.resolve(hex(buffer));
} }
+1 -1
View File
@@ -1,5 +1,5 @@
// This is a dummy module for vite/rollup to resolve. // This is a dummy module for vite/rollup to resolve.
export function createRequire() { export function createRequire() {
import('radash'); // we need to import something, so vite don't complain on build const _ = import('radash'); // we need to import something, so vite don't complain on build
throw new Error('this is a dummy module. Do not use'); throw new Error('this is a dummy module. Do not use');
} }
+5 -5
View File
@@ -9,31 +9,31 @@ export function FAQAboutProject() {
<Header3 id="failed">um-react 是什么</Header3> <Header3 id="failed">um-react 是什么</Header3>
<p> <p>
um-react 是由 um-react 是由
<a className="mx-1 link link-info" href="https://git.unlock-music.dev/um"> <a className="mx-1 link link-info" href="https://git.um-react.app/um">
Unlock Music Unlock Music
</a> </a>
基于 React 框架制作的一款用于移除已购音乐的加密保护的小工具,使用 基于 React 框架制作的一款用于移除已购音乐的加密保护的小工具,使用
<a className="mx-1 link link-info" href="https://git.unlock-music.dev/um/um-react/src/branch/main/LICENSE"> <a className="mx-1 link link-info" href="https://git.um-react.app/um/um-react/src/branch/main/LICENSE">
MIT MIT
</a> </a>
授权协议。 授权协议。
</p> </p>
<p> <p>
它的解密核心由 <FaRust className="inline" /> 它的解密核心由 <FaRust className="inline" />
<a className="mx-1 link link-info" href="https://git.unlock-music.dev/um/lib_um_crypto_rust"> <a className="mx-1 link link-info" href="https://git.um-react.app/um/lib_um_crypto_rust">
<code>lib_um_crypto_rust</code> <code>lib_um_crypto_rust</code>
</a> </a>
驱动,使用 驱动,使用
<a <a
className="mx-1 link link-info" className="mx-1 link link-info"
href="https://git.unlock-music.dev/um/lib_um_crypto_rust/src/branch/main/LICENSE_MIT" href="https://git.um-react.app/um/lib_um_crypto_rust/src/branch/main/LICENSE_MIT"
> >
MIT MIT
</a> </a>
+ +
<a <a
className="mx-1 link link-info" className="mx-1 link link-info"
href="https://git.unlock-music.dev/um/lib_um_crypto_rust/src/branch/main/LICENSE_APACHE" href="https://git.um-react.app/um/lib_um_crypto_rust/src/branch/main/LICENSE_APACHE"
> >
Apache Apache
</a> </a>
+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers'; import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions'; import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx'; import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { RiErrorWarningLine } from 'react-icons/ri'; import { RiErrorWarningLine } from 'react-icons/ri';
export function KugouFAQ() { export function KugouFAQ() {
+1 -1
View File
@@ -2,7 +2,7 @@ import { Header2, Header3 } from '~/components/HelpText/Headers';
import { VQuote } from '~/components/HelpText/VQuote'; import { VQuote } from '~/components/HelpText/VQuote';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer'; import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { HiWord } from '~/components/HelpText/HiWord'; import { HiWord } from '~/components/HelpText/HiWord';
import { KWMv2AllInstructions } from '~/features/settings/panels/KWMv2/KWMv2AllInstructions'; import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions'; import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { RiErrorWarningLine } from 'react-icons/ri'; import { RiErrorWarningLine } from 'react-icons/ri';
+17 -11
View File
@@ -1,6 +1,5 @@
import { ExtLink } from '~/components/ExtLink'; import { ExtLink } from '~/components/ExtLink';
import { Header2, Header3, Header4 } from '~/components/HelpText/Headers'; import { Header2, Header3, Header4 } from '~/components/HelpText/Headers';
import { ProjectIssue } from '~/components/ProjectIssue';
import { NavLink } from 'react-router'; import { NavLink } from 'react-router';
@@ -12,13 +11,20 @@ export function OtherFAQ() {
<p>该项目进行解密处理。如果加密前的资源没有内嵌元信息或封面,解密的文件也没有。</p> <p>该项目进行解密处理。如果加密前的资源没有内嵌元信息或封面,解密的文件也没有。</p>
<p>请使用第三方工具进行编辑或管理元信息。</p> <p>请使用第三方工具进行编辑或管理元信息。</p>
<Header3 id="batch-dl">批量下载</Header3> <Header3 id="batch-download">批量下载约十首后失败 / 无法全部下载</Header3>
<p> <p>
{'暂时没有实现,不过你可以在 '} Chromium 系浏览器会限制页面在短时间内通过程序触发的<strong>多个</strong>
<ProjectIssue id={34} title="[UI] 全部下载功能" /> 文件下载(常见表现为大约十个文件后静默中断,或提示「此网站正在尝试下载多个文件」)。
{' 以及 '} </p>
<ProjectIssue id={43} title="批量下载" /> <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> </p>
<Header3 id="android-browsers">安卓: 浏览器支持说明</Header3> <Header3 id="android-browsers">安卓: 浏览器支持说明</Header3>
@@ -26,7 +32,7 @@ export function OtherFAQ() {
<div className="flex flex-col md:flex-row gap-2 md:gap-8"> <div className="flex flex-col md:flex-row gap-2 md:gap-8">
<div> <div>
<Header4>已知有问题的浏览器</Header4> <Header4>已知有问题的浏览器</Header4>
<ul className="list-disc list-inside pl-2"> <ul className="list-disc pl-8">
<li>Via 浏览器</li> <li>Via 浏览器</li>
<li>夸克浏览器</li> <li>夸克浏览器</li>
<li>UC 浏览器</li> <li>UC 浏览器</li>
@@ -35,7 +41,7 @@ export function OtherFAQ() {
<div> <div>
<Header4>可能会遇到的问题包括</Header4> <Header4>可能会遇到的问题包括</Header4>
<ul className="list-disc list-inside pl-2"> <ul className="list-disc pl-8">
<li>网页白屏</li> <li>网页白屏</li>
<li>无法下载解密后内容</li> <li>无法下载解密后内容</li>
<li>下载的文件名错误</li> <li>下载的文件名错误</li>
@@ -77,7 +83,7 @@ export function OtherFAQ() {
</li> </li>
<li> <li>
<p> <p>
<ExtLink className="mr-2" href="https://git.unlock-music.dev/um/um-react-wry"> <ExtLink className="mr-2" href="https://git.um-react.app/um/um-react-wry">
<strong> <strong>
<code>um-react-wry</code> <code>um-react-wry</code>
</strong> </strong>
@@ -89,7 +95,7 @@ export function OtherFAQ() {
<ul className="list-disc pl-6"> <ul className="list-disc pl-6">
<li> <li>
<p> <p>
<ExtLink href="https://git.unlock-music.dev/um/um-react/releases/latest">仓库下载</ExtLink> <ExtLink href="https://git.um-react.app/um/um-react/releases/latest">仓库下载</ExtLink>
{' | 寻找文件名为 '} {' | 寻找文件名为 '}
<code>um-react-win64-</code> 开头的附件 <code>um-react-win64-</code> 开头的附件
</p> </p>
+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers'; import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer'; import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { QMCv2QQMusicAllInstructions } from '~/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions'; import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
export function QQMusicFAQ() { export function QQMusicFAQ() {
return ( return (
+4 -8
View File
@@ -26,14 +26,10 @@ export function FileError({ error, code }: FileErrorProps) {
const copyError = () => { const copyError = () => {
if (error) { if (error) {
navigator.clipboard navigator.clipboard.writeText(applyTemplate(ERROR_TEMPLATE, { summary, error })).then(
.writeText(applyTemplate(ERROR_TEMPLATE, { summary, error })) () => toast.success('错误信息已复制到剪贴板'),
.then(() => { (e) => toast.error(`复制错误信息失败: ${e as Error}`),
toast.success('错误信息已复制到剪贴板'); );
})
.catch((e) => {
toast.error(`复制错误信息失败: ${e}`);
});
} }
}; };
+14 -25
View File
@@ -3,22 +3,13 @@ import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import type { RootState } from '~/store'; import type { RootState } from '~/store';
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants'; import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
import type { import type { DecryptCommandOptions } from '~/decrypt-worker/types';
DecryptCommandOptions,
FetchMusicExNamePayload,
ParseKugouHeaderPayload,
ParseKugouHeaderResponse,
ParseKuwoHeaderPayload,
ParseKuwoHeaderResponse,
} from '~/decrypt-worker/types';
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client'; import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError'; import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
import { import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
selectKugouKey, import { selectKWMv2Key } from '~/features/kwm/keyLookup';
selectKWMv2Key, import { selectKugouKey } from '~/features/kugou/keyLookup';
selectQMCv2KeyByFileName, import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
selectQtfmAndroidKey,
} from '../settings/settingsSelector';
import { cleanFilename } from '~/util/cleanFilename'; import { cleanFilename } from '~/util/cleanFilename';
export enum ProcessState { export enum ProcessState {
@@ -80,27 +71,25 @@ export const processFile = createAsyncThunk<
}; };
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([ const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
workerClientBus.request<string, FetchMusicExNamePayload>(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, { workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
blobURI: file.raw,
}),
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
blobURI: file.raw,
}),
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
blobURI: file.raw, blobURI: file.raw,
}), }),
workerClientBus.request<ParseKuwoHeaderResponse, ParseKuwoHeaderPayload>(
DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER,
{ blobURI: file.raw },
),
workerClientBus.request<ParseKugouHeaderResponse, ParseKugouHeaderPayload>(
DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER,
{ blobURI: file.raw },
),
]); ]);
const options: DecryptCommandOptions = { const options: DecryptCommandOptions = {
fileName: file.fileName, fileName: file.fileName,
qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName), qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName),
kwm2key: selectKWMv2Key(state, kuwoHdr), kwm2Key: selectKWMv2Key(state, kuwoHdr),
kugouKey: selectKugouKey(state, kugouHdr), kugouKey: selectKugouKey(state, kugouHdr),
qingTingAndroidKey: selectQtfmAndroidKey(state), qingTingAndroidKey: selectQtfmAndroidKey(state),
}; };
return decryptionQueue.add({ id: fileId, blobURI: file.raw, options }, onPreProcess); return decryptionQueue.add({ fileId, blobURI: file.raw, options }, onPreProcess);
}); });
export const fileListingSlice = createSlice({ export const fileListingSlice = createSlice({
@@ -0,0 +1,35 @@
import { configureStore } from '@reduxjs/toolkit';
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
import type { RootState } from '~/store';
import { selectKugouKey } from '../keyLookup';
function storeWithKugouKeys(keys: Record<string, string>) {
const base = settingsSlice.getInitialState();
return configureStore({
reducer: { settings: settingsReducer },
preloadedState: {
settings: {
...base,
production: {
...base.production,
kugou: { keys },
},
},
},
});
}
describe('selectKugouKey', () => {
test('returns key for matching audioHash', () => {
const hash = 'a'.repeat(32);
const store = storeWithKugouKeys({ [hash]: 'ek' });
expect(selectKugouKey(store.getState() as RootState, { audioHash: hash } as never)).toBe('ek');
});
test('returns undefined for unknown hash or null header', () => {
const store = storeWithKugouKeys({ ['b'.repeat(32)]: 'ek' });
expect(selectKugouKey(store.getState() as RootState, { audioHash: 'c'.repeat(32) } as never)).toBeUndefined();
expect(selectKugouKey(store.getState() as RootState, null)).toBeUndefined();
});
});
+15
View File
@@ -0,0 +1,15 @@
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou';
import type { StagingKugouKey } from './types';
/** Parse a Kugou MMKV / encrypted DB dump into staging key rows (without `id`). */
export async function importKugouKeysFromFile(file: File): Promise<null | Omit<StagingKugouKey, 'id'>[]> {
if (/mggkey_multi_process/i.test(file.name)) {
return parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
}
if (/^KGMusicV3\.db$/.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
return extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
}
return null;
}
@@ -1,20 +1,11 @@
import { RiFileCopyLine } from 'react-icons/ri'; import { RiFileCopyLine } from 'react-icons/ri';
import { toast } from 'react-toastify';
import { ExtLink } from '~/components/ExtLink'; import { ExtLink } from '~/components/ExtLink';
import { FilePathBlock } from '~/components/FilePathBlock.tsx'; import { FilePathBlock } from '~/components/FilePathBlock.tsx';
import { copyToClipboard } from '~/util/clipboard';
const DB_PATH = '%APPDATA%\\KuGou8\\KGMusicV3.db';
export function InstructionsPC() { export function InstructionsPC() {
const DB_PATH = '%APPDATA%\\KuGou8\\KGMusicV3.db'; const copyDbPathToClipboard = () => copyToClipboard(DB_PATH);
const copyDbPathToClipboard = () => {
navigator.clipboard
.writeText(DB_PATH)
.then(() => {
toast.success('已复制到剪贴板');
})
.catch((err) => {
toast.error(`复制失败,请手动复制\n${err}`);
});
};
return ( return (
<> <>
+19
View File
@@ -0,0 +1,19 @@
import type { RootState } from '~/store';
import type { ParseKugouHeaderResponse } from '~/decrypt-worker/types.ts';
import { hasOwn } from '~/util/objects';
/** Staging KuGou/KGG keys (`state.settings.staging.kugou`; UI tab `kgg`). */
export const selectStagingKugouV5Keys = (state: RootState) => state.settings.staging.kugou.keys;
/** Production KuGou/KGG keys (`state.settings.production.kugou`; persist key `kugou`). */
export const selectFinalKugouV5Keys = (state: RootState) => state.settings.production.kugou.keys;
export const selectKugouKey = (state: RootState, hdr: ParseKugouHeaderResponse): string | undefined => {
if (!hdr) {
return;
}
const keys = selectFinalKugouV5Keys(state);
const lookupKey = hdr.audioHash;
return hasOwn(keys, lookupKey) ? keys[lookupKey] : undefined;
};
@@ -1,7 +1,7 @@
import { kugouDeleteKey, kugouUpdateKey } from '../../settingsSlice'; import { kugouDeleteKey, kugouUpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks'; import { useAppDispatch } from '~/hooks';
import { memo } from 'react'; import { memo } from 'react';
import { StagingKugouKey } from '../../keyFormats'; import type { StagingKugouKey } from '~/features/kugou/types';
import { KeyInput } from '~/components/KeyInput'; import { KeyInput } from '~/components/KeyInput';
export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => { export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => {
@@ -2,15 +2,12 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal'; import { ImportSecretModal } from '~/components/ImportSecretModal';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '~/features/settings/settingsSlice';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '../settingsSlice'; import { selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
import { selectStagingKugouV5Keys } from '../settingsSelector';
import type { StagingKugouKey } from '../keyFormats';
import { AddKey } from '~/components/AddKey.tsx'; import { AddKey } from '~/components/AddKey.tsx';
import { KugouEKeyItem } from '~/features/settings/panels/Kugou/KugouEKeyItem.tsx'; import { KugouEKeyItem } from './KugouEKeyItem';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx'; import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou.ts'; import { importKugouKeysFromFile } from '~/features/kugou/importKeys';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor.ts';
import { KeyListContainer } from '~/components/KeyListContainer'; import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult'; import { toastImportResult } from '~/util/toastImportResult';
@@ -22,13 +19,7 @@ export function PanelKGGKey() {
const addKey = () => dispatch(kugouAddKey()); const addKey = () => dispatch(kugouAddKey());
const clearAll = () => dispatch(kugouClearKeys()); const clearAll = () => dispatch(kugouClearKeys());
const handleSecretImport = async (file: File) => { const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKugouKey, 'id'>[] | null = null; const keys = await importKugouKeysFromFile(file);
if (/mggkey_multi_process/i.test(file.name)) {
keys = parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
} else if (/^KGMusicV3\.db$/.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
keys = extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
}
if (keys && keys.length > 0) { if (keys && keys.length > 0) {
dispatch(kugouImportKeys(keys)); dispatch(kugouImportKeys(keys));
+22
View File
@@ -0,0 +1,22 @@
import { nanoid } from 'nanoid';
/**
* KuGou / KGG (kgm v5).
* UI settings tab route: `kgg`. Redux + localStorage production field: `kugou`.
*/
export interface StagingKugouKey {
id: string;
audioHash: string;
ekey: string;
}
export type ProductionKugouKey = Record<string /* audioHash */, string /* ekey */>;
export const kugouStagingToProductionKey = (key: StagingKugouKey) => key.audioHash.normalize();
export const kugouStagingToProductionValue = (key: StagingKugouKey) => key.ekey.normalize();
export const kugouProductionToStaging = (
key: keyof ProductionKugouKey,
value: ProductionKugouKey[keyof ProductionKugouKey],
): null | StagingKugouKey => {
if (typeof value !== 'string') return null;
return { id: nanoid(), audioHash: key.normalize(), ekey: value };
};
@@ -0,0 +1,32 @@
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { importKWMv2KeysFromFile } from '../importKeys';
const fixtureDir = join(dirname(fileURLToPath(import.meta.url)), '../../../util/mmkv/__tests__/__fixture__');
function fileFromFixture(name: string, path: string): File {
const buff = readFileSync(path);
return new File([buff], name);
}
describe('importKWMv2KeysFromFile', () => {
test('parses Android Kuwo MMKV by filename', async () => {
const file = fileFromFixture('cn.kuwo.player.mmkv.defaultconfig', join(fixtureDir, 'kuwo_android.mmkv'));
await expect(importKWMv2KeysFromFile(file)).resolves.toEqual([
{ rid: '1234567', quality: '20201kmflac', ekey: 'xyz123' },
]);
});
test('parses iOS Kuwo ekey dump by filename', async () => {
const file = fileFromFixture('kw_ekey', join(fixtureDir, 'kuwo_ios.mmkv'));
await expect(importKWMv2KeysFromFile(file)).resolves.toEqual([
{ rid: '1234567', quality: '20201', ekey: 'xyz123' },
]);
});
test('returns null for unrecognized filenames', async () => {
await expect(importKWMv2KeysFromFile(new File([], 'notes.txt'))).resolves.toBeNull();
});
});
+13
View File
@@ -0,0 +1,13 @@
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo';
import type { StagingKWMv2Key } from './types';
/** Parse a Kuwo MMKV / iOS ekey dump into staging key rows (without `id`). */
export async function importKWMv2KeysFromFile(file: File): Promise<null | Omit<StagingKWMv2Key, 'id'>[]> {
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
return parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
}
if (/kw_ekey/.test(file.name)) {
return parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
}
return null;
}
+26
View File
@@ -0,0 +1,26 @@
import type { RootState } from '~/store';
import type { ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
import { hasOwn } from '~/util/objects';
import { kwm2StagingToProductionKey } from './types';
export const selectStagingKWMv2Keys = (state: RootState) => state.settings.staging.kwm2.keys;
export const selectFinalKWMv2Keys = (state: RootState) => state.settings.production.kwm2.keys;
export const selectKWMv2Key = (state: RootState, hdr: ParseKuwoHeaderResponse): string | undefined => {
if (!hdr) {
return;
}
const quality = String(hdr.qualityId);
const rid = String(hdr.resourceId);
const keys = selectFinalKWMv2Keys(state);
const lookupKey = kwm2StagingToProductionKey({ id: '', ekey: '', quality, rid });
let ekey: string | undefined;
if (hasOwn(keys, lookupKey)) {
ekey = keys[lookupKey];
}
return ekey;
};
@@ -1,8 +1,8 @@
import { PiFileAudio, PiHash } from 'react-icons/pi'; import { PiFileAudio, PiHash } from 'react-icons/pi';
import { kwm2DeleteKey, kwm2UpdateKey } from '../../settingsSlice'; import { kwm2DeleteKey, kwm2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks'; import { useAppDispatch } from '~/hooks';
import { memo } from 'react'; import { memo } from 'react';
import { StagingKWMv2Key } from '../../keyFormats'; import type { StagingKWMv2Key } from '~/features/kwm/types';
import { KeyInput } from '~/components/KeyInput'; import { KeyInput } from '~/components/KeyInput';
export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => { export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => {
@@ -2,13 +2,11 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal'; import { ImportSecretModal } from '~/components/ImportSecretModal';
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo'; import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '../settingsSlice'; import { KWMv2EKeyItem } from './KWMv2EKeyItem';
import { selectStagingKWMv2Keys } from '../settingsSelector'; import { importKWMv2KeysFromFile } from '~/features/kwm/importKeys';
import { KWMv2EKeyItem } from './KWMv2/KWMv2EKeyItem'; import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import type { StagingKWMv2Key } from '../keyFormats';
import { KWMv2AllInstructions } from './KWMv2/KWMv2AllInstructions';
import { AddKey } from '~/components/AddKey'; import { AddKey } from '~/components/AddKey';
import { KeyListContainer } from '~/components/KeyListContainer'; import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult'; import { toastImportResult } from '~/util/toastImportResult';
@@ -21,12 +19,7 @@ export function PanelKWMv2Key() {
const addKey = () => dispatch(kwm2AddKey()); const addKey = () => dispatch(kwm2AddKey());
const clearAll = () => dispatch(kwm2ClearKeys()); const clearAll = () => dispatch(kwm2ClearKeys());
const handleSecretImport = async (file: File) => { const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKWMv2Key, 'id'>[] | null = null; const keys = await importKWMv2KeysFromFile(file);
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
keys = parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
} else if (/kw_ekey/.test(file.name)) {
keys = parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
}
if (keys && keys.length > 0) { if (keys && keys.length > 0) {
dispatch(kwm2ImportKeys(keys)); dispatch(kwm2ImportKeys(keys));
+39
View File
@@ -0,0 +1,39 @@
import { nanoid } from 'nanoid';
/** KWMv2 staging key row (Kuwo). */
export interface StagingKWMv2Key {
id: string;
/**
* Resource ID
*/
rid: string;
/**
* Quality String
*/
quality: string;
ekey: string;
}
export type ProductionKWMv2Keys = Record<string /* `${rid}-${quality}` */, string /* ekey */>;
export const parseKwm2ProductionKey = (key: string): null | { rid: string; quality: string } => {
const m = key.match(/^(\d+)-(\w+)$/);
if (!m) return null;
const [_, rid, quality] = m;
return { rid, quality };
};
export const kwm2StagingToProductionKey = (key: StagingKWMv2Key) => `${key.rid}-${key.quality.replace(/\D/g, '')}`;
export const kwm2StagingToProductionValue = (key: StagingKWMv2Key) => key.ekey;
export const kwm2ProductionToStaging = (
key: keyof ProductionKWMv2Keys,
value: ProductionKWMv2Keys[keyof ProductionKWMv2Keys],
): null | StagingKWMv2Key => {
if (typeof value !== 'string') return null;
const parsed = parseKwm2ProductionKey(key);
if (!parsed) return null;
const { quality, rid } = parsed;
return { id: nanoid(), rid, quality, ekey: value };
};
@@ -0,0 +1,38 @@
import { configureStore } from '@reduxjs/toolkit';
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
import type { RootState } from '~/store';
import { selectQMCv2KeyByFileName } from '../keyLookup';
function storeWithQmcKeys(keys: Record<string, string>, allowFuzzyNameSearch = true) {
const base = settingsSlice.getInitialState();
return configureStore({
reducer: { settings: settingsReducer },
preloadedState: {
settings: {
...base,
production: {
...base.production,
qmc2: { allowFuzzyNameSearch, keys },
},
},
},
});
}
describe('selectQMCv2KeyByFileName', () => {
test('returns exact match', () => {
const store = storeWithQmcKeys({ 'song.mflac': 'ek-exact' });
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'song.mflac')).toBe('ek-exact');
});
test('falls back to closest name when fuzzy search is enabled', () => {
const store = storeWithQmcKeys({ 'song.mflac': 'ek-fuzzy' });
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'songg.mflac')).toBe('ek-fuzzy');
});
test('returns undefined when fuzzy search is disabled and name misses', () => {
const store = storeWithQmcKeys({ 'song.mflac': 'ek' }, false);
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'other.mflac')).toBeUndefined();
});
});
+21
View File
@@ -0,0 +1,21 @@
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
import { parseAndroidQmEKey } from '~/util/mmkv/qm';
import { getFileName } from '~/util/pathHelper';
import type { StagingQMCv2Key } from './types';
/** Parse a QMCv2 key database / MMKV dump into staging key rows (without `id`). */
export async function importQMCv2KeysFromFile(file: File): Promise<null | Omit<StagingQMCv2Key, 'id'>[]> {
const fileBuffer = await file.arrayBuffer();
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
return extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
}
if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
const map = parseAndroidQmEKey(new DataView(fileBuffer));
return Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
}
return null;
}
@@ -0,0 +1,31 @@
import { useId } from 'react';
import { InstructionsMacV8 } from './InstructionsMacV8';
import { InstructionsMacV10 } from './InstructionsMacV10';
export function InstructionsMac() {
const macInstructionId = useId();
return (
<>
<p>Mac 客户端使用 mmkv 数据库储存密钥。</p>
<p>建议使用 v8.8.0 或 v10.7 版本的客户端,其中 v8.8.0 版本需要屏蔽更新。</p>
<div className="join join-vertical bg-base-100 mt-2 max-w-full">
<div className="collapse collapse-arrow join-item border-base-300 border">
<input type="radio" name={macInstructionId} />
<div className="collapse-title font-semibold">使用 QQ 音乐 Mac v8.8.0</div>
<div className="collapse-content text-sm min-w-0">
<InstructionsMacV8 />
</div>
</div>
<div className="collapse collapse-arrow join-item border-base-300 border">
<input type="radio" name={macInstructionId} />
<div className="collapse-title font-semibold">使用 QQ 音乐 Mac v10.7.1</div>
<div className="collapse-content text-sm min-w-0">
<InstructionsMacV10 />
</div>
</div>
</div>
</>
);
}
@@ -0,0 +1,65 @@
import { ExtLink } from '~/components/ExtLink';
import {
commandName as DUMP_COMMAND_NAME,
tarName as DUMP_COMMAND_TARBALL_NAME,
tarball as DUMP_COMMAND_BASE64,
} from './assets/qqmusic_v10.7_dump.command?&name=QQ 音乐 Mac v10 密钥提取.command&mac-command';
import { DownloadBase64 } from '~/components/DownloadBase64';
import { VQuote } from '~/components/HelpText/VQuote';
import { InSecretImportModalContext } from '~/context/InSecretImportModal';
import { useContext } from 'react';
const MAC_CLIENT_URL =
'https://c.y.qq.com/cgi-bin/file_redirect.fcg?bid=dldir&file=ecosfile%2Fmusic_clntupate%2Fmac%2Fother%2FQQMusicMac10.7.1Build00.dmg&sign=1-0cb9ee4c40e7447e2113cfdee2dc11c88487b0e31fe37cfe1c59e12c20956dce-689e9373';
const MAC_CLIENT_TG_URL = 'https://t.me/um_lsr_ch/30';
export function InstructionsMacV10() {
const inSecretImportModal = useContext(InSecretImportModalContext);
return (
<>
<p className="mt-4">获取 QQ 音乐 Mac 客户端 10.7.1:</p>
<ul className="list-disc pl-6">
<li>
<ExtLink className="link-info" href={MAC_CLIENT_URL}>
通过 QQ 音乐官网下载(高速,但可能失效)
</ExtLink>
</li>
<li>
<ExtLink className="link-info" href={MAC_CLIENT_TG_URL}>
通过 Telegram 下载(缓存,需要账号)
</ExtLink>
</li>
</ul>
<h4 className="font-bold text-lg mt-4">导入密钥</h4>
<ol className="list-decimal pl-6">
<li>
下载 <DownloadBase64 data={DUMP_COMMAND_BASE64} filename={DUMP_COMMAND_TARBALL_NAME}></DownloadBase64>
,打开得到 <code>{DUMP_COMMAND_NAME}</code>。
</li>
<li>
<p>
双击 <code>{DUMP_COMMAND_NAME}</code> 执行。
</p>
<p>
※ 若是提示文件来自未知开发者,请右键点击该文件,选择菜单第一项
<VQuote>打开</VQuote>,在警告窗口再次选择<VQuote>打开</VQuote>。
</p>
</li>
<li>
运行后会在脚本当前目录生成 <code>qqmusic-mac-*.mmkv</code> 文件,其中 <code>*</code> 是一串随机字符。
</li>
{inSecretImportModal ? (
<li>
上传刚生成的 <code>qqmusic-mac-*.mmkv</code> 文件到上方的<VQuote>文件选择区域</VQuote>。
</li>
) : (
<li>
前往设定页面,提交生成的 <code>qqmusic-mac-*.mmkv</code> 文件。
</li>
)}
</ol>
</>
);
}
@@ -0,0 +1,89 @@
import { RiFileCopyLine } from 'react-icons/ri';
import { ExtLink } from '~/components/ExtLink';
import { FilePathBlock } from '~/components/FilePathBlock';
import { VQuote } from '~/components/HelpText/VQuote';
import { MacCommandKey } from '~/components/Key/MacCommandKey';
import { ShiftKey } from '~/components/Key/ShiftKey';
import { copyToClipboard } from '~/util/clipboard';
import {
commandName as BLOCK_UPDATE_COMAND,
tarName as BLOCK_UPDATE_TAR_NAME,
tarball as BLOCK_UPDATE_BASE64,
} from './assets/qqmusic_v8.8.0_patch_update.command?&name=QQ 音乐 Mac v8.8.0 屏蔽更新.command&mac-command';
import { DownloadBase64 } from '~/components/DownloadBase64';
import { useContext } from 'react';
import { InSecretImportModalContext } from '~/context/InSecretImportModal';
const MAC_CLIENT_URL =
'https://web.archive.org/web/20230903/https://dldir1.qq.com/music/clntupate/mac/QQMusicMac_Mgr.dmg';
const MAC_CLIENT_TG_URL = 'https://t.me/um_lsr_ch/21';
const DB_PATH =
'~/Library/Containers/com.tencent.QQMusicMac/Data/Library/Application Support/QQMusicMac/mmkv/MMKVStreamEncryptId';
export function InstructionsMacV8() {
const inSecretImportModal = useContext(InSecretImportModalContext);
return (
<>
<p className="mt-4">获取 QQ 音乐 Mac 客户端 8.8.0:</p>
<ul className="list-disc pl-6">
<li>
<ExtLink className="link-info" href={MAC_CLIENT_URL}>
通过 <code>Archive.org</code> 缓存下载(慢)
</ExtLink>
</li>
<li>
<ExtLink className="link-info" href={MAC_CLIENT_TG_URL}>
通过 Telegram 下载(需要账号)
</ExtLink>
</li>
</ul>
<p className="mt-4">
部分用户可能会被强制要求更新。你可以下载
<DownloadBase64 filename={BLOCK_UPDATE_TAR_NAME} data={BLOCK_UPDATE_BASE64}></DownloadBase64>
并执行 <code>{BLOCK_UPDATE_COMAND}</code>。
<span>其原理是修改 QQ 音乐的版本号,让其认为自己是最新版本,从而达到屏蔽更新的效果。</span>
</p>
<p>
※ 若是提示文件来自未知开发者,请右键点击该文件,选择菜单第一项
<VQuote>打开</VQuote>,在警告窗口再次选择<VQuote>打开</VQuote>。
</p>
<p className="mt-4">密钥文件通常存储在下述路径:</p>
<FilePathBlock>{DB_PATH}</FilePathBlock>
<h4 className="font-bold text-lg mt-4">导入密钥</h4>
<ol className="list-decimal pl-6">
<li>
<button className="btn btn-sm btn-outline btn-accent mr-2" onClick={() => copyToClipboard(DB_PATH)}>
<RiFileCopyLine className="text-xl" />
<span>复制</span>
</button>
<code>MMKVStreamEncryptId</code> 文件路径
</li>
<li>
{inSecretImportModal ? (
<p>
点击上方的<VQuote>文件选择区域</VQuote>,打开<VQuote>文件选择框</VQuote>
</p>
) : (
<p>前往设定页面,提交该密钥文件。</p>
)}
<p>
※ 你可以在文件选择对话框按下
<VQuote>
<ShiftKey className="mx-1" />
{'+'}
<MacCommandKey className="mx-1" />
{'+'}
<kbd className="kbd mx-1">G</kbd>
</VQuote>
组合键打开<VQuote>路径输入框</VQuote>,粘贴文件路径并回车提交。
</p>
</li>
</ol>
</>
);
}
@@ -3,6 +3,7 @@ import { HiWord } from '~/components/HelpText/HiWord';
import NoopExecutable from './assets/noop.exe?base64'; import NoopExecutable from './assets/noop.exe?base64';
import NoopExecutableSource from './assets/noop.asm.txt?base64'; import NoopExecutableSource from './assets/noop.asm.txt?base64';
const QMPC_MMKV_RELEASES_URL = 'https://git.um-react.app/um/qmpc-mmkv/releases';
const PC_CLIENT_URL = 'https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe'; const PC_CLIENT_URL = 'https://web.archive.org/web/2023/https://dldir1v6.qq.com/music/clntupate/QQMusic_Setup_1951.exe';
const PC_CLIENT_TG_URL = 'https://t.me/um_lsr_ch/24'; const PC_CLIENT_TG_URL = 'https://t.me/um_lsr_ch/24';
@@ -10,14 +11,20 @@ export function InstructionsPC() {
return ( return (
<> <>
<p className="mt-2"> <p className="mt-2">
使用 <span className="text-error">19.57 或更高版本</span>下载的歌曲文件 使用 <span className="text-primary">19.57 至 22.76</span>下载的歌曲文件
<HiWord>需要导入密钥</HiWord>。 <HiWord>需要导入密钥</HiWord>。
<br />
目前未公开密钥获取方式,因此不支持。
</p> </p>
<p className="mt-4"> <p className="mt-4">
使用 <span className="text-primary">19.51 或更低版本</span>下载的歌曲文件 请从{' '}
<ExtLink className="link-info" href={QMPC_MMKV_RELEASES_URL}>
qmpc-mmkv-cli
</ExtLink>{' '}
获取工具,提取密钥文件 <code>qmpc-mmkv-v1.mmkv</code> 后在本页导入。
</p>
<p className="mt-4">
使用 <span className="text-base-content/70">19.51 或更低版本</span>下载的歌曲文件
<HiWord>无需密钥</HiWord>。 <HiWord>无需密钥</HiWord>。
</p> </p>
@@ -0,0 +1,3 @@
com.tencent.QQMusicMac.plist
iData/
qqmusic-mac-*.mmkv
@@ -0,0 +1,213 @@
#!/usr/bin/env python3
# QQMusic Mac MMKV Decryptor by LSR@Unlock Music
import hashlib
import re
import sys
from argparse import ArgumentParser
from dataclasses import dataclass
from os import PathLike
from os.path import dirname
from pathlib import Path
from struct import pack, unpack
@dataclass
class MMKVDecryptionData:
udid: str
mmkv_path: Path
mmkv_key: str
data: bytes
@property
def mmkv_name(self) -> str:
return self.mmkv_path.name
def _aes_128_cfb_decrypt(key: bytes, iv: bytes, ciphertext: bytes) -> bytes:
"""Decrypt using `Crypto.Cipher.AES` _or_ fallback to `OpenSSL` otherwise"""
try:
from Crypto.Cipher import AES # pyright: ignore[reportMissingImports]
aes = AES.new(key[:16], AES.MODE_CFB, iv=iv, segment_size=128)
return aes.decrypt(ciphertext)
except ImportError:
from subprocess import PIPE, Popen
process = Popen(
["openssl", "enc", "-aes-128-cfb", "-d", "-K", key.hex(), "-iv", iv.hex()],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
text=False,
)
stdout, stderr = process.communicate(input=ciphertext)
if process.returncode != 0:
raise RuntimeError(
f"OpenSSL error (install PyCryptodome instead): {stderr.decode()}"
)
return stdout
def _caesar(text: str, shift: int) -> str:
"""A simple Caesar cipher implementation for alphanumeric characters"""
result = ""
for char in text:
if char.isalpha():
base = ord("A") if char.isupper() else ord("a")
result += chr((ord(char) - base + shift) % 26 + base)
elif char.isdigit():
result += chr((ord(char) - ord("0") + shift) % 10 + ord("0"))
else:
result += char
return result
__MMKV_TYPE_STREAM_KEY = 1
def _derive_mmkv_config(udid: str, mmkv_type: int):
"""Derive MMKV name and key from UDID, return (name, key)"""
str1 = _caesar(udid, mmkv_type + 3)
int1 = int(udid[5:7], 16)
int2 = 5 + (int1 + mmkv_type) % 4
mmkv_name = str1[0:int2]
int3 = mmkv_type + 0xA546
str3 = f"{udid}{int3:04x}"
mmkv_key = hashlib.md5(str3.encode()).hexdigest()
return mmkv_name, mmkv_key
def _decrypt_mmkv(path: PathLike, key: bytes):
"""Decrypt MMKV file using the given key, return decrypted data"""
with open(path, "rb") as mmkv, open(str(path) + ".crc", "rb") as crc:
crc.seek(12)
iv = crc.read(16)
(real_size,) = unpack("<I", crc.read(4))
(mmkv_payload_size,) = unpack("<I", mmkv.read(4))
if mmkv_payload_size != real_size:
raise ValueError("MMKV file size mismatch")
decrypted_data = pack("<I", real_size)
decrypted_data += _aes_128_cfb_decrypt(key, iv, mmkv.read(real_size))
return decrypted_data
def _dump_udid(plist_file: PathLike):
"""Extract UDIDs from the given plist file"""
with open(plist_file, "rb") as f:
plist = f.read()
for m in re.finditer(rb"_\x10\(([0-9a-f]{40})_", plist):
yield m.group(1).decode()
def _dump_mmkv(plist_file: PathLike, data_dir: PathLike):
"""Dump all MMKV files from the given plist file and iData directory"""
for udid in _dump_udid(plist_file):
mmkv_name, mmkv_key = _derive_mmkv_config(udid, __MMKV_TYPE_STREAM_KEY)
mmkv_path = Path(data_dir) / mmkv_name
if not mmkv_path.exists() or not mmkv_path.is_file():
print(f"MMKV file not found, skipping (path={mmkv_path})", file=sys.stderr)
continue
try:
decrypted_mmkv = _decrypt_mmkv(mmkv_path, mmkv_key.encode())
except Exception as e:
print(
"Error decrypting mmkv, skipping"
f" (path={mmkv_path}, key={mmkv_key}, error={e})",
file=sys.stderr,
)
continue
yield MMKVDecryptionData(
udid=udid,
mmkv_path=mmkv_path,
mmkv_key=mmkv_key,
data=decrypted_mmkv,
)
def main():
parser = ArgumentParser(
description="QQMusic Mac MMKV Decryptor by LSR@Unlock Music"
)
parser.add_argument(
"-p",
"--plist",
type=str,
nargs="+",
help="Path to com.tencent.QQMusicMac.plist file or files",
default=[],
)
parser.add_argument(
"-i",
"--idata",
type=str,
help="Path to iData directory",
default="",
)
parser.add_argument("-f", "--force", action="store_true", help="Force overwrite")
parser.add_argument(
"-o",
"--output",
type=str,
help="Output directory for decrypted MMKV files (default: script directory)",
default=dirname(__file__),
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="Enable verbose output"
)
args = parser.parse_args()
home_dir = Path.home()
app_sandbox_dir = home_dir / "Library/Containers/com.tencent.QQMusicMac/Data"
idata_dir = app_sandbox_dir / "Library/Application Support/QQMusicMac/iData"
if args.idata:
idata_dir = Path(args.idata)
plists = []
if args.plist:
plists = [Path(p) for p in args.plist]
else:
for base_dir in (home_dir, app_sandbox_dir):
plists.append(base_dir / "Library/Preferences/com.tencent.QQMusicMac.plist")
output_dir = Path(args.output)
output_dir.mkdir(parents=True, exist_ok=True)
force = args.force
verbose = args.verbose
for plist_file in plists:
if plist_file.exists() and plist_file.is_file():
for dump in _dump_mmkv(plist_file, idata_dir):
out_path = output_dir / f"qqmusic-mac-{dump.mmkv_path.name}.mmkv"
if out_path.exists() and not force:
print(f"output exists, skipping (name={out_path.name})")
continue
if verbose:
print("*** MMKV DUMP ENTRY START ***")
print(f"UDID: {dump.udid}")
print(f"MMKV Name: {dump.mmkv_path.name}")
print(f"MMKV Key: {dump.mmkv_key}")
print(f"Output: {out_path.name}")
print("**** MMKV DUMP ENTRY END ****")
else:
print(f"Dumping mmkv: {out_path.name}...")
try:
with open(out_path, "wb") as f:
f.write(dump.data)
except Exception as e:
print(f"Error writing decrypted mmkv: {e}", file=sys.stderr)
continue
if __name__ == "__main__":
main()
@@ -0,0 +1,28 @@
#!/bin/sh
echo '补丁中…'
patch_count=0
patch_qqmusic() {
SUDO="$1"
APP="$2"
if [ ! -d "$APP" ]; then
echo "路径不存在,跳过 $APP..."
return
fi
echo "修补 $APP..."
$SUDO sed -i.bak 's#<string>8.8.0</string>#<string>88.8.0</string>#' \
"$APP/Contents/Info.plist"
$SUDO codesign --force --deep --sign - "$APP"
$SUDO xattr -d com.apple.quarantine "$APP"
patch_count=$((patch_count + 1))
}
patch_qqmusic sudo "/Applications/QQMusic.app"
patch_qqmusic "" "$HOME/Applications/QQMusic.app"
echo "完成,已修补 $patch_count 个 QQ 音乐安装"
File renamed without changes.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

+25
View File
@@ -0,0 +1,25 @@
import type { RootState } from '~/store';
import { closestByLevenshtein } from '~/util/levenshtein';
import { hasOwn } from '~/util/objects';
export const selectStagingQMCv2Settings = (state: RootState) => state.settings.staging.qmc2;
export const selectFinalQMCv2Settings = (state: RootState) => state.settings.production.qmc2;
export const selectQMCv2KeyByFileName = (state: RootState, name: string): string | undefined => {
const normalizedName = name.normalize();
let ekey: string | undefined;
const { keys, allowFuzzyNameSearch } = selectFinalQMCv2Settings(state);
if (hasOwn(keys, normalizedName)) {
ekey = keys[normalizedName];
} else if (allowFuzzyNameSearch) {
const qmc2KeyStoreNames = Object.keys(keys);
if (qmc2KeyStoreNames.length > 0) {
const closestName = closestByLevenshtein(normalizedName, qmc2KeyStoreNames);
console.debug('qmc2: key db could not find %o, using closest %o instead.', normalizedName, closestName);
ekey = keys[closestName];
}
}
return ekey;
};
@@ -1,15 +1,12 @@
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '../settingsSlice'; import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingQMCv2Settings } from '../settingsSelector'; import { selectStagingQMCv2Settings } from '~/features/qmc/keyLookup';
import React, { useRef, useState } from 'react'; import React, { useRef, useState } from 'react';
import { QMCv2EKeyItem } from './QMCv2/QMCv2EKeyItem'; import { QMCv2EKeyItem } from './QMCv2EKeyItem';
import { ImportSecretModal } from '~/components/ImportSecretModal'; import { ImportSecretModal } from '~/components/ImportSecretModal';
import { StagingQMCv2Key } from '../keyFormats'; import { importQMCv2KeysFromFile } from '~/features/qmc/importKeys';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor'; import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
import { parseAndroidQmEKey } from '~/util/mmkv/qm'; import { QMCv2DoubanAllInstructions } from '~/features/qmc/instructions/QMCv2DoubanAllInstructions';
import { getFileName } from '~/util/pathHelper';
import { QMCv2QQMusicAllInstructions } from './QMCv2/QMCv2QQMusicAllInstructions';
import { QMCv2DoubanAllInstructions } from './QMCv2/QMCv2DoubanAllInstructions';
import { AddKey } from '~/components/AddKey'; import { AddKey } from '~/components/AddKey';
import { InfoModal } from '~/components/InfoModal.tsx'; import { InfoModal } from '~/components/InfoModal.tsx';
import { Ruby } from '~/components/Ruby.tsx'; import { Ruby } from '~/components/Ruby.tsx';
@@ -32,18 +29,7 @@ export function PanelQMCv2Key() {
const handleSecretImport = async (file: File) => { const handleSecretImport = async (file: File) => {
try { try {
const fileBuffer = await file.arrayBuffer(); const keys = await importQMCv2KeysFromFile(file);
let keys: null | Omit<StagingQMCv2Key, 'id'>[] = null;
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
keys = extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
} else if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
const fileBuffer = await file.arrayBuffer();
const map = parseAndroidQmEKey(new DataView(fileBuffer));
keys = Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
}
if (keys && keys.length > 0) { if (keys && keys.length > 0) {
dispatch(qmc2ImportKeys(keys)); dispatch(qmc2ImportKeys(keys));
@@ -53,7 +39,7 @@ export function PanelQMCv2Key() {
toastImportResult(file.name, keys); toastImportResult(file.name, keys);
} catch (e) { } catch (e) {
console.error('error during import: ', e); console.error('error during import: ', e);
alert(`导入数据库时发生错误:${e}`); alert(`导入数据库时发生错误:${e as Error}`);
} }
}; };
@@ -1,4 +1,4 @@
import { qmc2DeleteKey, qmc2UpdateKey } from '../../settingsSlice'; import { qmc2DeleteKey, qmc2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks'; import { useAppDispatch } from '~/hooks';
import { memo } from 'react'; import { memo } from 'react';
import { KeyInput } from '~/components/KeyInput.tsx'; import { KeyInput } from '~/components/KeyInput.tsx';
+23
View File
@@ -0,0 +1,23 @@
import { nanoid } from 'nanoid';
/** QMCv2 staging key row (QQ Music / Douban FM). */
export interface StagingQMCv2Key {
id: string;
name: string;
ekey: string;
}
export type ProductionQMCv2Keys = Record<string /* filename */, string /* ekey */>;
export const qmc2StagingToProductionKey = (key: StagingQMCv2Key) => key.name.normalize();
export const qmc2StagingToProductionValue = (key: StagingQMCv2Key) => key.ekey.trim();
export const qmc2ProductionToStaging = (
key: keyof ProductionQMCv2Keys,
value: ProductionQMCv2Keys[keyof ProductionQMCv2Keys],
): StagingQMCv2Key => {
return {
id: nanoid(),
name: key.normalize(),
ekey: value.trim(),
};
};
@@ -0,0 +1,27 @@
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '../importKeys';
import { sanitizeQtfmAndroidKey } from '../types';
describe('qtfm import / sanitize', () => {
test('parseQtfmDeviceSecretFromText extracts DEVICE_SECRET line', () => {
const text = 'foo\nDEVICE_SECRET: aBcD1234\nbar';
expect(parseQtfmDeviceSecretFromText(text)).toBe('aBcD1234');
expect(parseQtfmDeviceSecretFromText('no secret here')).toBeNull();
});
test('parseQtfmDeviceInfoFromText requires all fields', () => {
const full = ['PRODUCT: p', 'DEVICE: d', 'MANUFACTURER: m', 'BRAND: b', 'BOARD: board', 'MODEL: model'].join('\n');
expect(parseQtfmDeviceInfoFromText(full)).toEqual({
product: 'p',
device: 'd',
manufacturer: 'm',
brand: 'b',
board: 'board',
model: 'model',
});
expect(parseQtfmDeviceInfoFromText('PRODUCT: p\nDEVICE: d')).toBeNull();
});
test('sanitizeQtfmAndroidKey strips non-hex', () => {
expect(sanitizeQtfmAndroidKey('de-ad_be ef!!')).toBe('deadbeef');
});
});
+26
View File
@@ -0,0 +1,26 @@
import type { GetQingTingFMDeviceKeyPayload } from '~/decrypt-worker/types.ts';
/**
* Extract a hex device secret from clipboard / dump text.
* Matches lines like `DEVICE_SECRET: deadbeef…` (from qtfm-device-id).
*/
export function parseQtfmDeviceSecretFromText(text: string): string | null {
const match = text.match(/^DEVICE_SECRET: ([0-9a-fA-F]+)/m);
return match?.[1] ?? null;
}
/**
* Extract build.prop-style device fields for worker-side key derivation.
* Returns null unless all required fields are present.
*/
export function parseQtfmDeviceInfoFromText(text: string): GetQingTingFMDeviceKeyPayload | null {
const dataMap = Object.create(null) as GetQingTingFMDeviceKeyPayload;
for (const [, key, value] of text.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) {
dataMap[key.toLowerCase() as keyof GetQingTingFMDeviceKeyPayload] = value;
}
const { product, device, manufacturer, brand, board, model } = dataMap;
if (product && device && manufacturer && brand && board && model) {
return dataMap;
}
return null;
}
@@ -0,0 +1,48 @@
import { VQuote } from '~/components/HelpText/VQuote';
import { HiWord } from '~/components/HelpText/HiWord';
import { Ruby } from '~/components/Ruby';
/** File-location / naming notes for QingTing FM Android downloads. */
export function QingTingNotes() {
return (
<>
<h3 className="text-xl font-bold my-2">注意事项</h3>
<ul className="list-disc pl-6">
<li>
<p>
下载的文件位于
<VQuote>
<code className="break-words">
<HiWord>[内部储存]</HiWord>/<wbr />
Android/
<wbr />
data/
<wbr />
fm.qingting.qtradio/
<wbr />
files/Music/
</code>
</VQuote>
</p>
<ul className="list-disc pl-6">
<li>
<p>
你可能需要使用有
<Ruby caption="root">特权</Ruby>
的文件浏览器访问。
</p>
</li>
</ul>
</li>
<li>
<p>
音频文件文件名为「<code>.p~!</code>」后缀。
</p>
</li>
<li>
<p>因为解密密钥与文件名相关,因此解密前请不要更改文件名。</p>
</li>
</ul>
</>
);
}
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more