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.
This commit is contained in:
鲁树人 committed 2026-11-01 02:42:13 +09:00
1 parent a9a937bc5e
commit 7a11d4f941
58 files changed
+522 -311

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx';
import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { RiErrorWarningLine } from 'react-icons/ri';
export function KugouFAQ() {
+1 -1
View File
@@ -2,7 +2,7 @@ import { Header2, Header3 } from '~/components/HelpText/Headers';
import { VQuote } from '~/components/HelpText/VQuote';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { HiWord } from '~/components/HelpText/HiWord';
import { KWMv2AllInstructions } from '~/features/settings/panels/KWMv2/KWMv2AllInstructions';
import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import { SegmentKeyImportInstructions } from './SegmentKeyImportInstructions';
import { RiErrorWarningLine } from 'react-icons/ri';
+1 -1
View File
@@ -1,6 +1,6 @@
import { Header2, Header3 } from '~/components/HelpText/Headers';
import { SegmentTryOfficialPlayer } from './SegmentTryOfficialPlayer';
import { QMCv2QQMusicAllInstructions } from '~/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions';
import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
export function QQMusicFAQ() {
return (
@@ -13,12 +13,10 @@ import type {
} from '~/decrypt-worker/types';
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
import {
selectKugouKey,
selectKWMv2Key,
selectQMCv2KeyByFileName,
selectQtfmAndroidKey,
} from '../settings/settingsSelector';
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
import { selectKugouKey } from '~/features/kugou/keyLookup';
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
import { cleanFilename } from '~/util/cleanFilename';
export enum ProcessState {
@@ -0,0 +1,34 @@
import { configureStore } from '@reduxjs/toolkit';
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
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(), { 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(), { audioHash: 'c'.repeat(32) } as never)).toBeUndefined();
expect(selectKugouKey(store.getState(), null)).toBeUndefined();
});
});
+15
View File
@@ -0,0 +1,15 @@
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou';
import type { StagingKugouKey } from './types';
/** Parse a Kugou MMKV / encrypted DB dump into staging key rows (without `id`). */
export async function importKugouKeysFromFile(file: File): Promise<null | Omit<StagingKugouKey, 'id'>[]> {
if (/mggkey_multi_process/i.test(file.name)) {
return parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
}
if (/^KGMusicV3\.db$/.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
return extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
}
return null;
}
+19
View File
@@ -0,0 +1,19 @@
import type { RootState } from '~/store';
import type { ParseKugouHeaderResponse } from '~/decrypt-worker/types.ts';
import { hasOwn } from '~/util/objects';
/** Staging KuGou/KGG keys (`state.settings.staging.kugou`; UI tab `kgg`). */
export const selectStagingKugouV5Keys = (state: RootState) => state.settings.staging.kugou.keys;
/** Production KuGou/KGG keys (`state.settings.production.kugou`; persist key `kugou`). */
export const selectFinalKugouV5Keys = (state: RootState) => state.settings.production.kugou.keys;
export const selectKugouKey = (state: RootState, hdr: ParseKugouHeaderResponse): string | undefined => {
if (!hdr) {
return;
}
const keys = selectFinalKugouV5Keys(state);
const lookupKey = hdr.audioHash;
return hasOwn(keys, lookupKey) ? keys[lookupKey] : undefined;
};
@@ -1,7 +1,7 @@
import { kugouDeleteKey, kugouUpdateKey } from '../../settingsSlice';
import { kugouDeleteKey, kugouUpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks';
import { memo } from 'react';
import { StagingKugouKey } from '../../keyFormats';
import type { StagingKugouKey } from '~/features/kugou/types';
import { KeyInput } from '~/components/KeyInput';
export const KugouEKeyItem = memo(({ id, ekey, audioHash, i }: StagingKugouKey & { i: number }) => {
@@ -2,15 +2,12 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '../settingsSlice';
import { selectStagingKugouV5Keys } from '../settingsSelector';
import type { StagingKugouKey } from '../keyFormats';
import { kugouAddKey, kugouClearKeys, kugouImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
import { AddKey } from '~/components/AddKey.tsx';
import { KugouEKeyItem } from '~/features/settings/panels/Kugou/KugouEKeyItem.tsx';
import { KugouAllInstructions } from '~/features/settings/panels/Kugou/KugouAllInstructions.tsx';
import { parseAndroidKugouMMKV } from '~/util/mmkv/kugou.ts';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor.ts';
import { KugouEKeyItem } from './KugouEKeyItem';
import { KugouAllInstructions } from '~/features/kugou/instructions/KugouAllInstructions';
import { importKugouKeysFromFile } from '~/features/kugou/importKeys';
import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult';
@@ -22,13 +19,7 @@ export function PanelKGGKey() {
const addKey = () => dispatch(kugouAddKey());
const clearAll = () => dispatch(kugouClearKeys());
const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKugouKey, 'id'>[] | null = null;
if (/mggkey_multi_process/i.test(file.name)) {
keys = parseAndroidKugouMMKV(new DataView(await file.arrayBuffer()));
} else if (/^KGMusicV3\.db$/.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
keys = extractor.extractKugouKeyFromEncryptedDb(await file.arrayBuffer());
}
const keys = await importKugouKeysFromFile(file);
if (keys && keys.length > 0) {
dispatch(kugouImportKeys(keys));
+22
View File
@@ -0,0 +1,22 @@
import { nanoid } from 'nanoid';
/**
* KuGou / KGG (kgm v5).
* UI settings tab route: `kgg`. Redux + localStorage production field: `kugou`.
*/
export interface StagingKugouKey {
id: string;
audioHash: string;
ekey: string;
}
export type ProductionKugouKey = Record<string /* audioHash */, string /* ekey */>;
export const kugouStagingToProductionKey = (key: StagingKugouKey) => key.audioHash.normalize();
export const kugouStagingToProductionValue = (key: StagingKugouKey) => key.ekey.normalize();
export const kugouProductionToStaging = (
key: keyof ProductionKugouKey,
value: ProductionKugouKey[keyof ProductionKugouKey],
): null | StagingKugouKey => {
if (typeof value !== 'string') return null;
return { id: nanoid(), audioHash: key.normalize(), ekey: value };
};
@@ -0,0 +1,32 @@
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { importKWMv2KeysFromFile } from '../importKeys';
const fixtureDir = join(dirname(fileURLToPath(import.meta.url)), '../../../util/mmkv/__tests__/__fixture__');
function fileFromFixture(name: string, path: string): File {
const buff = readFileSync(path);
return new File([buff], name);
}
describe('importKWMv2KeysFromFile', () => {
test('parses Android Kuwo MMKV by filename', async () => {
const file = fileFromFixture('cn.kuwo.player.mmkv.defaultconfig', join(fixtureDir, 'kuwo_android.mmkv'));
await expect(importKWMv2KeysFromFile(file)).resolves.toEqual([
{ rid: '1234567', quality: '20201kmflac', ekey: 'xyz123' },
]);
});
test('parses iOS Kuwo ekey dump by filename', async () => {
const file = fileFromFixture('kw_ekey', join(fixtureDir, 'kuwo_ios.mmkv'));
await expect(importKWMv2KeysFromFile(file)).resolves.toEqual([
{ rid: '1234567', quality: '20201', ekey: 'xyz123' },
]);
});
test('returns null for unrecognized filenames', async () => {
await expect(importKWMv2KeysFromFile(new File([], 'notes.txt'))).resolves.toBeNull();
});
});
+13
View File
@@ -0,0 +1,13 @@
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo';
import type { StagingKWMv2Key } from './types';
/** Parse a Kuwo MMKV / iOS ekey dump into staging key rows (without `id`). */
export async function importKWMv2KeysFromFile(file: File): Promise<null | Omit<StagingKWMv2Key, 'id'>[]> {
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
return parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
}
if (/kw_ekey/.test(file.name)) {
return parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
}
return null;
}
+26
View File
@@ -0,0 +1,26 @@
import type { RootState } from '~/store';
import type { ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
import { hasOwn } from '~/util/objects';
import { kwm2StagingToProductionKey } from './types';
export const selectStagingKWMv2Keys = (state: RootState) => state.settings.staging.kwm2.keys;
export const selectFinalKWMv2Keys = (state: RootState) => state.settings.production.kwm2.keys;
export const selectKWMv2Key = (state: RootState, hdr: ParseKuwoHeaderResponse): string | undefined => {
if (!hdr) {
return;
}
const quality = String(hdr.qualityId);
const rid = String(hdr.resourceId);
const keys = selectFinalKWMv2Keys(state);
const lookupKey = kwm2StagingToProductionKey({ id: '', ekey: '', quality, rid });
let ekey: string | undefined;
if (hasOwn(keys, lookupKey)) {
ekey = keys[lookupKey];
}
return ekey;
};
@@ -1,8 +1,8 @@
import { PiFileAudio, PiHash } from 'react-icons/pi';
import { kwm2DeleteKey, kwm2UpdateKey } from '../../settingsSlice';
import { kwm2DeleteKey, kwm2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks';
import { memo } from 'react';
import { StagingKWMv2Key } from '../../keyFormats';
import type { StagingKWMv2Key } from '~/features/kwm/types';
import { KeyInput } from '~/components/KeyInput';
export const KWMv2EKeyItem = memo(({ id, ekey, quality, rid, i }: StagingKWMv2Key & { i: number }) => {
@@ -2,13 +2,11 @@ import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ImportSecretModal } from '~/components/ImportSecretModal';
import { parseAndroidKuwoEKey, parseIosKuwoEKey } from '~/util/mmkv/kuwo';
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '../settingsSlice';
import { selectStagingKWMv2Keys } from '../settingsSelector';
import { KWMv2EKeyItem } from './KWMv2/KWMv2EKeyItem';
import type { StagingKWMv2Key } from '../keyFormats';
import { KWMv2AllInstructions } from './KWMv2/KWMv2AllInstructions';
import { kwm2AddKey, kwm2ClearKeys, kwm2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
import { KWMv2EKeyItem } from './KWMv2EKeyItem';
import { importKWMv2KeysFromFile } from '~/features/kwm/importKeys';
import { KWMv2AllInstructions } from '~/features/kwm/instructions/KWMv2AllInstructions';
import { AddKey } from '~/components/AddKey';
import { KeyListContainer } from '~/components/KeyListContainer';
import { toastImportResult } from '~/util/toastImportResult';
@@ -21,12 +19,7 @@ export function PanelKWMv2Key() {
const addKey = () => dispatch(kwm2AddKey());
const clearAll = () => dispatch(kwm2ClearKeys());
const handleSecretImport = async (file: File) => {
let keys: Omit<StagingKWMv2Key, 'id'>[] | null = null;
if (/cn\.kuwo\.player\.mmkv/i.test(file.name)) {
keys = parseAndroidKuwoEKey(new DataView(await file.arrayBuffer()));
} else if (/kw_ekey/.test(file.name)) {
keys = parseIosKuwoEKey(new DataView(await file.arrayBuffer()));
}
const keys = await importKWMv2KeysFromFile(file);
if (keys && keys.length > 0) {
dispatch(kwm2ImportKeys(keys));
+39
View File
@@ -0,0 +1,39 @@
import { nanoid } from 'nanoid';
/** KWMv2 staging key row (Kuwo). */
export interface StagingKWMv2Key {
id: string;
/**
* Resource ID
*/
rid: string;
/**
* Quality String
*/
quality: string;
ekey: string;
}
export type ProductionKWMv2Keys = Record<string /* `${rid}-${quality}` */, string /* ekey */>;
export const parseKwm2ProductionKey = (key: string): null | { rid: string; quality: string } => {
const m = key.match(/^(\d+)-(\w+)$/);
if (!m) return null;
const [_, rid, quality] = m;
return { rid, quality };
};
export const kwm2StagingToProductionKey = (key: StagingKWMv2Key) => `${key.rid}-${key.quality.replace(/\D/g, '')}`;
export const kwm2StagingToProductionValue = (key: StagingKWMv2Key) => key.ekey;
export const kwm2ProductionToStaging = (
key: keyof ProductionKWMv2Keys,
value: ProductionKWMv2Keys[keyof ProductionKWMv2Keys],
): null | StagingKWMv2Key => {
if (typeof value !== 'string') return null;
const parsed = parseKwm2ProductionKey(key);
if (!parsed) return null;
const { quality, rid } = parsed;
return { id: nanoid(), rid, quality, ekey: value };
};
@@ -0,0 +1,37 @@
import { configureStore } from '@reduxjs/toolkit';
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
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(), '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(), '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(), 'other.mflac')).toBeUndefined();
});
});
+21
View File
@@ -0,0 +1,21 @@
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
import { parseAndroidQmEKey } from '~/util/mmkv/qm';
import { getFileName } from '~/util/pathHelper';
import type { StagingQMCv2Key } from './types';
/** Parse a QMCv2 key database / MMKV dump into staging key rows (without `id`). */
export async function importQMCv2KeysFromFile(file: File): Promise<null | Omit<StagingQMCv2Key, 'id'>[]> {
const fileBuffer = await file.arrayBuffer();
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
return extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
}
if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
const map = parseAndroidQmEKey(new DataView(fileBuffer));
return Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
}
return null;
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

+25
View File
@@ -0,0 +1,25 @@
import type { RootState } from '~/store';
import { closestByLevenshtein } from '~/util/levenshtein';
import { hasOwn } from '~/util/objects';
export const selectStagingQMCv2Settings = (state: RootState) => state.settings.staging.qmc2;
export const selectFinalQMCv2Settings = (state: RootState) => state.settings.production.qmc2;
export const selectQMCv2KeyByFileName = (state: RootState, name: string): string | undefined => {
const normalizedName = name.normalize();
let ekey: string | undefined;
const { keys, allowFuzzyNameSearch } = selectFinalQMCv2Settings(state);
if (hasOwn(keys, normalizedName)) {
ekey = keys[normalizedName];
} else if (allowFuzzyNameSearch) {
const qmc2KeyStoreNames = Object.keys(keys);
if (qmc2KeyStoreNames.length > 0) {
const closestName = closestByLevenshtein(normalizedName, qmc2KeyStoreNames);
console.debug('qmc2: key db could not find %o, using closest %o instead.', normalizedName, closestName);
ekey = keys[closestName];
}
}
return ekey;
};
@@ -1,15 +1,12 @@
import { useDispatch, useSelector } from 'react-redux';
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '../settingsSlice';
import { selectStagingQMCv2Settings } from '../settingsSelector';
import { qmc2AddKey, qmc2AllowFuzzyNameSearch, qmc2ClearKeys, qmc2ImportKeys } from '~/features/settings/settingsSlice';
import { selectStagingQMCv2Settings } from '~/features/qmc/keyLookup';
import React, { useRef, useState } from 'react';
import { QMCv2EKeyItem } from './QMCv2/QMCv2EKeyItem';
import { QMCv2EKeyItem } from './QMCv2EKeyItem';
import { ImportSecretModal } from '~/components/ImportSecretModal';
import { StagingQMCv2Key } from '../keyFormats';
import { DatabaseKeyExtractor } from '~/util/DatabaseKeyExtractor';
import { parseAndroidQmEKey } from '~/util/mmkv/qm';
import { getFileName } from '~/util/pathHelper';
import { QMCv2QQMusicAllInstructions } from './QMCv2/QMCv2QQMusicAllInstructions';
import { QMCv2DoubanAllInstructions } from './QMCv2/QMCv2DoubanAllInstructions';
import { importQMCv2KeysFromFile } from '~/features/qmc/importKeys';
import { QMCv2QQMusicAllInstructions } from '~/features/qmc/instructions/QMCv2QQMusicAllInstructions';
import { QMCv2DoubanAllInstructions } from '~/features/qmc/instructions/QMCv2DoubanAllInstructions';
import { AddKey } from '~/components/AddKey';
import { InfoModal } from '~/components/InfoModal.tsx';
import { Ruby } from '~/components/Ruby.tsx';
@@ -32,18 +29,7 @@ export function PanelQMCv2Key() {
const handleSecretImport = async (file: File) => {
try {
const fileBuffer = await file.arrayBuffer();
let keys: null | Omit<StagingQMCv2Key, 'id'>[] = null;
if (/(player_process[_.]db|music_audio_play)(\.db)?$/i.test(file.name)) {
const extractor = await DatabaseKeyExtractor.getInstance();
keys = extractor.extractQmcV2KeysFromSqliteDb(fileBuffer);
} else if (/MMKVStreamEncryptId|filenameEkeyMap|qmpc-mmkv-v1|(\.mmkv$)/i.test(file.name)) {
const fileBuffer = await file.arrayBuffer();
const map = parseAndroidQmEKey(new DataView(fileBuffer));
keys = Array.from(map.entries(), ([name, ekey]) => ({ name: getFileName(name), ekey }));
}
const keys = await importQMCv2KeysFromFile(file);
if (keys && keys.length > 0) {
dispatch(qmc2ImportKeys(keys));
@@ -1,4 +1,4 @@
import { qmc2DeleteKey, qmc2UpdateKey } from '../../settingsSlice';
import { qmc2DeleteKey, qmc2UpdateKey } from '~/features/settings/settingsSlice';
import { useAppDispatch } from '~/hooks';
import { memo } from 'react';
import { KeyInput } from '~/components/KeyInput.tsx';
+23
View File
@@ -0,0 +1,23 @@
import { nanoid } from 'nanoid';
/** QMCv2 staging key row (QQ Music / Douban FM). */
export interface StagingQMCv2Key {
id: string;
name: string;
ekey: string;
}
export type ProductionQMCv2Keys = Record<string /* filename */, string /* ekey */>;
export const qmc2StagingToProductionKey = (key: StagingQMCv2Key) => key.name.normalize();
export const qmc2StagingToProductionValue = (key: StagingQMCv2Key) => key.ekey.trim();
export const qmc2ProductionToStaging = (
key: keyof ProductionQMCv2Keys,
value: ProductionQMCv2Keys[keyof ProductionQMCv2Keys],
): StagingQMCv2Key => {
return {
id: nanoid(),
name: key.normalize(),
ekey: value.trim(),
};
};
@@ -0,0 +1,27 @@
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '../importKeys';
import { sanitizeQtfmAndroidKey } from '../types';
describe('qtfm import / sanitize', () => {
test('parseQtfmDeviceSecretFromText extracts DEVICE_SECRET line', () => {
const text = 'foo\nDEVICE_SECRET: aBcD1234\nbar';
expect(parseQtfmDeviceSecretFromText(text)).toBe('aBcD1234');
expect(parseQtfmDeviceSecretFromText('no secret here')).toBeNull();
});
test('parseQtfmDeviceInfoFromText requires all fields', () => {
const full = ['PRODUCT: p', 'DEVICE: d', 'MANUFACTURER: m', 'BRAND: b', 'BOARD: board', 'MODEL: model'].join('\n');
expect(parseQtfmDeviceInfoFromText(full)).toEqual({
product: 'p',
device: 'd',
manufacturer: 'm',
brand: 'b',
board: 'board',
model: 'model',
});
expect(parseQtfmDeviceInfoFromText('PRODUCT: p\nDEVICE: d')).toBeNull();
});
test('sanitizeQtfmAndroidKey strips non-hex', () => {
expect(sanitizeQtfmAndroidKey('de-ad_be ef!!')).toBe('deadbeef');
});
});
+26
View File
@@ -0,0 +1,26 @@
import type { GetQingTingFMDeviceKeyPayload } from '~/decrypt-worker/types.ts';
/**
* Extract a hex device secret from clipboard / dump text.
* Matches lines like `DEVICE_SECRET: deadbeef…` (from qtfm-device-id).
*/
export function parseQtfmDeviceSecretFromText(text: string): string | null {
const match = text.match(/^DEVICE_SECRET: ([0-9a-fA-F]+)/m);
return match?.[1] ?? null;
}
/**
* Extract build.prop-style device fields for worker-side key derivation.
* Returns null unless all required fields are present.
*/
export function parseQtfmDeviceInfoFromText(text: string): GetQingTingFMDeviceKeyPayload | null {
const dataMap = Object.create(null) as GetQingTingFMDeviceKeyPayload;
for (const [, key, value] of text.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) {
dataMap[key.toLowerCase() as keyof GetQingTingFMDeviceKeyPayload] = value;
}
const { product, device, manufacturer, brand, board, model } = dataMap;
if (product && device && manufacturer && brand && board && model) {
return dataMap;
}
return null;
}
@@ -0,0 +1,48 @@
import { VQuote } from '~/components/HelpText/VQuote';
import { HiWord } from '~/components/HelpText/HiWord';
import { Ruby } from '~/components/Ruby';
/** File-location / naming notes for QingTing FM Android downloads. */
export function QingTingNotes() {
return (
<>
<h3 className="text-xl font-bold my-2">注意事项</h3>
<ul className="list-disc pl-6">
<li>
<p>
下载的文件位于
<VQuote>
<code className="break-words">
<HiWord>[内部储存]</HiWord>/<wbr />
Android/
<wbr />
data/
<wbr />
fm.qingting.qtradio/
<wbr />
files/Music/
</code>
</VQuote>
</p>
<ul className="list-disc pl-6">
<li>
<p>
你可能需要使用有
<Ruby caption="root">特权</Ruby>
的文件浏览器访问。
</p>
</li>
</ul>
</li>
<li>
<p>
音频文件文件名为「<code>.p~!</code>」后缀。
</p>
</li>
<li>
<p>因为解密密钥与文件名相关,因此解密前请不要更改文件名。</p>
</li>
</ul>
</>
);
}
+4
View File
@@ -0,0 +1,4 @@
import type { RootState } from '~/store';
export const selectStagingQtfmAndroidKey = (state: RootState) => state.settings.staging.qtfm.android;
export const selectQtfmAndroidKey = (state: RootState) => state.settings.production.qtfm.android;
@@ -2,13 +2,13 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
import { ExtLink } from '~/components/ExtLink';
import { ChangeEvent, ClipboardEvent, useId } from 'react';
import { VQuote } from '~/components/HelpText/VQuote';
import { selectStagingQtfmAndroidKey } from '../settingsSelector';
import { qtfmAndroidUpdateKey } from '../settingsSlice';
import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
import { workerClientBus } from '~/decrypt-worker/client.ts';
import { GetQingTingFMDeviceKeyPayload } from '~/decrypt-worker/types.ts';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
import { Ruby } from '~/components/Ruby';
import { HiWord } from '~/components/HelpText/HiWord';
import { toast } from 'react-toastify';
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
@@ -22,26 +22,21 @@ export function PanelQingTing() {
const handleDataPaste = (e: ClipboardEvent<HTMLInputElement>) => {
const plainText = e.clipboardData.getData('text/plain');
const matchDeviceSecret = plainText.match(/^DEVICE_SECRET: ([0-9a-fA-F]+)/m);
if (matchDeviceSecret) {
const deviceSecret = parseQtfmDeviceSecretFromText(plainText);
if (deviceSecret) {
e.preventDefault();
setSecretKey(matchDeviceSecret[1]);
setSecretKey(deviceSecret);
return;
}
const dataMap = Object.create(null) as GetQingTingFMDeviceKeyPayload;
for (const [, key, value] of plainText.matchAll(/^(PRODUCT|DEVICE|MANUFACTURER|BRAND|BOARD|MODEL): (.+)/gim)) {
dataMap[key.toLowerCase() as keyof GetQingTingFMDeviceKeyPayload] = value;
}
const { product, device, manufacturer, brand, board, model } = dataMap;
if (product && device && manufacturer && brand && board && model) {
const dataMap = parseQtfmDeviceInfoFromText(plainText);
if (dataMap) {
e.preventDefault();
workerClientBus
.request<
string,
GetQingTingFMDeviceKeyPayload
>(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
.request<string, GetQingTingFMDeviceKeyPayload>(
DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY,
dataMap,
)
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
}
};
@@ -83,43 +78,7 @@ export function PanelQingTing() {
</fieldset>
</div>
<h3 className="text-xl font-bold my-2">注意事项</h3>
<ul className="list-disc pl-6">
<li>
<p>
下载的文件位于
<VQuote>
<code className="break-words">
<HiWord>[内部储存]</HiWord>/<wbr />
Android/
<wbr />
data/
<wbr />
fm.qingting.qtradio/
<wbr />
files/Music/
</code>
</VQuote>
</p>
<ul className="list-disc pl-6">
<li>
<p>
你可能需要使用有
<Ruby caption="root">特权</Ruby>
的文件浏览器访问。
</p>
</li>
</ul>
</li>
<li>
<p>
音频文件文件名为「<code>.p~!</code>」前缀。
</p>
</li>
<li>
<p>因为解密密钥与文件名相关,因此解密前请不要更改文件名。</p>
</li>
</ul>
<QingTingNotes />
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
/** QingTing FM staging settings (`state.settings.staging.qtfm`). */
export interface StagingQtfmSettings {
/** Android device key (hex). */
android: string;
}
/** QingTing FM production settings (`state.settings.production.qtfm`; persist key `qtfm`). */
export type ProductionQtfmSettings = StagingQtfmSettings;
export const EMPTY_QTFM_SETTINGS: StagingQtfmSettings = { android: '' };
/** Strip non-hex characters from a pasted / typed device key. */
export function sanitizeQtfmAndroidKey(key: string): string {
return key.replace(/[^0-9a-fA-F]/g, '');
}
@@ -13,14 +13,13 @@ import {
type StagingSettings,
} from '../settingsSlice';
import { mergeSettings } from '../persistSettings';
import { productionKeyToStaging, stagingKeyToProduction } from '../keyFormats';
import {
kwm2StagingToProductionKey,
productionKeyToStaging,
qmc2ProductionToStaging,
qmc2StagingToProductionKey,
qmc2StagingToProductionValue,
stagingKeyToProduction,
} from '../keyFormats';
} from '~/features/qmc/types';
import { kwm2StagingToProductionKey } from '~/features/kwm/types';
function createSettingsStore(preloaded?: ReturnType<typeof settingsSlice.getInitialState>) {
return configureStore({
@@ -1,7 +1,9 @@
import type { PayloadAction, WritableDraft } from '@reduxjs/toolkit';
import { nanoid } from 'nanoid';
import type { StagingKWMv2Key, StagingKugouKey, StagingQMCv2Key } from './keyFormats';
import type { StagingQMCv2Key } from '~/features/qmc/types';
import type { StagingKWMv2Key } from '~/features/kwm/types';
import type { StagingKugouKey } from '~/features/kugou/types';
/** Formats that store keys as a staging list (array with stable `id`). */
export type KeyListFormat = 'qmc2' | 'kwm2' | 'kugou';
+1 -82
View File
@@ -1,6 +1,6 @@
import { nanoid } from 'nanoid';
import { objectify } from 'radash';
/** Generic map↔list helpers shared by format feature types. */
export function productionKeyToStaging<S, P extends Record<string, unknown>>(
src: P,
make: (k: keyof P, v: P[keyof P]) => null | S,
@@ -18,84 +18,3 @@ export function productionKeyToStaging<S, P extends Record<string, unknown>>(
export function stagingKeyToProduction<S, P>(src: S[], toKey: (s: S) => keyof P, toValue: (s: S) => P[keyof P]): P {
return objectify(src, toKey, toValue) as P;
}
// QMCv2 (QQ)
export interface StagingQMCv2Key {
id: string;
name: string;
ekey: string;
}
export type ProductionQMCv2Keys = Record<string /* filename */, string /* ekey */>;
export const qmc2StagingToProductionKey = (key: StagingQMCv2Key) => key.name.normalize();
export const qmc2StagingToProductionValue = (key: StagingQMCv2Key) => key.ekey.trim();
export const qmc2ProductionToStaging = (
key: keyof ProductionQMCv2Keys,
value: ProductionQMCv2Keys[keyof ProductionQMCv2Keys],
): StagingQMCv2Key => {
return {
id: nanoid(),
name: key.normalize(),
ekey: value.trim(),
};
};
// KWMv2 (KuWo)
export interface StagingKWMv2Key {
id: string;
/**
* Resource ID
*/
rid: string;
/**
* Quality String
*/
quality: string;
ekey: string;
}
export type ProductionKWMv2Keys = Record<string /* `${rid}-${quality}` */, string /* ekey */>;
export const parseKwm2ProductionKey = (key: string): null | { rid: string; quality: string } => {
const m = key.match(/^(\d+)-(\w+)$/);
if (!m) return null;
const [_, rid, quality] = m;
return { rid, quality };
};
export const kwm2StagingToProductionKey = (key: StagingKWMv2Key) => `${key.rid}-${key.quality.replace(/\D/g, '')}`;
export const kwm2StagingToProductionValue = (key: StagingKWMv2Key) => key.ekey;
export const kwm2ProductionToStaging = (
key: keyof ProductionKWMv2Keys,
value: ProductionKWMv2Keys[keyof ProductionKWMv2Keys],
): null | StagingKWMv2Key => {
if (typeof value !== 'string') return null;
const parsed = parseKwm2ProductionKey(key);
if (!parsed) return null;
const { quality, rid } = parsed;
return { id: nanoid(), rid, quality, ekey: value };
};
/**
* KuGou / KGG (kgm v5).
* 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 };
};
@@ -1 +0,0 @@
// TODO: Popup dialog for QingTing instructions
+3 -2
View File
@@ -10,7 +10,8 @@ import {
} from './settingsSlice';
import { enumObject } from '~/util/objects';
import { getLogger } from '~/util/logUtils';
import { parseKwm2ProductionKey } from './keyFormats';
import { parseKwm2ProductionKey } from '~/features/kwm/types';
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
import { deepClone } from '~/util/deepClone';
const DEFAULT_STORAGE_KEY = 'um-react-settings';
@@ -68,7 +69,7 @@ export function mergeSettings(settings: ProductionSettings): ProductionSettings
}
if (typeof settings?.qtfm?.android === 'string') {
draft.qtfm.android = settings.qtfm.android.replace(/[^0-9a-fA-F]/g, '');
draft.qtfm.android = sanitizeQtfmAndroidKey(settings.qtfm.android);
}
return draft;
+10 -67
View File
@@ -1,73 +1,16 @@
import type { RootState } from '~/store';
import { closestByLevenshtein } from '~/util/levenshtein';
import { hasOwn } from '~/util/objects';
import { kwm2StagingToProductionKey } from './keyFormats';
import type { ParseKugouHeaderResponse, ParseKuwoHeaderResponse } from '~/decrypt-worker/types.ts';
/** Re-exports format key lookups so callers can keep a single settings import if desired. */
export {
selectFinalQMCv2Settings,
selectQMCv2KeyByFileName,
selectStagingQMCv2Settings,
} from '~/features/qmc/keyLookup';
export { selectFinalKWMv2Keys, selectKWMv2Key, selectStagingKWMv2Keys } from '~/features/kwm/keyLookup';
export { selectFinalKugouV5Keys, selectKugouKey, selectStagingKugouV5Keys } from '~/features/kugou/keyLookup';
export { selectQtfmAndroidKey, selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
export const selectIsSettingsNotSaved = (state: RootState) => state.settings.dirty;
export const selectStagingQMCv2Settings = (state: RootState) => state.settings.staging.qmc2;
export const selectFinalQMCv2Settings = (state: RootState) => state.settings.production.qmc2;
export const selectStagingKWMv2Keys = (state: RootState) => state.settings.staging.kwm2.keys;
export const selectFinalKWMv2Keys = (state: RootState) => state.settings.production.kwm2.keys;
/** 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 selectQMCv2KeyByFileName = (state: RootState, name: string): string | undefined => {
const normalizedName = name.normalize();
let ekey: string | undefined;
const { keys, allowFuzzyNameSearch } = selectFinalQMCv2Settings(state);
if (hasOwn(keys, normalizedName)) {
ekey = keys[normalizedName];
} else if (allowFuzzyNameSearch) {
const qmc2KeyStoreNames = Object.keys(keys);
if (qmc2KeyStoreNames.length > 0) {
const closestName = closestByLevenshtein(normalizedName, qmc2KeyStoreNames);
console.debug('qmc2: key db could not find %o, using closest %o instead.', normalizedName, closestName);
ekey = keys[closestName];
}
}
return ekey;
};
export const selectKWMv2Key = (state: RootState, hdr: ParseKuwoHeaderResponse): string | undefined => {
if (!hdr) {
return;
}
const quality = String(hdr.qualityId);
const rid = String(hdr.resourceId);
const keys = selectFinalKWMv2Keys(state);
const lookupKey = kwm2StagingToProductionKey({ id: '', ekey: '', quality, rid });
let ekey: string | undefined;
if (hasOwn(keys, lookupKey)) {
ekey = keys[lookupKey];
}
return ekey;
};
export const selectKugouKey = (state: RootState, hdr: ParseKugouHeaderResponse): string | undefined => {
if (!hdr) {
return;
}
const keys = selectFinalKugouV5Keys(state);
const lookupKey = hdr.audioHash;
return hasOwn(keys, lookupKey) ? keys[lookupKey] : undefined;
};
export const selectStagingQtfmAndroidKey = (state: RootState) => state.settings.staging.qtfm.android;
export const selectQtfmAndroidKey = (state: RootState) => state.settings.production.qtfm.android;
export const selectStagingBatchDownloadSettings = (state: RootState) => state.settings.staging.general.batchDownload;
export const selectFinalBatchDownloadSettings = (state: RootState) => state.settings.production.general.batchDownload;
+20 -20
View File
@@ -1,24 +1,28 @@
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import {
ProductionKWMv2Keys,
ProductionQMCv2Keys,
StagingKWMv2Key,
StagingQMCv2Key,
kwm2ProductionToStaging,
kwm2StagingToProductionKey,
kwm2StagingToProductionValue,
productionKeyToStaging,
type ProductionQMCv2Keys,
type StagingQMCv2Key,
qmc2ProductionToStaging,
qmc2StagingToProductionKey,
qmc2StagingToProductionValue,
stagingKeyToProduction,
ProductionKugouKey,
} from '~/features/qmc/types';
import {
type ProductionKWMv2Keys,
type StagingKWMv2Key,
kwm2ProductionToStaging,
kwm2StagingToProductionKey,
kwm2StagingToProductionValue,
} from '~/features/kwm/types';
import {
type ProductionKugouKey,
type StagingKugouKey,
kugouProductionToStaging,
kugouStagingToProductionKey,
kugouStagingToProductionValue,
StagingKugouKey,
} from './keyFormats';
} from '~/features/kugou/types';
import { EMPTY_QTFM_SETTINGS, type ProductionQtfmSettings, type StagingQtfmSettings } from '~/features/qtfm/types';
import { productionKeyToStaging, stagingKeyToProduction } from './keyFormats';
import { createKeyListReducers } from './createKeyListReducers';
export interface BatchDownloadSettings {
@@ -46,9 +50,7 @@ export interface StagingSettings {
kugou: {
keys: StagingKugouKey[];
};
qtfm: {
android: string;
};
qtfm: StagingQtfmSettings;
}
export interface ProductionSettings {
@@ -69,9 +71,7 @@ export interface ProductionSettings {
kugou: {
keys: ProductionKugouKey; // { [fileName]: ekey }
};
qtfm: {
android: string;
};
qtfm: ProductionQtfmSettings;
}
export const DEFAULT_BATCH_DOWNLOAD_SETTINGS: BatchDownloadSettings = {
@@ -93,7 +93,7 @@ const initialState: SettingsState = {
general: { batchDownload: { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS } },
qmc2: { allowFuzzyNameSearch: true, keys: [] },
kwm2: { keys: [] },
qtfm: { android: '' },
qtfm: { ...EMPTY_QTFM_SETTINGS },
kugou: { keys: [] },
},
production: {
@@ -101,7 +101,7 @@ const initialState: SettingsState = {
qmc2: { allowFuzzyNameSearch: true, keys: {} },
kwm2: { keys: {} },
kugou: { keys: {} },
qtfm: { android: '' },
qtfm: { ...EMPTY_QTFM_SETTINGS },
},
};
+5 -5
View File
@@ -1,9 +1,9 @@
import type { FC } from 'react';
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
import { PanelQMCv2Key } from '~/features/settings/panels/PanelQMCv2Key.tsx';
import { PanelKWMv2Key } from '~/features/settings/panels/PanelKWMv2Key.tsx';
import { PanelKGGKey } from '~/features/settings/panels/PanelKGGKey.tsx';
import { PanelQingTing } from '~/features/settings/panels/PanelQingTing.tsx';
import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
/**
* Settings UI route ids → panels.
@@ -11,7 +11,7 @@ import { PanelQingTing } from '~/features/settings/panels/PanelQingTing.tsx';
* Naming aliases (route vs Redux / persist):
* - `qmc` ↔ state `qmc2`
* - `kwm` ↔ state `kwm2`
* - `kgg` ↔ state `kugou` (persist key stays `kugou`; Phase 2 may align paths)
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
* - `qtfm` ↔ state `qtfm`
*/
export const SETTINGS_TABS: Record<string, { name: string; Tab: FC }> = {
+4 -9
View File
@@ -1,16 +1,11 @@
import { getFileName } from './pathHelper';
import { SQLDatabase, SQLStatic, loadSQL } from './sqlite';
import { KuGou } from '@unlock-music/crypto';
import type { StagingQMCv2Key } from '~/features/qmc/types';
import type { StagingKugouKey } from '~/features/kugou/types';
export interface QMAndroidKeyEntry {
name: string;
ekey: string;
}
export type KugouKeyEntry = {
audioHash: string;
ekey: string;
};
export type QMAndroidKeyEntry = Omit<StagingQMCv2Key, 'id'>;
export type KugouKeyEntry = Omit<StagingKugouKey, 'id'>;
export class DatabaseKeyExtractor {
private static _instance: DatabaseKeyExtractor;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StagingKugouKey } from '~/features/settings/keyFormats';
import type { StagingKugouKey } from '~/features/kugou/types';
import { MMKVParser } from '../MMKVParser';
export function parseAndroidKugouMMKV(view: DataView<ArrayBuffer>): Omit<StagingKugouKey, 'id'>[] {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StagingKWMv2Key } from '~/features/settings/keyFormats';
import type { StagingKWMv2Key } from '~/features/kwm/types';
import { MMKVParser } from '../MMKVParser';
export function parseAndroidKuwoEKey(view: DataView<ArrayBuffer>): Omit<StagingKWMv2Key, 'id'>[] {