refactor(packages): rename @snowluma/bridge → @snowluma/protocol
The package previously named "bridge" houses the protocol-byte layer (OIDB cmds, msg-push decoders, highway uploaders, element-builder, event bus). The name "bridge" suggested transport/lifecycle, which it isn't — that role lives in core/hook and core/bridge/manager. Rename to match what's actually inside. This is a pure rename: zero logic changes, all 73 import sites updated mechanically and TS-verified. core/onebot dependencies key updated. ESLint override path adjusted for the moved oidb-services directory. Rename detection threshold: git log --find-renames=20% recommended when following history across this commit — content-replacement (@snowluma/bridge → @snowluma/protocol) dropped per-file similarity below git's default 50% on import-heavy files.
This commit is contained in:
238 files changed
+247
-284
No files matched your search
@@ -0,0 +1,76 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
|
||||
|
||||
export type PushMsgBody = MessageBody;
|
||||
export type PushMsgResponseHead = ResponseHead;
|
||||
export type PushMsgContentHead = ContentHead;
|
||||
|
||||
export interface MsgPushHead {
|
||||
readonly msgType: number;
|
||||
readonly subType: number;
|
||||
readonly sequence: number;
|
||||
readonly timestamp: number;
|
||||
readonly msgId: number;
|
||||
}
|
||||
|
||||
export interface MsgPushContext {
|
||||
readonly head: MsgPushHead;
|
||||
readonly fromUin: number;
|
||||
readonly fromUid: string;
|
||||
readonly selfUin: number;
|
||||
readonly content: Uint8Array;
|
||||
readonly body: PushMsgBody | undefined;
|
||||
readonly responseHead: PushMsgResponseHead | undefined;
|
||||
readonly identity: IdentityService;
|
||||
}
|
||||
|
||||
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
|
||||
if (pkt.body.length === 0) return null;
|
||||
|
||||
// `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
|
||||
// @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
|
||||
// wrap was a no-op copy — Buffer is a Uint8Array subclass and
|
||||
// proton's decoder accepts the parent type directly. Dropping the
|
||||
// wrap saves one allocation per incoming push packet.
|
||||
const push = protobuf_decode<PushMsg>(pkt.body);
|
||||
if (!push?.message) return null;
|
||||
|
||||
const msg = push.message;
|
||||
if (!msg.contentHead) return null;
|
||||
|
||||
const head: MsgPushHead = {
|
||||
msgType: msg.contentHead.msgType ?? 0,
|
||||
subType: msg.contentHead.subType ?? 0,
|
||||
sequence: msg.contentHead.sequence ?? 0,
|
||||
timestamp: msg.contentHead.timestamp ?? 0,
|
||||
msgId: msg.contentHead.msgId ?? 0,
|
||||
};
|
||||
|
||||
let fromUin = 0;
|
||||
let fromUid = '';
|
||||
if (msg.responseHead) {
|
||||
fromUin = msg.responseHead.fromUin ?? 0;
|
||||
fromUid = msg.responseHead.fromUid ?? '';
|
||||
}
|
||||
|
||||
let selfUin = 0;
|
||||
if (pkt.uin) {
|
||||
const n = parseInt(pkt.uin, 10);
|
||||
if (!isNaN(n)) selfUin = n;
|
||||
}
|
||||
|
||||
const content = msg.body?.msgContent ?? new Uint8Array(0);
|
||||
|
||||
return {
|
||||
head,
|
||||
fromUin,
|
||||
fromUid,
|
||||
selfUin,
|
||||
content,
|
||||
body: msg.body,
|
||||
responseHead: msg.responseHead,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
FriendAddEvent,
|
||||
FriendPokeEvent,
|
||||
FriendRequestEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type {
|
||||
FriendRecall,
|
||||
FriendRequest,
|
||||
GeneralGrayTipInfo,
|
||||
NewFriend,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { MsgPushContext } from '../context';
|
||||
import { Event0x210SubType } from '../enums';
|
||||
import {
|
||||
buildTemplateMap, findTemplateValue,
|
||||
parseU64OrZero,
|
||||
resolveUidToUin,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x210SubType) {
|
||||
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
|
||||
// 138 (other-recalled) and 139 (self-recalled) share the same
|
||||
// FriendRecall wire shape; the helper picks the right uid side
|
||||
// based on the subType.
|
||||
case Event0x210SubType.FriendRecallNotice:
|
||||
case Event0x210SubType.FriendRecallSelfNotice:
|
||||
return decodeFriendRecall(ctx);
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
// 179 + 226 both carry the NewFriend payload — see enum comment.
|
||||
case Event0x210SubType.NewFriendNotice:
|
||||
case Event0x210SubType.NewFriendNoticeAlt:
|
||||
return decodeNewFriend(ctx);
|
||||
case Event0x210SubType.GroupAppStatePush:
|
||||
// QQ-client-internal troop shortcut bar / discussion app state
|
||||
// push — no OneBot-level event. See enum comment for the
|
||||
// decompiled-source breakdown of the sub_cmd dispatch.
|
||||
return [];
|
||||
case Event0x210SubType.UnmappedClientState380:
|
||||
// QQ-NT-era subType with no reference handler: the legacy QQ
|
||||
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
|
||||
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
|
||||
// an NT-era addition. None of the NT clients (Lagrange.Core,
|
||||
// LagrangeGo, lagrange-python, mania) handle it either. See the
|
||||
// enum comment for the full investigation; acknowledge silently
|
||||
// until someone maps the schema.
|
||||
return [];
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const request = protobuf_decode<FriendRequest>(ctx.content);
|
||||
if (!request?.info) return [];
|
||||
const sourceUid = request.info.newSource || request.info.sourceUid || '';
|
||||
const ev: FriendRequestEvent = {
|
||||
kind: 'friend_request',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin),
|
||||
fromUid: sourceUid,
|
||||
message: request.info.message ?? '',
|
||||
flag: sourceUid,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const recall = protobuf_decode<FriendRecall>(ctx.content);
|
||||
if (!recall?.info) return [];
|
||||
// 138 = friend recalled their own message sent to bot (peer = fromUid).
|
||||
// 139 = bot recalled own message sent to friend (peer = toUid). Same
|
||||
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
|
||||
// split, self-recall events surface `userUin` as the bot itself which
|
||||
// confuses downstream OneBot consumers that key off `user_id`.
|
||||
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
|
||||
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
|
||||
const ev: FriendRecallEvent = {
|
||||
kind: 'friend_recall',
|
||||
time: recall.info.time ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
|
||||
msgSeq: recall.info.clientSequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const nf = protobuf_decode<NewFriend>(ctx.content);
|
||||
if (!nf?.info) return [];
|
||||
const newFriendUid = nf.info.uid ?? '';
|
||||
const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin);
|
||||
if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot
|
||||
const ev: FriendAddEvent = {
|
||||
kind: 'friend_add',
|
||||
// proto field is `fixed32 Time` — already uint32 seconds epoch.
|
||||
// Fall back to head.timestamp if the field is missing (some
|
||||
// captures have it as 0).
|
||||
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: newFriendUin,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
|
||||
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: FriendPokeEvent = {
|
||||
kind: 'friend_poke',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
GroupEssenceEvent,
|
||||
GroupMsgEmojiLikeEvent,
|
||||
GroupMuteEvent,
|
||||
GroupPokeEvent,
|
||||
GroupRecallEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type {
|
||||
GroupMute,
|
||||
GroupReactNotify,
|
||||
NotifyMessageBody,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { MsgPushContext } from '../context';
|
||||
import { Event0x2DCSubType } from '../enums';
|
||||
import {
|
||||
buildTemplateMap, findTemplateValue,
|
||||
parseU64OrZero,
|
||||
resolveUidToUin,
|
||||
unwrapGroupNotifyPayload,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
|
||||
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
|
||||
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const mute = protobuf_decode<GroupMute>(ctx.content);
|
||||
if (!mute?.data?.state) return [];
|
||||
const duration = mute.data.state.duration ?? 0;
|
||||
const ev: GroupMuteEvent = {
|
||||
kind: 'group_mute',
|
||||
time: mute.data.timestamp ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: mute.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? '', ctx.fromUin),
|
||||
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
|
||||
const recalled = notify.recall.recallMessages[0];
|
||||
const ev: GroupRecallEvent = {
|
||||
kind: 'group_recall',
|
||||
time: recalled.time ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0,
|
||||
notify.recall.operatorUid || notify.operatorUid || '', ctx.fromUin),
|
||||
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? '', ctx.fromUin),
|
||||
msgSeq: recalled.sequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: GroupPokeEvent = {
|
||||
kind: 'group_poke',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.essenceMessage) return [];
|
||||
const essence = notify.essenceMessage;
|
||||
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
|
||||
const ev: GroupEssenceEvent = {
|
||||
kind: 'group_essence',
|
||||
time: essence.timestamp ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: essence.groupUin ?? notify.groupUin ?? 0,
|
||||
senderUin: essence.memberUin ?? 0,
|
||||
operatorUin: essence.operatorUin ?? ctx.fromUin,
|
||||
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
|
||||
random: essence.random ?? 0,
|
||||
set: setFlag === 1,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// Magic prefix QQ prepends to the GroupReactNotify payload inside
|
||||
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
|
||||
// (see api/group.ts: `msgContent?.slice(7)`).
|
||||
const GROUP_REACT_PREFIX_BYTES = 7;
|
||||
// Discriminator on GroupReactNotify.field13 — same subType is reused
|
||||
// for other notify variants, only 35 means "emoji react". Anything
|
||||
// else falls through to MsgPush.Unknown for protocol-drift visibility.
|
||||
const GROUP_REACT_DISCRIMINATOR = 35;
|
||||
|
||||
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
|
||||
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
|
||||
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
|
||||
const notify = protobuf_decode<GroupReactNotify>(payload);
|
||||
if (!notify) return [];
|
||||
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
|
||||
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
|
||||
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
|
||||
return [];
|
||||
}
|
||||
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
|
||||
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
|
||||
if (!content) return [];
|
||||
|
||||
const groupId = Number(notify.groupUin ?? 0n);
|
||||
const operatorUid = content.operatorUid ?? '';
|
||||
const emojiId = content.code ?? '';
|
||||
const count = content.count ?? 1;
|
||||
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
|
||||
// removed. Older payloads occasionally omit it; default to "add"
|
||||
// since most clients can only generate add events.
|
||||
const isAdd = (content.type ?? 1) === 1;
|
||||
const msgSeq = Number(target?.seq ?? 0n);
|
||||
|
||||
const ev: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
|
||||
operatorUid,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
count,
|
||||
isAdd,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { FriendMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: FriendMessage = {
|
||||
kind: 'friend_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
senderNick: '',
|
||||
};
|
||||
if (ctx.responseHead?.forward?.friendName) {
|
||||
ev.senderNick = ctx.responseHead.forward.friendName;
|
||||
}
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupAdminEvent } from '../../events';
|
||||
import type { GroupAdmin } from '@snowluma/proto-defs/notify';
|
||||
import { resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
|
||||
const admin = protobuf_decode<GroupAdmin>(ctx.content);
|
||||
if (!admin?.body) return [];
|
||||
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
|
||||
if (!extra) return [];
|
||||
const ev: GroupAdminEvent = {
|
||||
kind: 'group_admin',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: admin.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(ctx.identity, admin.groupUin ?? 0, extra.adminUid ?? '', ctx.fromUin),
|
||||
set: admin.body.extraEnable !== undefined,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupInviteEvent } from '../../events';
|
||||
import type {
|
||||
GroupInvitation, GroupInvite,
|
||||
GroupJoin,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import { resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
|
||||
const join = protobuf_decode<GroupJoin>(ctx.content);
|
||||
if (!join) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: join.groupUin ?? 0,
|
||||
// Strangers (not in our cache, not yet group members) won't resolve
|
||||
// here — pass 0 instead of ctx.fromUin (which on a group-scoped push
|
||||
// IS the group's own uin, so falling back to it produces a bogus
|
||||
// `fromUin === groupId` collision). The packet-pipeline's pre-
|
||||
// dispatch hook does an async UID-form FetchUserProfile lookup to
|
||||
// fill in the uin + nickname before the event is emitted — same
|
||||
// shape as Lagrange's flow at
|
||||
// `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
|
||||
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', 0),
|
||||
fromUid: join.targetUid ?? '',
|
||||
subType: 'add',
|
||||
message: '',
|
||||
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
|
||||
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
|
||||
if (!invitation?.info?.inner) return [];
|
||||
const inner = invitation.info.inner;
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: inner.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', 0),
|
||||
fromUid: inner.invitorUid ?? '',
|
||||
subType: 'invite',
|
||||
message: '',
|
||||
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
|
||||
const invite = protobuf_decode<GroupInvite>(ctx.content);
|
||||
if (!invite) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: invite.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', 0),
|
||||
fromUid: invite.invitorUid ?? '',
|
||||
subType: 'invite',
|
||||
message: '',
|
||||
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
|
||||
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
|
||||
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
|
||||
const change = protobuf_decode<GroupChange>(ctx.content);
|
||||
if (!change) return [];
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
|
||||
const change = protobuf_decode<GroupChange>(ctx.content);
|
||||
if (!change) return [];
|
||||
const dt = change.decreaseType ?? 0;
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberLeave = {
|
||||
kind: 'group_member_leave',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
isKick: dt !== 0 && dt !== 130,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
|
||||
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
|
||||
if (!joined) return [];
|
||||
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
|
||||
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
|
||||
// — saturate to 0 on the unlikely overflow rather than letting
|
||||
// BigInt propagate downstream where consumers expect a number.
|
||||
const groupUinBig = joined.groupUin ?? 0n;
|
||||
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
|
||||
const operatorUid = joined.operatorUid ?? '';
|
||||
// We're the one joining — surface the bot's own identity as userUin
|
||||
// so the existing converter's `notice.group_increase` shape works
|
||||
// unchanged.
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: ctx.selfUin,
|
||||
userUid: ctx.identity.selfUid ?? '',
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { GroupMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: GroupMessage = {
|
||||
kind: 'group_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements: decodeRichBody(ctx.body, true),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
senderCard: '',
|
||||
senderRole: '',
|
||||
};
|
||||
if (ctx.responseHead?.grp) {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
|
||||
if (member) {
|
||||
if (!ev.senderNick) ev.senderNick = member.nickname;
|
||||
ev.senderCard = member.card;
|
||||
ev.senderRole = member.role;
|
||||
}
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { TempMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: TempMessage = {
|
||||
kind: 'temp_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
};
|
||||
if (ctx.responseHead?.grp) {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
if (!ev.senderNick) {
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend) ev.senderNick = friend.nickname;
|
||||
}
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
export enum PkgType {
|
||||
ForwardFakePrivateMessage = 9,
|
||||
PrivateMessage = 166,
|
||||
GroupMessage = 82,
|
||||
TempMessage = 141,
|
||||
Event0x210 = 528,
|
||||
Event0x2DC = 732,
|
||||
PrivateRecordMessage = 208,
|
||||
PrivateFileMessage = 529,
|
||||
GroupRequestInvitationNotice = 525,
|
||||
GroupRequestJoinNotice = 84,
|
||||
/**
|
||||
* Self-join admittance — fires on the bot's session right after an
|
||||
* admin approves its `set_group_add_request` or an invite-accept
|
||||
* goes through. Ported from `lagrange-python`'s
|
||||
* `server_push/msg.py:108 case 85`. Maps to OneBot11
|
||||
* `notice.group_increase` with the bot itself as `user_id` —
|
||||
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
|
||||
* bot's own join, so without this case the bot never knows it
|
||||
* just entered a group until the first message arrives.
|
||||
*/
|
||||
GroupSelfJoinedNotice = 85,
|
||||
GroupInviteNotice = 87,
|
||||
GroupAdminChangedNotice = 44,
|
||||
GroupMemberIncreaseNotice = 33,
|
||||
GroupMemberDecreaseNotice = 34,
|
||||
}
|
||||
|
||||
export enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupMsgEmojiLikeNotice = 16,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
}
|
||||
|
||||
export enum Event0x210SubType {
|
||||
FriendRequestNotice = 35,
|
||||
/**
|
||||
* Outgoing friend-message recall — bot recalled its own message that
|
||||
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
|
||||
* difference is direction (138 = friend recalled their own message
|
||||
* sent to bot, 139 = bot recalled own message sent to friend).
|
||||
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
|
||||
* registered for both 138 and 139) + acidify (`138, 139 ->
|
||||
* parseFriendRecall`). The decoder uses the subType to figure out
|
||||
* which UID side ends up as `userUin` on the emitted event.
|
||||
*/
|
||||
FriendRecallSelfNotice = 139,
|
||||
FriendRecallNotice = 138,
|
||||
FriendPokeNotice = 290,
|
||||
/**
|
||||
* Mutual-accept friend notice — 179 fires when bot sent a friend
|
||||
* request and the other side accepted; 226 fires for the opposite
|
||||
* direction. Both decode through the same `NewFriend` wire shape
|
||||
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
|
||||
* in `client/listener.go:248-258`). Maps to OneBot11
|
||||
* `notice.friend_add`.
|
||||
*/
|
||||
NewFriendNotice = 179,
|
||||
NewFriendNoticeAlt = 226,
|
||||
/**
|
||||
* Group-app state push (troop shortcut bar / discussion app).
|
||||
*
|
||||
* Sourced from the decompiled stock QQ Android client decoder at
|
||||
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
|
||||
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
|
||||
* dispatching on `uint32_sub_cmd`:
|
||||
*
|
||||
* - 0x1 → `UpdateAppUnreadNum`: a list of
|
||||
* `{group_code, app_id, unread_num}` entries the QQ client uses
|
||||
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
|
||||
* / `101896870` for the shortcut bar) in sync.
|
||||
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
|
||||
* for discussion-group app tips, routed to `getGAudioHandler()`.
|
||||
* - 0x4 → delegated to the troop online-push handler.
|
||||
*
|
||||
* None of these have a OneBot event mapping — they're QQ-client-UI
|
||||
* state pushes (unread badges, in-app tips), not user-visible
|
||||
* conversation events. Acknowledge the subType so it doesn't keep
|
||||
* showing up as "unknown" in debug logs and drop it silently.
|
||||
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
|
||||
* fall through on this one because they don't surface the shortcut
|
||||
* bar either.
|
||||
*/
|
||||
GroupAppStatePush = 38,
|
||||
/**
|
||||
* Unmapped QQ-NT-internal subType — first seen as a recurring
|
||||
* "Event0x210 unknown subType=380" debug log in production captures.
|
||||
*
|
||||
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
|
||||
* enumerates SubType0x26 (38) through SubType0x146 (326) under
|
||||
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
|
||||
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
|
||||
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
|
||||
*
|
||||
* The NT-era reference clients also don't handle it: Lagrange.Core
|
||||
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
|
||||
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
|
||||
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
|
||||
*
|
||||
* Most likely a QQ-NT-client-UI state push (similar to 38) that
|
||||
* doesn't map to any OneBot event. Acknowledge silently to keep the
|
||||
* unknown log clean; if a real OneBot event ends up depending on it,
|
||||
* revisit with whichever NT-era project finally maps the schema.
|
||||
*/
|
||||
UnmappedClientState380 = 380,
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { inflateSync } from 'zlib';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
|
||||
|
||||
export function makeImageUrl(origUrl: string): string {
|
||||
if (!origUrl) return '';
|
||||
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
|
||||
return 'http://gchat.qpic.cn' + origUrl;
|
||||
}
|
||||
|
||||
export function decompressData(data: Uint8Array): string {
|
||||
if (!data || data.length === 0) return '';
|
||||
if (data[0] === 0x01 && data.length > 1) {
|
||||
try {
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1)));
|
||||
return inflated.toString('utf8');
|
||||
} catch { return ''; }
|
||||
}
|
||||
if (data[0] === 0x00 && data.length > 1) {
|
||||
return Buffer.from(data.subarray(1)).toString('utf8');
|
||||
}
|
||||
return Buffer.from(data).toString('utf8');
|
||||
}
|
||||
|
||||
export function isNumericUin(value: string): boolean {
|
||||
return value.length > 0 && /^\d+$/.test(value);
|
||||
}
|
||||
|
||||
export function parseU64OrZero(value: string): number {
|
||||
if (!value) return 0;
|
||||
const n = parseInt(value, 10);
|
||||
return isNaN(n) ? 0 : n;
|
||||
}
|
||||
|
||||
// Cascades group-scoped lookup → in-memory map → SQLite.
|
||||
// No network fallback on the parse hot path: missing identities fall back to
|
||||
// `fallback` and downstream events drive a roster refresh asynchronously.
|
||||
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
|
||||
if (!uid) return fallback;
|
||||
if (isNumericUin(uid)) {
|
||||
const n = parseInt(uid, 10);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
const uin = identity.findUinByUid(uid, groupId || undefined);
|
||||
if (uin !== null) return uin;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function decodeOperatorUid(bytes: Uint8Array): string {
|
||||
if (!bytes || bytes.length === 0) return '';
|
||||
const info = protobuf_decode<OperatorInfo>(bytes);
|
||||
if (info?.operatorField?.uid) return info.operatorField.uid;
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of params) {
|
||||
if (p.name !== undefined) map.set(p.name, p.value ?? '');
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
|
||||
for (const k of keys) {
|
||||
const v = map.get(k);
|
||||
if (v) return v;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
|
||||
if (content.length <= 7) return null;
|
||||
const lenBe = (content[5] << 8) | content[6];
|
||||
const lenLe = content[5] | (content[6] << 8);
|
||||
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
|
||||
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
|
||||
return content.subarray(7);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import { buildContext } from './context';
|
||||
import { decodeEvent0x210 } from './decoders/event-0x210';
|
||||
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
|
||||
import { decodeFriendMessage } from './decoders/friend-message';
|
||||
import { decodeGroupAdmin } from './decoders/group-admin';
|
||||
import {
|
||||
decodeGroupInvitation, decodeGroupInvite,
|
||||
decodeGroupJoinRequest,
|
||||
} from './decoders/group-join-request';
|
||||
import {
|
||||
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
|
||||
} from './decoders/group-member-change';
|
||||
import { decodeGroupMessage } from './decoders/group-message';
|
||||
import { decodeTempMessage } from './decoders/temp-message';
|
||||
import { PkgType } from './enums';
|
||||
import { MsgPushRegistry } from './registry';
|
||||
|
||||
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
const registry = new MsgPushRegistry();
|
||||
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
|
||||
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
|
||||
registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined);
|
||||
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
|
||||
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
|
||||
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);
|
||||
registry.register(PkgType.GroupInviteNotice, decodeGroupInvite);
|
||||
registry.register(PkgType.Event0x210, decodeEvent0x210);
|
||||
registry.register(PkgType.Event0x2DC, decodeEvent0x2DC);
|
||||
registry.register(PkgType.GroupMessage, decodeGroupMessage);
|
||||
registry.register(PkgType.TempMessage, decodeTempMessage);
|
||||
registry.register([
|
||||
PkgType.PrivateMessage,
|
||||
PkgType.ForwardFakePrivateMessage,
|
||||
PkgType.PrivateRecordMessage,
|
||||
PkgType.PrivateFileMessage,
|
||||
], decodeFriendMessage);
|
||||
|
||||
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
|
||||
const ctx = buildContext(pkt, identity);
|
||||
if (!ctx) return [];
|
||||
return registry.decode(ctx);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { MsgPushContext } from './context';
|
||||
import type { PkgType } from './enums';
|
||||
|
||||
const log = createLogger('MsgPush');
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
|
||||
|
||||
export class MsgPushRegistry {
|
||||
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
|
||||
|
||||
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
|
||||
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
|
||||
for (const t of list) {
|
||||
if (this.decoders_.has(t)) {
|
||||
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
|
||||
}
|
||||
this.decoders_.set(t, decoder);
|
||||
}
|
||||
}
|
||||
|
||||
decode(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
|
||||
if (!decoder) {
|
||||
// Unrecognized PkgType: either we don't care about this notify, or
|
||||
// the QQ NT client added a new variant. Surface at debug so a
|
||||
// protocol change can be spotted without spamming production logs.
|
||||
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return decoder(ctx);
|
||||
} catch (e) {
|
||||
log.error('decoder error for PkgType=%d subType=%d: %s',
|
||||
ctx.head.msgType, ctx.head.subType,
|
||||
e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
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,
|
||||
// `[图片]` / `[动画表情]` are the QQ-ecosystem default
|
||||
// bubble texts; mobile QQ + Lagrange.Core + NapCat all
|
||||
// expect these literal Chinese strings when the wire
|
||||
// doesn't carry a per-image override.
|
||||
summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'),
|
||||
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 || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'),
|
||||
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) {
|
||||
// `com.tencent.multimsg` is the multi-msg / forward preview
|
||||
// LightApp (the modern replacement for the XML serviceID=35
|
||||
// shape). Parse out resid + uniseq so downstream callers can
|
||||
// both render a `[聊天记录]` placeholder and walk into the
|
||||
// forward chain via `fetch(resId)` — the uniseq is what links
|
||||
// the inner layer to its piggybacked actions on the outer's
|
||||
// LongMsgResult. Other LightApp messages fall through to the
|
||||
// generic `{type: 'json'}` path.
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
if (parsed && parsed.app === 'com.tencent.multimsg') {
|
||||
const detail = parsed.meta?.detail ?? {};
|
||||
const resId = typeof detail.resid === 'string' ? detail.resid : '';
|
||||
const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : '';
|
||||
if (resId) {
|
||||
result.push({
|
||||
type: 'forward',
|
||||
resId,
|
||||
forwardUuid: uniseq || undefined,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch { /* fall through to generic json element */ }
|
||||
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
|
||||
|| (me.subType === 1 ? '[动画表情]' : '[图片]');
|
||||
}
|
||||
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 ?? '',
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user