Files
SnowLuma/packages/bridge/src/msg-push/rich-body-decoder.ts
T
DrSmoothl f7a03ca05a refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files —
events / event-bus / identity-service / packet-pipeline / element-
builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* +
the bridge-side formatters — out of `packages/core/src/bridge/`
into the new `@snowluma/bridge` workspace package. Everything that
translates QQ wire bytes ↔ typed events/elements now lives there.

Why
---
- `packages/core/src/bridge/` was actually two layers: a low-level
  "protocol decoder + I/O" set (msg-push, highway, packet-pipeline,
  identity, element-builder) AND the Api-class host (bridge.ts +
  apis/*). The Api layer can't move without the protocol layer
  moving first, but the two had grown into one directory.
- Bridge-internal consumers (highway uploaders, OIDB envelope
  helper, element-builder, msg-push parsers) only ever needed
  `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata
  cache. Splitting them out lets that minimal surface live in the
  bridge package as `BridgeContext` while the api-layer's extended
  context (with `apis: ApiHub`) stays in @snowluma/core.

What stays in @snowluma/core (apis layer):
  - bridge.ts          ── the god-class that composes the protocol
                          building blocks + mounts apis
  - bridge-interface.ts ── public façade for OneBot consumers
  - manager.ts          ── per-uin BridgeManager hub
  - apis/*              ── the 13 typed Api classes
  - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim
                              BridgeContext with `apis: ApiHub` so
                              the 13 Api classes keep their typed
                              `this.ctx.apis.X.method()` access.

Layout
------
Moved via `git mv` (history preserved):
  events / event-bus / identity-service / packet-pipeline /
  element-builder / bridge-oidb / qq-info / msg-push/* /
  highway/* / web/*           → @snowluma/bridge/<sub>
  utils/event-format.ts        → @snowluma/bridge/format.ts

  (the last one renamed because the destination directory only has
  bridge-related files; `format.ts` reads cleaner than `event-format`.
  Listed as a rename in git's `RM` output — content unchanged.)

Layering fixes (functionality preserved, just type signatures)
--------------------------------------------------------------
- `element-builder.SendContext.bridge` → typed as `BridgeContext`
  instead of `Bridge`. Reads only `bridge.identity` and the
  upload-cache (both on BridgeContext); the concrete `Bridge`
  instance still passes via free upcast.
- `bridge-oidb.runOidb` signature widened from `Bridge` to
  `BridgeContext` — same reason.
- `highway/{highway-client,pipeline,image-upload,ptt-upload,
  video-upload}.ts` — same.
- `format.ts::formatReply` parameter typed as a new local
  `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject |
  null }`) instead of `MessageStore` from @snowluma/onebot. The
  OneBot `MessageStore` is a structural superset; consumers pass
  it through unchanged.
- JSON value types moved to a new `@snowluma/common/json` subpath
  (consumed by format.ts) — `onebot/types.ts` re-exports them so
  external `import { JsonValue } from '<…>/onebot/types'` paths
  keep working.
- `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts`
  into `@snowluma/bridge/bridge-context.ts` — element-builder + the
  forward-builder both read the upload cache through BridgeContext,
  so the type has to live in @snowluma/bridge. `bridge.ts` keeps
  its re-export for back-compat.

Changes
-------
- New package `packages/bridge/` (package.json with per-file subpath
  exports mirroring legacy `core/src/bridge/<x>` layout 1:1,
  tsconfig.json, typecheck script).
- 35 `.ts` files moved via `git mv` (3 files counted by git as
  RM — rename + modify because Bridge → BridgeContext type swap).
- 150+ import sites rewritten across `packages/core/src` and
  `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`,
  `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest
  `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`.
- `@snowluma/core` depends on `@snowluma/bridge` (workspace:*).
- `@snowluma/bridge` depends on `@snowluma/common`,
  `@snowluma/proto-defs`, `@snowluma/proton`.
- `packages/core/src/utils/` directory removed (empty).

Verification
------------
- Full workspace `pnpm -r typecheck`: all 10 projects clean.
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same
  baseline as the previous refactor commits).
- Vite build (with stubbed native binary): clean — 143 modules,
  2.84 MB bundle / 224 KB gzip, identical envelope to the
  pre-split build.

Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The
runnable `index.ts` stays in @snowluma/core as the application
entry, importing `OneBotManager` from `@snowluma/onebot`.
2026-05-21 08:41:34 +08:00

453 lines
15 KiB
TypeScript

import { protobuf_decode } from '@snowluma/proton';
import { toHexUpper } from '@snowluma/common/hex';
import type { MessageElement } from '../events';
import type {
Elem,
GroupFileExtra,
MentionExtra,
MsgInfo,
NotOnlineImage,
QFaceExtra,
QSmallFaceExtra,
} from '@snowluma/proto-defs/element';
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
import { decompressData, makeImageUrl } from './helpers';
type ElemDecoded = Elem;
type RichTextDecoded = RichText;
export type PushMsgBody = MessageBody;
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
if (body?.richText) {
const rt = body.richText;
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
extractRichtextExtras(rt, elements, isGroup);
}
if (body?.msgContent && body.msgContent.length > 0) {
extractMsgContent(body.msgContent, elements);
}
return elements;
}
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
let skipNext = false;
for (const elem of elems) {
if (skipNext) { skipNext = false; continue; }
// Reply / quote
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
}
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: MentionExtra | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
mention = protobuf_decode<MentionExtra>(t.pbReserve);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
if (hasAttr6 || hasMention) {
const me: MessageElement = { type: 'at', text: t.str ?? '' };
if (hasAttr6) {
const buf = t.attr6Buf!;
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
}
result.push(me);
} else {
const text = t.str ?? '';
if (text) result.push({ type: 'text', text });
}
}
// Face
if (elem.face) {
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
}
// MarketFace
if (elem.marketFace) {
result.push({
type: 'mface',
text: elem.marketFace.faceName ?? '',
faceId: elem.marketFace.tabId ?? 0,
subType: elem.marketFace.subType ?? 0,
});
}
// NotOnlineImage (C2C image)
if (elem.notOnlineImage) {
const img = elem.notOnlineImage;
if (img.picMd5 && img.picMd5.length > 0) {
const urlPath = img.origUrl || img.bigUrl || '';
result.push({
type: 'image',
imageUrl: makeImageUrl(urlPath),
fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0,
width: img.picWidth ?? 0,
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: toHexUpper(img.picMd5),
});
}
}
// CustomFace (group image)
if (elem.customFace) {
const img = elem.customFace;
if (img.md5 && img.md5.length > 0) {
result.push({
type: 'image',
imageUrl: makeImageUrl(img.origUrl ?? ''),
fileId: img.filePath ?? '',
fileSize: img.size ?? 0,
width: img.width ?? 0,
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: toHexUpper(img.md5),
});
}
}
// VideoFile
if (elem.videoFile) {
const v = elem.videoFile;
result.push({
type: 'video',
fileId: v.fileUuid ?? '',
fileName: v.fileName ?? '',
fileSize: v.fileSize ?? 0,
duration: v.fileTime ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
mediaNode: {
fileUuid: v.fileUuid ?? '',
info: {
fileSize: v.fileSize ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
fileName: v.fileName ?? '',
width: v.fileWidth ?? 0,
height: v.fileHeight ?? 0,
time: v.fileTime ?? 0,
type: {
type: 2,
videoFormat: v.fileFormat ?? 0,
},
},
},
});
}
// GroupFile
if (elem.groupFile) {
const f = elem.groupFile;
result.push({
type: 'file',
fileId: f.fileId ?? '',
fileName: f.filename ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
});
}
// TransElem type=24 (group file via transport)
if (elem.transElem) {
const te = elem.transElem;
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
const extra = protobuf_decode<GroupFileExtra>(val.subarray(3, 3 + len));
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
type: 'file',
fileName: info.fileName ?? '',
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
fileId: info.fileId ?? '',
});
}
}
}
}
// RichMsg
if (elem.richMsg) {
const rm = elem.richMsg;
if (rm.template1 && rm.template1.length > 0) {
const content = decompressData(rm.template1);
if (content) {
const svcId = rm.serviceId ?? 0;
if (svcId === 35) {
const pos = content.indexOf('m_resid="');
if (pos !== -1) {
const start = pos + 9;
const end = content.indexOf('"', start);
if (end !== -1) {
result.push({ type: 'forward', resId: content.substring(start, end) });
continue;
}
}
result.push({ type: 'xml', text: content, subType: svcId });
} else if (svcId === 1) {
result.push({ type: 'json', text: content });
} else {
result.push({ type: 'xml', text: content, subType: svcId });
}
}
}
}
// LightApp
if (elem.lightApp) {
const la = elem.lightApp;
if (la.data && la.data.length > 0) {
const content = decompressData(la.data);
if (content) result.push({ type: 'json', text: content });
}
}
// CommonElem
if (elem.commonElem) {
const ce = elem.commonElem;
const svcType = ce.serviceType ?? 0;
const bizType = ce.businessType ?? 0;
if (svcType === 2) {
// Poke
result.push({ type: 'poke', subType: bizType });
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
// Flash image
const pb = ce.pbElem;
let pos = 1;
let length = 0, shift = 0;
while (pos < pb.length) {
const b = pb[pos++];
length |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
const img = protobuf_decode<NotOnlineImage>(pb.subarray(pos, pos + length));
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
};
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
if (img.picMd5 && img.picMd5.length > 0) {
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + toHexUpper(img.picMd5) + '/0';
}
result.push(me);
}
}
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
const info = protobuf_decode<MsgInfo>(ce.pbElem);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
const idx = body.index;
const fi = idx.info!;
if (bizType === 10 || bizType === 20) {
// Image
let url = '';
if (body.picture) {
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
const path = body.picture.urlPath ?? '';
if (path) {
url = 'https://' + domain + path;
if (body.picture.ext?.originalParameter) {
url += body.picture.ext.originalParameter;
}
}
}
const me: MessageElement = {
type: 'image', fileId: fi.fileName ?? '',
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
height: fi.height ?? 0, imageUrl: url,
};
if (fi.fileHash) me.md5Hex = fi.fileHash;
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
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 || '[image]';
}
result.push(me);
} else if (bizType === 12 || bizType === 22) {
// Record
result.push({
type: 'record', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
voiceFormat: fi.type?.voiceFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
} else if (bizType === 11 || bizType === 21) {
// Video
result.push({
type: 'video', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
width: fi.width ?? 0,
height: fi.height ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
videoFormat: fi.type?.videoFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
}
}
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
const extra = protobuf_decode<QSmallFaceExtra>(ce.pbElem);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
const extra = protobuf_decode<QFaceExtra>(ce.pbElem);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
}
}
return result;
}
function extractRichtextExtras(
rt: RichTextDecoded,
elements: MessageElement[],
isGroup = false
): void {
// Ptt (voice)
if (rt.ptt) {
const p = rt.ptt;
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '';
const me: MessageElement = {
type: 'record', fileName: p.fileName ?? '',
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
fileHash: md5Hex,
md5Hex,
voiceFormat: p.format ?? 0,
};
if (isGroup && (p.fileId ?? 0n) !== 0n) {
me.fileId = p.groupFileKey ?? '';
} else {
if (p.fileUuid && p.fileUuid.length > 0) {
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
}
}
me.mediaNode = {
fileUuid: me.fileId ?? '',
info: {
fileSize: p.fileSize ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '',
fileName: p.fileName ?? '',
time: p.time ?? 0,
type: {
type: 3,
voiceFormat: p.format ?? 0,
},
},
};
elements.push(me);
}
// NotOnlineFile (C2C file)
if (rt.notOnlineFile) {
const f = rt.notOnlineFile;
elements.push({
type: 'file', fileId: f.fileUuid ?? '',
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
// `MessageBody.msgContent` is where the QQ-NT server actually puts
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
// shape — every field landed at the wrong tag, so the four-field
// truthiness check below filtered out every real c2c file push as
// "incomplete metadata". After consolidating FileExtra to wrap
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
// this reads the right tags.
const extra = protobuf_decode<FileExtra>(msgContent);
if (!extra?.file) return;
const f = extra.file;
if (!f.fileUuid) return;
elements.push({
type: 'file',
fileId: f.fileUuid,
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}