diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index c6dfc3e7..9525d372 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -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(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', diff --git a/packages/core/tests/highway/ptt-upload.test.ts b/packages/core/tests/highway/ptt-upload.test.ts index 2162e0ed..94e0b6be 100644 --- a/packages/core/tests/highway/ptt-upload.test.ts +++ b/packages/core/tests/highway/ptt-upload.test.ts @@ -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', }); diff --git a/packages/onebot/src/media-indexer.ts b/packages/onebot/src/media-indexer.ts index d80664e9..3260eb46 100644 --- a/packages/onebot/src/media-indexer.ts +++ b/packages/onebot/src/media-indexer.ts @@ -52,6 +52,7 @@ export class MediaIndexer { md5Hex: element.md5Hex, sha1Hex: element.sha1Hex, voiceFormat: element.voiceFormat, + isNtv2: element.isNtv2, }); return; } diff --git a/packages/onebot/src/media-store.ts b/packages/onebot/src/media-store.ts index ff83777e..0f32c686 100644 --- a/packages/onebot/src/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -35,6 +35,7 @@ export interface CachedRecord { md5Hex?: string; sha1Hex?: string; voiceFormat?: number; + isNtv2?: boolean; } export interface CachedVideo { diff --git a/packages/onebot/src/message-media.ts b/packages/onebot/src/message-media.ts index cc45959c..c75b1729 100644 --- a/packages/onebot/src/message-media.ts +++ b/packages/onebot/src/message-media.ts @@ -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 bridge.apis.extras.translatePttToText({ isGroup, + isNtv2, + storeRegion, msgId: messageId, senderUin, peerUin, diff --git a/packages/onebot/tests/instance-context.test.ts b/packages/onebot/tests/instance-context.test.ts index e1ff7877..c22cd8b9 100644 --- a/packages/onebot/tests/instance-context.test.ts +++ b/packages/onebot/tests/instance-context.test.ts @@ -1141,6 +1141,8 @@ describe('buildApiContext media', () => { duration: 2, size: 16, format: 1, + isNtv2: false, + storeRegion: 0, }); }); diff --git a/packages/onebot/tests/media-actions-more.test.ts b/packages/onebot/tests/media-actions-more.test.ts index 6fa7b3dc..7af222b1 100644 --- a/packages/onebot/tests/media-actions-more.test.ts +++ b/packages/onebot/tests/media-actions-more.test.ts @@ -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, }); }); diff --git a/packages/onebot/tests/ptt-transcription.test.ts b/packages/onebot/tests/ptt-transcription.test.ts new file mode 100644 index 00000000..ae504d0f --- /dev/null +++ b/packages/onebot/tests/ptt-transcription.test.ts @@ -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> = []; + +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({ + 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(protobuf_encode(body)), + isGroup, + ); + expect(elements).toHaveLength(1); + return elements; +} + +async function saveVoice( + stores: Awaited>, + isGroup: boolean, + elements: ReturnType, + 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( + 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>, + 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(bytes); + expect(routing.isNtv2 ?? 0).toBe(ntv2 ? 1 : 0); + expect(routing.storeRegion ?? 0).toBe(storeRegion); + const request = protobuf_decode(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); + }); +}); diff --git a/packages/proto-defs/src/ptt-trans.ts b/packages/proto-defs/src/ptt-trans.ts index 9c7eca1e..d797c9e0 100644 --- a/packages/proto-defs/src/ptt-trans.ts +++ b/packages/proto-defs/src/ptt-trans.ts @@ -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. */ diff --git a/packages/protocol/src/element-manifest.ts b/packages/protocol/src/element-manifest.ts index 0c66901c..11b2822a 100644 --- a/packages/protocol/src/element-manifest.ts +++ b/packages/protocol/src/element-manifest.ts @@ -215,6 +215,7 @@ export const ELEMENT_MANIFEST = { 'md5Hex', 'sha1Hex', 'voiceFormat', + 'isNtv2', 'noByteFallback', 'mediaNode', ]), @@ -353,7 +354,7 @@ const NUMBER_FIELDS: ReadonlySet = new Set([ 'videoFormat', 'voiceFormat', ]); -const BOOLEAN_FIELDS: ReadonlySet = new Set(['flash', 'noByteFallback', 'large']); +const BOOLEAN_FIELDS: ReadonlySet = new Set(['flash', 'noByteFallback', 'large', 'isNtv2']); function throwValidation( code: MessageElementValidationCode, diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index b0706d17..16944f29 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -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; } diff --git a/packages/protocol/src/highway/ptt-upload.ts b/packages/protocol/src/highway/ptt-upload.ts index 50147f69..4b29428e 100644 --- a/packages/protocol/src/highway/ptt-upload.ts +++ b/packages/protocol/src/highway/ptt-upload.ts @@ -310,6 +310,7 @@ export async function uploadPtt( fileName: ptt.fileName, duration: ptt.duration, voiceFormat: ptt.voiceFormat, + isNtv2: true, fileId: mediaNode?.fileUuid, mediaNode, }); diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 605e8e99..04e6c45b 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -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'); diff --git a/packages/protocol/tests/element-manifest.test.ts b/packages/protocol/tests/element-manifest.test.ts index fc92d9a1..655cda14 100644 --- a/packages/protocol/tests/element-manifest.test.ts +++ b/packages/protocol/tests/element-manifest.test.ts @@ -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; }