diff --git a/src/faq/KugouFAQ.tsx b/src/faq/KugouFAQ.tsx index 6c55edc..b98aa88 100644 --- a/src/faq/KugouFAQ.tsx +++ b/src/faq/KugouFAQ.tsx @@ -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() { diff --git a/src/faq/KuwoFAQ.tsx b/src/faq/KuwoFAQ.tsx index 2d26a12..86abea3 100644 --- a/src/faq/KuwoFAQ.tsx +++ b/src/faq/KuwoFAQ.tsx @@ -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'; diff --git a/src/faq/QQMusicFAQ.tsx b/src/faq/QQMusicFAQ.tsx index 08e93ae..6025107 100644 --- a/src/faq/QQMusicFAQ.tsx +++ b/src/faq/QQMusicFAQ.tsx @@ -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 ( diff --git a/src/features/file-listing/fileListingSlice.ts b/src/features/file-listing/fileListingSlice.ts index 17e43cb..1652880 100644 --- a/src/features/file-listing/fileListingSlice.ts +++ b/src/features/file-listing/fileListingSlice.ts @@ -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 { diff --git a/src/features/kugou/__tests__/keyLookup.test.ts b/src/features/kugou/__tests__/keyLookup.test.ts new file mode 100644 index 0000000..a01058a --- /dev/null +++ b/src/features/kugou/__tests__/keyLookup.test.ts @@ -0,0 +1,34 @@ +import { configureStore } from '@reduxjs/toolkit'; + +import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice'; +import { selectKugouKey } from '../keyLookup'; + +function storeWithKugouKeys(keys: Record) { + 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(); + }); +}); diff --git a/src/features/kugou/importKeys.ts b/src/features/kugou/importKeys.ts new file mode 100644 index 0000000..e4feb8f --- /dev/null +++ b/src/features/kugou/importKeys.ts @@ -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[]> { + 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; +} diff --git a/src/features/settings/panels/Kugou/InstructionsPC.tsx b/src/features/kugou/instructions/InstructionsPC.tsx similarity index 100% rename from src/features/settings/panels/Kugou/InstructionsPC.tsx rename to src/features/kugou/instructions/InstructionsPC.tsx diff --git a/src/features/settings/panels/Kugou/KugouAllInstructions.tsx b/src/features/kugou/instructions/KugouAllInstructions.tsx similarity index 100% rename from src/features/settings/panels/Kugou/KugouAllInstructions.tsx rename to src/features/kugou/instructions/KugouAllInstructions.tsx diff --git a/src/features/kugou/keyLookup.ts b/src/features/kugou/keyLookup.ts new file mode 100644 index 0000000..2d87a64 --- /dev/null +++ b/src/features/kugou/keyLookup.ts @@ -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; +}; diff --git a/src/features/settings/panels/Kugou/KugouEKeyItem.tsx b/src/features/kugou/panel/KugouEKeyItem.tsx similarity index 85% rename from src/features/settings/panels/Kugou/KugouEKeyItem.tsx rename to src/features/kugou/panel/KugouEKeyItem.tsx index a9e13b5..fdcf6d1 100644 --- a/src/features/settings/panels/Kugou/KugouEKeyItem.tsx +++ b/src/features/kugou/panel/KugouEKeyItem.tsx @@ -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 }) => { diff --git a/src/features/settings/panels/PanelKGGKey.tsx b/src/features/kugou/panel/PanelKGGKey.tsx similarity index 67% rename from src/features/settings/panels/PanelKGGKey.tsx rename to src/features/kugou/panel/PanelKGGKey.tsx index 56f75b1..04820ab 100644 --- a/src/features/settings/panels/PanelKGGKey.tsx +++ b/src/features/kugou/panel/PanelKGGKey.tsx @@ -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[] | 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)); diff --git a/src/features/kugou/types.ts b/src/features/kugou/types.ts new file mode 100644 index 0000000..94128f2 --- /dev/null +++ b/src/features/kugou/types.ts @@ -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; +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 }; +}; diff --git a/src/features/kwm/__tests__/importKeys.test.ts b/src/features/kwm/__tests__/importKeys.test.ts new file mode 100644 index 0000000..669e8e0 --- /dev/null +++ b/src/features/kwm/__tests__/importKeys.test.ts @@ -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(); + }); +}); diff --git a/src/features/kwm/importKeys.ts b/src/features/kwm/importKeys.ts new file mode 100644 index 0000000..125cda6 --- /dev/null +++ b/src/features/kwm/importKeys.ts @@ -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[]> { + 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; +} diff --git a/src/features/settings/panels/KWMv2/InstructionsIOS.tsx b/src/features/kwm/instructions/InstructionsIOS.tsx similarity index 100% rename from src/features/settings/panels/KWMv2/InstructionsIOS.tsx rename to src/features/kwm/instructions/InstructionsIOS.tsx diff --git a/src/features/settings/panels/KWMv2/InstructionsPC.tsx b/src/features/kwm/instructions/InstructionsPC.tsx similarity index 100% rename from src/features/settings/panels/KWMv2/InstructionsPC.tsx rename to src/features/kwm/instructions/InstructionsPC.tsx diff --git a/src/features/settings/panels/KWMv2/KWMv2AllInstructions.tsx b/src/features/kwm/instructions/KWMv2AllInstructions.tsx similarity index 100% rename from src/features/settings/panels/KWMv2/KWMv2AllInstructions.tsx rename to src/features/kwm/instructions/KWMv2AllInstructions.tsx diff --git a/src/features/kwm/keyLookup.ts b/src/features/kwm/keyLookup.ts new file mode 100644 index 0000000..d837425 --- /dev/null +++ b/src/features/kwm/keyLookup.ts @@ -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; +}; diff --git a/src/features/settings/panels/KWMv2/KWMv2EKeyItem.tsx b/src/features/kwm/panel/KWMv2EKeyItem.tsx similarity index 90% rename from src/features/settings/panels/KWMv2/KWMv2EKeyItem.tsx rename to src/features/kwm/panel/KWMv2EKeyItem.tsx index b9daf4f..325fdd1 100644 --- a/src/features/settings/panels/KWMv2/KWMv2EKeyItem.tsx +++ b/src/features/kwm/panel/KWMv2EKeyItem.tsx @@ -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 }) => { diff --git a/src/features/settings/panels/PanelKWMv2Key.tsx b/src/features/kwm/panel/PanelKWMv2Key.tsx similarity index 74% rename from src/features/settings/panels/PanelKWMv2Key.tsx rename to src/features/kwm/panel/PanelKWMv2Key.tsx index a3fe778..ab169f3 100644 --- a/src/features/settings/panels/PanelKWMv2Key.tsx +++ b/src/features/kwm/panel/PanelKWMv2Key.tsx @@ -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[] | 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)); diff --git a/src/features/kwm/types.ts b/src/features/kwm/types.ts new file mode 100644 index 0000000..3110dd5 --- /dev/null +++ b/src/features/kwm/types.ts @@ -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; + +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 }; +}; diff --git a/src/features/qmc/__tests__/keyLookup.test.ts b/src/features/qmc/__tests__/keyLookup.test.ts new file mode 100644 index 0000000..19d7c9d --- /dev/null +++ b/src/features/qmc/__tests__/keyLookup.test.ts @@ -0,0 +1,37 @@ +import { configureStore } from '@reduxjs/toolkit'; + +import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice'; +import { selectQMCv2KeyByFileName } from '../keyLookup'; + +function storeWithQmcKeys(keys: Record, 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(); + }); +}); diff --git a/src/features/qmc/importKeys.ts b/src/features/qmc/importKeys.ts new file mode 100644 index 0000000..2e124c7 --- /dev/null +++ b/src/features/qmc/importKeys.ts @@ -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[]> { + 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; +} diff --git a/src/features/settings/panels/QMCv2/InstructionsIOS.tsx b/src/features/qmc/instructions/InstructionsIOS.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/InstructionsIOS.tsx rename to src/features/qmc/instructions/InstructionsIOS.tsx diff --git a/src/features/settings/panels/QMCv2/InstructionsIOSCondition.tsx b/src/features/qmc/instructions/InstructionsIOSCondition.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/InstructionsIOSCondition.tsx rename to src/features/qmc/instructions/InstructionsIOSCondition.tsx diff --git a/src/features/settings/panels/QMCv2/InstructionsMac.tsx b/src/features/qmc/instructions/InstructionsMac.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/InstructionsMac.tsx rename to src/features/qmc/instructions/InstructionsMac.tsx diff --git a/src/features/settings/panels/QMCv2/InstructionsMacV10.tsx b/src/features/qmc/instructions/InstructionsMacV10.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/InstructionsMacV10.tsx rename to src/features/qmc/instructions/InstructionsMacV10.tsx diff --git a/src/features/settings/panels/QMCv2/InstructionsMacV8.tsx b/src/features/qmc/instructions/InstructionsMacV8.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/InstructionsMacV8.tsx rename to src/features/qmc/instructions/InstructionsMacV8.tsx diff --git a/src/features/settings/panels/QMCv2/InstructionsPC.tsx b/src/features/qmc/instructions/InstructionsPC.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/InstructionsPC.tsx rename to src/features/qmc/instructions/InstructionsPC.tsx diff --git a/src/features/settings/panels/QMCv2/QMCv2DoubanAllInstructions.tsx b/src/features/qmc/instructions/QMCv2DoubanAllInstructions.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/QMCv2DoubanAllInstructions.tsx rename to src/features/qmc/instructions/QMCv2DoubanAllInstructions.tsx diff --git a/src/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions.tsx b/src/features/qmc/instructions/QMCv2QQMusicAllInstructions.tsx similarity index 100% rename from src/features/settings/panels/QMCv2/QMCv2QQMusicAllInstructions.tsx rename to src/features/qmc/instructions/QMCv2QQMusicAllInstructions.tsx diff --git a/src/features/settings/panels/QMCv2/assets/.gitignore b/src/features/qmc/instructions/assets/.gitignore similarity index 100% rename from src/features/settings/panels/QMCv2/assets/.gitignore rename to src/features/qmc/instructions/assets/.gitignore diff --git a/src/features/settings/panels/QMCv2/assets/noop.asm.txt b/src/features/qmc/instructions/assets/noop.asm.txt similarity index 100% rename from src/features/settings/panels/QMCv2/assets/noop.asm.txt rename to src/features/qmc/instructions/assets/noop.asm.txt diff --git a/src/features/settings/panels/QMCv2/assets/noop.exe b/src/features/qmc/instructions/assets/noop.exe similarity index 100% rename from src/features/settings/panels/QMCv2/assets/noop.exe rename to src/features/qmc/instructions/assets/noop.exe diff --git a/src/features/settings/panels/QMCv2/assets/qqmusic_v10.7_dump.command b/src/features/qmc/instructions/assets/qqmusic_v10.7_dump.command similarity index 100% rename from src/features/settings/panels/QMCv2/assets/qqmusic_v10.7_dump.command rename to src/features/qmc/instructions/assets/qqmusic_v10.7_dump.command diff --git a/src/features/settings/panels/QMCv2/assets/qqmusic_v8.8.0_patch_update.command b/src/features/qmc/instructions/assets/qqmusic_v8.8.0_patch_update.command similarity index 100% rename from src/features/settings/panels/QMCv2/assets/qqmusic_v8.8.0_patch_update.command rename to src/features/qmc/instructions/assets/qqmusic_v8.8.0_patch_update.command diff --git a/src/features/settings/panels/QMCv2/iosAllowBackup.webp b/src/features/qmc/instructions/iosAllowBackup.webp similarity index 100% rename from src/features/settings/panels/QMCv2/iosAllowBackup.webp rename to src/features/qmc/instructions/iosAllowBackup.webp diff --git a/src/features/qmc/keyLookup.ts b/src/features/qmc/keyLookup.ts new file mode 100644 index 0000000..4e3af53 --- /dev/null +++ b/src/features/qmc/keyLookup.ts @@ -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; +}; diff --git a/src/features/settings/panels/PanelQMCv2Key.tsx b/src/features/qmc/panel/PanelQMCv2Key.tsx similarity index 77% rename from src/features/settings/panels/PanelQMCv2Key.tsx rename to src/features/qmc/panel/PanelQMCv2Key.tsx index 342a69c..dd7c0dd 100644 --- a/src/features/settings/panels/PanelQMCv2Key.tsx +++ b/src/features/qmc/panel/PanelQMCv2Key.tsx @@ -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[] = 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)); diff --git a/src/features/settings/panels/QMCv2/QMCv2EKeyItem.tsx b/src/features/qmc/panel/QMCv2EKeyItem.tsx similarity index 91% rename from src/features/settings/panels/QMCv2/QMCv2EKeyItem.tsx rename to src/features/qmc/panel/QMCv2EKeyItem.tsx index 1e3c08b..db91847 100644 --- a/src/features/settings/panels/QMCv2/QMCv2EKeyItem.tsx +++ b/src/features/qmc/panel/QMCv2EKeyItem.tsx @@ -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'; diff --git a/src/features/qmc/types.ts b/src/features/qmc/types.ts new file mode 100644 index 0000000..24ca1f4 --- /dev/null +++ b/src/features/qmc/types.ts @@ -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; + +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(), + }; +}; diff --git a/src/features/qtfm/__tests__/importKeys.test.ts b/src/features/qtfm/__tests__/importKeys.test.ts new file mode 100644 index 0000000..129a6fc --- /dev/null +++ b/src/features/qtfm/__tests__/importKeys.test.ts @@ -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'); + }); +}); diff --git a/src/features/qtfm/importKeys.ts b/src/features/qtfm/importKeys.ts new file mode 100644 index 0000000..8ffa40e --- /dev/null +++ b/src/features/qtfm/importKeys.ts @@ -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; +} diff --git a/src/features/qtfm/instructions/QingTingNotes.tsx b/src/features/qtfm/instructions/QingTingNotes.tsx new file mode 100644 index 0000000..8fb9575 --- /dev/null +++ b/src/features/qtfm/instructions/QingTingNotes.tsx @@ -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 ( + <> +

注意事项

+
    +
  • +

    + 下载的文件位于 + + + [内部储存]/ + Android/ + + data/ + + fm.qingting.qtradio/ + + files/Music/ + + +

    +
      +
    • +

      + 你可能需要使用有 + 特权 + 的文件浏览器访问。 +

      +
    • +
    +
  • +
  • +

    + 音频文件文件名为「.p~!」后缀。 +

    +
  • +
  • +

    因为解密密钥与文件名相关,因此解密前请不要更改文件名。

    +
  • +
+ + ); +} diff --git a/src/features/qtfm/keyLookup.ts b/src/features/qtfm/keyLookup.ts new file mode 100644 index 0000000..54ba42c --- /dev/null +++ b/src/features/qtfm/keyLookup.ts @@ -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; diff --git a/src/features/settings/panels/PanelQingTing.tsx b/src/features/qtfm/panel/PanelQingTing.tsx similarity index 53% rename from src/features/settings/panels/PanelQingTing.tsx rename to src/features/qtfm/panel/PanelQingTing.tsx index 6c25b0e..038e023 100644 --- a/src/features/settings/panels/PanelQingTing.tsx +++ b/src/features/qtfm/panel/PanelQingTing.tsx @@ -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) => { 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( + DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, + dataMap, + ) .then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`)); } }; @@ -83,43 +78,7 @@ export function PanelQingTing() { -

注意事项

-
    -
  • -

    - 下载的文件位于 - - - [内部储存]/ - Android/ - - data/ - - fm.qingting.qtradio/ - - files/Music/ - - -

    -
      -
    • -

      - 你可能需要使用有 - 特权 - 的文件浏览器访问。 -

      -
    • -
    -
  • -
  • -

    - 音频文件文件名为「.p~!」前缀。 -

    -
  • -
  • -

    因为解密密钥与文件名相关,因此解密前请不要更改文件名。

    -
  • -
+ ); } diff --git a/src/features/qtfm/types.ts b/src/features/qtfm/types.ts new file mode 100644 index 0000000..e15aa00 --- /dev/null +++ b/src/features/qtfm/types.ts @@ -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, ''); +} diff --git a/src/features/settings/__tests__/settingsConverters.test.ts b/src/features/settings/__tests__/settingsConverters.test.ts index 573ebca..faedeec 100644 --- a/src/features/settings/__tests__/settingsConverters.test.ts +++ b/src/features/settings/__tests__/settingsConverters.test.ts @@ -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) { return configureStore({ diff --git a/src/features/settings/createKeyListReducers.ts b/src/features/settings/createKeyListReducers.ts index e6fe05c..f122f52 100644 --- a/src/features/settings/createKeyListReducers.ts +++ b/src/features/settings/createKeyListReducers.ts @@ -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'; diff --git a/src/features/settings/keyFormats.ts b/src/features/settings/keyFormats.ts index 4a75b6d..e81b7f9 100644 --- a/src/features/settings/keyFormats.ts +++ b/src/features/settings/keyFormats.ts @@ -1,6 +1,6 @@ -import { nanoid } from 'nanoid'; import { objectify } from 'radash'; +/** Generic map↔list helpers shared by format feature types. */ export function productionKeyToStaging>( src: P, make: (k: keyof P, v: P[keyof P]) => null | S, @@ -18,84 +18,3 @@ export function productionKeyToStaging>( export function stagingKeyToProduction(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; - -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; - -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; -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 }; -}; diff --git a/src/features/settings/panels/QingTingFM/QingTingImport.ts b/src/features/settings/panels/QingTingFM/QingTingImport.ts deleted file mode 100644 index abfdf1a..0000000 --- a/src/features/settings/panels/QingTingFM/QingTingImport.ts +++ /dev/null @@ -1 +0,0 @@ -// TODO: Popup dialog for QingTing instructions diff --git a/src/features/settings/persistSettings.ts b/src/features/settings/persistSettings.ts index aa25749..e7efaf5 100644 --- a/src/features/settings/persistSettings.ts +++ b/src/features/settings/persistSettings.ts @@ -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; diff --git a/src/features/settings/settingsSelector.ts b/src/features/settings/settingsSelector.ts index 5646db4..f1f6147 100644 --- a/src/features/settings/settingsSelector.ts +++ b/src/features/settings/settingsSelector.ts @@ -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; diff --git a/src/features/settings/settingsSlice.ts b/src/features/settings/settingsSlice.ts index 3d56f47..1e33538 100644 --- a/src/features/settings/settingsSlice.ts +++ b/src/features/settings/settingsSlice.ts @@ -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 }, }, }; diff --git a/src/features/settings/settingsTabs.tsx b/src/features/settings/settingsTabs.tsx index 855ada7..5f13c90 100644 --- a/src/features/settings/settingsTabs.tsx +++ b/src/features/settings/settingsTabs.tsx @@ -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 = { diff --git a/src/util/DatabaseKeyExtractor.ts b/src/util/DatabaseKeyExtractor.ts index b3db471..2a2930b 100644 --- a/src/util/DatabaseKeyExtractor.ts +++ b/src/util/DatabaseKeyExtractor.ts @@ -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; +export type KugouKeyEntry = Omit; export class DatabaseKeyExtractor { private static _instance: DatabaseKeyExtractor; diff --git a/src/util/mmkv/kugou.ts b/src/util/mmkv/kugou.ts index fb142c8..754eb40 100644 --- a/src/util/mmkv/kugou.ts +++ b/src/util/mmkv/kugou.ts @@ -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): Omit[] { diff --git a/src/util/mmkv/kuwo.ts b/src/util/mmkv/kuwo.ts index a8768ea..919b7dd 100644 --- a/src/util/mmkv/kuwo.ts +++ b/src/util/mmkv/kuwo.ts @@ -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): Omit[] {