diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 59da85b6..7bcb4ea7 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -27,6 +27,8 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])), })); +import { protobuf_encode } from '@snowluma/proton'; +import type { MsgInfo } from '@snowluma/proto-defs/element'; import { buildSendElems } from '@snowluma/protocol/element-builder'; import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload'; @@ -240,6 +242,47 @@ describe('element-builder / all-message validation preflight', () => { expect(uploadImageMsgInfo).not.toHaveBeenCalled(); }); + it('emits a customFace sibling for forwardFake group images (#441)', async () => { + const md5Hex = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + const msgInfo = protobuf_encode({ + msgInfoBody: [{ + index: { + fileUuid: 'EhRimg', + info: { + fileHash: md5Hex, + fileName: `${md5Hex}.png`, + fileSize: 12, + width: 10, + height: 10, + type: { picFormat: 1001 }, + }, + }, + }], + }); + vi.mocked(uploadImageMsgInfo).mockResolvedValueOnce(msgInfo); + + const elems = await buildSendElems( + [{ type: 'image', url: 'file:///tmp/a.png' }], + { bridge: fakeBridge, groupId: 12345, forwardFake: true, scene: 'forward' }, + ); + + expect(elems).toHaveLength(2); + expect(elems[0]!.commonElem).toBeDefined(); + expect(elems[1]!.customFace?.filePath).toBe(`${md5Hex}.png`); + expect(elems[1]!.customFace?.md5).toHaveLength(16); + }); + + it('does not emit a legacy sibling on a live group image send', async () => { + vi.mocked(uploadImageMsgInfo).mockResolvedValueOnce(new Uint8Array([7, 8, 9])); + const elems = await buildSendElems( + [{ type: 'image', url: 'file:///tmp/a.png' }], + { bridge: fakeBridge, groupId: 12345 }, + ); + expect(elems).toHaveLength(1); + expect(elems[0]!.commonElem).toBeDefined(); + expect(elems[0]!.customFace).toBeUndefined(); + }); + it('accepts a received imageUrl-only element for re-send', async () => { vi.mocked(uploadImageMsgInfo).mockClear(); await buildSendElems( diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts index f30a1f9f..d467cffd 100644 --- a/packages/onebot/src/event-converter/element-codecs.ts +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -259,7 +259,8 @@ export const ELEMENT_CODECS = { const url = ctx.imageUrlResolver ? await ctx.imageUrlResolver(element, ctx.isGroup) : (element.imageUrl ?? ''); const data: JsonObject = { url, - file: element.fileId ?? '', + file: element.fileId + || (element.md5Hex ? `${element.md5Hex.toLowerCase()}.png` : ''), sub_type: element.subType ?? 0, summary: element.summary ?? '', }; diff --git a/packages/proto-defs/src/message.ts b/packages/proto-defs/src/message.ts index b6c8cc94..01f8f082 100644 --- a/packages/proto-defs/src/message.ts +++ b/packages/proto-defs/src/message.ts @@ -74,15 +74,17 @@ export interface Ptt { // 1. 发送端必填:字段 9/50/55(subcmd=1, dangerEvel=0, expireTime=当前时间+7天)。 // 2. 接收端只读:核心标识槽位(Uuid/Md5/Name/Size/Hash)。 export interface NotOnlineFile { - fileType?: pb<1, uint_32>; - fileUuid?: pb<3, string>; - fileMd5?: pb<4, bytes>; - fileName?: pb<5, string>; - fileSize?: pb<6, uint_64>; - subcmd?: pb<9, uint_32>; // 发送必填:固定为 1 - dangerEvel?: pb<50, uint_32>; // 发送必填:固定为 0 - expireTime?: pb<55, uint_32>; // 发送必填:过期时间戳(now + 7 days) - fileHash?: pb<57, string>; + fileType?: pb<1, uint_32>; + fileUuid?: pb<3, string>; + fileMd5?: pb<4, bytes>; + fileName?: pb<5, string>; + fileSize?: pb<6, uint_64>; + subcmd?: pb<9, uint_32>; // 发送必填:固定为 1 + downloadFlag?: pb<12, uint_32>; // 2 = 对方已下载的回执,不是一条新文件消息 + dangerEvel?: pb<50, uint_32>; // 发送必填:固定为 0 + expireTime?: pb<55, uint_32>; // 发送必填:过期时间戳(now + 7 days) + pbReserve?: pb<56, bytes>; + fileHash?: pb<57, string>; } // RichText diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index b9fe0c0e..690c1a16 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -2,8 +2,8 @@ import type { MarkdownData, MentionExtraSend, } from '@snowluma/proto-defs/action'; -import type { Elem, GroupFileExtra, MarketFacePbReserve, PokeExtra, QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element'; -import { protobuf_encode } from '@snowluma/proton'; +import type { Elem, GroupFileExtra, MarketFacePbReserve, MsgInfo, PokeExtra, QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { randomUUID } from 'crypto'; import { deflateSync } from 'zlib'; import type { BridgeContext } from './bridge-context'; @@ -316,7 +316,69 @@ function makeForwardElem(element: MessageElement): ProtoElem { }; } -async function makeImageElem(ctx: SendContext, element: MessageElement): Promise { +function md5BytesFromHex(hex: string | undefined): Uint8Array | null { + if (!hex || !/^[0-9a-fA-F]{32}$/.test(hex)) return null; + const bytes = hexToBytes(hex); + return bytes.length === 16 ? bytes : null; +} + +function fingerprintsFromEncodedMsgInfo(msgInfo: Uint8Array): { + md5Hex: string; + fileName: string; + fileSize: number; + width: number; + height: number; +} | null { + let info: MsgInfo; + try { + info = protobuf_decode(msgInfo); + } catch { + return null; + } + const fi = info.msgInfoBody?.[0]?.index?.info; + if (!fi?.fileHash || !/^[0-9a-fA-F]{32}$/.test(fi.fileHash)) return null; + return { + md5Hex: fi.fileHash, + fileName: fi.fileName || `${fi.fileHash.toLowerCase()}.png`, + fileSize: fi.fileSize ?? 0, + width: fi.width ?? 0, + height: fi.height ?? 0, + }; +} + +/** + * Long-msg storage often strips NT image download paths. A CustomFace / + * NotOnlineImage sibling with the md5 lets get_forward_msg rebuild a + * fetchable URL the way native forwards do (#441). + */ +function makeLegacyForwardImageElem( + isGroup: boolean, + msgInfo: Uint8Array, + element: MessageElement, +): ProtoElem | null { + const fromInfo = fingerprintsFromEncodedMsgInfo(msgInfo); + const md5 = md5BytesFromHex(element.md5Hex) ?? md5BytesFromHex(fromInfo?.md5Hex); + if (!md5) return null; + const md5Hex = (element.md5Hex || fromInfo!.md5Hex); + const fileName = element.fileName || fromInfo?.fileName || `${md5Hex.toLowerCase()}.png`; + const fileSize = element.fileSize ?? fromInfo?.fileSize ?? 0; + const width = element.width ?? fromInfo?.width ?? 0; + const height = element.height ?? fromInfo?.height ?? 0; + if (isGroup) { + return { customFace: { filePath: fileName, md5, size: fileSize, width, height } }; + } + return { + notOnlineImage: { + filePath: fileName, + picMd5: md5, + fileLen: fileSize, + picWidth: width, + picHeight: height, + }, + }; +} + +async function makeImageElem(ctx: SendContext, element: MessageElement): Promise { const isGroup = ctx.groupId !== undefined; const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? ''); if (!isGroup && !targetIdOrUid) { @@ -324,14 +386,16 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise } const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element); - - return { + const nt: ProtoElem = { commonElem: { serviceType: 48, pbElem: msgInfo, businessType: isGroup ? 20 : 10, }, }; + if (!ctx.forwardFake) return [nt]; + const legacy = makeLegacyForwardImageElem(isGroup, msgInfo, element); + return legacy ? [nt, legacy] : [nt]; } async function makePttElem(ctx: SendContext, element: MessageElement): Promise { @@ -539,7 +603,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'image': - result.push(await makeImageElem(ctx!, elem)); + result.push(...await makeImageElem(ctx!, elem)); break; case 'forward': diff --git a/packages/protocol/src/msg-push/blank-filter.ts b/packages/protocol/src/msg-push/blank-filter.ts index f58e1beb..150e4aea 100644 --- a/packages/protocol/src/msg-push/blank-filter.ts +++ b/packages/protocol/src/msg-push/blank-filter.ts @@ -2,7 +2,7 @@ import { hexPreview } from '@snowluma/common/hex'; import { createLogger } from '@snowluma/common/logger'; import type { Elem } from '@snowluma/proto-defs/element'; import type { MsgPushHead, PushMsgBody } from './context'; -import { hasDecodableContent } from './rich-body-decoder'; +import { hasDecodableContent, isOfflineFileReceipt } from './rich-body-decoder'; const log = createLogger('MsgPush'); @@ -18,7 +18,7 @@ const C2C_CONTROL_TYPES = new Set([141, 166, 167]); // phantom (#102) is one of them. const C2C_CONTROL_CMDS = new Set([1, 73, 75, 129, 131, 133, 135, 192]); -export type MessageSurvival = 'drop-control' | 'drop-blank' | 'keep-undecoded' | 'keep'; +export type MessageSurvival = 'drop-control' | 'drop-receipt' | 'drop-blank' | 'keep-undecoded' | 'keep'; /** * Whether a push is a C2C control/system signal that QQ NT never renders as a @@ -55,6 +55,7 @@ export function classifyMessageSurvival( body: PushMsgBody | undefined, ): MessageSurvival { if (isC2cControlPush(head)) return 'drop-control'; + if (isOfflineFileReceipt(body)) return 'drop-receipt'; if (elements.length !== 0) return 'keep'; if (hasDecodableContent(body)) return 'keep-undecoded'; return 'drop-blank'; @@ -90,7 +91,7 @@ export function keepDecodedMessage( fromUin: number, ): boolean { const survival = classifyMessageSurvival(head, elements, body); - if (survival === 'drop-control' || survival === 'drop-blank') return false; + if (survival === 'drop-control' || survival === 'drop-receipt' || survival === 'drop-blank') return false; if (survival === 'keep-undecoded') { warnUndecodedMessage({ kind, diff --git a/packages/protocol/src/msg-push/index.ts b/packages/protocol/src/msg-push/index.ts index 70538a08..c32954c0 100644 --- a/packages/protocol/src/msg-push/index.ts +++ b/packages/protocol/src/msg-push/index.ts @@ -179,6 +179,21 @@ function parseMsgPushInternal( } return false; } + if (survival === 'drop-receipt') { + log.trace(() => [ + 'packet_branch serviceCmd=%j seqId=%d branch=offline_file_receipt msgType=%d subType=%d messageSeq=%d', + pkt.serviceCmd, + pkt.seqId, + ctx.head.msgType, + ctx.head.subType, + ctx.head.sequence, + ]); + log.debug( + 'dropped offline file receipt (kind=%s seq=%d from=%d msgType=%d)', + ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, + ); + return false; + } if (survival === 'drop-blank') { log.trace(() => [ 'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d', diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 37a67c8f..759f5f8a 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -854,7 +854,7 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement } } } - const fileId = fi.fileName || idx.fileUuid || ''; + let fileId = fi.fileName || idx.fileUuid || ''; if (!url && idx.fileUuid) url = ntImageUrlFromFileId(idx.fileUuid, isGroup); const me: MessageElement = { type: 'image', fileId, @@ -862,13 +862,21 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement height: fi.height ?? 0, imageUrl: url, }; assignValidFingerprints(me, fi.fileHash, fi.fileSha1, 'commonElem image'); + if (!fileId && me.md5Hex) fileId = `${me.md5Hex.toLowerCase()}.png`; + if (!url && me.md5Hex) url = imageUrlFromMd5(me.md5Hex); + me.fileId = fileId; + me.imageUrl = url; if (fi.type?.picFormat) me.picFormat = fi.type.picFormat; if (info.extBizInfo?.pic) { me.subType = info.extBizInfo.pic.bizType ?? 0; me.summary = info.extBizInfo.pic.textSummary || (me.subType === 1 ? '[动画表情]' : '[图片]'); } - result.push(me); + // Long-msg fetch of a bot-built forward can leave a stub NT + // image (format only, no id/url/md5). Do not emit that hollow + // bubble — it would also suppress the customFace sibling that + // still carries a usable md5 (#441). + if (hasUsableImageIdentity(me)) result.push(me); } else if (bizType === 12 || bizType === 22) { // Record const record: MessageElementOf<'record'> = { @@ -960,8 +968,15 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement return dropLegacyImageSiblings(result); } -function isNtImage(element: MessageElement): boolean { +function hasUsableImageIdentity(element: MessageElement): boolean { if (element.type !== 'image') return false; + if (element.fileId) return true; + if (element.md5Hex && /^[0-9a-fA-F]{32}$/.test(element.md5Hex)) return true; + return isUsableImageUrl(element.imageUrl ?? ''); +} + +function isNtImage(element: MessageElement): boolean { + if (!hasUsableImageIdentity(element)) return false; if (element.picFormat != null || element.sha1Hex) return true; const url = element.imageUrl ?? ''; return url.includes('://multimedia.nt.qq.com.cn/'); @@ -1185,7 +1200,7 @@ function extractRichtextExtras( } // NotOnlineFile (C2C file) - if (rt.notOnlineFile) { + if (rt.notOnlineFile && !isOfflineFileReceiptFlag(rt.notOnlineFile.downloadFlag)) { const f = rt.notOnlineFile; elements.push({ type: 'file', fileId: f.fileUuid ?? '', @@ -1213,6 +1228,7 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): ); if (!extra?.file) return; const f = extra.file; + if (isOfflineFileReceiptFlag(f.downloadFlag)) return; if (!f.fileUuid) return; elements.push({ type: 'file', @@ -1222,3 +1238,20 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): fileHash: f.fileHash ?? '', }); } + +/** QQ treats downloadFlag=2 as an offline-file receipt gray tip, not a chat bubble. */ +function isOfflineFileReceiptFlag(flag: number | undefined): boolean { + return flag === 2; +} + +/** True when this body is an offline-file download receipt, not a new file message. */ +export function isOfflineFileReceipt(body: PushMsgBody | undefined): boolean { + if (isOfflineFileReceiptFlag(body?.richText?.notOnlineFile?.downloadFlag)) return true; + if (!body?.msgContent || body.msgContent.length === 0) return false; + const extra = decodeProtobufPayload( + 'messageBody.msgContent', + body.msgContent, + () => protobuf_decode(body.msgContent!), + ); + return isOfflineFileReceiptFlag(extra?.file?.downloadFlag); +} diff --git a/packages/protocol/tests/msg-push/blank-filter.test.ts b/packages/protocol/tests/msg-push/blank-filter.test.ts index ec700fc9..2ae66b22 100644 --- a/packages/protocol/tests/msg-push/blank-filter.test.ts +++ b/packages/protocol/tests/msg-push/blank-filter.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { FileExtra } from '@snowluma/proto-defs/message'; import { classifyMessageSurvival, isBlankMessage, @@ -34,4 +36,19 @@ describe('classifyMessageSurvival', () => { richText: { elems: [{ text: { str: 'hi' } }] }, })).toBe('keep'); }); + + it('drops an offline-file download receipt even if a file element decoded (#442)', () => { + const body = { + msgContent: protobuf_encode({ + file: { + fileUuid: 'fid-sent-by-bot', + fileName: 'doc.bin', + fileSize: 6119608n, + subcmd: 1, + downloadFlag: 2, + }, + }), + }; + expect(classifyMessageSurvival(privateHead, [{ type: 'file' }], body)).toBe('drop-receipt'); + }); }); diff --git a/packages/protocol/tests/msg-push/empty-message-drop.test.ts b/packages/protocol/tests/msg-push/empty-message-drop.test.ts index 3ee23c87..79ca4cd9 100644 --- a/packages/protocol/tests/msg-push/empty-message-drop.test.ts +++ b/packages/protocol/tests/msg-push/empty-message-drop.test.ts @@ -13,7 +13,7 @@ import { } from '@snowluma/common/logger'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import { protobuf_encode } from '@snowluma/proton'; -import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; +import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; import { afterEach, describe, expect, it } from 'vitest'; import type { IdentityService } from '../../src/identity-service'; import { parseMsgPush } from '../../src/msg-push'; @@ -101,6 +101,46 @@ describe('parseMsgPush — empty message drop (#102)', () => { }); }); + it('drops an offline-file download receipt instead of a friend file message (#442)', () => { + const extra = protobuf_encode({ + file: { + fileUuid: 'fid-sent-by-bot', + fileName: 'doc.bin', + fileSize: 6119608n, + subcmd: 1, + downloadFlag: 2, + fileHash: 'abc', + }, + }); + const out = parseMsgPush(pushPacket({ + responseHead: { fromUin: 10001, fromUid: 'u_x' }, + contentHead: { msgType: 529, subType: 0, sequence: 1, timestamp: 1, msgId: 1 }, + body: { msgContent: extra }, + }), identity); + expect(out).toEqual([]); + }); + + it('keeps a real incoming c2c file (#442)', () => { + const extra = protobuf_encode({ + file: { + fileUuid: 'fid-from-user', + fileName: 'doc.bin', + fileSize: 10n, + subcmd: 1, + }, + }); + const out = parseMsgPush(pushPacket({ + responseHead: { fromUin: 10001, fromUid: 'u_x' }, + contentHead: { msgType: 529, subType: 0, sequence: 2, timestamp: 1, msgId: 2 }, + body: { msgContent: extra }, + }), identity); + expect(out).toHaveLength(1); + expect(out[0]).toMatchObject({ + kind: 'friend_message', + elements: [{ type: 'file', fileId: 'fid-from-user', fileName: 'doc.bin' }], + }); + }); + it('records the precise branch for a C2C control push with content', () => { // 166 + c2c_cmd ∈ {1,73,75,129,131,133,135,192} is a control/system signal // QQ NT routes via OnRecvSysMsg, never a bubble — drop regardless of body. diff --git a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts index 2b32555a..c68a61ef 100644 --- a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -1093,6 +1093,106 @@ describe('decodeRichBody / unknown wire element observability', () => { })]); }); + it('does not emit a hollow NT image that has only picFormat (#441)', () => { + const msgInfo: MsgInfo = { + msgInfoBody: [{ + index: { + info: { + type: { picFormat: 1001 }, + width: 1080, + height: 1080, + }, + }, + }], + extBizInfo: { pic: { bizType: 0, textSummary: '[图片]' } }, + }; + const out = decodeRichBody({ + richText: { + elems: [{ + commonElem: { + serviceType: 48, + businessType: 20, + pbElem: protobuf_encode(msgInfo), + }, + }], + }, + }, true); + expect(out).toEqual([]); + }); + + it('keeps the customFace sibling when the NT image is hollow (#441)', () => { + const hollow: MsgInfo = { + msgInfoBody: [{ + index: { info: { type: { picFormat: 1001 } } }, + }], + extBizInfo: { pic: { bizType: 0, textSummary: '[图片]' } }, + }; + const out = decodeRichBody({ + richText: { + elems: [ + { + commonElem: { + serviceType: 48, + businessType: 20, + pbElem: protobuf_encode(hollow), + }, + }, + customFaceElem(fileName, '', otherMd5), + ], + }, + }, true); + + expect(out).toEqual([{ + type: 'image', + imageUrl: 'http://gchat.qpic.cn/gchatpic_new/0/0-0-0102030405060708090A0B0C0D0E0F10/0', + fileId: fileName, + fileSize: 10711, + width: 1080, + height: 1080, + subType: 0, + summary: '[图片]', + md5Hex: '0102030405060708090A0B0C0D0E0F10', + }]); + }); + + it('rebuilds file id and url from fileHash when name and uuid are missing (#441)', () => { + const hash = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + const msgInfo: MsgInfo = { + msgInfoBody: [{ + index: { + info: { + fileHash: hash, + fileSha1: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + fileSize: 10711, + width: 1080, + height: 1080, + type: { picFormat: 1001 }, + }, + }, + }], + extBizInfo: { pic: { bizType: 0, textSummary: '[图片]' } }, + }; + const out = decodeRichBody({ + richText: { + elems: [{ + commonElem: { + serviceType: 48, + businessType: 20, + pbElem: protobuf_encode(msgInfo), + }, + }], + }, + }, true); + + expect(out).toEqual([expect.objectContaining({ + type: 'image', + fileId: `${hash}.png`, + imageUrl: `http://gchat.qpic.cn/gchatpic_new/0/0-0-${hash.toUpperCase()}/0`, + md5Hex: hash, + picFormat: 1001, + })]); + }); + it('keeps two distinct pictures', () => { const second = 'other.png'; const out = decodeRichBody({