fix(onebot): preserve voice transcription metadata

Refs #607
This commit is contained in:
DrSmoothl committed 2026-11-08 17:33:46 +08:00
1 parent 0cb5daed5e
commit 9df7b7524b
15 files changed
+351 -14

No files matched your search

+8 -1
View File
@@ -35,6 +35,9 @@ export interface PttTransInput {
duration: number;
size: number;
format: number;
/** Omitted by older callers for legacy voice media. */
isNtv2?: boolean;
storeRegion?: number;
/** Group ptt numeric file id (group only; optional). */
fileId?: number;
}
@@ -390,6 +393,8 @@ export class ExtrasApi {
md5,
},
};
req.isNtv2 = input.isNtv2 ? 1 : 0;
req.storeRegion = input.isNtv2 ? (input.storeRegion ?? 0) : 0;
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
@@ -406,9 +411,11 @@ export class ExtrasApi {
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
'ptt translate errCode=%d isGroup=%s ntv2=%d region=%d md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode,
input.isGroup,
req.isNtv2,
req.storeRegion,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format,
input.uuid ? 'set' : 'EMPTY',
@@ -39,11 +39,12 @@ describe('ptt-upload', () => {
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
msgInfo: { msgInfoBody: [{ index: node }] },
} as any);
const element = { ...FINGERPRINT };
const element = { ...FINGERPRINT, isNtv2: false };
await uploadPttMsgInfo({} as any, true, 12345, element);
expect(element).toMatchObject({
fileId: 'uploaded-resource',
mediaNode: node,
isNtv2: true,
md5Hex: 'aa',
sha1Hex: 'bb',
});
+1
View File
@@ -52,6 +52,7 @@ export class MediaIndexer {
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
voiceFormat: element.voiceFormat,
isNtv2: element.isNtv2,
});
return;
}
+1
View File
@@ -35,6 +35,7 @@ export interface CachedRecord {
md5Hex?: string;
sha1Hex?: string;
voiceFormat?: number;
isNtv2?: boolean;
}
export interface CachedVideo {
+9 -1
View File
@@ -78,6 +78,7 @@ export function attachMessageMedia(segment: JsonObject, element: MessageElement)
picFormat,
duration,
voiceFormat,
isNtv2,
videoFormat,
fileHash,
mediaNode,
@@ -100,6 +101,7 @@ export function attachMessageMedia(segment: JsonObject, element: MessageElement)
picFormat,
duration,
voiceFormat,
isNtv2,
videoFormat,
fileHash,
mediaNode,
@@ -207,7 +209,13 @@ function mergeKnownMediaFields(old: object, next: object): Record<string, unknow
for (const [key, value] of Object.entries(next)) {
// Zero dimensions, sizes and durations are incomplete observations, not
// evidence that known properties of the same resource have changed.
if (value === undefined || value === null || value === '' || value === 0) {
// Storage region zero is a valid destination and must replace old values.
if (
value === undefined ||
value === null ||
value === '' ||
(value === 0 && key !== 'storeId')
) {
continue;
}
@@ -222,10 +222,17 @@ export async function fetchPttText(
const senderUin = Number(event.user_id) || 0;
// c2c: receiver is self (inbound voice); group: the group uin.
const peerUin = isGroup ? Number(event.group_id) || cached.sessionId : selfId;
// Before the explicit marker was persisted, only NT records carried a
// storage region. Legacy records also have mediaNode, but no storeId.
// Old decoded NT records can store null for the default region as well.
const isNtv2 = cached.isNtv2 ?? cached.mediaNode?.storeId !== undefined;
const storeRegion = isNtv2 ? (cached.mediaNode?.storeId ?? 0) : 0;
const text = await requestPttTransText(pttTransKey(selfId, messageId), 20_000, () =>
bridge.apis.extras.translatePttToText({
isGroup,
isNtv2,
storeRegion,
msgId: messageId,
senderUin,
peerUin,
@@ -1141,6 +1141,8 @@ describe('buildApiContext media', () => {
duration: 2,
size: 16,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -428,6 +428,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -461,6 +463,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -494,6 +498,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -526,6 +532,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -564,6 +572,8 @@ describe('fetchPttText', () => {
duration: 0,
size: 0,
format: 0,
isNtv2: false,
storeRegion: 0,
});
});
@@ -591,6 +601,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -0,0 +1,292 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { pb, uint_32 } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { MessageBody } from '@snowluma/proto-defs/message';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { ExtrasApi } from '../../core/src/bridge/apis/extras';
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
import { elementsToOneBotSegments, type ConverterContext } from '../src/event-converter';
import { MediaIndexer } from '../src/media-indexer';
import { MediaStore } from '../src/media-store';
import { migrateLegacyMedia } from '../src/media-store-migration';
import { MessageStore } from '../src/message-store';
import { fetchPttText } from '../src/modules/media-actions';
// Decode the routing fields independently of the production request schema.
interface TranscriptionRouting {
isNtv2?: pb<5, uint_32>;
storeRegion?: pb<6, uint_32>;
}
const selfId = 10001;
const peerId = 20002;
const groupId = 30003;
const messageId = -607;
const md5 = '00112233445566778899aabbccddeeff';
const cleanups: Array<() => void | Promise<void>> = [];
afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) {
await cleanup();
}
});
function location() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ptt-transcription-'));
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
return {
dbPath: path.join(directory, 'messages.db'),
legacyPath: path.join(directory, 'media.db'),
};
}
async function openStores(dbPath: string) {
const messages = new MessageStore(dbPath);
await messages.initialization;
const media = new MediaStore(dbPath, 1);
let closed = false;
const close = async () => {
if (closed) {
return;
}
closed = true;
await media.close();
await messages.close();
};
cleanups.push(close);
await media.initialization;
const indexer = new MediaIndexer(media);
const converter: ConverterContext = {
selfId,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: (...args) => indexer.remember(...args),
};
return { messages, media, converter, close };
}
function voice(isGroup: boolean, ntv2: boolean, storeId?: number) {
const body: MessageBody = {
richText: ntv2
? {
elems: [
{
commonElem: {
serviceType: 48,
businessType: isGroup ? 12 : 22,
pbElem: protobuf_encode<MsgInfo>({
msgInfoBody: [
{
index: {
fileUuid: 'voice-resource',
storeId,
info: {
fileName: 'voice.silk',
fileSize: 4003,
fileHash: md5,
time: 2,
type: { type: 3, voiceFormat: 1 },
},
},
},
],
}),
},
},
],
}
: {
ptt: {
fileName: 'voice.silk',
fileUuid: Buffer.from('voice-resource'),
fileMd5: Buffer.from(md5, 'hex'),
fileSize: 4003,
time: 2,
format: 1,
},
},
};
const elements = decodeRichBody(
protobuf_decode<MessageBody>(protobuf_encode<MessageBody>(body)),
isGroup,
);
expect(elements).toHaveLength(1);
return elements;
}
async function saveVoice(
stores: Awaited<ReturnType<typeof openStores>>,
isGroup: boolean,
elements: ReturnType<typeof voice>,
withSnapshot = true,
) {
const segments = await elementsToOneBotSegments(
stores.converter,
elements,
isGroup,
isGroup ? groupId : peerId,
);
await stores.messages.storeEvent(
messageId,
isGroup,
isGroup ? groupId : peerId,
42,
isGroup ? 'GroupMessage' : 'PrivateMessage',
{
message_id: messageId,
message_type: isGroup ? 'group' : 'private',
user_id: peerId,
...(isGroup ? { group_id: groupId } : {}),
message: withSnapshot ? segments : JSON.parse(JSON.stringify(segments)),
},
);
}
function transport(isGroup: boolean, errCode = 0) {
const sendRawPacket = vi.fn(async (_cmd: string, _bytes: Uint8Array) => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: protobuf_encode<PttTransResp>(
isGroup
? { type: 1, groupResult: { errCode, text: errCode ? '' : '测试转写结果' } }
: { type: 2, c2cResult: { errCode, text: errCode ? '' : '测试转写结果' } },
),
}));
const extras = new ExtrasApi({ sendRawPacket } as unknown as ConstructorParameters<
typeof ExtrasApi
>[0]);
const bridge = { apis: { extras } } as unknown as BridgeInterface;
return { sendRawPacket, bridge };
}
async function checkRequest(
stores: Awaited<ReturnType<typeof openStores>>,
isGroup: boolean,
ntv2: boolean,
storeRegion = 0,
) {
const { sendRawPacket, bridge } = transport(isGroup);
await expect(
fetchPttText(stores.messages, stores.media, bridge, selfId, messageId),
).resolves.toEqual({ text: '测试转写结果' });
expect(sendRawPacket).toHaveBeenCalledTimes(1);
const [cmd, bytes] = sendRawPacket.mock.calls[0]!;
expect(cmd).toBe(isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq');
const routing = protobuf_decode<TranscriptionRouting>(bytes);
expect(routing.isNtv2 ?? 0).toBe(ntv2 ? 1 : 0);
expect(routing.storeRegion ?? 0).toBe(storeRegion);
const request = protobuf_decode<PttTransReq>(bytes);
expect(isGroup ? request.groupItem : request.c2cItem).toMatchObject({
msgId: BigInt.asUintN(64, BigInt(messageId)),
senderUin: BigInt(peerId),
uuid: 'voice-resource',
md5,
duration: 2,
size: 4003,
format: 1,
...(isGroup ? { groupUin: BigInt(groupId) } : { receiverUin: BigInt(selfId) }),
});
}
describe.each([false, true])('voice transcription (isGroup=%s)', (isGroup) => {
it.each([
{ name: 'NT voice', ntv2: true, storeId: 1 },
{ name: 'NT voice in region zero', ntv2: true, storeId: 0 },
{ name: 'NT voice without a region', ntv2: true, storeId: undefined },
{ name: 'legacy voice', ntv2: false, storeId: undefined },
])('preserves $name routing through storage and reopening', async ({ ntv2, storeId }) => {
const { dbPath } = location();
let stores = await openStores(dbPath);
await saveVoice(stores, isGroup, voice(isGroup, ntv2, storeId));
await checkRequest(stores, isGroup, ntv2, storeId);
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, ntv2, storeId);
expect((await stores.messages.findMedia(messageId))?.[0]).toMatchObject({ isNtv2: ntv2 });
expect(await stores.media.findRecord('voice.silk')).toMatchObject({ isNtv2: ntv2 });
const event = await stores.messages.findEvent(messageId);
expect(event?.message_id).toBe(messageId);
expect(JSON.stringify(event)).not.toMatch(/isNtv2|storeId|storeRegion/);
});
it.each([true, false])('reads pre-marker snapshots (ntv2=%s)', async (ntv2) => {
const { dbPath } = location();
let stores = await openStores(dbPath);
const elements = voice(isGroup, ntv2, ntv2 ? 1 : undefined);
Reflect.deleteProperty(elements[0]!, 'isNtv2');
await saveVoice(stores, isGroup, elements);
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, ntv2, ntv2 ? 1 : 0);
});
it('recognizes pre-marker NT snapshots with a null default region', async () => {
const { dbPath } = location();
let stores = await openStores(dbPath);
const elements = voice(isGroup, true);
Reflect.deleteProperty(elements[0]!, 'isNtv2');
Reflect.set(elements[0]!.mediaNode!, 'storeId', null);
await saveVoice(stores, isGroup, elements);
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, true);
});
it('retains an explicit zero region when updating the same voice', async () => {
const { dbPath } = location();
let stores = await openStores(dbPath);
await saveVoice(stores, isGroup, voice(isGroup, true, 1));
await saveVoice(stores, isGroup, voice(isGroup, true, 0));
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, true, 0);
});
it.each([true, false])(
'reads migrated media without a message snapshot (ntv2=%s)',
async (ntv2) => {
const { dbPath, legacyPath } = location();
const old = await openStores(legacyPath);
const elements = voice(isGroup, ntv2, ntv2 ? 1 : undefined);
Reflect.deleteProperty(elements[0]!, 'isNtv2');
await saveVoice(old, isGroup, elements);
await old.close();
let stores = await openStores(dbPath);
await saveVoice(stores, isGroup, elements, false);
await stores.close();
await migrateLegacyMedia(dbPath);
stores = await openStores(dbPath);
// A same-named current entry must not replace the migrated source.
await elementsToOneBotSegments(
stores.converter,
voice(isGroup, true, 9),
isGroup,
peerId,
);
expect(await stores.messages.findMedia(messageId)).toBeNull();
await checkRequest(stores, isGroup, ntv2, ntv2 ? 1 : 0);
},
);
it('preserves the server failure without retrying', async () => {
const { dbPath } = location();
const stores = await openStores(dbPath);
await saveVoice(stores, isGroup, voice(isGroup, true, 1));
const { sendRawPacket, bridge } = transport(isGroup, 9);
await expect(
fetchPttText(stores.messages, stores.media, bridge, selfId, messageId),
).rejects.toThrow('ptt translate failed: error=9');
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
});
+3 -8
View File
@@ -4,14 +4,6 @@ import type { pb, uint_32, uint_64 } from '@snowluma/proton';
* Voice-to-text (语音转文字) request/response protobufs for the
* `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` SSO commands.
*
* Reverse-engineered from QQ-NT `wrapper.node` (macOS 9.9.x) —
* `im_core/msg/ptt/ptt_trans_worker.cc` (`EncodeC2CPtt` / `EncodeTroopPtt`
* build the request, `OnTranslateResp` decodes the response). The wire shape
* here is RE-derived and NOT yet verified against a live server: the numeric
* field tags are read straight from the encoder, but the length-delimited
* fields (uuid / md5) and the response `text` tag should be confirmed with a
* single live capture before relying on them.
*
* Flow: the response can carry completed text inline. Otherwise, the caller
* waits for an asynchronous result correlated with the original message ID.
*/
@@ -55,6 +47,9 @@ export interface PttTransReq {
type?: pb<1, uint_32>;
groupItem?: pb<2, GroupPttTransItem>;
c2cItem?: pb<3, C2CPttTransItem>;
/** 1 for NT media, 0 for legacy media; not the audio codec. */
isNtv2?: pb<5, uint_32>;
storeRegion?: pb<6, uint_32>;
}
/** Per-scene result. `errCode` 0 = ok; `text` carries the recognised speech. */
+2 -1
View File
@@ -215,6 +215,7 @@ export const ELEMENT_MANIFEST = {
'md5Hex',
'sha1Hex',
'voiceFormat',
'isNtv2',
'noByteFallback',
'mediaNode',
]),
@@ -353,7 +354,7 @@ const NUMBER_FIELDS: ReadonlySet<string> = new Set([
'videoFormat',
'voiceFormat',
]);
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback', 'large']);
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback', 'large', 'isNtv2']);
function throwValidation(
code: MessageElementValidationCode,
+2
View File
@@ -145,6 +145,8 @@ export interface RecordElement extends FingerprintFields {
url?: string;
duration?: number;
voiceFormat?: number;
/** Media protocol generation; independent of the audio codec. */
isNtv2?: boolean;
mediaNode?: MediaNode;
}
@@ -310,6 +310,7 @@ export async function uploadPtt(
fileName: ptt.fileName,
duration: ptt.duration,
voiceFormat: ptt.voiceFormat,
isNtv2: true,
fileId: mediaNode?.fileUuid,
mediaNode,
});
@@ -599,7 +599,7 @@ function assignValidFingerprints(
function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode'] {
return {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
storeId: idx.storeId ?? 0,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
@@ -1153,6 +1153,7 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
voiceFormat: fi.type?.voiceFormat ?? 0,
isNtv2: true,
mediaNode: buildMediaNode(idx, fi),
};
assignValidFingerprints(
@@ -1579,6 +1580,7 @@ function extractRichtextExtras(
duration: p.time ?? 0,
fileHash: md5Hex ?? '',
voiceFormat: p.format ?? 0,
isNtv2: false,
};
assignValidFingerprints(me, md5Hex, undefined, 'ptt');
@@ -81,7 +81,12 @@ describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)
return 'cd'.repeat(20);
}
if (field === 'flash' || field === 'noByteFallback' || field === 'large') {
if (
field === 'flash' ||
field === 'noByteFallback' ||
field === 'large' ||
field === 'isNtv2'
) {
return true;
}