diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index f023b670..edf7d0ab 100644 --- a/packages/onebot/src/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -127,12 +127,27 @@ async function elementToSegment( } if (element.type === 'mface') { + // Unify market faces (商城表情) to an `image` segment so OneBot clients + // that don't special-case `mface` still render the sticker, while the + // `emoji_id`/`emoji_package_id`/`key` markers let aware clients (and our + // own send path) reproduce it as a real market face. Mirrors NapCat's + // marketFaceElement → image conversion. The gxh URL is a self-contained + // external link (no rkey), so we set it directly and skip mediaSegmentSink. + const emojiId = element.emojiId ?? ''; + const dir = emojiId.slice(0, 2); + const url = emojiId + ? `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif` + : ''; return { - type: 'mface', + type: 'image', data: { - name: element.text ?? '', - tab_id: element.faceId ?? 0, - sub_type: element.subType ?? 0, + file: emojiId ? `${dir}-${emojiId}.gif` : '', + url, + summary: element.text ?? '', + sub_type: 0, + emoji_id: emojiId, + emoji_package_id: element.emojiPackageId ?? 0, + key: element.emojiKey ?? '', }, }; } diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 9ddaa897..627f98d7 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -23,6 +23,20 @@ function intOr(value: unknown, fallback = 0): number { return Number.isFinite(n) ? n : fallback; } +/** Build a market-face (`mface`) element from an OneBot segment's data. + * Shared by the dedicated `mface` segment and the `image`-with-`emoji_id` + * round-trip path. `emojiId` is the hex GUID the wire builder converts back + * to `MarketFace.faceId`. */ +function marketFaceElement(emojiId: string, data: Record): MessageElement { + return { + type: 'mface', + text: String(data.summary ?? data.name ?? ''), + emojiId, + emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0), + emojiKey: String(data.key ?? ''), + }; +} + export function parseCQParams(raw: string): Record { const params: Record = {}; if (!raw) return params; @@ -114,6 +128,11 @@ export async function segmentToElement(type: string, data: Record 0 ? { type: 'reply', replySeq: id } : null; } case 'image': { + // A market face that was surfaced as an `image` (see to-segment) can be + // echoed straight back: when `emoji_id` is present we rebuild the market + // face instead of re-uploading the gif as a plain picture. + const imgEmojiId = String(data.emoji_id ?? '').trim(); + if (imgEmojiId) return marketFaceElement(imgEmojiId, data); return { type: 'image', url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''), @@ -122,6 +141,16 @@ export async function segmentToElement(type: string, data: Record { }); }); - it('mface: text + tab_id + sub_type', async () => { - const seg = await segment({ type: 'mface', text: 'sticker', faceId: 7, subType: 2 }); - expect(seg).toEqual({ type: 'mface', data: { name: 'sticker', tab_id: 7, sub_type: 2 } }); + it('mface: unified to an image segment carrying market-face markers', async () => { + const emojiId = '235a82d9c0acd2e2db6e0b94e1a1c4f3'; + const seg = await segment({ + type: 'mface', text: '可爱', emojiId, emojiPackageId: 12, emojiKey: 'abc', + }); + expect(seg).toEqual({ + type: 'image', + data: { + file: `23-${emojiId}.gif`, + url: `https://gxh.vip.qq.com/club/item/parcel/item/23/${emojiId}/raw300.gif`, + summary: '可爱', + sub_type: 0, + emoji_id: emojiId, + emoji_package_id: 12, + key: 'abc', + }, + }); }); it('poke: subType forwarded as data.type', async () => { diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 11f882ae..cbd80e1f 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -6,6 +6,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { parseMessage } from '../src/message-parser'; import { buildSendElems } from '@snowluma/protocol/element-builder'; import type { MentionExtraSend } from '@snowluma/proto-defs/action'; +import type { MarketFacePbReserve } from '@snowluma/proto-defs/element'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; @@ -313,6 +314,72 @@ describe('parseMessage', () => { }); }); + describe('market face (mface)', () => { + const EMOJI_ID = '235a82d9c0acd2e2db6e0b94e1a1c4f3'; + + it('parses an mface segment into a market-face element', async () => { + const result = await parseMessage( + [{ type: 'mface', data: { emoji_id: EMOJI_ID, emoji_package_id: 12, key: 'abc', summary: '可爱' } }] as any, + false, + ); + expect(result).toEqual([{ + type: 'mface', text: '可爱', emojiId: EMOJI_ID, emojiPackageId: 12, emojiKey: 'abc', + }]); + }); + + it('round-trips an image-with-emoji_id back into a market face (not a re-uploaded picture)', async () => { + const result = await parseMessage( + [{ + type: 'image', + data: { + file: `23-${EMOJI_ID}.gif`, + url: `https://gxh.vip.qq.com/club/item/parcel/item/23/${EMOJI_ID}/raw300.gif`, + emoji_id: EMOJI_ID, emoji_package_id: 12, key: 'abc', summary: '可爱', + }, + }] as any, + false, + ); + expect(result).toEqual([{ + type: 'mface', text: '可爱', emojiId: EMOJI_ID, emojiPackageId: 12, emojiKey: 'abc', + }]); + }); + + it('leaves a plain image (no emoji_id) as an image element', async () => { + const result = await parseMessage( + [{ type: 'image', data: { file: 'https://example.com/a.png' } }] as any, + false, + ); + expect(result[0]!.type).toBe('image'); + expect((result[0] as any).emojiId).toBeUndefined(); + }); + + it('drops an mface segment without emoji_id', async () => { + const result = await parseMessage( + [{ type: 'mface', data: { emoji_package_id: 12, summary: 'x' } }] as any, + false, + ); + expect(result).toEqual([]); + }); + + it('builds the wire marketFace element (faceId = hex(emoji_id), NapCat constants)', async () => { + const elements = await parseMessage( + [{ type: 'mface', data: { emoji_id: EMOJI_ID, emoji_package_id: 12, key: 'abc', summary: '可爱' } }] as any, + false, + ); + const protoElems = await buildSendElems(elements); + expect(protoElems).toHaveLength(1); + const mf = protoElems[0]!.marketFace; + expect(mf).toBeDefined(); + expect(Buffer.from(mf!.faceId as Uint8Array).toString('hex')).toBe(EMOJI_ID); + expect(mf).toMatchObject({ + faceName: '可爱', itemType: 6, faceInfo: 1, tabId: 12, subType: 3, + key: 'abc', imageWidth: 300, imageHeight: 300, + }); + const reserve = protobuf_decode(mf!.pbReserve as Uint8Array); + expect(reserve).toMatchObject({ field8: 1 }); + }); + }); + describe('special segments', () => { it('parses json segment', async () => { const result = await parseMessage( diff --git a/packages/proto-defs/src/element.ts b/packages/proto-defs/src/element.ts index 07512392..108f61dc 100644 --- a/packages/proto-defs/src/element.ts +++ b/packages/proto-defs/src/element.ts @@ -85,6 +85,14 @@ export interface TransElem { elemValue?: pb<2, bytes>; } +// MarketFace.pbReserve(13) inner message. NapCat/Lagrange set field8=1 on +// send (marks the sticker as a "magic"/animated face). We encode it via +// protobuf_encode into the bytes field — same pattern as +// the mention pbReserve in element-builder.makeMentionElem. +export interface MarketFacePbReserve { + field8?: pb<8, uint_32>; +} + export interface MarketFace { faceName?: pb<1, string>; itemType?: pb<2, uint_32>; @@ -92,7 +100,10 @@ export interface MarketFace { faceId?: pb<4, bytes>; tabId?: pb<5, uint_32>; subType?: pb<6, uint_32>; - key?: pb<7, bytes>; + // `key` is a short ASCII token (e.g. "0"); Lagrange.Core and NapCat both + // type it as a string. Kept as string so it round-trips verbatim through + // the receive→`emoji_id` marker→re-send path without a bytes/utf8 hop. + key?: pb<7, string>; param?: pb<8, bytes>; mediaType?: pb<9, uint_32>; imageWidth?: pb<10, uint_32>; diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index 049b6422..d251084a 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -2,7 +2,7 @@ import type { MarkdownData, MentionExtraSend, } from '@snowluma/proto-defs/action'; -import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element'; +import type { Elem, GroupFileExtra, MarketFacePbReserve } from '@snowluma/proto-defs/element'; import { protobuf_encode } from '@snowluma/proton'; import { randomUUID } from 'crypto'; import { deflateSync } from 'zlib'; @@ -147,6 +147,34 @@ function makeMarkdownElem(element: MessageElement): ProtoElem { } +/** + * Build a market-face (商城表情) wire element from the markers carried on the + * receive-side `image` segment (`emoji_id`/`emoji_package_id`/`key`/summary). + * + * The constants (`itemType=6`, `faceInfo=1`, `subType=3`, 300×300, + * `pbReserve.field8=1`) mirror NapCat's `PacketMsgMarkFaceElement.buildElement` + * (`dev/NapCatQQ/.../packet/message/element.ts:318-335`) — the QQ-NT server + * pairs them with the faceId/tabId/key to relay the sticker. `faceId` is the + * raw GUID bytes, recovered from the hex `emojiId`. + */ +function makeMarketFaceElem(element: MessageElement): ProtoElem { + const emojiId = (element.emojiId ?? '').trim(); + return { + marketFace: { + faceName: element.text ?? '', + itemType: 6, + faceInfo: 1, + faceId: hexToBytes(emojiId), + tabId: element.emojiPackageId ?? 0, + subType: 3, + key: element.emojiKey ?? '', + imageWidth: 300, + imageHeight: 300, + pbReserve: protobuf_encode({ field8: 1 }), + }, + }; +} + function makeForwardElem(element: MessageElement): ProtoElem { const resId = (element.resId ?? '').trim(); if (!resId) { @@ -345,7 +373,7 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise /** * Build proto Elem objects from an array of MessageElements. - * Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward. + * Supports: text, face, mface, at, reply, json, xml, markdown, image, record, video, forward. * Image, record and video elements trigger NTV2 highway upload via the SendContext. */ export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise { @@ -361,6 +389,10 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId)); break; + case 'mface': + if (elem.emojiId) result.push(makeMarketFaceElem(elem)); + break; + case 'at': result.push(makeMentionElem(elem, ctx)); break; diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 948d8308..8edc06ba 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -21,6 +21,15 @@ export interface MessageElement { width?: number; height?: number; summary?: string; + // Market face (商城表情). Decoded from the wire `marketFace` element; the + // OneBot layer surfaces it as an `image` segment carrying these as markers, + // and the send path rebuilds the wire `marketFace` from them. + // emojiId = hex(MarketFace.faceId) → also builds the gxh gif URL + // emojiPackageId = MarketFace.tabId + // emojiKey = MarketFace.key + emojiId?: string; + emojiPackageId?: number; + emojiKey?: string; flash?: boolean; resId?: string; fileHash?: string; diff --git a/packages/protocol/src/format.ts b/packages/protocol/src/format.ts index b6bd1a6f..163ff015 100644 --- a/packages/protocol/src/format.ts +++ b/packages/protocol/src/format.ts @@ -89,7 +89,13 @@ export function formatMessageSegments(message: JsonValue): string { function renderSegment(type: string, data: Record): string { switch (type) { case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW); - case 'image': return '[图片]'; + // Market faces (商城表情) are surfaced as `image` segments carrying an + // `emoji_id` marker (+ `summary` = face name). Keep the sticker readable in + // previews instead of collapsing it to a generic "[图片]". + case 'image': + return data.emoji_id + ? (data.summary ? `[${String(data.summary)}]` : '[表情]') + : '[图片]'; case 'face': return '[表情]'; case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]'; case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`; diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 07fee1fe..f49d486e 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -1,5 +1,5 @@ import { protobuf_decode } from '@snowluma/proton'; -import { toHexUpper } from '@snowluma/common/hex'; +import { toHex, toHexUpper } from '@snowluma/common/hex'; import type { MessageElement } from '../events'; import type { Elem, @@ -74,13 +74,19 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { result.push({ type: 'face', faceId: elem.face.index ?? 0 }); } - // MarketFace + // MarketFace (商城表情). Keep the wire identity (`emojiId`/`tabId`/`key`) + // on the element; the OneBot layer unifies it to an `image` segment with + // these as markers (NapCat-compatible), and the send path rebuilds the + // wire `marketFace` from them. `emojiId` is the lowercase hex of the + // `faceId` GUID bytes — it also forms the gxh gif URL on the segment side. if (elem.marketFace) { + const mf = elem.marketFace; result.push({ type: 'mface', - text: elem.marketFace.faceName ?? '', - faceId: elem.marketFace.tabId ?? 0, - subType: elem.marketFace.subType ?? 0, + text: mf.faceName ?? '', + emojiId: mf.faceId && mf.faceId.length > 0 ? toHex(mf.faceId) : '', + emojiPackageId: mf.tabId ?? 0, + emojiKey: mf.key ?? '', }); } 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 da981409..78eb7361 100644 --- a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -10,7 +10,10 @@ import { describe, expect, it } from 'vitest'; import { deflateSync } from 'zlib'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { decodeRichBody } from '../../src/msg-push/rich-body-decoder'; +import { buildSendElems } from '../../src/element-builder'; +import type { MessageElement } from '../../src/events'; import type { MessageBody } from '@snowluma/proto-defs/message'; function lightAppBytes(json: unknown): Uint8Array { @@ -121,3 +124,42 @@ describe('decodeRichBody / forward LightApp', () => { expect(out[0]).toMatchObject({ type: 'forward', resId: 'legacy-res' }); }); }); + +// Market face (商城表情): decode the wire `marketFace` element into the +// `emoji_id`/`emoji_package_id`/`key` markers, and round-trip an mface element +// back through the real proton codegen (faceId hex bytes + pbReserve) so a +// sticker SnowLuma re-sends decodes identically on the receiver. +describe('decodeRichBody / market face', () => { + const EMOJI_ID = '235a82d9c0acd2e2db6e0b94e1a1c4f3'; + + it('decodes a wire marketFace into an mface element (emojiId = lowercase hex of faceId)', () => { + const body: MessageBody = { + richText: { + elems: [ + { + marketFace: { + faceName: '可爱', + faceId: Buffer.from(EMOJI_ID, 'hex'), + tabId: 12, + key: 'abc', + }, + } as any, + ], + }, + }; + const out = decodeRichBody(body, true); + expect(out).toEqual([{ + type: 'mface', text: '可爱', emojiId: EMOJI_ID, emojiPackageId: 12, emojiKey: 'abc', + }]); + }); + + it('round-trips an mface element → wire → element through real proton codegen', async () => { + const el: MessageElement = { + type: 'mface', text: '可爱', emojiId: EMOJI_ID, emojiPackageId: 12, emojiKey: 'abc', + }; + const elems = await buildSendElems([el]); + const wire = protobuf_encode({ richText: { elems: elems as any } }); + const decoded = protobuf_decode(wire); + expect(decodeRichBody(decoded, true)).toEqual([el]); + }); +});