Fix merge conflict and remove one group avatar implement

This commit is contained in:
H3CoF6 committed 2026-05-16 12:39:00 +08:00
commit 16bdf1be1e
111 files changed
+6830 -2916

No files matched your search

+155
View File
@@ -0,0 +1,155 @@
// Tier-2 napcat-parity actions ported as pure oidb calls. Each function
// here corresponds to one napcat PacketApi.pkt.operation.* entry; the
// schemas live in proto/oidb-action.ts. Nothing in this file touches
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbGroupTodoSchema,
OidbStrangerStatusReqSchema,
OidbStrangerStatusRespSchema,
OidbAiVoiceListReqSchema,
OidbAiVoiceListRespSchema,
OidbAiVoiceReqSchema,
OidbAiVoiceRespSchema,
} from '../proto/oidb-action';
import type { MediaIndexNode } from './shared';
// ─────────────── Group todo (0xF90) ───────────────
export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_1',
oidbCmd: 0xF90, subCmd: 1,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_2',
oidbCmd: 0xF90, subCmd: 2,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_3',
oidbCmd: 0xF90, subCmd: 3,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
export interface StrangerStatus {
status: number;
ext_status: number;
}
/**
* Mirror napcat's GetStrangerStatus: decode the extBigInt status word.
* Values ≤10 fold into a 10×status; everything else is split into the
* high-byte / low-byte ext_status the OneBot dialect uses.
*
* Returns null on transport / decode failure rather than throwing, so
* the OneBot action can produce a clean retcode without try/catch
* gymnastics.
*/
export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<StrangerStatus | null> {
try {
const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
},
response: { schema: OidbStrangerStatusRespSchema },
});
const raw = resp?.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
if (extBig <= 10n) {
return { status: Number(extBig) * 10, ext_status: 0 };
}
const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
return { status: 10, ext_status: status };
} catch {
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export async function fetchAiVoiceList(
bridge: Bridge,
groupId: number,
chatType: AiVoiceChatType,
): Promise<AiVoiceCategory[]> {
const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929d_0',
oidbCmd: 0x929D, subCmd: 0,
request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } },
response: { schema: OidbAiVoiceListRespSchema },
});
return resp?.content ?? [];
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* `bridge.fetchGroupPttUrlByNode`, which already handles every other
* download-URL fetch in SnowLuma.
*/
export async function fetchAiVoice(
bridge: Bridge,
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const resp = await runOidb<{
statusCode?: number;
msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> };
}>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929b_0',
oidbCmd: 0x929B, subCmd: 0,
request: {
schema: OidbAiVoiceReqSchema,
value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
},
response: { schema: OidbAiVoiceRespSchema },
});
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index;
if (node) return node;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
+5 -5
View File
@@ -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 {
@@ -29,7 +29,7 @@ async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
): Promise<Record<string, unknown>> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.qqInfo.uin);
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin);
@@ -41,7 +41,7 @@ async function buildForwardPushBody(
return {
responseHead: {
fromUin,
toUid: bridge.qqInfo.selfUid ?? '',
toUid: bridge.identity.selfUid ?? '',
forward: {
friendName: nickname,
},
@@ -173,14 +173,14 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const pkt: PacketInfo = {
pid: 0,
uin: bridge.qqInfo.uin,
uin: bridge.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: wrapped,
};
const events = parseMsgPush(pkt, bridge.qqInfo);
const events = parseMsgPush(pkt, bridge.identity);
const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue;
+33 -22
View File
@@ -3,7 +3,7 @@
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
@@ -13,32 +13,40 @@ import {
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await resolveUserUid(bridge, parseInt(uidOrFlag, 10));
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
}
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb5d_44', 0xB5D, 44,
{ accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb5d_44',
oidbCmd: 0xB5D, subCmd: 44,
request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } },
});
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await resolveUserUid(bridge, userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0,
{
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
const targetUid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x126b_0',
oidbCmd: 0x126B, subCmd: 0,
request: {
schema: OidbDeleteFriendSchema,
value: {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
block,
field4: false,
},
},
OidbDeleteFriendSchema);
});
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
@@ -47,7 +55,10 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2,
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema);
const uid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb6e_2',
oidbCmd: 0xB6E, subCmd: 2,
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
});
}
+107 -44
View File
@@ -4,7 +4,7 @@
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
@@ -26,26 +26,50 @@ import {
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1,
{ groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1253_1',
oidbCmd: 0x1253, subCmd: 1,
request: {
schema: OidbMuteMemberSchema,
value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } },
},
});
}
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
});
}
// ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0AddOptionSchema,
value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 },
},
});
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0SearchSchema,
value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 },
},
});
}
export async function setGroupAddRequest(
@@ -54,53 +78,92 @@ export async function setGroupAddRequest(
): Promise<void> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await sendOidbAndCheck(bridge, cmd, 0x10C8, subCmd,
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
OidbGroupRequestActionSchema, true);
await runOidb(bridge, {
cmd,
oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
}
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: OidbKickMemberSchema,
value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason },
},
});
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => resolveUserUid(bridge, userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema);
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: Oidb0x8a0ReqSchema,
value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 },
},
});
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1,
{ groupUin: groupId }, OidbLeaveGroupSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
}
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1,
{ groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1096_1',
oidbCmd: 0x1096, subCmd: 1,
request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } },
});
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3,
{ groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_3',
oidbCmd: 0x8FC, subCmd: 3,
request: {
schema: OidbRenameMemberSchema,
value: { groupUin: groupId, body: { targetUid: uid, targetName: card } },
},
});
}
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_15', 0x89A, 15,
{ groupUin: groupId, body: { targetName: name } }, OidbRenameGroupSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_15',
oidbCmd: 0x89A, subCmd: 15,
request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } },
});
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2,
{ groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
});
}
// ─────────────── personal-side metadata ───────────────
@@ -109,8 +172,11 @@ export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, user
// here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1,
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
}
// ─────────────── group-level quota query ───────────────
@@ -123,20 +189,17 @@ export async function getGroupAtAllRemain(
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.qqInfo.uin),
uin: BigInt(bridge.identity.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x8a7_0',
0x8A7,
0,
req,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a7_0',
oidbCmd: 0x8A7, subCmd: 0,
request: { schema: Oidb0x8a7ReqSchema, value: req },
response: { schema: Oidb0x8a7RespSchema },
});
if (!result) {
throw new Error('get group at all remain result empty');
+201 -200
View File
@@ -7,7 +7,7 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import {
@@ -27,6 +27,7 @@ import {
NTV2RichMediaRespSchema,
} from '../proto/oidb-action';
import { FileUploadExtSchema } from '../proto/highway';
import { toHexUpper } from '../../utils/hex';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
// ─────────────── public result types ───────────────
@@ -76,7 +77,7 @@ function normalizeDirectory(dir?: string): string {
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return Buffer.from(data).toString('hex').toUpperCase();
return toHexUpper(data);
}
function normalizeUploadFileName(name: string, fallback: string): string {
@@ -241,16 +242,12 @@ async function fetchNtv2DownloadUrl(
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const resp = await sendOidbAndDecode<any>(
bridge,
serviceCmd,
oidbCmd,
200,
payload,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
true,
);
const resp = await runOidb<any>(bridge, {
cmd: serviceCmd,
oidbCmd, subCmd: 200,
request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
@@ -266,11 +263,15 @@ async function fetchNtv2DownloadUrl(
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await sendOidbAndDecode<any>(bridge,
'OidbSvcTrpcTcp.0x6d8_3', 0x6D8, 3,
{ count: { groupUin: groupId, appId: 7, busId: 0 } },
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_3',
oidbCmd: 0x6D8, subCmd: 3,
request: {
schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
@@ -293,31 +294,31 @@ export async function uploadGroupFile(
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_0',
0x6D6,
0,
{
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_0',
oidbCmd: 0x6D6, subCmd: 0,
request: {
schema: OidbGroupFileReqSchema,
value: {
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
@@ -327,7 +328,7 @@ export async function uploadGroupFile(
if (!fileId) throw new Error('group file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(bridge.qqInfo.uin);
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
@@ -368,48 +369,48 @@ export async function uploadPrivateFile(
const loaded = await loadBinarySource(source, 'file');
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await resolveUserUid(bridge, userId);
let selfUid = bridge.qqInfo.selfUid;
const targetUid = await bridge.resolveUserUid(userId);
let selfUid = bridge.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(bridge.qqInfo.uin);
const selfUin = toInt(bridge.identity.uin);
if (selfUin > 0) {
selfUid = await resolveUserUid(bridge, selfUin);
selfUid = await bridge.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(bridge.qqInfo.uin);
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1700',
0xE37,
1700,
{
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1700',
oidbCmd: 0xE37, subCmd: 1700,
request: {
schema: OidbPrivateFileUploadReqSchema,
value: {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
);
response: { schema: OidbPrivateFileUploadRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing');
@@ -458,27 +459,27 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d8_1',
0x6D8,
1,
{
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_1',
oidbCmd: 0x6D8, subCmd: 1,
request: {
schema: OidbGroupFileViewReqSchema,
value: {
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
},
isUid: true,
},
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
true,
);
response: { schema: OidbGroupFileViewRespSchema },
});
const list = resp?.list;
if (!list) break;
@@ -489,7 +490,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
const uploader = toInt(file.uploaderUin);
const cached = bridge.qqInfo.findGroupMember(groupId, uploader);
const cached = bridge.identity.findGroupMember(groupId, uploader);
files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '',
@@ -508,7 +509,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
} else if (type === 2 && item?.folderInfo) {
const folder = item.folderInfo;
const creator = toInt(folder.creatorUin);
const cached = bridge.qqInfo.findGroupMember(groupId, creator);
const cached = bridge.identity.findGroupMember(groupId, creator);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
@@ -533,23 +534,23 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
// ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_2',
0x6D6,
2,
{
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_2',
oidbCmd: 0x6D6, subCmd: 2,
request: {
schema: OidbGroupFileReqSchema,
value: {
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
@@ -568,30 +569,30 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
}
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await resolveUserUid(bridge, userId);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1200',
0xE37,
1200,
{
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
const uid = await bridge.resolveUserUid(userId);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1200',
oidbCmd: 0xE37, subCmd: 1200,
request: {
schema: OidbPrivateFileDownloadReqSchema,
value: {
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
);
response: { schema: OidbPrivateFileDownloadRespSchema },
});
const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : '';
@@ -606,22 +607,22 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId
// ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_3',
0x6D6,
3,
{
delete: {
groupUin: groupId,
busId: 102,
fileId,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_3',
oidbCmd: 0x6D6, subCmd: 3,
request: {
schema: OidbGroupFileReqSchema,
value: {
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group file delete response missing');
@@ -635,25 +636,25 @@ export async function moveGroupFile(
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_5',
0x6D6,
5,
{
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_5',
oidbCmd: 0x6D6, subCmd: 5,
request: {
schema: OidbGroupFileReqSchema,
value: {
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.move;
if (!result) throw new Error('group file move response missing');
@@ -663,22 +664,22 @@ export async function moveGroupFile(
// ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_0',
0x6D7,
0,
{
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_0',
oidbCmd: 0x6D7, subCmd: 0,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
isUid: true,
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.create;
if (!result) throw new Error('group folder create response missing');
@@ -686,21 +687,21 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam
}
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_1',
0x6D7,
1,
{
delete: {
groupUin: groupId,
folderId,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_1',
oidbCmd: 0x6D7, subCmd: 1,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
delete: {
groupUin: groupId,
folderId,
},
},
isUid: true,
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing');
@@ -708,22 +709,22 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol
}
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_2',
0x6D7,
2,
{
rename: {
groupUin: groupId,
folderId,
newFolderName,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_2',
oidbCmd: 0x6D7, subCmd: 2,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
isUid: true,
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing');
@@ -5,7 +5,7 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
@@ -28,7 +28,7 @@ export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number,
): Promise<void> {
const targetUid = await resolveUserUid(bridge, userUin);
const targetUid = await bridge.resolveUserUid(userUin);
const request = protoEncode({
type: 1,
targetUid,
@@ -53,7 +53,7 @@ export async function markPrivateMessageRead(
msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
const uid = await bridge.resolveUserUid(userId);
const request = protoEncode({
c2cList: [
@@ -96,6 +96,9 @@ export async function markGroupMessageRead(
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await sendOidbAndCheck(bridge, cmd, 0xEAC, subCmd,
{ groupUin: groupId, sequence, random }, OidbEssenceSchema);
await runOidb(bridge, {
cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
}
+38 -13
View File
@@ -3,7 +3,7 @@
// edit message content — they're purely social signals.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
@@ -13,25 +13,45 @@ import {
} from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xed3_1', 0xED3, 1,
{
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
}, OidbPokeSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xed3_1',
oidbCmd: 0xED3, subCmd: 1,
request: {
schema: OidbPokeSchema,
value: {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
},
},
});
}
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104,
{ targetUin: userId, count }, OidbLikeSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7e5_104',
oidbCmd: 0x7E5, subCmd: 104,
request: { schema: OidbLikeSchema, value: { targetUin: userId, count } },
});
}
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd,
{ groupUin: groupId, sequence, code }, OidbGroupReactionSchema);
// Same heuristic NapCat uses: QQ face ids are 1–3 digits ("76"),
// unicode codepoints are longer ("128516"). Server requires the
// type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1;
await runOidb(bridge, {
cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
}
export async function getEmojiLikes(
@@ -53,7 +73,12 @@ export async function getEmojiLikes(
count,
field12: 1,
};
const resp = await sendOidbAndDecode<any>(bridge, 'OidbSvcTrpcTcp.0x9083_1', 0x9083, 1, req, Oidb0x9083ReqSchema, Oidb0x9083RespSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9083_1',
oidbCmd: 0x9083, subCmd: 1,
request: { schema: Oidb0x9083ReqSchema, value: req },
response: { schema: Oidb0x9083RespSchema },
});
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
+20 -29
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
MiniAppShareReqSchema,
MiniAppShareRespSchema,
@@ -30,15 +30,12 @@ export async function translateEn2Zh(
tag12: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x990_2',
0x990,
2,
req,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x990_2',
oidbCmd: 0x990, subCmd: 2,
request: { schema: Oidb0x990ReqSchema, value: req },
response: { schema: Oidb0x990RespSchema },
});
const resp = result?.translateResp;
if (!resp) {
@@ -125,15 +122,12 @@ export async function clickInlineKeyboardButton(
unknown9: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112e_1',
0x112E,
1,
req,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112e_1',
oidbCmd: 0x112E, subCmd: 1,
request: { schema: Oidb0x112eReqSchema, value: req },
response: { schema: Oidb0x112eRespSchema },
});
if (!result) {
throw new Error('click inline keyboard button result empty');
@@ -155,19 +149,16 @@ export async function sendGroupSign(
) {
const req = {
signInInfo: {
uin: String(bridge.qqInfo.uin),
uin: String(bridge.identity.uin),
groupId: String(groupId),
version: '9.0.90',
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xEB7_1',
0xEB7,
1,
req,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
);
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xEB7_1',
oidbCmd: 0xEB7, subCmd: 1,
request: { schema: Oidb0xeb7ReqSchema, value: req },
response: { schema: Oidb0xeb7RespSchema },
});
}
+101 -57
View File
@@ -4,12 +4,13 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
FaceroamOpReqSchema,
FaceroamOpRespSchema,
GroupAvatarExtraSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0x7edReqSchema,
@@ -32,11 +33,39 @@ export async function setOnlineStatus(
extStatus: number = 0,
batteryStatus: number = 100,
): Promise<void> {
const request = protoEncode({
status,
extStatus,
batteryStatus,
}, SetStatusReqSchema);
await dispatchSetStatus(bridge, { status, extStatus, batteryStatus });
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
export async function setDiyOnlineStatus(
bridge: Bridge,
faceId: number,
wording: string,
faceType: number,
): Promise<void> {
await dispatchSetStatus(bridge, {
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
async function dispatchSetStatus(
bridge: Bridge,
value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
},
): Promise<void> {
const request = protoEncode(value, SetStatusReqSchema);
const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request);
@@ -60,7 +89,7 @@ export async function setProfile(
nickname?: string,
personalNote?: string,
): Promise<void> {
const uin = BigInt(bridge.qqInfo.uin);
const uin = BigInt(bridge.identity.uin);
const stringProfiles: any[] = [];
const intProfiles: any[] = [];
@@ -81,14 +110,11 @@ export async function setProfile(
stringProfiles,
};
await sendOidbAndCheck(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
OidbSetProfileSchema,
);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: OidbSetProfileSchema, value: req },
});
}
export async function setSelfLongNick(
@@ -96,22 +122,19 @@ export async function setSelfLongNick(
longNick: string,
) {
const req = {
uin: BigInt(bridge.qqInfo.uin),
uin: BigInt(bridge.identity.uin),
profile: {
tag: 102,
value: String(longNick),
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
);
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: Oidb0x112aReqSchema, value: req },
response: { schema: Oidb0x112aRespSchema },
});
}
export async function setInputStatus(
@@ -119,7 +142,7 @@ export async function setInputStatus(
userId: number,
eventType: number,
) {
const targetUid = await resolveUserUid(bridge, userId);
const targetUid = await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
@@ -133,15 +156,12 @@ export async function setInputStatus(
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xcd4_1',
0xCD4,
1,
req,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
);
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xcd4_1',
oidbCmd: 0xCD4, subCmd: 1,
request: { schema: Oidb0xcd4ReqSchema, value: req },
response: { schema: Oidb0xcd4RespSchema },
});
}
export async function setAvatar(
@@ -156,6 +176,36 @@ export async function setAvatar(
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
}
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
export async function setGroupAvatar(
bridge: Bridge,
groupId: number,
source: string,
): Promise<void> {
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protoEncode({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
}, GroupAvatarExtraSchema);
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
export async function getProfileLike(
@@ -167,7 +217,7 @@ export async function getProfileLike(
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, userId);
: await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
@@ -182,15 +232,12 @@ export async function getProfileLike(
limit: limit,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x7ed_12',
0x7ED,
12,
req,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7ed_12',
oidbCmd: 0x7ED, subCmd: 12,
request: { schema: Oidb0x7edReqSchema, value: req },
response: { schema: Oidb0x7edRespSchema },
});
const data = result?.userLikeInfos?.[0];
if (!data) {
@@ -220,7 +267,7 @@ export async function getUnidirectionalFriendList(
bridge: Bridge,
) {
const reqObj = {
uint64_uin: String(bridge.qqInfo.uin),
uint64_uin: String(bridge.identity.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
@@ -230,15 +277,12 @@ export async function getUnidirectionalFriendList(
jsonBody: JSON.stringify(reqObj),
};
const result = await sendOidbAndDecode<any>(
bridge,
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
0xE17,
0,
req,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
oidbCmd: 0xE17, subCmd: 0,
request: { schema: Oidb0xe17ReqSchema, value: req },
response: { schema: Oidb0xe17RespSchema },
});
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
@@ -251,7 +295,7 @@ export async function getUnidirectionalFriendList(
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.qqInfo.uin),
uin: BigInt(bridge.identity.uin),
field3: 1,
field6: 1,
};
@@ -265,5 +309,5 @@ export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promi
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
}
const faceIds = (resp as any).item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.qqInfo.uin}/${id}/0`);
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`);
}
+6 -6
View File
@@ -3,7 +3,6 @@
// same five-line utility from every themed file.
import type { Bridge } from '../bridge';
import { resolveUserUid } from '../bridge-oidb';
/**
* Coerce numbers, strings, and bigints to a plain integer.
@@ -37,18 +36,19 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
}
/**
* Look up the bot's own UID. Cached on QQInfo when warmed up, but
* forward/profile actions need a fast path before warmup completes.
* Look up the bot's own UID. Cached on Identity once warmup populates
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.qqInfo.selfUid;
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.qqInfo.uin);
const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await resolveUserUid(bridge, selfUin);
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
+37 -19
View File
@@ -4,7 +4,7 @@ import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode';
import { sendOidbAndDecode } from './bridge-oidb';
import { runOidb } from './bridge-oidb';
import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
@@ -71,9 +71,12 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
body.nextUin = { uin: nextUin };
}
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body,
OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfd4_1',
oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
if (resp?.friends) {
for (const raw of resp.friends) {
@@ -121,9 +124,12 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
},
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body,
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe5_2',
oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
@@ -165,9 +171,12 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
};
if (token) body.token = token;
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body,
OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe7_3',
oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
if (resp?.members) {
for (const raw of resp.members) {
@@ -205,9 +214,12 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
keys: keys.map(k => ({ key: k })),
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body,
OidbUserInfoRequestSchema, OidbUserInfoResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
response: { schema: OidbUserInfoResponseSchema },
});
if (!resp?.body) throw new Error('user info response body missing');
@@ -259,9 +271,12 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await sendOidbAndDecode<any>(
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 },
OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd,
oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) {
@@ -308,9 +323,12 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyIn
},
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body,
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9067_202',
oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
@@ -0,0 +1,152 @@
// BridgeInterface — the surface OneBot (and any other external consumer)
// is allowed to see. The concrete Bridge class additionally exposes raw
// protocol primitives (sendRawPacket, packet dispatch, PID management)
// used by the in-tree action / contacts / highway modules; those internal
// methods deliberately do NOT appear here so that callers depending on
// the interface stay decoupled from the wire format.
//
// Every method below has a matching signature on Bridge; `Bridge
// implements BridgeInterface` is the compile-time enforcement.
import type { BridgeEventBus } from './event-bus';
import type { IdentityService } from './identity-service';
import type {
FriendInfo, QQGroupInfo, GroupMemberInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import type { MessageElement, ForwardNodePayload } from './events';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import type { WebHonorType } from './web/group-honor';
import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
export interface BridgeInterface {
// ─── Shared state ───
readonly identity: IdentityService;
readonly events: BridgeEventBus;
readonly activePid: number | null;
// ─── Resolution ───
resolveUserUid(uin: number, groupId?: number): Promise<string>;
// ─── Raw packet (deliberate escape hatch for `send_packet` action) ───
// OneBot clients use this to debug or invoke commands SnowLuma has no
// typed wrapper for. Every other method on this interface eventually
// routes through here.
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
// ─── Send (messages) ───
sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
// ─── Fetch (contacts / profile / system) ───
fetchFriendList(): Promise<FriendInfo[]>;
fetchGroupList(): Promise<QQGroupInfo[]>;
fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise<GroupMemberInfo[]>;
fetchUserProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupRequests(filtered?: boolean): Promise<GroupRequestInfo[]>;
fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]>;
// ─── Group admin ───
muteGroupMember(groupId: number, userId: number, duration: number): Promise<void>;
muteGroupAll(groupId: number, enable: boolean): Promise<void>;
setGroupAddOption(groupId: number, addType: number): Promise<void>;
setGroupSearch(groupId: number): Promise<void>;
setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason?: string, filtered?: boolean): Promise<void>;
kickGroupMember(groupId: number, userId: number, reject: boolean, reason?: string): Promise<void>;
kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void>;
leaveGroup(groupId: number): Promise<void>;
setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void>;
setGroupCard(groupId: number, userId: number, card: string): Promise<void>;
setGroupName(groupId: number, name: string): Promise<void>;
setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void>;
setGroupRemark(groupId: number, remark: string): Promise<void>;
setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void>;
setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void>;
// ─── Friend ───
setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void>;
deleteFriend(userId: number, block?: boolean): Promise<void>;
setFriendRemark(userId: number, remark: string): Promise<void>;
// ─── Files ───
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
fetchGroupFiles(groupId: number, folderId?: string): Promise<GroupFilesResult>;
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string>;
fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string>;
deleteGroupFile(groupId: number, fileId: string): Promise<void>;
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void>;
createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise<void>;
deleteGroupFileFolder(groupId: number, folderId: string): Promise<void>;
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Group Album ───
getGroupAlbumList(groupId: number): Promise<any>;
uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void>;
getGroupAlbumMediaList(groupId: number, albumId: string): Promise<any>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
// ─── Message ops ───
recallGroupMessage(groupId: number, sequence: number): Promise<void>;
recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void>;
markGroupMsgAsRead(groupId: number, sequence: number): Promise<void>;
markPrivateMsgAsRead(userId: number, sequence: number): Promise<void>;
// ─── Interaction ───
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void>;
sendLike(userId: number, count: number): Promise<void>;
getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }>;
// ─── Web-backed ───
getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any>;
forceFetchClientKey(): Promise<ClientKeyInfo>;
getGroupEssence(groupId: number, pageStart?: number, pageLimit?: number): Promise<any>;
getGroupEssenceAll(groupId: number): Promise<any>;
sendGroupNotice(groupId: number, content: string, options?: any): Promise<any>;
getGroupNotice(groupId: number): Promise<any>;
deleteGroupNotice(groupId: number, fid: string): Promise<boolean>;
getCookiesStr(domain: string): Promise<string>;
getCsrfToken(): Promise<number>;
getCredentials(domain: string): Promise<any>;
// ─── Personal profile ───
setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise<void>;
setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void>;
setProfile(nickname?: string, personalNote?: string): Promise<void>;
setSelfLongNick(longNick: string): Promise<any>;
setInputStatus(userId: number, eventType: number): Promise<any>;
setAvatar(source: string): Promise<void>;
setGroupAvatar(groupId: number, source: string): Promise<void>;
fetchCustomFace(count?: number): Promise<string[]>;
getProfileLike(userId?: number, start?: number, limit?: number): Promise<any>;
getUnidirectionalFriendList(): Promise<any>;
getGroupAtAllRemain(groupId: number): Promise<any>;
// ─── Misc ───
translateEn2Zh(words: string[]): Promise<any>;
getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any>;
clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise<any>;
sendGroupSign(groupId: number): Promise<any>;
// ─── Tier-2 napcat parity extras ───
setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>;
fetchAiVoiceList(groupId: number, chatType: number): Promise<Array<{ category: string; voices: Array<{ voiceId: string; voiceDisplayName: string; voiceExampleUrl: string }> }>>;
fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise<MediaIndexNode>;
}
+68 -69
View File
@@ -1,91 +1,90 @@
// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution.
// One deep entry point for a single OIDB round-trip: build the envelope,
// dispatch via Bridge.sendRawPacket, validate the response status, and
// optionally decode the body. Replaces the three positional helpers
// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to
// scatter the same five-step pattern across every action file.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb';
/**
* Build a raw OIDB request buffer (base envelope wrapping a typed body).
*/
export function makeOidbRequest(
command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, isUid = false,
): Uint8Array {
const baseSchema = makeOidbBaseSchema(bodySchema);
return protoEncode({
command,
subCommand,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
}, baseSchema);
export interface OidbCall<TResp = void> {
/** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
cmd: string;
/** OIDB command number, e.g. 0x1253. */
oidbCmd: number;
/** OIDB sub-command, e.g. 1. */
subCmd: number;
request: {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
*/
isUid?: boolean;
};
/** Omit to skip decoding the response body (fire-and-check). */
response?: {
schema: ProtoSchema;
};
}
/**
* Send an OIDB packet and verify it succeeded (no decode of body).
* Issue one OIDB request. Without `response`, returns void after
* verifying the envelope's retCode. With `response`, decodes the
* envelope, validates retCode, and returns the inner body.
*
* Throws on transport failure, missing response, decode failure, or any
* non-zero envelope retCode. Action modules layer their own retCode
* checks (on inner sub-replies like `upload.retCode`) on top of this.
*/
export async function sendOidbAndCheck(
bridge: Bridge,
serviceCmd: string, command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, isUid = false,
): Promise<void> {
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
const envelope = encodeOidbEnvelope(call);
const result = await bridge.sendRawPacket(call.cmd, envelope);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (call.response) {
if (!result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'no response');
}
const baseSchema = makeOidbBaseSchema(call.response.schema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
throwIfOidbError(resp);
return (resp as any).body as TResp;
}
// Fire-and-check: response data is optional, but if present we still
// peek at the envelope so a server-side retCode doesn't silently slip past.
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
// Check OIDB error code if response present
if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase);
if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
if (resp) throwIfOidbError(resp);
}
}
/**
* Send an OIDB packet and decode the response body with the given schema.
*/
export async function sendOidbAndDecode<T>(
bridge: Bridge,
serviceCmd: string, command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false,
): Promise<T> {
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response');
const baseSchema = makeOidbBaseSchema(responseSchema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
if ((resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
return (resp as any).body as T;
function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
const baseSchema = makeOidbBaseSchema(call.request.schema);
return protoEncode({
command: call.oidbCmd,
subCommand: call.subCmd,
errorCode: 0,
body: call.request.value,
errorMsg: '',
reserved: call.request.isUid ? 1 : 0,
}, baseSchema);
}
/**
* Resolve a UIN to a UID string, using cache or fetching as needed.
* Mirrors C++ resolve_user_uid_for_action.
*/
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
// Try group member first
if (groupId !== undefined) {
const uid = bridge.identity.findUidByUin(uin, groupId);
if (uid) return uid;
// Try fetching member list
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const uid2 = bridge.identity.findUidByUin(uin, groupId);
if (uid2) return uid2;
function throwIfOidbError(resp: unknown): void {
const code = (resp as any).errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
}
// Try cached
const uid = bridge.identity.findUidByUin(uin);
if (uid) return uid;
// Fetch profile
const profile = await bridge.fetchUserProfile(uin);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${uin}`);
}
+64 -269
View File
@@ -5,12 +5,13 @@
import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } 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';
import { IdentityService } from './identity-service';
import type { BridgeInterface } from './bridge-interface';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
@@ -18,7 +19,6 @@ import {
} from './proto/action';
// Delegated modules
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
@@ -43,7 +43,6 @@ import {
setGroupSpecialTitle as setGroupSpecialTitle_,
setGroupRemark as setGroupRemark_,
getGroupAtAllRemain as getGroupAtAllRemain_,
setGroupAvatar as setGroupAvatar_,
} from './actions/group-admin';
import {
uploadGroupFile as uploadGroupFile_,
@@ -86,10 +85,12 @@ import {
} from './actions/friend';
import {
setOnlineStatus as setOnlineStatus_,
setDiyOnlineStatus as setDiyOnlineStatus_,
setProfile as setProfile_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
setAvatar as setAvatar_,
setGroupAvatar as setGroupAvatar_,
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
@@ -100,6 +101,20 @@ import {
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
} from './actions/misc';
import {
setGroupTodo as setGroupTodo_,
completeGroupTodo as completeGroupTodo_,
cancelGroupTodo as cancelGroupTodo_,
getStrangerStatus as getStrangerStatus_,
fetchAiVoiceList as fetchAiVoiceList_,
fetchAiVoice as fetchAiVoice_,
AiVoiceChatType,
type AiVoiceCategory,
type AiVoiceChatType as AiVoiceChatTypeT,
type StrangerStatus,
} from './actions/extras';
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import {
getGroupHonorInfo as getGroupHonorInfo_,
forceFetchClientKey as forceFetchClientKey_,
@@ -119,8 +134,6 @@ import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
export interface SendMessageReceipt {
messageId: number;
sequence: number;
@@ -143,26 +156,21 @@ export interface ClientKeyInfo {
keyIndex: string
}
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
export class Bridge {
export class Bridge implements BridgeInterface {
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
private qqInfo_: QQInfo;
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and `emitEvent` fans out in parallel.
* care about and the pipeline fans out in parallel.
*/
readonly events = new BridgeEventBus();
private cmdHandlers_ = new Map<string, CmdParser[]>();
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private memberRefreshTasks_ = new Map<number, Promise<void>>();
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
// and serves a fresh result for `kMemberListTtlMs` to all callers.
// Without this, a busy OneBot client (e.g. MaiBot calling
@@ -177,14 +185,21 @@ export class Bridge {
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) {
this.qqInfo_ = qqInfo;
constructor(identity: IdentityService) {
this.identity = identity;
this.registerDefaultHandlers();
this.identity.setFetcher({
fetchProfile: (uin) => this.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
get qqInfo(): QQInfo { return this.qqInfo_; }
dispose(): void {
this.identity.close();
this.events.clear();
@@ -194,18 +209,12 @@ export class Bridge {
this.packetClient_ = client;
}
private registerDefaultHandlers(): void {
this.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
return this.pipeline.handlesCmd(cmd);
}
// --- PID management ---
@@ -226,183 +235,14 @@ export class Bridge {
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.qqInfo_);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.triggerMemberCacheRefresh(event);
printEvent(event);
this.emitEvent(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.triggerMemberCacheRefresh(event, refreshed);
printEvent(event);
this.emitEvent(event);
}
private emitEvent(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.events.emit(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.refreshMemberCache(
event.groupId,
!this.qqInfo_.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.resolveUidFromCache(event.groupId, event.userUid);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.resolveUidFromCache(event.groupId, event.operatorUid);
if (uin !== null) event.operatorUin = uin;
}
}
private resolveUidFromCache(groupId: number, uid: string): number | null {
return this.identity.findUinByUid(uid, groupId);
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.qqInfo_.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.qqInfo_.selfUid);
}
private triggerMemberCacheRefresh(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.qqInfo_.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.qqInfo_.findGroup(groupId)) return false;
if (!this.identity.findGroup(groupId)) return false;
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
@@ -557,7 +397,7 @@ export class Bridge {
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return resolveUserUid_(this, uin, groupId);
return this.identity.resolveUid(uin, groupId);
}
// --- Delegated: Contact / info queries ---
@@ -635,7 +475,6 @@ export class Bridge {
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
async setGroupRemark(groupId: number, remark: string): Promise<void> { return setGroupRemark_(this, groupId, remark); }
async setGroupAvatar(groupId: number, source: string): Promise<void> { return setGroupAvatar_(this, groupId, source); }
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
return getGroupHonorInfo_(this, groupId, type);
}
@@ -681,6 +520,9 @@ export class Bridge {
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
}
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
return setDiyOnlineStatus_(this, faceId, wording, faceType);
}
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
return setProfile_(this, nickname, personalNote);
}
@@ -714,82 +556,35 @@ export class Bridge {
async setAvatar(source: string): Promise<void> {
return setAvatar_(this, source);
}
async setGroupAvatar(groupId: number, source: string): Promise<void> {
return setGroupAvatar_(this, groupId, source);
}
async fetchCustomFace(count?: number): Promise<string[]> {
return fetchCustomFace_(this, count);
}
async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) {
return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie);
}
}
// --- Module-level helper functions ---
// --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) ---
function elementsToText(elements: MessageElement[]): string {
return elements.map(e => {
switch (e.type) {
case 'text': return e.text ?? '';
case 'at': return `@${e.targetUin ?? 'all'}`;
case 'face': return `[表情:${e.faceId}]`;
case 'mface': return `[${e.summary ?? '表情'}]`;
case 'image': return '[图片]';
case 'video': return '[视频]';
case 'record': return '[语音]';
case 'file': return `[文件:${e.fileName ?? ''}]`;
case 'json': return '[JSON卡片]';
case 'xml': return '[XML卡片]';
case 'reply': return `[回复:${e.replySeq}]`;
case 'poke': return '[戳一戳]';
case 'forward': return '[合并转发]';
case 'markdown': return '[Markdown]';
default: return `[${e.type}]`;
}
}).join('');
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return setGroupTodo_(this, groupId, BigInt(msgSeq));
}
async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return completeGroupTodo_(this, groupId, BigInt(msgSeq));
}
async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return cancelGroupTodo_(this, groupId, BigInt(msgSeq));
}
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
return getStrangerStatus_(this, uin);
}
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise<AiVoiceCategory[]> {
return fetchAiVoiceList_(this, groupId, chatType);
}
async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) {
return fetchAiVoice_(this, groupId, voiceId, text, chatType);
}
}
+8 -2
View File
@@ -208,11 +208,14 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 22,
businessType: isGroup ? 22 : 12,
} as any,
};
}
@@ -226,11 +229,14 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 21,
businessType: isGroup ? 21 : 11,
} as any,
};
}
@@ -191,7 +191,7 @@ export async function uploadHighwayHttp(
bridge: Bridge, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
const socket = await tcpConnect(session.host, session.port);
try {
@@ -201,7 +201,7 @@ export async function uploadHighwayHttp(
const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
const frame = packHighwayFrame(head, chunk);
@@ -487,7 +487,11 @@ export async function uploadVideoMsgInfo(
subFileType: 100,
},
],
compatQmsgSceneType: 2,
// Scene tag the NTV2 upload registers under. image-upload and
// ptt-upload both differentiate (group=2, c2c=1); video was
// hardcoded to the group value, which contributed to the c2c
// send-back rejection (PbSendMsg result=79).
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: { bizType: 0, textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
+233 -88
View File
@@ -2,12 +2,25 @@ import fs from 'fs';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } from './qq-info';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger } from '../utils/logger';
const log = createLogger('Identity');
/**
* Hooks Identity uses when its read methods miss every cache layer. Wired in
* after construction (Bridge owns these methods, but Bridge can't exist
* before Identity does). Each call is expected to invoke the matching
* remember* observation on this service as a side effect.
*/
export interface IdentityFetcher {
fetchProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupMemberList?(groupId: number): Promise<unknown>;
}
interface UserInput {
uid?: string;
uin?: number;
@@ -66,16 +79,43 @@ interface MemberRow {
active: number;
}
/**
* Authoritative store for everything we know about QQ actors observed
* during this session: the bot's own identity, friends, groups, group
* members, user profiles, plus the bidirectional UID↔UIN index that
* powers all OIDB-bound translation.
*
* Two layers internally:
* - In-memory state (this file) — O(1) for find* on the hot path.
* - SQLite (optional, opened by openForUin) — survives restarts.
*
* Both layers are kept in sync by the remember* / refresh paths.
* Callers should never reach below the public surface; the cascade and
* storage details are intentionally hidden.
*/
export class IdentityService {
private readonly db: DatabaseSync | null;
// ─── Self identity ───
private readonly uin_: string;
private nickname_ = '';
private selfProfile_: UserProfileInfo | null = null;
// ─── In-memory domain state ───
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private readonly groups_ = new Map<number, QQGroupInfo>();
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
private readonly uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>();
private inTransaction = false;
constructor(
private readonly qqInfo: QQInfo,
dbPath: string | null,
) {
// ─── Persistence + fetcher ───
private readonly db: DatabaseSync | null;
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
constructor(uin: string, dbPath: string | null) {
this.uin_ = uin;
if (!dbPath) {
this.db = null;
return;
@@ -89,12 +129,12 @@ export class IdentityService {
this.loadSnapshot();
}
static openForUin(qqInfo: QQInfo, dataRoot = 'data'): IdentityService {
return new IdentityService(qqInfo, path.join(dataRoot, qqInfo.uin, 'snowluma_identity.db'));
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
}
static memory(qqInfo: QQInfo): IdentityService {
return new IdentityService(qqInfo, null);
static memory(uin: string): IdentityService {
return new IdentityService(uin, null);
}
close(): void {
@@ -105,8 +145,143 @@ export class IdentityService {
return this.db !== null;
}
setFetcher(fetcher: IdentityFetcher): void {
this.fetcher = fetcher;
}
// ─── Self identity surface ───
get uin(): string { return this.uin_; }
get nickname(): string { return this.nickname_; }
set nickname(v: string) { this.nickname_ = v; }
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
// ─── Domain object reads ───
findUserProfile(uin: number): UserProfileInfo | null {
return this.userProfiles_.get(uin) ?? null;
}
get friends(): FriendInfo[] { return this.friends_; }
findFriend(uin: number): FriendInfo | null {
return this.friends_.find((f) => f.uin === uin) ?? null;
}
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
findGroup(groupId: number): QQGroupInfo | null {
return this.groups_.get(groupId) ?? null;
}
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
return this.groups_.get(groupId)?.members.get(uin) ?? null;
}
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.set(member.uin, member);
this.rememberUidUin(member.uid, member.uin);
}
// ─── ID translation ───
/**
* UIN → UID with network fallback. Returns cached value on hit; otherwise
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
* which is expected to write the result back through `rememberUserProfile`
* before this method re-queries the cache. Throws if no UID can be
* obtained from any layer.
*/
async resolveUid(uin: number, groupId?: number): Promise<string> {
const normalized = normalizeUin(uin);
if (normalized === null) throw new Error(`invalid uin: ${uin}`);
const cached = this.findUidByUin(normalized, groupId);
if (cached) return cached;
if (groupId !== undefined && this.fetcher?.fetchGroupMemberList) {
try { await this.fetcher.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const afterMembers = this.findUidByUin(normalized, groupId);
if (afterMembers) return afterMembers;
}
if (!this.fetcher) throw new Error(`failed to resolve UID for UIN ${normalized}: no fetcher`);
const profile = await this.fetcher.fetchProfile(normalized);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${normalized}`);
}
findUinByUid(uid: string, groupId?: number): number | null {
const normalized = normalizeUid(uid);
if (!normalized) return null;
if (groupId !== undefined) {
const member = this.findGroupMemberByUid(groupId, normalized);
if (member) return member.uin;
}
const mapped = this.uinByUid.get(normalized);
if (mapped !== undefined) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uin: number | null } | undefined;
const uin = normalizeUin(row?.uin);
if (uin !== null) return uin;
}
const row = this.db.prepare(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
}
findUidByUin(uin: number, groupId?: number): string | null {
const normalized = normalizeUin(uin);
if (normalized === null) return null;
if (groupId !== undefined) {
const member = this.groups_.get(groupId)?.members.get(normalized);
if (member?.uid) return member.uid;
}
const mapped = this.uidByUin.get(normalized);
if (mapped) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uid: string | null } | undefined;
const uid = normalizeUid(row?.uid);
if (uid) return uid;
}
const row = this.db.prepare(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
}
// ─── Observation (write side) ───
rememberFriends(friends: FriendInfo[]): void {
this.qqInfo.setFriends(friends);
this.friends_ = friends;
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
this.runWrite('friends', () => this.transaction(() => {
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
@@ -125,7 +300,7 @@ export class IdentityService {
}
rememberGroups(groups: QQGroupInfo[]): void {
this.qqInfo.setGroups(groups);
this.setGroupsInMemory(groups);
this.runWrite('groups', () => this.transaction(() => {
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
.run(nowSeconds());
@@ -143,7 +318,7 @@ export class IdentityService {
}
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
this.qqInfo.setGroupMembers(groupId, members);
this.setGroupMembersInMemory(groupId, members);
for (const member of members) this.rememberUidUin(member.uid, member.uin);
this.runWrite('group members', () => this.transaction(() => {
this.upsertGroup({ groupId, memberCount: members.length });
@@ -169,9 +344,9 @@ export class IdentityService {
}
rememberUserProfile(info: UserProfileInfo): void {
this.qqInfo.setUserProfile(info);
const selfUin = parseInt(this.qqInfo.uin, 10) || 0;
if (info.uin === selfUin) this.qqInfo.setSelfProfile(info);
this.userProfiles_.set(info.uin, info);
const selfUin = parseInt(this.uin_, 10) || 0;
if (info.uin === selfUin) this.selfProfile_ = info;
this.rememberUidUin(info.uid, info.uin);
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
uid: info.uid,
@@ -259,67 +434,7 @@ export class IdentityService {
});
}
findUinByUid(uid: string, groupId?: number): number | null {
const normalized = normalizeUid(uid);
if (!normalized) return null;
if (groupId !== undefined) {
const cached = this.qqInfo.resolveGroupMemberUid(groupId, normalized);
if (cached !== null) return cached;
}
const globalCached = this.qqInfo.resolveUid(normalized);
if (globalCached !== null) return globalCached;
const mapped = this.uinByUid.get(normalized);
if (mapped !== undefined) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uin: number | null } | undefined;
const uin = normalizeUin(row?.uin);
if (uin !== null) return uin;
}
const row = this.db.prepare(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
}
findUidByUin(uin: number, groupId?: number): string | null {
const normalized = normalizeUin(uin);
if (normalized === null) return null;
if (groupId !== undefined) {
const cached = this.qqInfo.findUidByUinInGroup(groupId, normalized);
if (cached) return cached;
}
const globalCached = this.qqInfo.findUidByUin(normalized);
if (globalCached) return globalCached;
const mapped = this.uidByUin.get(normalized);
if (mapped) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uid: string | null } | undefined;
const uid = normalizeUid(row?.uid);
if (uid) return uid;
}
const row = this.db.prepare(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
}
// ─── Private helpers ───
private rememberUidUin(uid: unknown, uin: unknown): void {
const normalizedUid = normalizeUid(uid);
@@ -329,6 +444,38 @@ export class IdentityService {
this.uidByUin.set(normalizedUin, normalizedUid);
}
private setGroupsInMemory(groups: QQGroupInfo[]): void {
// Preserve existing member maps where possible so a roster refresh
// doesn't blow away cached members for groups we already track.
const previous = new Map(this.groups_);
this.groups_.clear();
for (const g of groups) {
const existing = previous.get(g.groupId);
this.groups_.set(g.groupId, {
...g,
members: existing?.members ?? g.members ?? new Map(),
});
}
}
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.clear();
for (const m of members) {
g.members.set(m.uin, m);
}
}
private findGroupMemberByUid(groupId: number, uid: string): GroupMemberInfo | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uid === uid) return m;
}
return null;
}
private initSchema(): void {
this.db!.exec(`
CREATE TABLE IF NOT EXISTS users (
@@ -387,12 +534,13 @@ export class IdentityService {
FROM users
WHERE is_friend = 1 AND uin IS NOT NULL`,
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>;
this.qqInfo.setFriends(friendRows.map((row) => ({
this.friends_ = friendRows.map((row) => ({
uid: row.uid ?? '',
uin: row.uin ?? 0,
nickname: row.nickname,
remark: row.remark,
})));
}));
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
const groups = this.db!.prepare(
`SELECT group_id, group_name, remark, member_count, member_max
@@ -405,7 +553,7 @@ export class IdentityService {
member_count: number;
member_max: number;
}>;
this.qqInfo.setGroups(groups.map((row) => ({
this.setGroupsInMemory(groups.map((row) => ({
groupId: row.group_id,
groupName: row.group_name,
remark: row.remark,
@@ -419,7 +567,6 @@ export class IdentityService {
private hydrateActiveMembersForGroups(groupIds: number[]): void {
if (!this.db || groupIds.length === 0) return;
const membersByGroup = new Map<number, GroupMemberInfo[]>();
const select = this.db.prepare(
`SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time
@@ -440,11 +587,9 @@ export class IdentityService {
last_sent_time: number;
shut_up_time: number;
}>;
membersByGroup.set(groupId, rows.map(rowToMemberInfo));
}
for (const [groupId, members] of membersByGroup) {
this.qqInfo.setGroupMembers(groupId, members);
const members = rows.map(rowToMemberInfo);
this.setGroupMembersInMemory(groupId, members);
for (const m of members) this.rememberUidUin(m.uid, m.uin);
}
}
+6 -9
View File
@@ -6,15 +6,13 @@
import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
import { QQInfo } from './qq-info';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
interface QQSession {
qqInfo: QQInfo;
bridge: Bridge;
}
@@ -67,7 +65,7 @@ export class BridgeManager {
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
this.onSessionStarted_(uin, session.bridge);
}
}
}
@@ -92,7 +90,7 @@ export class BridgeManager {
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
this.onSessionStarted_(uin, session.bridge);
}
}
@@ -104,9 +102,8 @@ export class BridgeManager {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const qqInfo = new QQInfo(uin);
const bridge = new Bridge(qqInfo, IdentityService.openForUin(qqInfo));
session = { qqInfo, bridge };
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
@@ -119,7 +116,7 @@ export class BridgeManager {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> {
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
}
@@ -1,886 +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 { QQInfo } from './qq-info';
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(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number {
if (!uid) return fallback;
if (isNumericUin(uid)) {
const n = parseInt(uid, 10);
if (!isNaN(n)) return n;
}
if (groupId) {
const uin = qqInfo.resolveGroupMemberUid(groupId, uid);
if (uin !== null) return uin;
}
const uin = qqInfo.resolveUid(uid);
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<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;
}
function findTemplateValue(map: Map<string, string>, ...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<typeof import('./proto/element').ElemSchema>;
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<typeof MentionExtraSchema> | 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<typeof import('./proto/message').RichTextSchema>,
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, qqInfo: QQInfo): 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(qqInfo, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, 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(qqInfo, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, 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(qqInfo, 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(qqInfo, 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(qqInfo, 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(qqInfo, 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(qqInfo, 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(qqInfo, 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(qqInfo, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, 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(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
userUin: resolveUidToUin(qqInfo, 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(qqInfo, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '', fromUin),
authorUin: resolveUidToUin(qqInfo, 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(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, 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 = qqInfo.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 = qqInfo.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 = qqInfo.findFriend(fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev];
}
// const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48)));
return [];
}
@@ -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<typeof MessageBodySchema>;
export type PushMsgResponseHead = ProtoDecoded<typeof ResponseHeadSchema>;
export type PushMsgContentHead = ProtoDecoded<typeof ContentHeadSchema>;
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,
};
}
@@ -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];
}
@@ -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];
}
@@ -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];
};
@@ -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];
};
@@ -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];
};
@@ -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];
};
@@ -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];
};
@@ -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];
};
@@ -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,
}
@@ -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<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,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);
}
@@ -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<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) 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,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<typeof ElemSchema>;
type RichTextDecoded = ProtoDecoded<typeof RichTextSchema>;
export type PushMsgBody = ProtoDecoded<typeof MessageBodySchema>;
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<typeof MentionExtraSchema> | 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,
});
}
}
+275
View File
@@ -0,0 +1,275 @@
// Incoming packet pipeline — the chain that turns a single PacketInfo
// arriving from the hook layer into a stream of QQEventVariant
// emissions on the typed event bus. Replaces the inline orchestration
// that previously lived on Bridge.onPacket / triggerMemberCacheRefresh /
// rememberEventIdentity / dispatchAfterIdentityRefresh / etc.
//
// Stage chain per parser output:
// parse → enrich identity (sync, or async refresh)
// → side-effects (remember UID/UIN + schedule roster refresh)
// → log
// → emit on bus
//
// The pipeline owns its cmd handler map and its per-group coalesce table
// for background member-list refreshes. It does NOT own protocol calls
// — `refreshMemberCache` is injected by Bridge because it ultimately
// dispatches OIDB packets through Bridge.fetchGroupList /
// Bridge.fetchGroupMemberList.
import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import { createLogger } from '../utils/logger';
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
}
export class IncomingPacketPipeline {
private cmdHandlers_ = new Map<string, CmdParser[]>();
private memberRefreshTasks_ = new Map<number, Promise<void>>();
constructor(private readonly deps: PacketPipelineDeps) {}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
process(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.deps.identity);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.handleSideEffects(event);
printEvent(event);
this.emit(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private emit(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.deps.events.emit(event);
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.handleSideEffects(event, refreshed);
printEvent(event);
this.emit(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.deps.refreshMemberCache(
event.groupId,
!this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.deps.identity.findUinByUid(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
if (uin !== null) event.operatorUin = uin;
}
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.deps.identity.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.deps.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.deps.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
}
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
}
}
@@ -395,6 +395,11 @@ export const OidbGroupReactionSchema = {
groupUin: { field: 1, type: 'uint32' as const },
sequence: { field: 2, type: 'uint32' as const },
code: { field: 3, type: 'string' as const },
// 1 = legacy QQ face (short numeric id like "76"), 2 = unicode emoji
// (decimal codepoint string like "128516" for 😄). Omitting this
// field used to make unicode reactions fail server-side because the
// server defaulted to type=1 and couldn't resolve a 6-digit code.
type: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0x6D8_1: Group file list ---
@@ -856,6 +861,20 @@ export const OidbGetPskeyRespSchema = {
} satisfies ProtoSchema;
// customExt sub-message of SetStatus. Populated only by
// set_diy_online_status (status=10 + extStatus=2000 + this payload);
// regular set_online_status leaves field 4 unset.
//
// Wire (from napcat packet/transformer/proto/action/action.ts SetStatusCustomExt):
// 1 faceId (uint32) — face icon id, e.g. "Q我吧" sticker
// 2 text (string) — wording shown next to the icon
// 3 field3 (uint32) — face_type / template id; observed values 1..3
export const SetStatusCustomExtSchema = {
faceId: { field: 1, type: 'uint32' as const },
text: { field: 2, type: 'string' as const },
faceType: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SetStatusReqSchema = {
status: { field: 1, type: 'int32' as const },
extStatus: { field: 2, type: 'int32' as const },
@@ -1122,6 +1141,139 @@ export const Oidb0xf16ReqSchema = {
export const Oidb0xf16RespSchema = {} satisfies ProtoSchema;
// --- 0xF90_{1,2,3}: Set / complete / cancel group todo ---
// All three subCmds share the same body (groupUin + msgSeq); only the
// envelope subCmd differs. Sources: napcat
// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts.
export const OidbGroupTodoSchema = {
groupUin: { field: 1, type: 'uint32' as const },
msgSeq: { field: 2, type: 'uint64' as const },
} satisfies ProtoSchema;
// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) ---
export const OidbStrangerStatusKeySchema = {
key: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbStrangerStatusReqSchema = {
uin: { field: 1, type: 'uint32' as const },
key: { field: 3, type: 'repeated_message' as const, schema: OidbStrangerStatusKeySchema },
} satisfies ProtoSchema;
export const OidbStrangerStatusRespStatusSchema = {
key: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'uint64' as const },
} satisfies ProtoSchema;
export const OidbStrangerStatusRespDataSchema = {
status: { field: 2, type: 'message' as const, schema: OidbStrangerStatusRespStatusSchema },
} satisfies ProtoSchema;
export const OidbStrangerStatusRespSchema = {
data: { field: 1, type: 'message' as const, schema: OidbStrangerStatusRespDataSchema },
} satisfies ProtoSchema;
// --- 0x929D_0: Fetch AI voice character list ---
export const OidbAiVoiceListReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
chatType: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceListEntrySchema = {
voiceId: { field: 1, type: 'string' as const },
voiceDisplayName: { field: 2, type: 'string' as const },
voiceExampleUrl: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceListCategorySchema = {
category: { field: 1, type: 'string' as const },
voices: { field: 2, type: 'repeated_message' as const, schema: OidbAiVoiceListEntrySchema },
} satisfies ProtoSchema;
export const OidbAiVoiceListRespSchema = {
content: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceListCategorySchema },
} satisfies ProtoSchema;
// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) ---
export const OidbAiVoiceSessionSchema = {
sessionId: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
voiceId: { field: 2, type: 'string' as const },
text: { field: 3, type: 'string' as const },
chatType: { field: 4, type: 'uint32' as const },
session: { field: 5, type: 'message' as const, schema: OidbAiVoiceSessionSchema },
} satisfies ProtoSchema;
// We only need the fields the OneBot adapter consumes back: the
// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the
// statusCode that the server uses to signal "still rendering, retry".
export const OidbAiVoiceFileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceFileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: OidbAiVoiceFileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceIndexNodeSchema = {
info: { field: 1, type: 'message' as const, schema: OidbAiVoiceFileInfoSchema },
fileUuid: { field: 2, type: 'string' as const },
storeId: { field: 3, type: 'uint32' as const },
uploadTime: { field: 4, type: 'uint32' as const },
ttl: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceMsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: OidbAiVoiceIndexNodeSchema },
} satisfies ProtoSchema;
export const OidbAiVoiceMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceMsgInfoBodySchema },
} satisfies ProtoSchema;
export const OidbAiVoiceRespSchema = {
statusCode: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
msgInfo: { field: 4, type: 'message' as const, schema: OidbAiVoiceMsgInfoSchema },
} satisfies ProtoSchema;
// --- Highway cmdId 3000: GroupAvatarExtra ---
// Ported from Lagrange.Core/Internal/Packets/Service/Highway/GroupAvatarExtra.cs.
// Field values are protocol-prescribed constants (Lagrange comments on each).
export const GroupAvatarExtraField3Schema = {
field1: { field: 1, type: 'uint32' as const }, // observed value: 1
} satisfies ProtoSchema;
export const GroupAvatarExtraSchema = {
type: { field: 1, type: 'uint32' as const }, // observed value: 101
groupUin: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'message' as const, schema: GroupAvatarExtraField3Schema },
field5: { field: 5, type: 'uint32' as const }, // observed value: 3
field6: { field: 6, type: 'uint32' as const }, // observed value: 1
} satisfies ProtoSchema;
///////// --- group album
// --- Request Schemas ---
+4 -145
View File
@@ -1,5 +1,7 @@
// QQ info store — per-UIN state for friends, groups, member lookup.
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp
// Domain object shapes shared by IdentityService and its callers. The
// concrete state (own UIN, friends list, group rosters, profile cache)
// lives inside IdentityService — these interfaces just describe the
// records that flow across remember*/refresh* and find* boundaries.
export interface UserProfileInfo {
uin: number;
@@ -60,146 +62,3 @@ export interface GroupRequestInfo {
comment: string;
filtered: boolean;
}
export class QQInfo {
private uin_: string;
private nickname_ = '';
private selfProfile_: UserProfileInfo | null = null;
private userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private groups_ = new Map<number, QQGroupInfo>();
constructor(uin: string) {
this.uin_ = uin;
}
get uin(): string { return this.uin_; }
get nickname(): string { return this.nickname_; }
set nickname(v: string) { this.nickname_ = v; }
// --- Self profile ---
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
// --- User profiles ---
setUserProfile(info: UserProfileInfo): void {
this.userProfiles_.set(info.uin, info);
}
findUserProfile(uin: number): UserProfileInfo | null {
return this.userProfiles_.get(uin) ?? null;
}
// --- Friends ---
setFriends(friends: FriendInfo[]): void { this.friends_ = friends; }
get friends(): FriendInfo[] { return this.friends_; }
findFriend(uin: number): FriendInfo | null {
return this.friends_.find(f => f.uin === uin) ?? null;
}
// --- Groups ---
setGroups(groups: QQGroupInfo[]): void {
this.groups_.clear();
for (const g of groups) {
this.groups_.set(g.groupId, g);
}
}
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
findGroup(groupId: number): QQGroupInfo | null {
return this.groups_.get(groupId) ?? null;
}
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
return this.groups_.get(groupId)?.members.get(uin) ?? null;
}
setGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.clear();
for (const m of members) {
g.members.set(m.uin, m);
}
}
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.set(member.uin, member);
}
// --- UID resolution ---
resolveUid(uid: string): number | null {
// Check self
if (this.selfProfile_?.uid === uid) {
return this.selfProfile_.uin || parseInt(this.uin_, 10) || null;
}
// Check friends
for (const f of this.friends_) {
if (f.uid === uid) return f.uin;
}
// Check user profiles
for (const [, p] of this.userProfiles_) {
if (p.uid === uid) return p.uin;
}
// Check all group members
for (const [, g] of this.groups_) {
for (const [, m] of g.members) {
if (m.uid === uid) return m.uin;
}
}
return null;
}
resolveGroupMemberUid(groupId: number, uid: string): number | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uid === uid) return m.uin;
}
return null;
}
// --- Reverse UID lookup (UIN → UID) ---
findUidByUin(uin: number): string | null {
// Check self
if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) {
return this.selfProfile_.uid;
}
// Check friends
for (const f of this.friends_) {
if (f.uin === uin && f.uid) return f.uid;
}
// Check user profiles
for (const [, p] of this.userProfiles_) {
if (p.uin === uin && p.uid) return p.uid;
}
// Check all group members
for (const [, g] of this.groups_) {
for (const [, m] of g.members) {
if (m.uin === uin && m.uid) return m.uid;
}
}
return null;
}
findUidByUinInGroup(groupId: number, uin: number): string | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uin === uin && m.uid) return m.uid;
}
return null;
}
}
+16 -22
View File
@@ -4,7 +4,7 @@
// thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge';
import { sendOidbAndDecode } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
OidbClientKeyRespSchema,
OidbClientKeyReqSchema,
@@ -14,15 +14,12 @@ import {
import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_1',
0x102A,
1,
{},
OidbClientKeyReqSchema,
OidbClientKeyRespSchema,
);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_1',
oidbCmd: 0x102A, subCmd: 1,
request: { schema: OidbClientKeyReqSchema, value: {} },
response: { schema: OidbClientKeyRespSchema },
});
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
@@ -37,15 +34,12 @@ export async function forceFetchClientKey(bridge: Bridge) {
}
export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_0',
0x102A,
0,
{ domainList },
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_0',
oidbCmd: 0x102A, subCmd: 0,
request: { schema: OidbGetPskeyReqSchema, value: { domainList } },
response: { schema: OidbGetPskeyRespSchema },
});
const domainPskeyMap = new Map<string, string>();
@@ -66,9 +60,9 @@ export async function getCookies(bridge: Bridge, domain: string) {
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
@@ -99,7 +93,7 @@ export async function getSKey(bridge: Bridge): Promise<string> {
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.qqInfo.uin +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
@@ -6,7 +6,7 @@ import { getCookies } from './cookies';
export async function getGroupAlbumListWeb(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const uin = bridge.qqInfo.uin;
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
@@ -22,7 +22,7 @@ export async function uploadImageToGroupAlbumWeb(
filePath: string
): Promise<void> {
const groupCode = groupId.toString();
const uin = bridge.qqInfo.uin;
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
+267 -38
View File
@@ -36,7 +36,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const times = asNumber(params.times) || 1;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.sendLike(userId, times);
await ctx.bridge.sendLike(userId, times);
return okResponse();
});
@@ -94,9 +94,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const essenceDataAll = await ctx.getGroupEssenceAll(groupId);
const essenceDataAll = await ctx.bridge.getGroupEssenceAll(groupId);
const allMsgs = essenceDataAll.flatMap(res => res.data?.msg_list || []);
const allMsgs = essenceDataAll.flatMap((res: any) => res.data?.msg_list || []);
return okResponse(allMsgs);
} catch (e) {
@@ -125,7 +125,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
await ctx.bridge.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
return okResponse();
});
@@ -168,7 +168,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
await ctx.markGroupMsgAsRead(groupId, meta.sequence);
await ctx.bridge.markGroupMsgAsRead(groupId, meta.sequence);
return okResponse();
});
@@ -191,7 +191,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
await ctx.markPrivateMsgAsRead(userId, meta.sequence);
await ctx.bridge.markPrivateMsgAsRead(userId, meta.sequence);
return okResponse();
});
@@ -211,9 +211,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
if (meta.isGroup) {
await ctx.markGroupMsgAsRead(targetId, meta.sequence);
await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence);
} else {
await ctx.markPrivateMsgAsRead(targetId, meta.sequence);
await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence);
}
return okResponse();
});
@@ -221,12 +221,16 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- RKey ---
h.registerAction('get_rkey', async () => {
const handleGetRkey = async () => {
if (ctx.getDownloadRKeys) {
return okResponse(await ctx.getDownloadRKeys());
}
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
});
};
h.registerAction('get_rkey', handleGetRkey);
// napcat exposes the same payload under `nc_get_rkey`; mirror the alias
// so clients that follow napcat's docs work out-of-the-box.
h.registerAction('nc_get_rkey', handleGetRkey);
// --- OCR stubs ---
@@ -258,7 +262,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1,
};
await ctx.sendGroupNotice(groupId, content, options);
await ctx.bridge.sendGroupNotice(groupId, content, options);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -271,7 +275,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const notices = await ctx.getGroupNotice(groupId);
const notices = await ctx.bridge.getGroupNotice(groupId);
return okResponse(notices);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -288,7 +292,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const success = await ctx.deleteGroupNotice(groupId, fid);
const success = await ctx.bridge.deleteGroupNotice(groupId, fid);
if (success) {
return okResponse();
} else {
@@ -427,7 +431,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const cookies = await ctx.getCookiesStr(domain);
const cookies = await ctx.bridge.getCookiesStr(domain);
return okResponse({ cookies });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -437,7 +441,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_csrf_token', async () => {
try {
const token = await ctx.getCsrfToken();
const token = await ctx.bridge.getCsrfToken();
return okResponse({ token });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -449,7 +453,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const creds = await ctx.getCredentials(domain);
const creds = await ctx.bridge.getCredentials(domain);
return okResponse(creds);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -480,7 +484,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const remark = asString(params.remark) ?? '';
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.setFriendRemark(userId, remark);
await ctx.bridge.setFriendRemark(userId, remark);
return okResponse();
});
@@ -488,7 +492,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const remark = asString(params.remark) ?? '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupRemark(groupId, remark);
await ctx.bridge.setGroupRemark(groupId, remark);
return okResponse();
});
@@ -570,7 +574,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setProfile(nickname, personalNote);
await ctx.bridge.setProfile(nickname, personalNote);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -590,17 +594,81 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setOnlineStatus(status, extStatus, batteryStatus);
await ctx.bridge.setOnlineStatus(status, extStatus, batteryStatus);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_group_ignored_notifies', async () => {
return okResponse([]);
// DIY status — same wire packet as set_online_status, only the
// customExt sub-message is populated and status/extStatus are forced
// to the QQ-defined "I have a custom status" values (10 / 2000).
// face_id / face_type accept either number or numeric string (napcat
// parity); wording is the human-readable text shown next to the icon.
h.registerAction('set_diy_online_status', async (params) => {
const faceId = asNumber(params.face_id);
const faceType = asNumber(params.face_type) || 1;
const wording = asString(params.wording);
if (!faceId) return failedResponse(RETCODE.BAD_REQUEST, 'face_id is required');
try {
await ctx.bridge.setDiyOnlineStatus(faceId, wording, faceType);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
// Filtered (机器人/被忽略) group join requests. SnowLuma already
// implements the underlying oidb 0x10c8_2 fetch via fetchGroupRequests;
// these three actions just rename / project the same data for the
// OneBot dialects clients use in the wild.
const fetchFilteredGroupRequests = async () => {
try {
return await ctx.bridge.fetchGroupRequests(true);
} catch {
return [];
}
};
h.registerAction('get_group_ignored_notifies', async () => {
const reqs = await fetchFilteredGroupRequests();
return okResponse(reqs.map((r) => ({
group_id: r.groupId,
group_name: r.groupName,
request_id: r.sequence,
requester_uin: r.targetUin,
requester_nick: r.targetName,
message: r.comment,
checked: r.state !== 1,
actor: r.operatorUin,
invitor_uin: r.invitorUin,
invitor_nick: r.invitorName,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`,
})));
});
// napcat name for the subset of ignored notifies that are join requests
// (notify type==7). We map every entry that flowed through filtered
// 0x10c8_2 into napcat's shape — eventType already encodes the request
// category in our pipeline.
h.registerAction('get_group_ignore_add_request', async () => {
const reqs = await fetchFilteredGroupRequests();
return okResponse(reqs.map((r) => ({
request_id: r.sequence,
invitor_uin: r.invitorUin,
invitor_nick: r.invitorName,
group_id: r.groupId,
message: r.comment,
group_name: r.groupName,
checked: r.state !== 1,
actor: r.operatorUin,
requester_nick: r.targetName,
})));
});
// get_group_shut_list lives behind an oidb we don't yet wrap; honour
// the napcat contract (empty list) so callers don't blow up.
h.registerAction('get_group_shut_list', async () => {
return okResponse([]);
});
@@ -653,7 +721,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('fetch_custom_face', async (params) => {
const count = asNumber(params.count) || 10;
try {
const urls = await ctx.fetchCustomFace(count);
const urls = await ctx.bridge.fetchCustomFace(count);
return okResponse(urls);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -667,7 +735,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
const result = await ctx.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
const result = await ctx.bridge.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -684,7 +752,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
const result = await ctx.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
const result = await ctx.bridge.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
return okResponse({
result: 0,
errMsg: '',
@@ -733,7 +801,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const data = await ctx.getGroupAtAllRemain(groupId);
const data = await ctx.bridge.getGroupAtAllRemain(groupId);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -743,7 +811,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_unidirectional_friend_list', async () => {
try {
const data = await ctx.getUnidirectionalFriendList();
const data = await ctx.bridge.getUnidirectionalFriendList();
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -759,7 +827,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setSelfLongNick(longNick);
await ctx.bridge.setSelfLongNick(longNick);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -780,7 +848,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setAvatar(file);
await ctx.bridge.setAvatar(file);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -802,7 +870,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setInputStatus(userId, eventType);
await ctx.bridge.setInputStatus(userId, eventType);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -820,7 +888,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const translated = await ctx.translateEn2Zh(words);
const translated = await ctx.bridge.translateEn2Zh(words);
return okResponse({ words: translated });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -828,11 +896,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
h.registerAction('get_clientkey', async () => {
const clientKeyInfo = await ctx.forceFetchClientKey();
const clientKeyInfo = await ctx.bridge.forceFetchClientKey();
if (!clientKeyInfo.clientKey) {
return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error');
}
return okResponse(clientKeyInfo);
return okResponse({ ...clientKeyInfo });
});
h.registerAction('get_mini_app_ark', async (params) => {
@@ -844,7 +912,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const data = await ctx.getMiniAppArk(
const data = await ctx.bridge.getMiniAppArk(
String(type),
String(title),
String(desc),
@@ -870,7 +938,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const data = await ctx.clickInlineKeyboardButton(
const data = await ctx.bridge.clickInlineKeyboardButton(
groupId,
botAppid,
String(buttonId),
@@ -892,7 +960,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.sendGroupSign(groupId);
await ctx.bridge.sendGroupSign(groupId);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -934,9 +1002,170 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('.send_packet', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
// --- Raw packet escape hatch (napcat parity) ---
//
// napcat exposes both names; the dot-prefix variant is the original
// gocqhttp-era backdoor, the no-prefix one is the modern API. They do
// the same thing in SnowLuma: encode hex → Bridge.sendRawPacket → hex.
const handleSendPacket = async (params: import('../types').JsonObject) => {
const cmd = asString(params.cmd);
const dataHex = asString(params.data);
const rsp = asBoolean(params.rsp, true);
if (!cmd) return failedResponse(RETCODE.BAD_REQUEST, 'cmd is required');
if (!/^[0-9a-fA-F]*$/.test(dataHex) || dataHex.length % 2 !== 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length');
}
try {
const body = hexToBytes(dataHex);
const result = await ctx.bridge.sendRawPacket(cmd, body);
if (!result.success) {
return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed');
}
if (!rsp) return okResponse(null);
const respHex = result.responseData ? bytesToHex(result.responseData) : '';
return okResponse(respHex);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
};
h.registerAction('send_packet', handleSendPacket);
h.registerAction('.send_packet', handleSendPacket);
// --- Bot lifecycle (napcat parity) ---
h.registerAction('bot_exit', async () => {
// Defer so the OK response actually flushes before the process dies.
setTimeout(() => process.exit(0), 50);
return okResponse();
});
// SnowLuma has no separate packet-backend process (napcat's packet
// service runs out-of-process and can fail independently). Always
// report healthy.
h.registerAction('nc_get_packet_status', async () => {
return okResponse(null);
});
// napcat exposes `delete_group_folder`; SnowLuma's existing
// `delete_group_file_folder` is the same operation. Alias so clients
// following napcat docs work without rewriting payloads.
h.registerAction('delete_group_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.bridge.deleteGroupFileFolder(groupId, folderId);
return okResponse();
});
// --- Group todo (oidb 0xF90) ---
//
// The three subcommands share an identical payload (group + msgSeq);
// we extract once and dispatch by action name. msgSeq comes from the
// message metadata cache (set/complete/cancel always target a real
// message the bot has seen).
type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise<void>;
const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => {
const groupId = asNumber(params.group_id);
const messageId = asNumber(params.message_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
const meta = ctx.getMessageMeta(messageId);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
if (!meta.isGroup || meta.targetId !== groupId) {
return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group');
}
try {
await op(groupId, BigInt(meta.sequence));
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
};
h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.setGroupTodo(g, s)));
h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.completeGroupTodo(g, s)));
h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.cancelGroupTodo(g, s)));
// --- User online/ext status (napcat: nc_get_user_status) ---
h.registerAction('nc_get_user_status', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
const status = await ctx.bridge.getStrangerStatus(userId);
if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status');
return okResponse(status);
});
// --- AI voice (oidb 0x929D / 0x929B) ---
h.registerAction('get_ai_characters', async (params) => {
const groupId = asNumber(params.group_id);
const chatType = asNumber(params.chat_type) || 1;
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
try {
const list = await ctx.bridge.fetchAiVoiceList(groupId, chatType);
return okResponse(list.map((cat) => ({
type: cat.category,
characters: cat.voices.map((v) => ({
character_id: v.voiceId,
character_name: v.voiceDisplayName,
preview_url: v.voiceExampleUrl,
})),
})));
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
h.registerAction('get_ai_record', async (params) => {
const groupId = asNumber(params.group_id);
const character = asString(params.character);
const text = asString(params.text);
const chatType = asNumber(params.chat_type) || 1;
if (!groupId || !character || !text) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required');
}
try {
const node = await ctx.bridge.fetchAiVoice(groupId, character, text, chatType);
const url = await ctx.bridge.fetchGroupPttUrlByNode(groupId, node);
return okResponse(url);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
// napcat's send_group_ai_record is a side-effect-only call: invoking
// fetchAiVoice publishes the voice into the group; the returned
// message_id is always 0 because the oidb call doesn't echo one back.
h.registerAction('send_group_ai_record', async (params) => {
const groupId = asNumber(params.group_id);
const character = asString(params.character);
const text = asString(params.text);
const chatType = asNumber(params.chat_type) || 1;
if (!groupId || !character || !text) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required');
}
try {
await ctx.bridge.fetchAiVoice(groupId, character, text, chatType);
return okResponse({ message_id: 0 });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
function hexToBytes(hex: string): Uint8Array {
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return out;
}
function bytesToHex(buf: Buffer | Uint8Array): string {
const arr = buf instanceof Buffer ? buf : Buffer.from(buf);
return arr.toString('hex');
}
/**
+19 -10
View File
@@ -42,14 +42,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
await ctx.setGroupAddOption(groupId, addType);
await ctx.bridge.setGroupAddOption(groupId, addType);
return okResponse();
});
h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupSearch(groupId);
await ctx.bridge.setGroupSearch(groupId);
return okResponse();
});
@@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupAdmin(groupId, userId, enable);
await ctx.bridge.setGroupAdmin(groupId, userId, enable);
return okResponse();
});
@@ -67,7 +67,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupCard(groupId, userId, card);
await ctx.bridge.setGroupCard(groupId, userId, card);
return okResponse();
});
@@ -75,7 +75,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupName(groupId, name);
await ctx.bridge.setGroupName(groupId, name);
return okResponse();
});
@@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupSpecialTitle(groupId, userId, title);
await ctx.bridge.setGroupSpecialTitle(groupId, userId, title);
return okResponse();
});
@@ -103,11 +103,20 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol).
// `file` accepts everything bridge.setGroupAvatar's underlying
// loadBinarySource handles: local paths, file:// URLs, http(s) URLs,
// and base64:// data URIs — same surface as set_qq_avatar.
h.registerAction('set_group_portrait', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
await ctx.setGroupAvatar(groupId, file);
return okResponse();
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.bridge.setGroupAvatar(groupId, file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
}
@@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
await ctx.deleteGroupFile(groupId, fileId);
await ctx.bridge.deleteGroupFile(groupId, fileId);
return okResponse();
});
@@ -70,7 +70,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
await ctx.bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
@@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.deleteGroupFileFolder(groupId, folderId);
await ctx.bridge.deleteGroupFileFolder(groupId, folderId);
return okResponse();
});
@@ -102,7 +102,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.renameGroupFileFolder(groupId, folderId, newName);
await ctx.bridge.renameGroupFileFolder(groupId, folderId, newName);
return okResponse();
});
@@ -68,7 +68,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
try {
const honorInfo = await ctx.getGroupHonorInfo(groupId, typeStr as WebHonorType);
const honorInfo = await ctx.bridge.getGroupHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
+24 -35
View File
@@ -1,5 +1,6 @@
import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { RETCODE, failedResponse } from './types';
import { register as registerInfo } from './actions/info';
@@ -13,7 +14,7 @@ import { register as registerExtended } from './actions/extended';
import { register as registerGroupAlbum } from './actions/group-album';
import { WebHonorType } from '@/bridge/web/group-honor';
// import {ClientKeyInfo} from "@/bridge/bridge";
import { ClientKeyInfo } from '@/bridge/bridge';
export interface MessageSendResult {
messageId: number;
@@ -32,6 +33,14 @@ export interface GroupEssenceMsgRet {
}
export interface ApiActionContext {
/**
* Direct access to the BridgeInterface. Use for actions that are pure
* 1:1 calls to a Bridge method — no rename, no default args, no
* composition with messageStore / mediaStore. When translation IS
* needed, route through the named adapters declared below instead.
*/
bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
@@ -48,57 +57,39 @@ export interface ApiActionContext {
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo: (userId: number) => Promise<JsonObject | null>;
// Group admin
// Group admin (adapters: rename Bridge methods to OneBot vocabulary)
setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan: (groupId: number, enable: boolean) => Promise<void>;
setGroupAddOption: (groupId: number, addType: number) => Promise<void>;
setGroupSearch: (groupId: number) => Promise<void>;
setGroupAdmin: (groupId: number, userId: number, enable: boolean) => Promise<void>;
setGroupCard: (groupId: number, userId: number, card: string) => Promise<void>;
setGroupName: (groupId: number, name: string) => Promise<void>;
setGroupLeave: (groupId: number) => Promise<void>;
setGroupSpecialTitle: (groupId: number, userId: number, title: string) => Promise<void>;
getGroupAtAllRemain: (groupId: number) => Promise<any>;
// Group file
// Group file (adapters: field extraction + Bridge name translation)
uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>;
deleteGroupFile: (groupId: number, fileId: string) => Promise<void>;
moveGroupFile: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
createGroupFileFolder: (groupId: number, name: string, parentId?: string) => Promise<void>;
deleteGroupFileFolder: (groupId: number, folderId: string) => Promise<void>;
renameGroupFileFolder: (groupId: number, folderId: string, newName: string) => Promise<void>;
getPrivateFileUrl: (userId: number, fileId: string, fileHash: string) => Promise<string>;
// Requests
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
// Requests (adapters: rename to OneBot vocabulary)
handleFriendRequest: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Extended
sendLike: (userId: number, times: number) => Promise<void>;
// Pokes (adapters: flatten isGroup into bridge.sendPoke signature)
sendFriendPoke: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke: (groupId: number, userId: number) => Promise<void>;
// Essence (adapter: bakes the set/unset boolean)
setEssenceMsg: (messageId: number) => Promise<void>;
deleteEssenceMsg: (messageId: number) => Promise<void>;
forceFetchClientKey: () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
getUnidirectionalFriendList: () => Promise<any>;
setSelfLongNick: (longNick: string) => Promise<void>;
setInputStatus: (userId: number, eventType: number) => Promise<void>;
translateEn2Zh: (words: string[]) => Promise<string[]>;
getMiniAppArk: (type: string, title: string, desc: string, picUrl: string, jumpUrl: string) => Promise<any>;
clickInlineKeyboardButton: (groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) => Promise<any>;
sendGroupSign: (groupId: number) => Promise<void>;
// New context methods
setGroupReaction: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
// Profile reads with OneBot-specific default args
getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
// Friend deletion (adapter: rename + force-boolean)
handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>;
// Module wrappers / multi-dep compositions
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
getDownloadRKeys: () => Promise<JsonObject[]>;
// Forward message
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
@@ -108,16 +99,15 @@ export interface ApiActionContext {
setFriendRemark: (userId: number, remark: string) => Promise<void>;
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
setGroupAvatar: (groupId: number, source: string) => Promise<void>;
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead: (userId: number, sequence: number) => Promise<void>;
getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
fetchCustomFace: (count?: number) => Promise<string[]>;
getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
// Web
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise<any>;
getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
getGroupEssenceAll: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
getGroupAlbumList: (groupId: number) => Promise<any>;
uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise<void>;
@@ -128,11 +118,10 @@ export interface ApiActionContext {
getCookiesStr: (domain: string) => Promise<string>;
getCsrfToken: () => Promise<number>;
getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
forceFetchClientKey: () => Promise<ClientKeyInfo>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
// Avatar
setAvatar: (source: string) => Promise<void>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
+61 -53
View File
@@ -1,6 +1,5 @@
import type { WebHonorType } from '@/bridge/web/group-honor';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
@@ -36,6 +35,7 @@ import {
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { BridgeInterface } from '../bridge/bridge-interface';
/**
* Single shared context bag that flows through every OneBot instance-internal
@@ -56,8 +56,7 @@ export interface OneBotInstanceContext {
/** Self UIN parsed once, used in event payloads. */
selfId: number;
qqInfo: QQInfo;
bridge: Bridge;
bridge: BridgeInterface;
messageStore: MessageStore;
mediaStore: MediaStore;
@@ -73,10 +72,25 @@ export interface OneBotInstanceContext {
dispatchEvent(event: JsonObject): void;
}
/**
* Build the ApiActionContext that ApiHandler hands to each action file.
*
* Two flavours of entries live in here:
* - Adapters — rename a Bridge method (setGroupKick → kickGroupMember),
* compose with messageStore / mediaStore / ref, bake in a constant
* (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a
* bridge call into OneBot vocabulary (sendFriendPoke flattens the
* isGroup boolean), or extract a field from the bridge return shape.
* - Pass-throughs used to live here too but added zero value; OneBot
* actions now call `ctx.bridge.<name>` directly when no translation is
* happening (set_group_admin, set_online_status, set_avatar, …).
*/
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, qqInfo, messageStore, mediaStore } = ref;
const { bridge, messageStore, mediaStore } = ref;
return {
bridge,
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId),
@@ -89,29 +103,22 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions.
getFriendList: () => getFriendList(bridge, qqInfo),
getGroupList: (noCache) => getGroupList(bridge, qqInfo, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, qqInfo, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, qqInfo, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, qqInfo, userId),
// OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin.
// Group admin — names translate to OneBot vocabulary.
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
setGroupAddOption: (groupId, addType) => bridge.setGroupAddOption(groupId, addType),
setGroupSearch: (groupId) => bridge.setGroupSearch(groupId),
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
getGroupAtAllRemain: (groupId) => bridge.getGroupAtAllRemain(groupId),
// Group file.
// Group file — fileId field extraction + defaults.
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
@@ -122,45 +129,31 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => {
return bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
},
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
// Requests.
// Requests — name translation.
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Extended.
sendLike: (userId, times) => bridge.sendLike(userId, times),
// Pokes — flatten isGroup into the bridge signature.
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
// Essence — bake the set/unset boolean.
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => {
return bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie);
},
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
translateEn2Zh: (words) => bridge.translateEn2Zh(words),
getMiniAppArk: (type, title, desc, picUrl, jumpUrl) => bridge.getMiniAppArk(type, title, desc, picUrl, jumpUrl),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => {
return bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq);
},
sendGroupSign: (groupId) => bridge.sendGroupSign(groupId),
// NapCat-compatible extended actions.
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
// Profile-like / get_group_essence — OneBot-specific defaults that the
// action handlers don't supply.
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
// Message-store-backed history reads.
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
// Module wrappers / multi-dep compositions.
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
@@ -168,24 +161,30 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
forceFetchClientKey: () => bridge.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
if (!meta) throw new Error('message not found');
// QQ itself doesn't expose emoji reactions on private chats, so
// there is no wire path to forward this to; fail loudly instead
// of silently no-op'ing.
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.markGroupMsgAsRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => bridge.markPrivateMsgAsRead(userId, sequence),
setOnlineStatus: (status, extStatus, batteryStatus) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname, personalNote) => bridge.setProfile(nickname, personalNote),
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote),
// Web-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId),
getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId),
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath),
@@ -197,11 +196,20 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain) => bridge.getCredentials(domain),
// Extended
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
// Avatar.
setAvatar: (source) => bridge.setAvatar(source),
};
}
// Re-export Bridge type so consumers of OneBotInstanceContext that need it
// (legacy) keep the import surface stable.
export type { Bridge };
// Re-export WebHonorType so legacy spots that imported it via this module
// keep working.
export type { WebHonorType };
+7 -6
View File
@@ -1,5 +1,6 @@
import type { MessageElement } from '../bridge/events';
import type { Bridge, DownloadRKeyInfo } from '../bridge/bridge';
import type { DownloadRKeyInfo } from '../bridge/bridge';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { createLogger } from '../utils/logger';
const log = createLogger('OneBot');
@@ -26,7 +27,7 @@ export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
warmUp(bridge: Bridge, uin: string): void {
warmUp(bridge: BridgeInterface, uin: string): void {
bridge.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
@@ -38,7 +39,7 @@ export class RKeyCache {
);
}
resolveImageUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
@@ -54,7 +55,7 @@ export class RKeyCache {
* Resolve a URL for video/record/file media elements.
* Appends the correct RKey type based on media kind and group/private context.
*/
resolveMediaUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
@@ -93,12 +94,12 @@ export class RKeyCache {
}
}
private findRKey(bridge: Bridge, isGroup: boolean): string | null {
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
private findRKeyForType(bridge: Bridge, primaryType: number): string | null {
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => {
+5 -7
View File
@@ -1,6 +1,5 @@
import path from 'path';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { ApiHandler } from './api-handler';
import type { ConverterContext } from './event-converter';
import { MediaIndexer } from './media-indexer';
@@ -27,8 +26,7 @@ const log = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
readonly qqInfo: QQInfo;
private readonly bridge: Bridge;
private readonly bridge: BridgeInterface;
private readonly apiHandler: ApiHandler;
private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore;
@@ -43,9 +41,10 @@ export class OneBotInstance {
private heartbeatTimer: NodeJS.Timeout | null = null;
private static readonly HEARTBEAT_INTERVAL = 30000;
constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) {
get nickname(): string { return this.bridge.identity.nickname; }
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.qqInfo = qqInfo;
this.bridge = bridge;
this.rkeyCache = new RKeyCache();
@@ -75,7 +74,6 @@ export class OneBotInstance {
const ctx: OneBotInstanceContext = {
uin: this.uin,
selfId: parseInt(this.uin, 10) || 0,
qqInfo: this.qqInfo,
bridge: this.bridge,
messageStore: this.messageStore,
mediaStore: this.mediaStore,
+13 -14
View File
@@ -1,5 +1,4 @@
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { BridgeManager } from '../bridge/manager';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
@@ -12,8 +11,8 @@ export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
bind(bridgeManager: BridgeManager): void {
bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => {
this.onSessionStarted(uin, qqInfo, bridge);
bridgeManager.setSessionStartedCallback((uin, bridge) => {
this.onSessionStarted(uin, bridge);
});
bridgeManager.setSessionClosedCallback((uin) => {
@@ -49,11 +48,11 @@ export class OneBotManager {
this.instances.clear();
}
private onSessionStarted(uin: string, qqInfo: QQInfo, bridge: Bridge): void {
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin);
const instance = new OneBotInstance(uin, qqInfo, bridge, config);
const instance = new OneBotInstance(uin, bridge, config);
const activePid = bridge.activePid;
if (activePid !== null) {
@@ -62,13 +61,13 @@ export class OneBotManager {
// Seed nickname with the UIN so the WebUI never renders blank while
// warmup is in flight or if warmup never resolves a real nickname.
if (!qqInfo.nickname) qqInfo.nickname = uin;
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin);
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
warmUpBridgeState(uin, qqInfo, bridge).catch((err) => {
warmUpBridgeState(uin, bridge).catch((err) => {
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
@@ -84,13 +83,13 @@ export class OneBotManager {
}
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
// Step 1: Fetch friend list + derive self profile when QQ happens to
// include self in the response. Some accounts / versions omit self,
// which used to leave qqInfo.nickname empty — see step 1b for the
// which used to leave identity.nickname empty — see step 1b for the
// explicit fallback.
try {
const friends = await bridge.fetchFriendList();
@@ -98,12 +97,12 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
for (const f of friends) {
if (f.uin === selfUin) {
qqInfo.setSelfProfile({
bridge.identity.setSelfProfile({
uin: f.uin, uid: f.uid,
nickname: f.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
});
qqInfo.nickname = f.nickname || uin;
bridge.identity.nickname = f.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
selfResolved = true;
break;
@@ -120,8 +119,8 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
if (!selfResolved && selfUin > 0) {
try {
const profile = await bridge.fetchUserProfile(selfUin);
qqInfo.setSelfProfile(profile);
qqInfo.nickname = profile.nickname || uin;
bridge.identity.setSelfProfile(profile);
bridge.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
uin, profile.uid, profile.nickname);
} catch (e) {
@@ -12,13 +12,13 @@
//
// Used as the `mediaUrlResolver` callback in `ConverterContext`.
import type { Bridge } from '../bridge/bridge';
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { MessageElement } from '../bridge/events';
import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver {
constructor(
private readonly bridge: Bridge,
private readonly bridge: BridgeInterface,
private readonly rkeyCache: RKeyCache,
) {}
@@ -1,17 +1,17 @@
import type { Bridge } from '../../bridge/bridge';
import type { QQInfo } from '../../bridge/qq-info';
import type { BridgeInterface } from '../../bridge/bridge-interface';
import type { IdentityService } from '../../bridge/identity-service';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
const nickname = ref.bridge.identity.nickname || ref.uin;
return { userId, nickname };
}
// Keep refreshes scoped. A broad "refresh all members in all groups" call can
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promise<void> {
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise<void> {
try {
await bridge.fetchGroupMemberList(groupId);
} catch {
@@ -19,7 +19,7 @@ async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promi
}
}
export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const friends = await bridge.fetchFriendList();
return friends.map(f => ({
@@ -28,7 +28,7 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
remark: f.remark as any,
}));
} catch {
return qqInfo.friends.map(f => ({
return bridge.identity.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
@@ -37,18 +37,17 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
}
export async function getGroupList(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
noCache?: boolean,
): Promise<JsonObject[]> {
try {
if (noCache || qqInfo.groups.length === 0) {
if (noCache || bridge.identity.groups.length === 0) {
await bridge.fetchGroupList();
}
} catch {
// Use cached data.
}
return qqInfo.groups.map(g => ({
return bridge.identity.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
@@ -57,19 +56,18 @@ export async function getGroupList(
}
export async function getGroupInfo(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroup(groupId)) {
if (noCache || !bridge.identity.findGroup(groupId)) {
try {
await bridge.fetchGroupList();
} catch {
// Use cached data.
}
}
const g = qqInfo.findGroup(groupId);
const g = bridge.identity.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
@@ -80,41 +78,39 @@ export async function getGroupInfo(
}
export async function getGroupMemberList(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject[]> {
if (noCache) {
await refreshSingleGroupMembers(bridge, groupId);
return getCachedGroupMembers(qqInfo, groupId);
return getCachedGroupMembers(bridge.identity, groupId);
}
try {
const members = await bridge.fetchGroupMemberList(groupId);
return members.map(m => formatGroupMember(groupId, m));
} catch {
return getCachedGroupMembers(qqInfo, groupId);
return getCachedGroupMembers(bridge.identity, groupId);
}
}
export async function getGroupMemberInfo(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
groupId: number,
userId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroupMember(groupId, userId)) {
if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
await refreshSingleGroupMembers(bridge, groupId);
}
const m = qqInfo.findGroupMember(groupId, userId);
const m = bridge.identity.findGroupMember(groupId, userId);
if (!m) return null;
return formatGroupMember(groupId, m);
}
export async function getGroupFiles(
bridge: Bridge,
bridge: BridgeInterface,
groupId: number,
folderId?: string,
): Promise<JsonObject> {
@@ -146,8 +142,7 @@ export async function getGroupFiles(
}
export async function getStrangerInfo(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
userId: number,
): Promise<JsonObject | null> {
try {
@@ -159,7 +154,7 @@ export async function getStrangerInfo(
age: p.age as any,
};
} catch {
const p = qqInfo.findUserProfile(userId);
const p = bridge.identity.findUserProfile(userId);
if (!p) return null;
return {
user_id: p.uin as any,
@@ -170,7 +165,7 @@ export async function getStrangerInfo(
}
}
export async function getGroupSystemMessages(bridge: Bridge): Promise<JsonObject[]> {
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const reqs = await bridge.fetchGroupRequests();
return reqs.map(r => ({
@@ -187,7 +182,7 @@ export async function getGroupSystemMessages(bridge: Bridge): Promise<JsonObject
}
}
export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const rkeys = await bridge.fetchDownloadRKeys();
return rkeys.map(r => ({
@@ -201,8 +196,8 @@ export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
}
}
function getCachedGroupMembers(qqInfo: QQInfo, groupId: number): JsonObject[] {
const g = qqInfo.findGroup(groupId);
function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
const g = identity.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, member] of g.members) {
@@ -1,4 +1,4 @@
import type { Bridge } from '../../bridge/bridge';
import type { BridgeInterface } from '../../bridge/bridge-interface';
import { createLogger } from '../../utils/logger';
import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types';
@@ -21,7 +21,7 @@ export async function getImageInfo(
}
export async function getRecordInfo(
bridge: Bridge,
bridge: BridgeInterface,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
@@ -1,4 +1,4 @@
import type { Bridge } from '../../bridge/bridge';
import type { BridgeInterface } from '../../bridge/bridge-interface';
import type { ForwardNodePayload, MessageElement } from '../../bridge/events';
import { createLogger } from '../../utils/logger';
import type { MessageSendResult } from '../api-handler';
@@ -63,7 +63,7 @@ export async function getFriendMsgHistory(
.map(sanitizeMessageEventForApi);
}
export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
if (meta.isGroup) {
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
} else {
@@ -78,7 +78,7 @@ export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise<
}
export async function setEssenceMessage(
bridge: Bridge,
bridge: BridgeInterface,
messageStore: MessageStore,
messageId: number,
enable: boolean,
@@ -1,7 +1,7 @@
import type { Bridge } from '../../bridge/bridge';
import type { BridgeInterface } from '../../bridge/bridge-interface';
export async function handleGroupAddRequest(
bridge: Bridge,
bridge: BridgeInterface,
flag: string,
approve: boolean,
reason: string,
+10
View File
@@ -1,4 +1,5 @@
const HEX_CHARS = '0123456789abcdef';
const HEX_CHARS_UPPER = '0123456789ABCDEF';
export function toHex(data: Uint8Array | Buffer): string {
let h = '';
@@ -9,6 +10,15 @@ export function toHex(data: Uint8Array | Buffer): string {
return h;
}
export function toHexUpper(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS_UPPER[b >> 4];
h += HEX_CHARS_UPPER[b & 0xf];
}
return h;
}
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
const limit = Math.max(0, Math.min(maxBytes, data.length));
const head = toHex(data.subarray(0, limit));
+1 -1
View File
@@ -306,7 +306,7 @@ export async function initWebUI(
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.qqInfo.nickname }));
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
return c.json({ list });
});