diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 8d232d52..0181a5fc 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -7,7 +7,7 @@ import type { Bridge } from '../bridge'; import { gunzipSync, gzipSync } from 'zlib'; import { protoDecode, protoEncode } from '../../protobuf/decode'; import { buildSendElems } from '../element-builder'; -import { parseMsgPush } from '../msg-push-handler'; +import { parseMsgPush } from '../msg-push'; import type { ForwardNodePayload } from '../events'; import type { PacketInfo } from '../../protocol/types'; import { diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index f1c127ce..fc7932ea 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -5,7 +5,7 @@ import type { PacketInfo } from '../protocol/types'; import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events'; import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; -import { MSG_PUSH_CMD, parseMsgPush } from './msg-push-handler'; +import { MSG_PUSH_CMD, parseMsgPush } from './msg-push'; import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; import { protoEncode, protoDecode } from '../protobuf/decode'; import { buildSendElems } from './element-builder'; diff --git a/packages/core/src/bridge/msg-push-handler.ts b/packages/core/src/bridge/msg-push-handler.ts deleted file mode 100644 index 7b317d96..00000000 --- a/packages/core/src/bridge/msg-push-handler.ts +++ /dev/null @@ -1,885 +0,0 @@ -// MsgPush packet handler — parses trpc.msg.olpush.OlPushService.MsgPush -// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp - -import { inflateSync } from 'zlib'; -import { protoDecode } from '../protobuf/decode'; -import { WireMessage } from '../protobuf/wire'; -import { PushMsgSchema } from './proto/message'; -import { - MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema, - MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema, -} from './proto/element'; -import { FileExtraSchema } from './proto/message'; -import { - GroupChangeSchema, GroupAdminSchema, GroupJoinSchema, - GroupInvitationSchema, GroupInviteSchema, - FriendRequestSchema, FriendRecallSchema, - GroupMuteSchema, NotifyMessageBodySchema, - GeneralGrayTipInfoSchema, OperatorInfoSchema, -} from './proto/notify'; -import type { IdentityService } from './identity-service'; -import type { PacketInfo } from '../protocol/types'; -import type { - QQEventVariant, MessageElement, - FriendMessage, GroupMessage, TempMessage, - GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent, - FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent, - FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent, -} from './events'; -import type { ProtoDecoded, ProtoSchema } from '../protobuf/decode'; - -// --- PkgType enum --- -const enum PkgType { - ForwardFakePrivateMessage = 9, - PrivateMessage = 166, - GroupMessage = 82, - TempMessage = 141, - Event0x210 = 528, - Event0x2DC = 732, - PrivateRecordMessage = 208, - PrivateFileMessage = 529, - GroupRequestInvitationNotice = 525, - GroupRequestJoinNotice = 84, - GroupInviteNotice = 87, - GroupAdminChangedNotice = 44, - GroupMemberIncreaseNotice = 33, - GroupMemberDecreaseNotice = 34, -} - -const enum Event0x2DCSubType { - GroupMuteNotice = 12, - GroupRecallNotice = 17, - GroupGreyTipNotice = 20, - GroupEssenceNotice = 21, -} - -const enum Event0x210SubType { - FriendRequestNotice = 35, - FriendRecallNotice = 138, - FriendPokeNotice = 290, -} - -// --- Helpers --- - -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; -} - -const HEX_CHARS = '0123456789ABCDEF'; -function bytesToHex(data: Uint8Array): string { - let r = ''; - for (const b of data) { r += HEX_CHARS[b >> 4]; r += HEX_CHARS[b & 0x0f]; } - return r; -} - -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'); -} - -function isNumericUin(value: string): boolean { - return value.length > 0 && /^\d+$/.test(value); -} - -function parseU64OrZero(value: string): number { - if (!value) return 0; - const n = parseInt(value, 10); - return isNaN(n) ? 0 : n; -} - -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; - } - // identity.findUinByUid 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. - const uin = identity.findUinByUid(uid, groupId || undefined); - if (uin !== null) return uin; - return fallback; -} - -function decodeOperatorUid(bytes: Uint8Array): string { - if (!bytes || bytes.length === 0) return ''; - const info = protoDecode(bytes, OperatorInfoSchema); - if (info?.operatorField?.uid) return info.operatorField.uid; - return Buffer.from(bytes).toString('utf8'); -} - -function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map { - const map = new Map(); - for (const p of params) { - if (p.name !== undefined) map.set(p.name, p.value ?? ''); - } - return map; -} - -function findTemplateValue(map: Map, ...keys: string[]): string { - for (const k of keys) { - const v = map.get(k); - if (v) return v; - } - return ''; -} - -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); -} - -// --- Element conversion --- - -type ElemDecoded = ProtoDecoded; - -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: ProtoDecoded | null = null; - if (t.pbReserve && t.pbReserve.length > 0) { - mention = protoDecode(t.pbReserve, MentionExtraSchema); - } - 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: bytesToHex(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: bytesToHex(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 ? bytesToHex(v.fileMd5) : '', - mediaNode: { - fileUuid: v.fileUuid ?? '', - info: { - fileSize: v.fileSize ?? 0, - fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(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 = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema); - 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 = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema); - 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-' + bytesToHex(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 = protoDecode(ce.pbElem, MsgInfoSchema); - 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 = protoDecode(ce.pbElem, QSmallFaceExtraSchema); - if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 }); - } else if (svcType === 37 && ce.pbElem) { - // Big face - const extra = protoDecode(ce.pbElem, QFaceExtraSchema); - if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid }); - skipNext = true; - } - } - } - - return result; -} - -function extractRichtextExtras( - rt: ProtoDecoded, - elements: MessageElement[], - isGroup = false -): void { - // Ptt (voice) - if (rt.ptt) { - const p = rt.ptt; - const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(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 ? bytesToHex(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 { - const extra = protoDecode(msgContent, FileExtraSchema); - if (!extra?.file) return; - const f = extra.file; - if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) { - elements.push({ - type: 'file', fileName: f.fileName, fileId: f.fileUuid, - fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, - fileHash: f.fileHash, - }); - } -} - -// --- Main handler --- - -export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; - -export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] { - if (pkt.body.length === 0) return []; - - const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema); - if (!push?.message) return []; - - const msg = push.message; - if (!msg.contentHead) return []; - - const head = msg.contentHead; - const msgType = head.msgType ?? 0; - const subType = head.subType ?? 0; - const sequence = head.sequence ?? 0; - const timestamp = head.timestamp ?? 0; - const msgId = head.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) ? msg.body.msgContent : new Uint8Array(0); - - const buildElements = (isGroup: boolean): MessageElement[] => { - const elements: MessageElement[] = []; - if (msg.body?.richText) { - const rt = msg.body.richText; - if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[])); - extractRichtextExtras(rt, elements, isGroup); - } - if (msg.body?.msgContent && msg.body.msgContent.length > 0) { - extractMsgContent(msg.body.msgContent, elements); - } - return elements; - }; - - // --- Switch on msgType --- - - switch (msgType as PkgType) { - case PkgType.GroupMemberIncreaseNotice: { - const change = protoDecode(content, GroupChangeSchema); - 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: timestamp, selfUin, - groupId, - userUin: resolveUidToUin(identity, groupId, userUid, 0), - operatorUin: resolveUidToUin(identity, groupId, operatorUid, 0), - userUid, - operatorUid, - }; - return [ev]; - } - - case PkgType.GroupMemberDecreaseNotice: { - const change = protoDecode(content, GroupChangeSchema); - 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: timestamp, selfUin, - groupId, - userUin: resolveUidToUin(identity, groupId, userUid, 0), - operatorUin: resolveUidToUin(identity, groupId, operatorUid, 0), - userUid, - operatorUid, - isKick: dt !== 0 && dt !== 130, - }; - return [ev]; - } - - case PkgType.GroupAdminChangedNotice: { - const admin = protoDecode(content, GroupAdminSchema); - if (!admin?.body) return []; - const extra = admin.body.extraEnable ?? admin.body.extraDisable; - if (!extra) return []; - const ev: GroupAdminEvent = { - kind: 'group_admin', time: timestamp, selfUin, - groupId: admin.groupUin ?? 0, - userUin: resolveUidToUin(identity, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin), - set: admin.body.extraEnable !== undefined, - }; - return [ev]; - } - - case PkgType.GroupRequestJoinNotice: { - const join = protoDecode(content, GroupJoinSchema); - if (!join) return []; - const ev: GroupInviteEvent = { - kind: 'group_invite', time: timestamp, selfUin, - groupId: join.groupUin ?? 0, - fromUin: resolveUidToUin(identity, join.groupUin ?? 0, join.targetUid ?? '', fromUin), - fromUid: join.targetUid ?? '', - subType: 'add', message: '', - flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''), - }; - return [ev]; - } - - case PkgType.GroupRequestInvitationNotice: { - const invitation = protoDecode(content, GroupInvitationSchema); - if (!invitation?.info?.inner) return []; - const inner = invitation.info.inner; - const ev: GroupInviteEvent = { - kind: 'group_invite', time: timestamp, selfUin, - groupId: inner.groupUin ?? 0, - fromUin: resolveUidToUin(identity, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin), - fromUid: inner.invitorUid ?? '', - subType: 'invite', message: '', - flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''), - }; - return [ev]; - } - - case PkgType.GroupInviteNotice: { - const invite = protoDecode(content, GroupInviteSchema); - if (!invite) return []; - const ev: GroupInviteEvent = { - kind: 'group_invite', time: timestamp, selfUin, - groupId: invite.groupUin ?? 0, - fromUin: resolveUidToUin(identity, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin), - fromUid: invite.invitorUid ?? '', - subType: 'invite', message: '', - flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''), - }; - return [ev]; - } - - case PkgType.Event0x210: { - switch (subType as Event0x210SubType) { - case Event0x210SubType.FriendRequestNotice: { - const request = protoDecode(content, FriendRequestSchema); - if (!request?.info) return []; - const sourceUid = request.info.newSource || request.info.sourceUid || ''; - const ev: FriendRequestEvent = { - kind: 'friend_request', time: timestamp, selfUin, - fromUin: resolveUidToUin(identity, 0, sourceUid, fromUin), - fromUid: sourceUid, - message: request.info.message ?? '', flag: sourceUid, - }; - return [ev]; - } - case Event0x210SubType.FriendRecallNotice: { - const recall = protoDecode(content, FriendRecallSchema); - if (!recall?.info) return []; - const ev: FriendRecall = { - kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin, - userUin: resolveUidToUin(identity, 0, recall.info.fromUid ?? '', fromUin), - msgSeq: recall.info.clientSequence ?? 0, - }; - return [ev]; - } - case Event0x210SubType.FriendPokeNotice: { - const grayTip = protoDecode(content, GeneralGrayTipInfoSchema); - 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: timestamp, selfUin, - userUin: resolveUidToUin(identity, 0, actor, parseU64OrZero(actor)), - targetUin: resolveUidToUin(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]; - } - } - break; - } - - case PkgType.Event0x2DC: { - switch (subType as Event0x2DCSubType) { - case Event0x2DCSubType.GroupMuteNotice: { - const mute = protoDecode(content, GroupMuteSchema); - if (!mute?.data?.state) return []; - const duration = mute.data.state.duration ?? 0; - const ev: GroupMuteEvent = { - kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin, - groupId: mute.groupUin ?? 0, - operatorUin: resolveUidToUin(identity, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin), - userUin: resolveUidToUin(identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0), - duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration, - }; - return [ev]; - } - case Event0x2DCSubType.GroupRecallNotice: { - const payload = unwrapGroupNotifyPayload(content); - if (!payload) return []; - const notify = protoDecode(payload, NotifyMessageBodySchema); - 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 ?? timestamp, selfUin, - groupId: notify.groupUin ?? 0, - operatorUin: resolveUidToUin(identity, notify.groupUin ?? 0, - notify.recall.operatorUid || notify.operatorUid || '', fromUin), - authorUin: resolveUidToUin(identity, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin), - msgSeq: recalled.sequence ?? 0, - }; - return [ev]; - } - case Event0x2DCSubType.GroupGreyTipNotice: { - const payload = unwrapGroupNotifyPayload(content); - if (!payload) return []; - const notify = protoDecode(payload, NotifyMessageBodySchema); - 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: timestamp, selfUin, - groupId: notify.groupUin ?? 0, - userUin: resolveUidToUin(identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)), - targetUin: resolveUidToUin(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]; - } - case Event0x2DCSubType.GroupEssenceNotice: { - const payload = unwrapGroupNotifyPayload(content); - if (!payload) return []; - const notify = protoDecode(payload, NotifyMessageBodySchema); - if (!notify?.essenceMessage) return []; - const essence = notify.essenceMessage; - const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0; - const ev: GroupEssenceEvent = { - kind: 'group_essence', time: essence.timestamp ?? timestamp, selfUin, - groupId: essence.groupUin ?? notify.groupUin ?? 0, - senderUin: essence.memberUin ?? 0, - operatorUin: essence.operatorUin ?? fromUin, - msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0, - random: essence.random ?? 0, - set: setFlag === 1, - }; - return [ev]; - } - } - break; - } - } - - // --- Message types --- - - if (msgType === PkgType.GroupMessage) { - const ev: GroupMessage = { - kind: 'group_message', time: timestamp, selfUin, - senderUin: fromUin, msgSeq: sequence, - msgId: msgId & 0x7FFFFFFF, - elements: buildElements(true), - groupId: 0, senderNick: '', senderCard: '', senderRole: '', - }; - if (msg.responseHead?.grp) { - ev.groupId = msg.responseHead.grp.groupUin ?? 0; - ev.senderNick = msg.responseHead.grp.memberName ?? ''; - } - const member = identity.findGroupMember(ev.groupId, fromUin); - if (member) { - if (!ev.senderNick) ev.senderNick = member.nickname; - ev.senderCard = member.card; - ev.senderRole = member.role; - } - return [ev]; - } - - if (msgType === PkgType.TempMessage) { - const ev: TempMessage = { - kind: 'temp_message', time: timestamp, selfUin, - senderUin: fromUin, msgSeq: sequence, - elements: buildElements(false), - groupId: 0, senderNick: '', - }; - if (msg.responseHead?.grp) { - ev.groupId = msg.responseHead.grp.groupUin ?? 0; - ev.senderNick = msg.responseHead.grp.memberName ?? ''; - } - if (!ev.senderNick) { - const friend = identity.findFriend(fromUin); - if (friend) ev.senderNick = friend.nickname; - } - return [ev]; - } - - if (msgType === PkgType.PrivateMessage || - msgType === PkgType.ForwardFakePrivateMessage || - msgType === PkgType.PrivateRecordMessage || - msgType === PkgType.PrivateFileMessage) { - const ev: FriendMessage = { - kind: 'friend_message', time: timestamp, selfUin, - senderUin: fromUin, msgSeq: sequence, - msgId: msgId & 0x7FFFFFFF, - elements: buildElements(false), - senderNick: '', - }; - if (msg.responseHead?.forward?.friendName) { - ev.senderNick = msg.responseHead.forward.friendName; - } - const friend = identity.findFriend(fromUin); - if (friend && !ev.senderNick) ev.senderNick = friend.nickname; - return [ev]; - } - - // const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48))); - return []; -} diff --git a/packages/core/src/bridge/msg-push/context.ts b/packages/core/src/bridge/msg-push/context.ts new file mode 100644 index 00000000..556be152 --- /dev/null +++ b/packages/core/src/bridge/msg-push/context.ts @@ -0,0 +1,78 @@ +// MsgPushContext — the decoded envelope fields every decoder may need. +// One unified shape: notice decoders pick from `content`, message decoders +// pick from `body` / `responseHead`. Decoders ignore fields they don't need. + +import { protoDecode } from '../../protobuf/decode'; +import type { ProtoDecoded } from '../../protobuf/decode'; +import { + PushMsgSchema, MessageBodySchema, ResponseHeadSchema, ContentHeadSchema, +} from '../proto/message'; +import type { PacketInfo } from '../../protocol/types'; +import type { IdentityService } from '../identity-service'; + +export type PushMsgBody = ProtoDecoded; +export type PushMsgResponseHead = ProtoDecoded; +export type PushMsgContentHead = ProtoDecoded; + +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; + + const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema); + 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, + }; +} diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts new file mode 100644 index 00000000..5343d4bb --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -0,0 +1,73 @@ +// Handles Event0x210 wrapper (528). Internal switch on subType dispatches +// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290). + +import { protoDecode } from '../../../protobuf/decode'; +import { + FriendRequestSchema, FriendRecallSchema, GeneralGrayTipInfoSchema, +} from '../../proto/notify'; +import type { + FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant, +} from '../../events'; +import type { MsgPushDecoder } from '../registry'; +import type { MsgPushContext } from '../context'; +import { Event0x210SubType } from '../enums'; +import { + resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, +} from '../helpers'; + +export const decodeEvent0x210: MsgPushDecoder = (ctx) => { + switch (ctx.head.subType as Event0x210SubType) { + case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx); + case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx); + case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); + } + return []; +}; + +function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { + const request = protoDecode(ctx.content, FriendRequestSchema); + 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 = protoDecode(ctx.content, FriendRecallSchema); + if (!recall?.info) return []; + const ev: FriendRecall = { + kind: 'friend_recall', + time: recall.info.time ?? ctx.head.timestamp, + selfUin: ctx.selfUin, + userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin), + msgSeq: recall.info.clientSequence ?? 0, + }; + return [ev]; +} + +function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { + const grayTip = protoDecode(ctx.content, GeneralGrayTipInfoSchema); + 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]; +} diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts new file mode 100644 index 00000000..e8f485a8 --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts @@ -0,0 +1,106 @@ +// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches +// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21). + +import { protoDecode } from '../../../protobuf/decode'; +import { + GroupMuteSchema, NotifyMessageBodySchema, +} from '../../proto/notify'; +import type { + GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent, + QQEventVariant, +} from '../../events'; +import type { MsgPushDecoder } from '../registry'; +import type { MsgPushContext } from '../context'; +import { Event0x2DCSubType } from '../enums'; +import { + resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, + unwrapGroupNotifyPayload, +} from '../helpers'; + +export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { + switch (ctx.head.subType as Event0x2DCSubType) { + case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx); + case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx); + case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx); + case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx); + } + return []; +}; + +function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] { + const mute = protoDecode(ctx.content, GroupMuteSchema); + 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 = protoDecode(payload, NotifyMessageBodySchema); + 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 = protoDecode(payload, NotifyMessageBodySchema); + 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 = protoDecode(payload, NotifyMessageBodySchema); + 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]; +} diff --git a/packages/core/src/bridge/msg-push/decoders/friend-message.ts b/packages/core/src/bridge/msg-push/decoders/friend-message.ts new file mode 100644 index 00000000..c07a28bc --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/friend-message.ts @@ -0,0 +1,28 @@ +// Handles the four PkgTypes that produce a FriendMessage event: +// PrivateMessage (166), ForwardFakePrivateMessage (9), +// PrivateRecordMessage (208), PrivateFileMessage (529). The PkgType +// difference only affects which proto-level elements show up in the +// body — decodeRichBody handles all of them uniformly. + +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]; +}; diff --git a/packages/core/src/bridge/msg-push/decoders/group-admin.ts b/packages/core/src/bridge/msg-push/decoders/group-admin.ts new file mode 100644 index 00000000..57bd9f23 --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/group-admin.ts @@ -0,0 +1,24 @@ +// Handles GroupAdminChangedNotice (44). extraEnable / extraDisable +// distinguishes set vs. unset. + +import { protoDecode } from '../../../protobuf/decode'; +import { GroupAdminSchema } from '../../proto/notify'; +import type { GroupAdminEvent } from '../../events'; +import type { MsgPushDecoder } from '../registry'; +import { resolveUidToUin } from '../helpers'; + +export const decodeGroupAdmin: MsgPushDecoder = (ctx) => { + const admin = protoDecode(ctx.content, GroupAdminSchema); + 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]; +}; diff --git a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts b/packages/core/src/bridge/msg-push/decoders/group-join-request.ts new file mode 100644 index 00000000..2cfdf6a3 --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/group-join-request.ts @@ -0,0 +1,63 @@ +// Handles GroupRequestJoinNotice (84) + GroupRequestInvitationNotice (525) +// + GroupInviteNotice (87). All three produce GroupInviteEvent with +// different subType ('add' / 'invite') and flag prefixes. + +import { protoDecode } from '../../../protobuf/decode'; +import { + GroupJoinSchema, GroupInvitationSchema, GroupInviteSchema, +} from '../../proto/notify'; +import type { GroupInviteEvent } from '../../events'; +import type { MsgPushDecoder } from '../registry'; +import { resolveUidToUin } from '../helpers'; + +export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => { + const join = protoDecode(ctx.content, GroupJoinSchema); + if (!join) return []; + const ev: GroupInviteEvent = { + kind: 'group_invite', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + groupId: join.groupUin ?? 0, + fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', ctx.fromUin), + fromUid: join.targetUid ?? '', + subType: 'add', + message: '', + flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''), + }; + return [ev]; +}; + +export const decodeGroupInvitation: MsgPushDecoder = (ctx) => { + const invitation = protoDecode(ctx.content, GroupInvitationSchema); + 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 ?? '', ctx.fromUin), + fromUid: inner.invitorUid ?? '', + subType: 'invite', + message: '', + flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''), + }; + return [ev]; +}; + +export const decodeGroupInvite: MsgPushDecoder = (ctx) => { + const invite = protoDecode(ctx.content, GroupInviteSchema); + 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 ?? '', ctx.fromUin), + fromUid: invite.invitorUid ?? '', + subType: 'invite', + message: '', + flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''), + }; + return [ev]; +}; diff --git a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts new file mode 100644 index 00000000..25cdf59a --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts @@ -0,0 +1,49 @@ +// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34). +// Both share GroupChangeSchema; the decreaseType field distinguishes kick vs +// voluntary leave (dt != 0 && dt != 130 means kicked). + +import { protoDecode } from '../../../protobuf/decode'; +import { GroupChangeSchema } from '../../proto/notify'; +import type { GroupMemberJoin, GroupMemberLeave } from '../../events'; +import type { MsgPushDecoder } from '../registry'; +import { decodeOperatorUid, resolveUidToUin } from '../helpers'; + +export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { + const change = protoDecode(ctx.content, GroupChangeSchema); + 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 = protoDecode(ctx.content, GroupChangeSchema); + 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]; +}; diff --git a/packages/core/src/bridge/msg-push/decoders/group-message.ts b/packages/core/src/bridge/msg-push/decoders/group-message.ts new file mode 100644 index 00000000..6def3b67 --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/group-message.ts @@ -0,0 +1,33 @@ +// Handles GroupMessage (82). Resolves senderCard / senderRole from the +// group member roster when present. + +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]; +}; diff --git a/packages/core/src/bridge/msg-push/decoders/temp-message.ts b/packages/core/src/bridge/msg-push/decoders/temp-message.ts new file mode 100644 index 00000000..f2c89f72 --- /dev/null +++ b/packages/core/src/bridge/msg-push/decoders/temp-message.ts @@ -0,0 +1,28 @@ +// Handles TempMessage (141). Pulls senderNick from group hint first +// then falls back to friend roster. + +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]; +}; diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/core/src/bridge/msg-push/enums.ts new file mode 100644 index 00000000..c94b3875 --- /dev/null +++ b/packages/core/src/bridge/msg-push/enums.ts @@ -0,0 +1,33 @@ +// MsgPush PkgType taxonomy. The top-level msgType field in PushMsg.contentHead +// names a QQ-protocol-defined packet shape; Event0x210 / Event0x2DC are wrapper +// PkgTypes whose payload is further dispatched by subType. + +export enum PkgType { + ForwardFakePrivateMessage = 9, + PrivateMessage = 166, + GroupMessage = 82, + TempMessage = 141, + Event0x210 = 528, + Event0x2DC = 732, + PrivateRecordMessage = 208, + PrivateFileMessage = 529, + GroupRequestInvitationNotice = 525, + GroupRequestJoinNotice = 84, + GroupInviteNotice = 87, + GroupAdminChangedNotice = 44, + GroupMemberIncreaseNotice = 33, + GroupMemberDecreaseNotice = 34, +} + +export enum Event0x2DCSubType { + GroupMuteNotice = 12, + GroupRecallNotice = 17, + GroupGreyTipNotice = 20, + GroupEssenceNotice = 21, +} + +export enum Event0x210SubType { + FriendRequestNotice = 35, + FriendRecallNotice = 138, + FriendPokeNotice = 290, +} diff --git a/packages/core/src/bridge/msg-push/helpers.ts b/packages/core/src/bridge/msg-push/helpers.ts new file mode 100644 index 00000000..125d5d9e --- /dev/null +++ b/packages/core/src/bridge/msg-push/helpers.ts @@ -0,0 +1,83 @@ +// MsgPush decode helpers — pure functions shared across PkgType decoders +// and the rich-body decoder. No state, no I/O. + +import { inflateSync } from 'zlib'; +import { protoDecode } from '../../protobuf/decode'; +import { OperatorInfoSchema } from '../proto/notify'; +import type { IdentityService } from '../identity-service'; + +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 = protoDecode(bytes, OperatorInfoSchema); + if (info?.operatorField?.uid) return info.operatorField.uid; + return Buffer.from(bytes).toString('utf8'); +} + +export function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map { + const map = new Map(); + for (const p of params) { + if (p.name !== undefined) map.set(p.name, p.value ?? ''); + } + return map; +} + +export function findTemplateValue(map: Map, ...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); +} diff --git a/packages/core/src/bridge/msg-push/index.ts b/packages/core/src/bridge/msg-push/index.ts new file mode 100644 index 00000000..536c4c6f --- /dev/null +++ b/packages/core/src/bridge/msg-push/index.ts @@ -0,0 +1,48 @@ +// MsgPush entry point — assembles the PkgType registry and exposes +// `parseMsgPush(pkt, identity)` as the single CmdParser registered against +// `MSG_PUSH_CMD` on the IncomingPacketPipeline. + +import type { PacketInfo } from '../../protocol/types'; +import type { IdentityService } from '../identity-service'; +import type { QQEventVariant } from '../events'; +import { buildContext } from './context'; +import { MsgPushRegistry } from './registry'; +import { PkgType } from './enums'; +import { + decodeGroupMemberJoin, decodeGroupMemberLeave, +} from './decoders/group-member-change'; +import { decodeGroupAdmin } from './decoders/group-admin'; +import { + decodeGroupJoinRequest, decodeGroupInvitation, decodeGroupInvite, +} from './decoders/group-join-request'; +import { decodeEvent0x210 } from './decoders/event-0x210'; +import { decodeEvent0x2DC } from './decoders/event-0x2dc'; +import { decodeGroupMessage } from './decoders/group-message'; +import { decodeTempMessage } from './decoders/temp-message'; +import { decodeFriendMessage } from './decoders/friend-message'; + +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.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); +} diff --git a/packages/core/src/bridge/msg-push/registry.ts b/packages/core/src/bridge/msg-push/registry.ts new file mode 100644 index 00000000..1ac309ec --- /dev/null +++ b/packages/core/src/bridge/msg-push/registry.ts @@ -0,0 +1,40 @@ +// MsgPushRegistry — per-PkgType dispatch table. Each PkgType maps to a single +// decoder; double-registration is a programming error (throws at register time). +// Decoder errors are caught and logged with the PkgType so a single bad decoder +// can never silently take down sibling decoders sharing the cmd. + +import { createLogger } from '../../utils/logger'; +import type { QQEventVariant } from '../events'; +import type { MsgPushContext } from './context'; +import type { PkgType } from './enums'; + +const log = createLogger('MsgPush'); + +export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[]; + +export class MsgPushRegistry { + private readonly decoders_ = new Map(); + + 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) 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 []; + } + } +} diff --git a/packages/core/src/bridge/msg-push/rich-body-decoder.ts b/packages/core/src/bridge/msg-push/rich-body-decoder.ts new file mode 100644 index 00000000..118a26b4 --- /dev/null +++ b/packages/core/src/bridge/msg-push/rich-body-decoder.ts @@ -0,0 +1,447 @@ +// Rich body decoder — turns the proto MessageBody (richText.elems + +// richText.ptt/notOnlineFile + msgContent) of a MsgPush message into +// the bridge-internal MessageElement[] sequence. Pure, no identity +// lookups, no I/O. The single small interface `decodeRichBody` hides +// ~400 lines of per-element-type decoding behind it. + +import { protoDecode } from '../../protobuf/decode'; +import type { ProtoDecoded } from '../../protobuf/decode'; +import { ElemSchema } from '../proto/element'; +import { + MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema, + MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema, +} from '../proto/element'; +import { + MessageBodySchema, RichTextSchema, FileExtraSchema, +} from '../proto/message'; +import type { MessageElement } from '../events'; +import { toHexUpper } from '../../utils/hex'; +import { decompressData, makeImageUrl } from './helpers'; + +type ElemDecoded = ProtoDecoded; +type RichTextDecoded = ProtoDecoded; +export type PushMsgBody = ProtoDecoded; + +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: ProtoDecoded | null = null; + if (t.pbReserve && t.pbReserve.length > 0) { + mention = protoDecode(t.pbReserve, MentionExtraSchema); + } + 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 = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema); + 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 = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema); + 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 = protoDecode(ce.pbElem, MsgInfoSchema); + 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 = protoDecode(ce.pbElem, QSmallFaceExtraSchema); + if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 }); + } else if (svcType === 37 && ce.pbElem) { + // Big face + const extra = protoDecode(ce.pbElem, QFaceExtraSchema); + 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 { + const extra = protoDecode(msgContent, FileExtraSchema); + if (!extra?.file) return; + const f = extra.file; + if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) { + elements.push({ + type: 'file', fileName: f.fileName, fileId: f.fileUuid, + fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, + fileHash: f.fileHash, + }); + } +} diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 4fc8b245..554b5f10 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push-handler'; +import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push'; import { IdentityService } from '../src/bridge/identity-service'; import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info'; import { PushMsgSchema } from '../src/bridge/proto/message';