mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-25 06:46:59 +00:00
feat: introduce worker action types and refactor decryption handling
- Added a new `actions.ts` file defining `WorkerActionMap` for better type management of worker actions. - Updated `client.ts`, `worker.ts`, and `decrypt.ts` to utilize the new action types, enhancing type safety. - Refactored `DecryptCommandPayload` to rename `id` to `fileId` for clarity and consistency. - Adjusted various components to align with the new payload structure and improved error handling in the worker event bus. - Enhanced tests to ensure compatibility with the new action type definitions and payload structures.
This commit is contained in:
1 parent
7a11d4f941
commit
4a7994df96
13 files changed
+105
-78
No files matched your search
@@ -0,0 +1,21 @@
|
||||
import type { DecryptionResult } from './constants';
|
||||
import type {
|
||||
DecryptCommandPayload,
|
||||
FetchMusicExNamePayload,
|
||||
GetQingTingFMDeviceKeyPayload,
|
||||
ParseKugouHeaderPayload,
|
||||
ParseKugouHeaderResponse,
|
||||
ParseKuwoHeaderPayload,
|
||||
ParseKuwoHeaderResponse,
|
||||
} from './types';
|
||||
|
||||
export type WorkerActionMap = {
|
||||
DECRYPT: { req: DecryptCommandPayload; res: DecryptionResult };
|
||||
FIND_QMC_MUSICEX_NAME: { req: FetchMusicExNamePayload; res: string | null };
|
||||
KUWO_PARSE_HEADER: { req: ParseKuwoHeaderPayload; res: ParseKuwoHeaderResponse };
|
||||
KUGOU_PARSE_HEADER: { req: ParseKugouHeaderPayload; res: ParseKugouHeaderResponse };
|
||||
QINGTING_FM_GET_DEVICE_KEY: { req: GetQingTingFMDeviceKeyPayload; res: string };
|
||||
VERSION: { req: null; res: string };
|
||||
};
|
||||
|
||||
export type WorkerActionName = keyof WorkerActionMap;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { WorkerClientBus } from '~/util/WorkerEventBus';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
|
||||
import type { WorkerActionMap } from './actions';
|
||||
import { DecryptionQueue } from '~/util/DecryptionQueue';
|
||||
|
||||
// TODO: Worker pool?
|
||||
@@ -8,5 +8,5 @@ export const workerClient = new Worker(new URL('./worker', import.meta.url), { t
|
||||
// FIXME: report the error so is obvious to the user.
|
||||
workerClient.addEventListener('error', console.error);
|
||||
|
||||
export const workerClientBus = new WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>(workerClient);
|
||||
export const workerClientBus = new WorkerClientBus<WorkerActionMap>(workerClient);
|
||||
export const decryptionQueue = new DecryptionQueue(workerClientBus);
|
||||
@@ -12,7 +12,7 @@ export class KuwoMusicDecipher implements DecipherInstance {
|
||||
|
||||
try {
|
||||
header = KuwoHeader.parse(buffer.subarray(0, 0x400));
|
||||
kwm = new KWMDecipher(header, options.kwm2key);
|
||||
kwm = new KWMDecipher(header, options.kwm2Key);
|
||||
|
||||
const audioBuffer = new Uint8Array(buffer.subarray(0x400));
|
||||
for (const [block, offset] of chunkBuffer(audioBuffer)) {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
export interface DecryptCommandOptions {
|
||||
fileName: string;
|
||||
qmc2Key?: string;
|
||||
kwm2key?: string;
|
||||
kwm2Key?: string;
|
||||
kugouKey?: string;
|
||||
qingTingAndroidKey?: string;
|
||||
}
|
||||
|
||||
export interface DecryptCommandPayload {
|
||||
id: string;
|
||||
fileId: string;
|
||||
blobURI: string;
|
||||
options: DecryptCommandOptions;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WorkerServerBus } from '~/util/WorkerEventBus';
|
||||
import type { WorkerActionMap } from './actions';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from './constants';
|
||||
import { getUmcVersion } from '@unlock-music/crypto';
|
||||
|
||||
@@ -8,7 +9,7 @@ import { workerGetQtfmDeviceKey } from '~/decrypt-worker/worker/qtfm_device_key.
|
||||
import { workerParseKuwoHeader } from '~/decrypt-worker/worker/kuwo_header_parse.ts';
|
||||
import { workerParseKugouHeader } from '~/decrypt-worker/worker/kugou_parse_header.ts';
|
||||
|
||||
const bus = new WorkerServerBus();
|
||||
const bus = new WorkerServerBus<WorkerActionMap>();
|
||||
onmessage = bus.onmessage;
|
||||
|
||||
bus.addEventHandler(DECRYPTION_WORKER_ACTION_NAME.DECRYPT, workerDecryptHandler);
|
||||
|
||||
@@ -80,13 +80,12 @@ class DecryptCommandHandler {
|
||||
}
|
||||
}
|
||||
|
||||
export const workerDecryptHandler = async ({ id: payloadId, blobURI, options }: DecryptCommandPayload) => {
|
||||
export const workerDecryptHandler = async ({ fileId, blobURI, options }: DecryptCommandPayload) => {
|
||||
await umCryptoReady;
|
||||
const id = payloadId.replace('://', ':');
|
||||
const label = `decrypt(${id})`;
|
||||
const label = `decrypt(${fileId})`;
|
||||
return withTimeGroupedLogs(label, async () => {
|
||||
const buffer = await fetch(blobURI).then((r) => r.arrayBuffer());
|
||||
const handler = new DecryptCommandHandler(id, new Uint8Array(buffer), options);
|
||||
const handler = new DecryptCommandHandler(fileId, new Uint8Array(buffer), options);
|
||||
return handler.decrypt(allCryptoFactories);
|
||||
});
|
||||
};
|
||||
@@ -3,14 +3,7 @@ import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
|
||||
import type { RootState } from '~/store';
|
||||
|
||||
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
||||
import type {
|
||||
DecryptCommandOptions,
|
||||
FetchMusicExNamePayload,
|
||||
ParseKugouHeaderPayload,
|
||||
ParseKugouHeaderResponse,
|
||||
ParseKuwoHeaderPayload,
|
||||
ParseKuwoHeaderResponse,
|
||||
} from '~/decrypt-worker/types';
|
||||
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
|
||||
import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
|
||||
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
|
||||
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
|
||||
@@ -78,27 +71,25 @@ export const processFile = createAsyncThunk<
|
||||
};
|
||||
|
||||
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
|
||||
workerClientBus.request<string, FetchMusicExNamePayload>(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
|
||||
blobURI: file.raw,
|
||||
}),
|
||||
workerClientBus.request<ParseKuwoHeaderResponse, ParseKuwoHeaderPayload>(
|
||||
DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER,
|
||||
{ blobURI: file.raw },
|
||||
),
|
||||
workerClientBus.request<ParseKugouHeaderResponse, ParseKugouHeaderPayload>(
|
||||
DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER,
|
||||
{ blobURI: file.raw },
|
||||
),
|
||||
]);
|
||||
|
||||
const options: DecryptCommandOptions = {
|
||||
fileName: file.fileName,
|
||||
qmc2Key: selectQMCv2KeyByFileName(state, qmcv2MusicExMediaFile || file.fileName),
|
||||
kwm2key: selectKWMv2Key(state, kuwoHdr),
|
||||
kwm2Key: selectKWMv2Key(state, kuwoHdr),
|
||||
kugouKey: selectKugouKey(state, kugouHdr),
|
||||
qingTingAndroidKey: selectQtfmAndroidKey(state),
|
||||
};
|
||||
return decryptionQueue.add({ id: fileId, blobURI: file.raw, options }, onPreProcess);
|
||||
return decryptionQueue.add({ fileId, blobURI: file.raw, options }, onPreProcess);
|
||||
});
|
||||
|
||||
export const fileListingSlice = createSlice({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
|
||||
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
|
||||
import type { RootState } from '~/store';
|
||||
import { selectKugouKey } from '../keyLookup';
|
||||
|
||||
function storeWithKugouKeys(keys: Record<string, string>) {
|
||||
@@ -23,12 +24,12 @@ 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');
|
||||
expect(selectKugouKey(store.getState() as RootState, { audioHash: hash } as never)).toBe('ek');
|
||||
});
|
||||
|
||||
test('returns undefined for unknown hash or null header', () => {
|
||||
const store = storeWithKugouKeys({ ['b'.repeat(32)]: 'ek' });
|
||||
expect(selectKugouKey(store.getState(), { audioHash: 'c'.repeat(32) } as never)).toBeUndefined();
|
||||
expect(selectKugouKey(store.getState(), null)).toBeUndefined();
|
||||
expect(selectKugouKey(store.getState() as RootState, { audioHash: 'c'.repeat(32) } as never)).toBeUndefined();
|
||||
expect(selectKugouKey(store.getState() as RootState, null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
|
||||
import settingsReducer, { settingsSlice } from '~/features/settings/settingsSlice';
|
||||
import type { RootState } from '~/store';
|
||||
import { selectQMCv2KeyByFileName } from '../keyLookup';
|
||||
|
||||
function storeWithQmcKeys(keys: Record<string, string>, allowFuzzyNameSearch = true) {
|
||||
@@ -22,16 +23,16 @@ function storeWithQmcKeys(keys: Record<string, string>, allowFuzzyNameSearch = t
|
||||
describe('selectQMCv2KeyByFileName', () => {
|
||||
test('returns exact match', () => {
|
||||
const store = storeWithQmcKeys({ 'song.mflac': 'ek-exact' });
|
||||
expect(selectQMCv2KeyByFileName(store.getState(), 'song.mflac')).toBe('ek-exact');
|
||||
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'song.mflac')).toBe('ek-exact');
|
||||
});
|
||||
|
||||
test('falls back to closest name when fuzzy search is enabled', () => {
|
||||
const store = storeWithQmcKeys({ 'song.mflac': 'ek-fuzzy' });
|
||||
expect(selectQMCv2KeyByFileName(store.getState(), 'songg.mflac')).toBe('ek-fuzzy');
|
||||
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'songg.mflac')).toBe('ek-fuzzy');
|
||||
});
|
||||
|
||||
test('returns undefined when fuzzy search is disabled and name misses', () => {
|
||||
const store = storeWithQmcKeys({ 'song.mflac': 'ek' }, false);
|
||||
expect(selectQMCv2KeyByFileName(store.getState(), 'other.mflac')).toBeUndefined();
|
||||
expect(selectQMCv2KeyByFileName(store.getState() as RootState, 'other.mflac')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/fe
|
||||
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 { toast } from 'react-toastify';
|
||||
|
||||
@@ -33,10 +32,7 @@ export function PanelQingTing() {
|
||||
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}`));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import type { WorkerActionMap } from '~/decrypt-worker/actions';
|
||||
import type { DecryptCommandPayload } from '~/decrypt-worker/types';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME, DecryptionResult } from '~/decrypt-worker/constants';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
|
||||
|
||||
import { ConcurrentQueue } from './ConcurrentQueue';
|
||||
import { WorkerClientBus } from './WorkerEventBus';
|
||||
|
||||
export class DecryptionQueue extends ConcurrentQueue<DecryptCommandPayload, DecryptionResult> {
|
||||
constructor(
|
||||
private workerClientBus: WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>,
|
||||
private workerClientBus: WorkerClientBus<WorkerActionMap>,
|
||||
maxQueue?: number,
|
||||
) {
|
||||
super(maxQueue);
|
||||
|
||||
+45
-28
@@ -1,27 +1,45 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
import { DecryptError } from '~/decrypt-worker/util/DecryptError';
|
||||
|
||||
type WorkerActionEntry = { req: unknown; res: unknown };
|
||||
type WorkerServerHandler<P, R> = (payload: P) => R | Promise<R>;
|
||||
|
||||
interface SerializedError {
|
||||
export interface SerializedError {
|
||||
message: string;
|
||||
stack?: string;
|
||||
code?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface WorkerClientRequestPayload<P = unknown> {
|
||||
id: string;
|
||||
requestId: string;
|
||||
action: string;
|
||||
payload: P;
|
||||
}
|
||||
|
||||
interface WorkerServerResponsePayload<R = unknown> {
|
||||
id: string;
|
||||
result: R;
|
||||
error: SerializedError;
|
||||
requestId: string;
|
||||
result: R | null;
|
||||
error: SerializedError | null;
|
||||
}
|
||||
|
||||
export class WorkerClientBus<T = string> {
|
||||
export function serializeError(err: unknown): SerializedError {
|
||||
if (err instanceof DecryptError) {
|
||||
return err.toJSON();
|
||||
}
|
||||
if (err instanceof Error) {
|
||||
const withCode = err as Error & { code?: string };
|
||||
return {
|
||||
name: err.name,
|
||||
message: err.message,
|
||||
stack: err.stack,
|
||||
code: withCode.code,
|
||||
};
|
||||
}
|
||||
return { message: String(err) };
|
||||
}
|
||||
|
||||
export class WorkerClientBus<TMap extends Record<string, WorkerActionEntry>> {
|
||||
private idPromiseMap = new Map<string, [(data: never) => void, (error: Error) => void]>();
|
||||
|
||||
constructor(private worker: Worker) {
|
||||
@@ -29,13 +47,13 @@ export class WorkerClientBus<T = string> {
|
||||
}
|
||||
|
||||
eventHandler = (e: MessageEvent<WorkerServerResponsePayload>) => {
|
||||
const { id, result, error } = e.data;
|
||||
const actionPromise = this.idPromiseMap.get(id);
|
||||
const { requestId, result, error } = e.data;
|
||||
const actionPromise = this.idPromiseMap.get(requestId);
|
||||
if (!actionPromise) {
|
||||
console.error('cound not fetch worker promise for action: %s', id);
|
||||
console.error('could not fetch worker promise for request: %s', requestId);
|
||||
return;
|
||||
}
|
||||
this.idPromiseMap.delete(id);
|
||||
this.idPromiseMap.delete(requestId);
|
||||
|
||||
const [resolve, reject] = actionPromise;
|
||||
if (error) {
|
||||
@@ -48,47 +66,46 @@ export class WorkerClientBus<T = string> {
|
||||
}
|
||||
};
|
||||
|
||||
async request<R, P>(actionName: T, payload: P): Promise<R> {
|
||||
async request<K extends keyof TMap & string>(actionName: K, payload: TMap[K]['req']): Promise<TMap[K]['res']> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = `request://${actionName as string}/${nanoid()}`;
|
||||
this.idPromiseMap.set(id, [resolve, reject]);
|
||||
const requestId = `request://${actionName}/${nanoid()}`;
|
||||
this.idPromiseMap.set(requestId, [resolve, reject]);
|
||||
this.worker.postMessage({
|
||||
id,
|
||||
requestId,
|
||||
action: actionName,
|
||||
payload,
|
||||
});
|
||||
} satisfies WorkerClientRequestPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkerServerBus {
|
||||
export class WorkerServerBus<TMap extends Record<string, WorkerActionEntry> = Record<string, WorkerActionEntry>> {
|
||||
private handlers = new Map<string, WorkerServerHandler<unknown, unknown>>();
|
||||
|
||||
addEventHandler<R, P>(actionName: string, handler: WorkerServerHandler<P, R>) {
|
||||
this.handlers.set(actionName, handler as WorkerServerHandler<unknown, unknown>);
|
||||
addEventHandler<K extends keyof TMap & string>(
|
||||
actionName: K,
|
||||
handler: WorkerServerHandler<TMap[K]['req'], TMap[K]['res']>,
|
||||
) {
|
||||
this.handlers.set(actionName, handler);
|
||||
}
|
||||
|
||||
onmessage = async (e: MessageEvent<WorkerClientRequestPayload>) => {
|
||||
const { id, action, payload } = e.data;
|
||||
const { requestId, action, payload } = e.data;
|
||||
const handler = this.handlers.get(action);
|
||||
|
||||
let result = null;
|
||||
let error = null;
|
||||
let result: unknown = null;
|
||||
let error: SerializedError | null = null;
|
||||
|
||||
if (!handler) {
|
||||
error = new Error('Handler missing for action ' + action);
|
||||
error = serializeError(new Error('Handler missing for action ' + action));
|
||||
} else {
|
||||
try {
|
||||
result = await handler(payload);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof DecryptError) {
|
||||
error = err.toJSON();
|
||||
} else {
|
||||
error = err;
|
||||
}
|
||||
error = serializeError(err);
|
||||
}
|
||||
}
|
||||
|
||||
postMessage({ id, result, error });
|
||||
postMessage({ requestId, result, error } satisfies WorkerServerResponsePayload);
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { WorkerActionMap } from '~/decrypt-worker/actions';
|
||||
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
|
||||
import { WorkerClientBus } from '../WorkerEventBus';
|
||||
import { DecryptionQueue } from '../DecryptionQueue';
|
||||
@@ -14,21 +15,19 @@ vi.mock('../WorkerEventBus', () => {
|
||||
|
||||
test('should be able to forward request to worker client bus', async () => {
|
||||
// This class is mocked
|
||||
const bus = new WorkerClientBus<DECRYPTION_WORKER_ACTION_NAME>(null as never);
|
||||
vi.spyOn(bus, 'request').mockImplementation(
|
||||
async (actionName: DECRYPTION_WORKER_ACTION_NAME, payload: unknown): Promise<unknown> => {
|
||||
return Promise.resolve({ actionName, payload });
|
||||
},
|
||||
);
|
||||
const bus = new WorkerClientBus<WorkerActionMap>(null as never);
|
||||
vi.spyOn(bus, 'request').mockImplementation((actionName, payload) => {
|
||||
return Promise.resolve({ actionName, payload } as never);
|
||||
});
|
||||
|
||||
const queue = new DecryptionQueue(bus, 1);
|
||||
await expect(
|
||||
queue.add({ id: 'file://1', blobURI: 'blob://mock-file', options: { fileName: 'test.bin' } }),
|
||||
queue.add({ fileId: 'file://1', blobURI: 'blob://mock-file', options: { fileName: 'test.bin' } }),
|
||||
).resolves.toEqual({
|
||||
actionName: DECRYPTION_WORKER_ACTION_NAME.DECRYPT,
|
||||
payload: {
|
||||
blobURI: 'blob://mock-file',
|
||||
id: 'file://1',
|
||||
fileId: 'file://1',
|
||||
options: { fileName: 'test.bin' },
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user