Merge pull request #36 from SnowLuma/dev

chore: promote dev → main (85b59bc)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-05-15 01:48:08 +08:00
commit 07449788c6
59 files changed
+2238 -1474

No files matched your search

+3 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "snowluma-monorepo", "name": "snowluma-monorepo",
"version": "1.7.9", "version": "1.8.0",
"description": "SnowLuma monorepo workspace (pnpm)", "description": "SnowLuma monorepo workspace (pnpm)",
"private": true, "private": true,
"type": "module", "type": "module",
@@ -17,7 +17,8 @@
"typecheck": "pnpm -r --if-present typecheck", "typecheck": "pnpm -r --if-present typecheck",
"lint": "pnpm -r --if-present lint", "lint": "pnpm -r --if-present lint",
"start": "node dist/index.mjs", "start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs" "bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
}, },
"devDependencies": { "devDependencies": {
"cross-env": "^10.1.0", "cross-env": "^10.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@snowluma/core", "name": "@snowluma/core",
"version": "1.7.9", "version": "1.8.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true, "private": true,
"type": "module", "type": "module",
+4 -4
View File
@@ -29,7 +29,7 @@ async function buildForwardPushBody(
bridge: Bridge, bridge: Bridge,
node: ForwardNodePayload, node: ForwardNodePayload,
): Promise<Record<string, unknown>> { ): 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'); if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin); const nickname = node.nickname.trim() || String(fromUin);
@@ -41,7 +41,7 @@ async function buildForwardPushBody(
return { return {
responseHead: { responseHead: {
fromUin, fromUin,
toUid: bridge.qqInfo.selfUid ?? '', toUid: bridge.identity.selfUid ?? '',
forward: { forward: {
friendName: nickname, friendName: nickname,
}, },
@@ -173,14 +173,14 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema); const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const pkt: PacketInfo = { const pkt: PacketInfo = {
pid: 0, pid: 0,
uin: bridge.qqInfo.uin, uin: bridge.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0, seqId: 0,
retCode: 0, retCode: 0,
fromClient: false, fromClient: false,
body: wrapped, body: wrapped,
}; };
const events = parseMsgPush(pkt, bridge.qqInfo); const events = parseMsgPush(pkt, bridge.identity);
const event = events.find(e => const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message'); e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue; if (!event) continue;
+33 -22
View File
@@ -3,7 +3,7 @@
// protocol uses opaque UIDs rather than QQ uin numbers. // protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
OidbDeleteFriendSchema, OidbDeleteFriendSchema,
OidbFriendRequestActionSchema, OidbFriendRequestActionSchema,
@@ -13,32 +13,40 @@ import {
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> { export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag; let targetUid = uidOrFlag;
if (/^\d+$/.test(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, await runOidb(bridge, {
{ accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema); 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> { export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await resolveUserUid(bridge, userId); const targetUid = await bridge.resolveUserUid(userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0, await runOidb(bridge, {
{ cmd: 'OidbSvcTrpcTcp.0x126b_0',
field1: { oidbCmd: 0x126B, subCmd: 0,
targetUid, request: {
field2: { schema: OidbDeleteFriendSchema,
field1: 130, value: {
field2: 109, field1: {
field3: { targetUid,
field1: 8, field2: {
field2: 8, field1: 130,
field3: 50, 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 // Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here // 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> { export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId); const uid = await bridge.resolveUserUid(userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2, await runOidb(bridge, {
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema); 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. // so callers can grep across the two layers.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
Oidb0x89a_0AddOptionSchema, Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema, Oidb0x89a_0SearchSchema,
@@ -26,26 +26,50 @@ import {
// ─────────────── mute / un-mute ─────────────── // ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> { export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1, await runOidb(bridge, {
{ groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema); 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> { export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, await runOidb(bridge, {
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema); cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
});
} }
// ─────────────── join-policy ─────────────── // ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> { export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, await runOidb(bridge, {
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema); 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> { export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, await runOidb(bridge, {
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema); 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( export async function setGroupAddRequest(
@@ -54,53 +78,92 @@ export async function setGroupAddRequest(
): Promise<void> { ): Promise<void> {
const subCmd = filtered ? 2 : 1; const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await sendOidbAndCheck(bridge, cmd, 0x10C8, subCmd, await runOidb(bridge, {
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, cmd,
OidbGroupRequestActionSchema, true); oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
} }
// ─────────────── kick / leave ─────────────── // ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1, await runOidb(bridge, {
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema); 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> { 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))); const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1, await runOidb(bridge, {
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema); 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> { export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1, await runOidb(bridge, {
{ groupUin: groupId }, OidbLeaveGroupSchema); cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
} }
// ─────────────── role / display name ─────────────── // ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> { export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1, await runOidb(bridge, {
{ groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema); 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> { export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3, await runOidb(bridge, {
{ groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema); 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> { export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_15', 0x89A, 15, await runOidb(bridge, {
{ groupUin: groupId, body: { targetName: name } }, OidbRenameGroupSchema); 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> { export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2, await runOidb(bridge, {
{ groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema); cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
});
} }
// ─────────────── personal-side metadata ─────────────── // ─────────────── 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 // here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list". // group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> { export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1, await runOidb(bridge, {
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema); cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
} }
// ─────────────── group-level quota query ─────────────── // ─────────────── group-level quota query ───────────────
@@ -123,20 +189,17 @@ export async function getGroupAtAllRemain(
basic1: 1, basic1: 1,
basic2: 2, basic2: 2,
basic3: 1, basic3: 1,
uin: BigInt(bridge.qqInfo.uin), uin: BigInt(bridge.identity.uin),
groupId: BigInt(groupId), groupId: BigInt(groupId),
type: 0, type: 0,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x8a7_0',
'OidbSvcTrpcTcp.0x8a7_0', oidbCmd: 0x8A7, subCmd: 0,
0x8A7, request: { schema: Oidb0x8a7ReqSchema, value: req },
0, response: { schema: Oidb0x8a7RespSchema },
req, });
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
);
if (!result) { if (!result) {
throw new Error('get group at all remain result empty'); throw new Error('get group at all remain result empty');
+199 -199
View File
@@ -7,7 +7,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode'; import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode, resolveUserUid } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils'; import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import { import {
@@ -241,16 +241,12 @@ async function fetchNtv2DownloadUrl(
oidbCmd: number, oidbCmd: number,
payload: Record<string, unknown>, payload: Record<string, unknown>,
): Promise<string> { ): Promise<string> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: serviceCmd,
serviceCmd, oidbCmd, subCmd: 200,
oidbCmd, request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
200, response: { schema: NTV2RichMediaRespSchema },
payload, });
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
true,
);
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
@@ -266,11 +262,15 @@ async function fetchNtv2DownloadUrl(
// ─────────────── file count ─────────────── // ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await sendOidbAndDecode<any>(bridge, const resp = await runOidb<any>(bridge, {
'OidbSvcTrpcTcp.0x6d8_3', 0x6D8, 3, cmd: 'OidbSvcTrpcTcp.0x6d8_3',
{ count: { groupUin: groupId, appId: 7, busId: 0 } }, oidbCmd: 0x6D8, subCmd: 3,
OidbGroupFileCountViewReqSchema, request: {
OidbGroupFileCountViewRespSchema); schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
return { return {
fileCount: toInt(resp?.count?.fileCount ?? 0), fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000), maxCount: toInt(resp?.count?.maxCount ?? 10000),
@@ -293,31 +293,31 @@ export async function uploadGroupFile(
const fileName = normalizeUploadFileName(name, loaded.fileName); const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes); const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_0',
'OidbSvcTrpcTcp.0x6d6_0', oidbCmd: 0x6D6, subCmd: 0,
0x6D6, request: {
0, schema: OidbGroupFileReqSchema,
{ value: {
file: { file: {
groupUin: groupId, groupUin: groupId,
appId: 4, appId: 4,
busId: 102, busId: 102,
entrance: 6, entrance: 6,
targetDirectory: normalizeDirectory(folderId), targetDirectory: normalizeDirectory(folderId),
fileName, fileName,
localDirectory: `/${fileName}`, localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length), fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1, fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0), fileSha3: new Uint8Array(0),
fileMd5: hashes.md5, fileMd5: hashes.md5,
field15: true, field15: true,
},
}, },
isUid: true,
}, },
OidbGroupFileReqSchema, response: { schema: OidbGroupFileRespSchema },
OidbGroupFileRespSchema, });
true,
);
const upload = resp?.upload; const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing'); if (!upload) throw new Error('group file upload response missing');
@@ -327,7 +327,7 @@ export async function uploadGroupFile(
if (!fileId) throw new Error('group file upload response missing file_id'); if (!fileId) throw new Error('group file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) { 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'); if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
@@ -368,48 +368,48 @@ export async function uploadPrivateFile(
const loaded = await loadBinarySource(source, 'file'); const loaded = await loadBinarySource(source, 'file');
if (!loaded.bytes.length) throw new Error('private file is empty'); if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await resolveUserUid(bridge, userId); const targetUid = await bridge.resolveUserUid(userId);
let selfUid = bridge.qqInfo.selfUid; let selfUid = bridge.identity.selfUid;
if (!selfUid) { if (!selfUid) {
const selfUin = toInt(bridge.qqInfo.uin); const selfUin = toInt(bridge.identity.uin);
if (selfUin > 0) { if (selfUin > 0) {
selfUid = await resolveUserUid(bridge, selfUin); selfUid = await bridge.resolveUserUid(selfUin);
} }
} }
if (!selfUid) throw new Error('self uid is unavailable'); 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'); if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName); const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes); const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xe37_1700',
'OidbSvcTrpcTcp.0xe37_1700', oidbCmd: 0xE37, subCmd: 1700,
0xE37, request: {
1700, schema: OidbPrivateFileUploadReqSchema,
{ value: {
command: 1700, command: 1700,
seq: 0, seq: 0,
upload: { upload: {
senderUid: selfUid, senderUid: selfUid,
receiverUid: targetUid, receiverUid: targetUid,
fileSize: loaded.bytes.length, fileSize: loaded.bytes.length,
fileName, fileName,
md510MCheckSum: md5First10MB(loaded.bytes), md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1, sha1CheckSum: hashes.sha1,
localPath: '/', localPath: '/',
md5CheckSum: hashes.md5, md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0), sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
}, },
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
}, },
OidbPrivateFileUploadReqSchema, response: { schema: OidbPrivateFileUploadRespSchema },
OidbPrivateFileUploadRespSchema, });
);
const upload = resp?.upload; const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing'); if (!upload) throw new Error('private file upload response missing');
@@ -458,27 +458,27 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
const pageSize = 20; const pageSize = 20;
let startIndex = 0; let startIndex = 0;
for (let page = 0; page < 200; page++) { for (let page = 0; page < 200; page++) {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d8_1',
'OidbSvcTrpcTcp.0x6d8_1', oidbCmd: 0x6D8, subCmd: 1,
0x6D8, request: {
1, schema: OidbGroupFileViewReqSchema,
{ value: {
list: { list: {
groupUin: groupId, groupUin: groupId,
appId: 7, appId: 7,
targetDirectory, targetDirectory,
fileCount: pageSize, fileCount: pageSize,
sortBy: 1, sortBy: 1,
startIndex, startIndex,
field17: 2, field17: 2,
field18: 0, field18: 0,
},
}, },
isUid: true,
}, },
OidbGroupFileViewReqSchema, response: { schema: OidbGroupFileViewRespSchema },
OidbGroupFileViewRespSchema, });
true,
);
const list = resp?.list; const list = resp?.list;
if (!list) break; if (!list) break;
@@ -489,7 +489,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
if (type === 1 && item?.fileInfo) { if (type === 1 && item?.fileInfo) {
const file = item.fileInfo; const file = item.fileInfo;
const uploader = toInt(file.uploaderUin); const uploader = toInt(file.uploaderUin);
const cached = bridge.qqInfo.findGroupMember(groupId, uploader); const cached = bridge.identity.findGroupMember(groupId, uploader);
files.push({ files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '', fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '', fileName: typeof file.fileName === 'string' ? file.fileName : '',
@@ -508,7 +508,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
} else if (type === 2 && item?.folderInfo) { } else if (type === 2 && item?.folderInfo) {
const folder = item.folderInfo; const folder = item.folderInfo;
const creator = toInt(folder.creatorUin); const creator = toInt(folder.creatorUin);
const cached = bridge.qqInfo.findGroupMember(groupId, creator); const cached = bridge.identity.findGroupMember(groupId, creator);
folders.push({ folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '', folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '', folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
@@ -533,23 +533,23 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
// ─────────────── url fetch (group / private files) ─────────────── // ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> { export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_2',
'OidbSvcTrpcTcp.0x6d6_2', oidbCmd: 0x6D6, subCmd: 2,
0x6D6, request: {
2, schema: OidbGroupFileReqSchema,
{ value: {
download: { download: {
groupUin: groupId, groupUin: groupId,
appId: 7, appId: 7,
busId, busId,
fileId, fileId,
},
}, },
isUid: true,
}, },
OidbGroupFileReqSchema, response: { schema: OidbGroupFileRespSchema },
OidbGroupFileRespSchema, });
true,
);
const download = resp?.download; const download = resp?.download;
if (!download) throw new Error('group file url response missing'); if (!download) throw new Error('group file url response missing');
@@ -568,30 +568,30 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
} }
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> { export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await resolveUserUid(bridge, userId); const uid = await bridge.resolveUserUid(userId);
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xe37_1200',
'OidbSvcTrpcTcp.0xe37_1200', oidbCmd: 0xE37, subCmd: 1200,
0xE37, request: {
1200, schema: OidbPrivateFileDownloadReqSchema,
{ value: {
subCommand: 1200, subCommand: 1200,
field2: 1, field2: 1,
body: { body: {
receiverUid: uid, receiverUid: uid,
fileUuid: fileId, fileUuid: fileId,
type: 2, type: 2,
fileHash, fileHash,
t2: 0, 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, response: { schema: OidbPrivateFileDownloadRespSchema },
OidbPrivateFileDownloadRespSchema, });
);
const result = resp?.body?.result; const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : ''; const server = typeof result?.server === 'string' ? result.server : '';
@@ -606,22 +606,22 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId
// ─────────────── delete / move ─────────────── // ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> { export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_3',
'OidbSvcTrpcTcp.0x6d6_3', oidbCmd: 0x6D6, subCmd: 3,
0x6D6, request: {
3, schema: OidbGroupFileReqSchema,
{ value: {
delete: { delete: {
groupUin: groupId, groupUin: groupId,
busId: 102, busId: 102,
fileId, fileId,
},
}, },
isUid: true,
}, },
OidbGroupFileReqSchema, response: { schema: OidbGroupFileRespSchema },
OidbGroupFileRespSchema, });
true,
);
const result = resp?.delete; const result = resp?.delete;
if (!result) throw new Error('group file delete response missing'); if (!result) throw new Error('group file delete response missing');
@@ -635,25 +635,25 @@ export async function moveGroupFile(
parentDirectory: string, parentDirectory: string,
targetDirectory: string, targetDirectory: string,
): Promise<void> { ): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_5',
'OidbSvcTrpcTcp.0x6d6_5', oidbCmd: 0x6D6, subCmd: 5,
0x6D6, request: {
5, schema: OidbGroupFileReqSchema,
{ value: {
move: { move: {
groupUin: groupId, groupUin: groupId,
appId: 7, appId: 7,
busId: 102, busId: 102,
fileId, fileId,
parentDirectory, parentDirectory,
targetDirectory, targetDirectory,
},
}, },
isUid: true,
}, },
OidbGroupFileReqSchema, response: { schema: OidbGroupFileRespSchema },
OidbGroupFileRespSchema, });
true,
);
const result = resp?.move; const result = resp?.move;
if (!result) throw new Error('group file move response missing'); if (!result) throw new Error('group file move response missing');
@@ -663,22 +663,22 @@ export async function moveGroupFile(
// ─────────────── folders ─────────────── // ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> { export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d7_0',
'OidbSvcTrpcTcp.0x6d7_0', oidbCmd: 0x6D7, subCmd: 0,
0x6D7, request: {
0, schema: OidbGroupFileFolderReqSchema,
{ value: {
create: { create: {
groupUin: groupId, groupUin: groupId,
rootDirectory: normalizeDirectory(parentId), rootDirectory: normalizeDirectory(parentId),
folderName: name, folderName: name,
},
}, },
isUid: true,
}, },
OidbGroupFileFolderReqSchema, response: { schema: OidbGroupFileFolderRespSchema },
OidbGroupFileFolderRespSchema, });
true,
);
const result = resp?.create; const result = resp?.create;
if (!result) throw new Error('group folder create response missing'); if (!result) throw new Error('group folder create response missing');
@@ -686,21 +686,21 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam
} }
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> { export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d7_1',
'OidbSvcTrpcTcp.0x6d7_1', oidbCmd: 0x6D7, subCmd: 1,
0x6D7, request: {
1, schema: OidbGroupFileFolderReqSchema,
{ value: {
delete: { delete: {
groupUin: groupId, groupUin: groupId,
folderId, folderId,
},
}, },
isUid: true,
}, },
OidbGroupFileFolderReqSchema, response: { schema: OidbGroupFileFolderRespSchema },
OidbGroupFileFolderRespSchema, });
true,
);
const result = resp?.delete; const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing'); if (!result) throw new Error('group folder delete response missing');
@@ -708,22 +708,22 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol
} }
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> { export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d7_2',
'OidbSvcTrpcTcp.0x6d7_2', oidbCmd: 0x6D7, subCmd: 2,
0x6D7, request: {
2, schema: OidbGroupFileFolderReqSchema,
{ value: {
rename: { rename: {
groupUin: groupId, groupUin: groupId,
folderId, folderId,
newFolderName, newFolderName,
},
}, },
isUid: true,
}, },
OidbGroupFileFolderReqSchema, response: { schema: OidbGroupFileFolderRespSchema },
OidbGroupFileFolderRespSchema, });
true,
);
const result = resp?.rename; const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing'); if (!result) throw new Error('group folder rename response missing');
@@ -5,7 +5,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode'; import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
C2CRecallRequestSchema, C2CRecallRequestSchema,
GroupRecallRequestSchema, GroupRecallRequestSchema,
@@ -28,7 +28,7 @@ export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number, bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number, msgSeq: number, random: number, timestamp: number,
): Promise<void> { ): Promise<void> {
const targetUid = await resolveUserUid(bridge, userUin); const targetUid = await bridge.resolveUserUid(userUin);
const request = protoEncode({ const request = protoEncode({
type: 1, type: 1,
targetUid, targetUid,
@@ -53,7 +53,7 @@ export async function markPrivateMessageRead(
msgSeq: number, msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000), timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> { ): Promise<void> {
const uid = await resolveUserUid(bridge, userId); const uid = await bridge.resolveUserUid(userId);
const request = protoEncode({ const request = protoEncode({
c2cList: [ 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> { export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2; const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await sendOidbAndCheck(bridge, cmd, 0xEAC, subCmd, await runOidb(bridge, {
{ groupUin: groupId, sequence, random }, OidbEssenceSchema); cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
} }
+33 -13
View File
@@ -3,7 +3,7 @@
// edit message content — they're purely social signals. // edit message content — they're purely social signals.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
Oidb0x9083ReqSchema, Oidb0x9083ReqSchema,
Oidb0x9083RespSchema, Oidb0x9083RespSchema,
@@ -13,18 +13,27 @@ import {
} from '../proto/oidb-action'; } from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xed3_1', 0xED3, 1, await runOidb(bridge, {
{ cmd: 'OidbSvcTrpcTcp.0xed3_1',
uin: targetUin ?? peerUin, oidbCmd: 0xED3, subCmd: 1,
groupUin: isGroup ? peerUin : 0, request: {
friendUin: isGroup ? 0 : peerUin, schema: OidbPokeSchema,
ext: 0, value: {
}, OidbPokeSchema); 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> { export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104, await runOidb(bridge, {
{ targetUin: userId, count }, OidbLikeSchema); 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> { export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
@@ -35,8 +44,14 @@ export async function setGroupReaction(bridge: Bridge, groupId: number, sequence
// type field to pick the right resolution table; omitting it makes // type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail. // unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1; const type = code.length > 3 ? 2 : 1;
await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd, await runOidb(bridge, {
{ groupUin: groupId, sequence, code, type }, OidbGroupReactionSchema); cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
} }
export async function getEmojiLikes( export async function getEmojiLikes(
@@ -58,7 +73,12 @@ export async function getEmojiLikes(
count, count,
field12: 1, 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 uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : []; const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
+20 -29
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode'; import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
MiniAppShareReqSchema, MiniAppShareReqSchema,
MiniAppShareRespSchema, MiniAppShareRespSchema,
@@ -30,15 +30,12 @@ export async function translateEn2Zh(
tag12: 1, tag12: 1,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x990_2',
'OidbSvcTrpcTcp.0x990_2', oidbCmd: 0x990, subCmd: 2,
0x990, request: { schema: Oidb0x990ReqSchema, value: req },
2, response: { schema: Oidb0x990RespSchema },
req, });
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
);
const resp = result?.translateResp; const resp = result?.translateResp;
if (!resp) { if (!resp) {
@@ -125,15 +122,12 @@ export async function clickInlineKeyboardButton(
unknown9: 1, unknown9: 1,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x112e_1',
'OidbSvcTrpcTcp.0x112e_1', oidbCmd: 0x112E, subCmd: 1,
0x112E, request: { schema: Oidb0x112eReqSchema, value: req },
1, response: { schema: Oidb0x112eRespSchema },
req, });
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
);
if (!result) { if (!result) {
throw new Error('click inline keyboard button result empty'); throw new Error('click inline keyboard button result empty');
@@ -155,19 +149,16 @@ export async function sendGroupSign(
) { ) {
const req = { const req = {
signInInfo: { signInInfo: {
uin: String(bridge.qqInfo.uin), uin: String(bridge.identity.uin),
groupId: String(groupId), groupId: String(groupId),
version: '9.0.90', version: '9.0.90',
}, },
}; };
await sendOidbAndDecode<any>( await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xEB7_1',
'OidbSvcTrpcTcp.0xEB7_1', oidbCmd: 0xEB7, subCmd: 1,
0xEB7, request: { schema: Oidb0xeb7ReqSchema, value: req },
1, response: { schema: Oidb0xeb7RespSchema },
req, });
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
);
} }
+37 -52
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode'; 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 { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils'; import { computeHashes, loadBinarySource } from '../highway/utils';
import { import {
@@ -60,7 +60,7 @@ export async function setProfile(
nickname?: string, nickname?: string,
personalNote?: string, personalNote?: string,
): Promise<void> { ): Promise<void> {
const uin = BigInt(bridge.qqInfo.uin); const uin = BigInt(bridge.identity.uin);
const stringProfiles: any[] = []; const stringProfiles: any[] = [];
const intProfiles: any[] = []; const intProfiles: any[] = [];
@@ -81,14 +81,11 @@ export async function setProfile(
stringProfiles, stringProfiles,
}; };
await sendOidbAndCheck( await runOidb(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x112a_2',
'OidbSvcTrpcTcp.0x112a_2', oidbCmd: 0x112A, subCmd: 2,
0x112A, request: { schema: OidbSetProfileSchema, value: req },
2, });
req,
OidbSetProfileSchema,
);
} }
export async function setSelfLongNick( export async function setSelfLongNick(
@@ -96,22 +93,19 @@ export async function setSelfLongNick(
longNick: string, longNick: string,
) { ) {
const req = { const req = {
uin: BigInt(bridge.qqInfo.uin), uin: BigInt(bridge.identity.uin),
profile: { profile: {
tag: 102, tag: 102,
value: String(longNick), value: String(longNick),
}, },
}; };
await sendOidbAndDecode<any>( await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x112a_2',
'OidbSvcTrpcTcp.0x112a_2', oidbCmd: 0x112A, subCmd: 2,
0x112A, request: { schema: Oidb0x112aReqSchema, value: req },
2, response: { schema: Oidb0x112aRespSchema },
req, });
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
);
} }
export async function setInputStatus( export async function setInputStatus(
@@ -119,7 +113,7 @@ export async function setInputStatus(
userId: number, userId: number,
eventType: number, eventType: number,
) { ) {
const targetUid = await resolveUserUid(bridge, userId); const targetUid = await bridge.resolveUserUid(userId);
if (!targetUid) { if (!targetUid) {
throw new Error('target uid not found'); throw new Error('target uid not found');
@@ -133,15 +127,12 @@ export async function setInputStatus(
}, },
}; };
await sendOidbAndDecode<any>( await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xcd4_1',
'OidbSvcTrpcTcp.0xcd4_1', oidbCmd: 0xCD4, subCmd: 1,
0xCD4, request: { schema: Oidb0xcd4ReqSchema, value: req },
1, response: { schema: Oidb0xcd4RespSchema },
req, });
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
);
} }
export async function setAvatar( export async function setAvatar(
@@ -167,7 +158,7 @@ export async function getProfileLike(
const isSelf = !userId; const isSelf = !userId;
const targetUid = isSelf const targetUid = isSelf
? await resolveSelfUid(bridge) ? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, userId); : await bridge.resolveUserUid(userId);
if (!targetUid) { if (!targetUid) {
throw new Error('target uid not found'); throw new Error('target uid not found');
@@ -182,15 +173,12 @@ export async function getProfileLike(
limit: limit, limit: limit,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x7ed_12',
'OidbSvcTrpcTcp.0x7ed_12', oidbCmd: 0x7ED, subCmd: 12,
0x7ED, request: { schema: Oidb0x7edReqSchema, value: req },
12, response: { schema: Oidb0x7edRespSchema },
req, });
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
);
const data = result?.userLikeInfos?.[0]; const data = result?.userLikeInfos?.[0];
if (!data) { if (!data) {
@@ -220,7 +208,7 @@ export async function getUnidirectionalFriendList(
bridge: Bridge, bridge: Bridge,
) { ) {
const reqObj = { const reqObj = {
uint64_uin: String(bridge.qqInfo.uin), uint64_uin: String(bridge.identity.uin),
uint64_top: 0, uint64_top: 0,
uint32_req_num: 99, uint32_req_num: 99,
bytes_cookies: '', bytes_cookies: '',
@@ -230,15 +218,12 @@ export async function getUnidirectionalFriendList(
jsonBody: JSON.stringify(reqObj), jsonBody: JSON.stringify(reqObj),
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', oidbCmd: 0xE17, subCmd: 0,
0xE17, request: { schema: Oidb0xe17ReqSchema, value: req },
0, response: { schema: Oidb0xe17RespSchema },
req, });
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
);
if (!result || !result.jsonBody) { if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty'); throw new Error('get unidirectional friend list empty');
@@ -251,7 +236,7 @@ export async function getUnidirectionalFriendList(
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> { export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = { const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.qqInfo.uin), uin: BigInt(bridge.identity.uin),
field3: 1, field3: 1,
field6: 1, field6: 1,
}; };
@@ -265,5 +250,5 @@ export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promi
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`); throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
} }
const faceIds = (resp as any).item?.faceIds || []; 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. // same five-line utility from every themed file.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { resolveUserUid } from '../bridge-oidb';
/** /**
* Coerce numbers, strings, and bigints to a plain integer. * 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 * Look up the bot's own UID. Cached on Identity once warmup populates
* forward/profile actions need a fast path before warmup completes. * `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/ */
export async function resolveSelfUid(bridge: Bridge): Promise<string> { export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.qqInfo.selfUid; let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid; if (selfUid) return selfUid;
const selfUin = toInt(bridge.qqInfo.uin); const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) { if (selfUin <= 0) {
throw new Error('self uid is unavailable'); throw new Error('self uid is unavailable');
} }
selfUid = await resolveUserUid(bridge, selfUin); selfUid = await bridge.resolveUserUid(selfUin);
return selfUid; return selfUid;
} }
+37 -19
View File
@@ -4,7 +4,7 @@ import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge'; import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode'; import { protoDecode } from '../protobuf/decode';
import { sendOidbAndDecode } from './bridge-oidb'; import { runOidb } from './bridge-oidb';
import { import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema,
@@ -71,9 +71,12 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
body.nextUin = { uin: nextUin }; body.nextUin = { uin: nextUin };
} }
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body, cmd: 'OidbSvcTrpcTcp.0xfd4_1',
OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema); oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
if (resp?.friends) { if (resp?.friends) {
for (const raw of 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>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body, cmd: 'OidbSvcTrpcTcp.0xfe5_2',
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true); oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const groups: QQGroupInfo[] = []; const groups: QQGroupInfo[] = [];
if (resp?.groups) { if (resp?.groups) {
@@ -165,9 +171,12 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
}; };
if (token) body.token = token; if (token) body.token = token;
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body, cmd: 'OidbSvcTrpcTcp.0xfe7_3',
OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema); oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
if (resp?.members) { if (resp?.members) {
for (const raw of 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 })), keys: keys.map(k => ({ key: k })),
}; };
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body, cmd: 'OidbSvcTrpcTcp.0xfe1_2',
OidbUserInfoRequestSchema, OidbUserInfoResponseSchema); oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
response: { schema: OidbUserInfoResponseSchema },
});
if (!resp?.body) throw new Error('user info response body missing'); 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[]> { export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1; const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 }, cmd,
OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema); oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
const requests: GroupRequestInfo[] = []; const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) { for (const raw of resp?.requests ?? []) {
@@ -308,9 +323,12 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyIn
}, },
}; };
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body, cmd: 'OidbSvcTrpcTcp.0x9067_202',
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true); oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
@@ -0,0 +1,130 @@
// 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';
export interface BridgeInterface {
// ─── Shared state ───
readonly identity: IdentityService;
readonly events: BridgeEventBus;
readonly activePid: number | null;
// ─── Resolution ───
resolveUserUid(uin: number, groupId?: number): Promise<string>;
// ─── 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 }>;
// ─── 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>;
setProfile(nickname?: string, personalNote?: string): Promise<void>;
setSelfLongNick(longNick: string): Promise<any>;
setInputStatus(userId: number, eventType: number): Promise<any>;
setAvatar(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>;
}
+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 { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode'; import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode'; import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb'; import { makeOidbBaseSchema } from './proto/oidb';
/** export interface OidbCall<TResp = void> {
* Build a raw OIDB request buffer (base envelope wrapping a typed body). /** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
*/ cmd: string;
export function makeOidbRequest( /** OIDB command number, e.g. 0x1253. */
command: number, subCommand: number, oidbCmd: number;
body: any, bodySchema: ProtoSchema, isUid = false, /** OIDB sub-command, e.g. 1. */
): Uint8Array { subCmd: number;
const baseSchema = makeOidbBaseSchema(bodySchema); request: {
return protoEncode({ schema: ProtoSchema;
command, value: any;
subCommand, /**
errorCode: 0, * Sets the OIDB envelope `reserved` field to 1 when true. A handful
body, * of commands (group/friend list, rkey download) operate on
errorMsg: '', * UID-keyed data and require this flag — the wire format is
reserved: isUid ? 1 : 0, * otherwise identical.
}, baseSchema); */
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( export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
bridge: Bridge, export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
serviceCmd: string, command: number, subCommand: number, export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
body: any, bodySchema: ProtoSchema, isUid = false, const envelope = encodeOidbEnvelope(call);
): Promise<void> { const result = await bridge.sendRawPacket(call.cmd, envelope);
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.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'); if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
// Check OIDB error code if response present
if (result.responseData && result.responseData.length > 0) { if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } }); const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase); const resp = protoDecode(result.responseData, emptyBase);
if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) { if (resp) throwIfOidbError(resp);
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
} }
} }
/** function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
* Send an OIDB packet and decode the response body with the given schema. const baseSchema = makeOidbBaseSchema(call.request.schema);
*/ return protoEncode({
export async function sendOidbAndDecode<T>( command: call.oidbCmd,
bridge: Bridge, subCommand: call.subCmd,
serviceCmd: string, command: number, subCommand: number, errorCode: 0,
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false, body: call.request.value,
): Promise<T> { errorMsg: '',
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid); reserved: call.request.isUid ? 1 : 0,
const result = await bridge.sendRawPacket(serviceCmd, request); }, baseSchema);
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 throwIfOidbError(resp: unknown): void {
* Resolve a UIN to a UID string, using cache or fetching as needed. const code = (resp as any).errorCode;
* Mirrors C++ resolve_user_uid_for_action. if (code && code !== 0) {
*/ throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
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;
} }
// 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}`);
} }
+22 -268
View File
@@ -5,12 +5,13 @@
import type { PacketInfo } from '../protocol/types'; import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events'; import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; 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-handler';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode'; import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './element-builder'; import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service'; import { IdentityService } from './identity-service';
import type { BridgeInterface } from './bridge-interface';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import { createLogger } from '../utils/logger'; import { createLogger } from '../utils/logger';
import { import {
SendMessageRequestSchema, SendMessageRequestSchema,
@@ -18,7 +19,6 @@ import {
} from './proto/action'; } from './proto/action';
// Delegated modules // Delegated modules
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
import { import {
fetchFriendList as fetchFriendList_, fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_, fetchGroupList as fetchGroupList_,
@@ -115,8 +115,6 @@ import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared'; import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus'; import { BridgeEventBus } from './event-bus';
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
export interface SendMessageReceipt { export interface SendMessageReceipt {
messageId: number; messageId: number;
sequence: number; sequence: number;
@@ -139,26 +137,21 @@ export interface ClientKeyInfo {
keyIndex: string keyIndex: string
} }
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
const log = createLogger('Bridge'); 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 static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
private qqInfo_: QQInfo;
readonly identity: IdentityService; readonly identity: IdentityService;
private pids_ = new Set<number>(); private pids_ = new Set<number>();
/** /**
* Per-kind event subscription. Replaces the legacy single-callback * Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they * 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(); readonly events = new BridgeEventBus();
private cmdHandlers_ = new Map<string, CmdParser[]>(); private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null; private packetClient_: PacketSender | null = null;
private memberRefreshTasks_ = new Map<number, Promise<void>>();
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls // Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
// and serves a fresh result for `kMemberListTtlMs` to all callers. // and serves a fresh result for `kMemberListTtlMs` to all callers.
// Without this, a busy OneBot client (e.g. MaiBot calling // Without this, a busy OneBot client (e.g. MaiBot calling
@@ -173,14 +166,21 @@ export class Bridge {
private clientSeq_ = 100000000 + (Date.now() % 1000000000); private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) { constructor(identity: IdentityService) {
this.qqInfo_ = qqInfo;
this.identity = identity; 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 { dispose(): void {
this.identity.close(); this.identity.close();
this.events.clear(); this.events.clear();
@@ -190,18 +190,12 @@ export class Bridge {
this.packetClient_ = client; this.packetClient_ = client;
} }
private registerDefaultHandlers(): void {
this.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
registerCmd(cmd: string, parser: CmdParser): void { registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? []; this.pipeline.registerCmd(cmd, parser);
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
} }
handlesCmd(cmd: string): boolean { handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd); return this.pipeline.handlesCmd(cmd);
} }
// --- PID management --- // --- PID management ---
@@ -222,183 +216,14 @@ export class Bridge {
// --- Packet dispatch --- // --- Packet dispatch ---
onPacket(pkt: PacketInfo): void { onPacket(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd); this.pipeline.process(pkt);
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;
}
} }
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> { private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) { if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ } 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 }); await this.fetchGroupMemberList(groupId, { force: forceMemberList });
return true; return true;
} }
@@ -553,7 +378,7 @@ export class Bridge {
// --- Delegated: OIDB helpers --- // --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> { async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return resolveUserUid_(this, uin, groupId); return this.identity.resolveUid(uin, groupId);
} }
// --- Delegated: Contact / info queries --- // --- Delegated: Contact / info queries ---
@@ -705,74 +530,3 @@ export class Bridge {
} }
} }
// --- Module-level helper functions ---
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;
}
}
@@ -191,7 +191,7 @@ export async function uploadHighwayHttp(
bridge: Bridge, session: HighwaySession, commandId: number, bridge: Bridge, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array, bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> { ): 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); const socket = await tcpConnect(session.host, session.port);
try { try {
@@ -201,7 +201,7 @@ export async function uploadHighwayHttp(
const chunk = bytes.subarray(offset, offset + chunkSize); const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk); const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead( const head = makeHighwayHead(
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize, bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend, chunkMd5, fileMd5, session.sigSession, extend,
); );
const frame = packHighwayFrame(head, chunk); const frame = packHighwayFrame(head, chunk);
+233 -88
View File
@@ -2,12 +2,25 @@ import fs from 'fs';
import path from 'path'; import path from 'path';
import { DatabaseSync } from 'node:sqlite'; import { DatabaseSync } from 'node:sqlite';
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; import type {
import { QQInfo } from './qq-info'; FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger } from '../utils/logger'; import { createLogger } from '../utils/logger';
const log = createLogger('Identity'); 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 { interface UserInput {
uid?: string; uid?: string;
uin?: number; uin?: number;
@@ -66,16 +79,43 @@ interface MemberRow {
active: number; 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 { 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 uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>(); private readonly uidByUin = new Map<number, string>();
private inTransaction = false;
constructor( // ─── Persistence + fetcher ───
private readonly qqInfo: QQInfo, private readonly db: DatabaseSync | null;
dbPath: string | null, private inTransaction = false;
) { private fetcher: IdentityFetcher | null = null;
constructor(uin: string, dbPath: string | null) {
this.uin_ = uin;
if (!dbPath) { if (!dbPath) {
this.db = null; this.db = null;
return; return;
@@ -89,12 +129,12 @@ export class IdentityService {
this.loadSnapshot(); this.loadSnapshot();
} }
static openForUin(qqInfo: QQInfo, dataRoot = 'data'): IdentityService { static openForUin(uin: string, dataRoot = 'data'): IdentityService {
return new IdentityService(qqInfo, path.join(dataRoot, qqInfo.uin, 'snowluma_identity.db')); return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
} }
static memory(qqInfo: QQInfo): IdentityService { static memory(uin: string): IdentityService {
return new IdentityService(qqInfo, null); return new IdentityService(uin, null);
} }
close(): void { close(): void {
@@ -105,8 +145,143 @@ export class IdentityService {
return this.db !== null; 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 { rememberFriends(friends: FriendInfo[]): void {
this.qqInfo.setFriends(friends); this.friends_ = friends;
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin); for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
this.runWrite('friends', () => this.transaction(() => { this.runWrite('friends', () => this.transaction(() => {
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1') 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 { rememberGroups(groups: QQGroupInfo[]): void {
this.qqInfo.setGroups(groups); this.setGroupsInMemory(groups);
this.runWrite('groups', () => this.transaction(() => { this.runWrite('groups', () => this.transaction(() => {
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1') this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
.run(nowSeconds()); .run(nowSeconds());
@@ -143,7 +318,7 @@ export class IdentityService {
} }
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void { 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); for (const member of members) this.rememberUidUin(member.uid, member.uin);
this.runWrite('group members', () => this.transaction(() => { this.runWrite('group members', () => this.transaction(() => {
this.upsertGroup({ groupId, memberCount: members.length }); this.upsertGroup({ groupId, memberCount: members.length });
@@ -169,9 +344,9 @@ export class IdentityService {
} }
rememberUserProfile(info: UserProfileInfo): void { rememberUserProfile(info: UserProfileInfo): void {
this.qqInfo.setUserProfile(info); this.userProfiles_.set(info.uin, info);
const selfUin = parseInt(this.qqInfo.uin, 10) || 0; const selfUin = parseInt(this.uin_, 10) || 0;
if (info.uin === selfUin) this.qqInfo.setSelfProfile(info); if (info.uin === selfUin) this.selfProfile_ = info;
this.rememberUidUin(info.uid, info.uin); this.rememberUidUin(info.uid, info.uin);
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({ this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
uid: info.uid, uid: info.uid,
@@ -259,67 +434,7 @@ export class IdentityService {
}); });
} }
findUinByUid(uid: string, groupId?: number): number | null { // ─── Private helpers ───
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 rememberUidUin(uid: unknown, uin: unknown): void { private rememberUidUin(uid: unknown, uin: unknown): void {
const normalizedUid = normalizeUid(uid); const normalizedUid = normalizeUid(uid);
@@ -329,6 +444,38 @@ export class IdentityService {
this.uidByUin.set(normalizedUin, normalizedUid); 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 { private initSchema(): void {
this.db!.exec(` this.db!.exec(`
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
@@ -387,12 +534,13 @@ export class IdentityService {
FROM users FROM users
WHERE is_friend = 1 AND uin IS NOT NULL`, WHERE is_friend = 1 AND uin IS NOT NULL`,
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>; ).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 ?? '', uid: row.uid ?? '',
uin: row.uin ?? 0, uin: row.uin ?? 0,
nickname: row.nickname, nickname: row.nickname,
remark: row.remark, remark: row.remark,
}))); }));
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
const groups = this.db!.prepare( const groups = this.db!.prepare(
`SELECT group_id, group_name, remark, member_count, member_max `SELECT group_id, group_name, remark, member_count, member_max
@@ -405,7 +553,7 @@ export class IdentityService {
member_count: number; member_count: number;
member_max: number; member_max: number;
}>; }>;
this.qqInfo.setGroups(groups.map((row) => ({ this.setGroupsInMemory(groups.map((row) => ({
groupId: row.group_id, groupId: row.group_id,
groupName: row.group_name, groupName: row.group_name,
remark: row.remark, remark: row.remark,
@@ -419,7 +567,6 @@ export class IdentityService {
private hydrateActiveMembersForGroups(groupIds: number[]): void { private hydrateActiveMembersForGroups(groupIds: number[]): void {
if (!this.db || groupIds.length === 0) return; if (!this.db || groupIds.length === 0) return;
const membersByGroup = new Map<number, GroupMemberInfo[]>();
const select = this.db.prepare( const select = this.db.prepare(
`SELECT group_id, uid, uin, nickname, card, role, level, title, `SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time join_time, last_sent_time, shut_up_time
@@ -440,11 +587,9 @@ export class IdentityService {
last_sent_time: number; last_sent_time: number;
shut_up_time: number; shut_up_time: number;
}>; }>;
membersByGroup.set(groupId, rows.map(rowToMemberInfo)); const members = rows.map(rowToMemberInfo);
} this.setGroupMembersInMemory(groupId, members);
for (const m of members) this.rememberUidUin(m.uid, m.uin);
for (const [groupId, members] of membersByGroup) {
this.qqInfo.setGroupMembers(groupId, members);
} }
} }
+6 -9
View File
@@ -6,15 +6,13 @@
import type { PacketInfo } from '../protocol/types'; import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge'; import { Bridge } from './bridge';
import { IdentityService } from './identity-service'; import { IdentityService } from './identity-service';
import { QQInfo } from './qq-info';
import type { PacketSender } from '../protocol/packet-sender'; import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger'; 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; export type SessionClosedCallback = (uin: string) => void;
interface QQSession { interface QQSession {
qqInfo: QQInfo;
bridge: Bridge; bridge: Bridge;
} }
@@ -67,7 +65,7 @@ export class BridgeManager {
if (created) { if (created) {
log.debug('session started: UIN=%s', uin); log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) { if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge); this.onSessionStarted_(uin, session.bridge);
} }
} }
} }
@@ -92,7 +90,7 @@ export class BridgeManager {
if (created) { if (created) {
log.debug('session started: UIN=%s', uin); log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) { 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); let session = this.sessions_.get(uin);
if (session) return { session, created: false }; if (session) return { session, created: false };
const qqInfo = new QQInfo(uin); const bridge = new Bridge(IdentityService.openForUin(uin));
const bridge = new Bridge(qqInfo, IdentityService.openForUin(qqInfo)); session = { bridge };
session = { qqInfo, bridge };
this.sessions_.set(uin, session); this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to // Each downstream consumer (e.g. OneBotInstance) subscribes to
@@ -119,7 +116,7 @@ export class BridgeManager {
return this.sessions_.get(uin) ?? null; return this.sessions_.get(uin) ?? null;
} }
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> { get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_; return this.sessions_;
} }
} }
+28 -29
View File
@@ -17,7 +17,7 @@ import {
GroupMuteSchema, NotifyMessageBodySchema, GroupMuteSchema, NotifyMessageBodySchema,
GeneralGrayTipInfoSchema, OperatorInfoSchema, GeneralGrayTipInfoSchema, OperatorInfoSchema,
} from './proto/notify'; } from './proto/notify';
import type { QQInfo } from './qq-info'; import type { IdentityService } from './identity-service';
import type { PacketInfo } from '../protocol/types'; import type { PacketInfo } from '../protocol/types';
import type { import type {
QQEventVariant, MessageElement, QQEventVariant, MessageElement,
@@ -98,17 +98,16 @@ function parseU64OrZero(value: string): number {
return isNaN(n) ? 0 : n; return isNaN(n) ? 0 : n;
} }
function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number { function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
if (!uid) return fallback; if (!uid) return fallback;
if (isNumericUin(uid)) { if (isNumericUin(uid)) {
const n = parseInt(uid, 10); const n = parseInt(uid, 10);
if (!isNaN(n)) return n; if (!isNaN(n)) return n;
} }
if (groupId) { // identity.findUinByUid cascades group-scoped lookup → in-memory map → SQLite.
const uin = qqInfo.resolveGroupMemberUid(groupId, uid); // No network fallback on the parse hot path: missing identities fall back to
if (uin !== null) return uin; // `fallback` and downstream events drive a roster refresh asynchronously.
} const uin = identity.findUinByUid(uid, groupId || undefined);
const uin = qqInfo.resolveUid(uid);
if (uin !== null) return uin; if (uin !== null) return uin;
return fallback; return fallback;
} }
@@ -564,7 +563,7 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]):
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] { export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
if (pkt.body.length === 0) return []; if (pkt.body.length === 0) return [];
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema); const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
@@ -620,8 +619,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupMemberJoin = { const ev: GroupMemberJoin = {
kind: 'group_member_join', time: timestamp, selfUin, kind: 'group_member_join', time: timestamp, selfUin,
groupId, groupId,
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0), userUin: resolveUidToUin(identity, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0), operatorUin: resolveUidToUin(identity, groupId, operatorUid, 0),
userUid, userUid,
operatorUid, operatorUid,
}; };
@@ -638,8 +637,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupMemberLeave = { const ev: GroupMemberLeave = {
kind: 'group_member_leave', time: timestamp, selfUin, kind: 'group_member_leave', time: timestamp, selfUin,
groupId, groupId,
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0), userUin: resolveUidToUin(identity, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0), operatorUin: resolveUidToUin(identity, groupId, operatorUid, 0),
userUid, userUid,
operatorUid, operatorUid,
isKick: dt !== 0 && dt !== 130, isKick: dt !== 0 && dt !== 130,
@@ -655,7 +654,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupAdminEvent = { const ev: GroupAdminEvent = {
kind: 'group_admin', time: timestamp, selfUin, kind: 'group_admin', time: timestamp, selfUin,
groupId: admin.groupUin ?? 0, groupId: admin.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin), userUin: resolveUidToUin(identity, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
set: admin.body.extraEnable !== undefined, set: admin.body.extraEnable !== undefined,
}; };
return [ev]; return [ev];
@@ -667,7 +666,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupInviteEvent = { const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin, kind: 'group_invite', time: timestamp, selfUin,
groupId: join.groupUin ?? 0, groupId: join.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin), fromUin: resolveUidToUin(identity, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
fromUid: join.targetUid ?? '', fromUid: join.targetUid ?? '',
subType: 'add', message: '', subType: 'add', message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''), flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
@@ -682,7 +681,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupInviteEvent = { const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin, kind: 'group_invite', time: timestamp, selfUin,
groupId: inner.groupUin ?? 0, groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin), fromUin: resolveUidToUin(identity, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
fromUid: inner.invitorUid ?? '', fromUid: inner.invitorUid ?? '',
subType: 'invite', message: '', subType: 'invite', message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''), flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
@@ -696,7 +695,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupInviteEvent = { const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin, kind: 'group_invite', time: timestamp, selfUin,
groupId: invite.groupUin ?? 0, groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin), fromUin: resolveUidToUin(identity, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
fromUid: invite.invitorUid ?? '', fromUid: invite.invitorUid ?? '',
subType: 'invite', message: '', subType: 'invite', message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''), flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
@@ -712,7 +711,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const sourceUid = request.info.newSource || request.info.sourceUid || ''; const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = { const ev: FriendRequestEvent = {
kind: 'friend_request', time: timestamp, selfUin, kind: 'friend_request', time: timestamp, selfUin,
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin), fromUin: resolveUidToUin(identity, 0, sourceUid, fromUin),
fromUid: sourceUid, fromUid: sourceUid,
message: request.info.message ?? '', flag: sourceUid, message: request.info.message ?? '', flag: sourceUid,
}; };
@@ -723,7 +722,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
if (!recall?.info) return []; if (!recall?.info) return [];
const ev: FriendRecall = { const ev: FriendRecall = {
kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin, kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin,
userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin), userUin: resolveUidToUin(identity, 0, recall.info.fromUid ?? '', fromUin),
msgSeq: recall.info.clientSequence ?? 0, msgSeq: recall.info.clientSequence ?? 0,
}; };
return [ev]; return [ev];
@@ -736,8 +735,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const target = findTemplateValue(templates, 'uin_str2'); const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = { const ev: FriendPokeEvent = {
kind: 'friend_poke', time: timestamp, selfUin, kind: 'friend_poke', time: timestamp, selfUin,
userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)), userUin: resolveUidToUin(identity, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)), targetUin: resolveUidToUin(identity, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'), action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'), suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'), actionImgUrl: findTemplateValue(templates, 'action_img_url'),
@@ -757,8 +756,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupMuteEvent = { const ev: GroupMuteEvent = {
kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin, kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin,
groupId: mute.groupUin ?? 0, groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin), operatorUin: resolveUidToUin(identity, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0), userUin: resolveUidToUin(identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration, duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
}; };
return [ev]; return [ev];
@@ -772,9 +771,9 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupRecallEvent = { const ev: GroupRecallEvent = {
kind: 'group_recall', time: recalled.time ?? timestamp, selfUin, kind: 'group_recall', time: recalled.time ?? timestamp, selfUin,
groupId: notify.groupUin ?? 0, groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, operatorUin: resolveUidToUin(identity, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '', fromUin), notify.recall.operatorUid || notify.operatorUid || '', fromUin),
authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin), authorUin: resolveUidToUin(identity, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
msgSeq: recalled.sequence ?? 0, msgSeq: recalled.sequence ?? 0,
}; };
return [ev]; return [ev];
@@ -790,8 +789,8 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: GroupPokeEvent = { const ev: GroupPokeEvent = {
kind: 'group_poke', time: timestamp, selfUin, kind: 'group_poke', time: timestamp, selfUin,
groupId: notify.groupUin ?? 0, groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)), userUin: resolveUidToUin(identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)), targetUin: resolveUidToUin(identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'), action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'), suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'), actionImgUrl: findTemplateValue(templates, 'action_img_url'),
@@ -835,7 +834,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
ev.groupId = msg.responseHead.grp.groupUin ?? 0; ev.groupId = msg.responseHead.grp.groupUin ?? 0;
ev.senderNick = msg.responseHead.grp.memberName ?? ''; ev.senderNick = msg.responseHead.grp.memberName ?? '';
} }
const member = qqInfo.findGroupMember(ev.groupId, fromUin); const member = identity.findGroupMember(ev.groupId, fromUin);
if (member) { if (member) {
if (!ev.senderNick) ev.senderNick = member.nickname; if (!ev.senderNick) ev.senderNick = member.nickname;
ev.senderCard = member.card; ev.senderCard = member.card;
@@ -856,7 +855,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
ev.senderNick = msg.responseHead.grp.memberName ?? ''; ev.senderNick = msg.responseHead.grp.memberName ?? '';
} }
if (!ev.senderNick) { if (!ev.senderNick) {
const friend = qqInfo.findFriend(fromUin); const friend = identity.findFriend(fromUin);
if (friend) ev.senderNick = friend.nickname; if (friend) ev.senderNick = friend.nickname;
} }
return [ev]; return [ev];
@@ -876,7 +875,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
if (msg.responseHead?.forward?.friendName) { if (msg.responseHead?.forward?.friendName) {
ev.senderNick = msg.responseHead.forward.friendName; ev.senderNick = msg.responseHead.forward.friendName;
} }
const friend = qqInfo.findFriend(fromUin); const friend = identity.findFriend(fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname; if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev]; return [ev];
} }
+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;
}
}
+4 -145
View File
@@ -1,5 +1,7 @@
// QQ info store — per-UIN state for friends, groups, member lookup. // Domain object shapes shared by IdentityService and its callers. The
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp // 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 { export interface UserProfileInfo {
uin: number; uin: number;
@@ -60,146 +62,3 @@ export interface GroupRequestInfo {
comment: string; comment: string;
filtered: boolean; 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. // thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
OidbClientKeyRespSchema, OidbClientKeyRespSchema,
OidbClientKeyReqSchema, OidbClientKeyReqSchema,
@@ -14,15 +14,12 @@ import {
import { RequestUtil } from '../web/request-util'; import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) { export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x102a_1',
'OidbSvcTrpcTcp.0x102a_1', oidbCmd: 0x102A, subCmd: 1,
0x102A, request: { schema: OidbClientKeyReqSchema, value: {} },
1, response: { schema: OidbClientKeyRespSchema },
{}, });
OidbClientKeyReqSchema,
OidbClientKeyRespSchema,
);
const clientKey = resp?.clientKey || ''; const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what // 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[]) { export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x102a_0',
'OidbSvcTrpcTcp.0x102a_0', oidbCmd: 0x102A, subCmd: 0,
0x102A, request: { schema: OidbGetPskeyReqSchema, value: { domainList } },
0, response: { schema: OidbGetPskeyRespSchema },
{ domainList }, });
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
);
const domainPskeyMap = new Map<string, string>(); 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 // Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given // bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain. // 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 + '&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); 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 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' + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.qqInfo.uin + '&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey + '&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 + '&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex; '&keyindex=' + ClientKeyData.keyIndex;
+32 -32
View File
@@ -36,7 +36,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id); const userId = asNumber(params.user_id);
const times = asNumber(params.times) || 1; const times = asNumber(params.times) || 1;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.sendLike(userId, times); await ctx.bridge.sendLike(userId, times);
return okResponse(); return okResponse();
}); });
@@ -94,9 +94,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { 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); return okResponse(allMsgs);
} catch (e) { } 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'); 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(); 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(); 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(); return okResponse();
}); });
@@ -211,9 +211,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
} }
if (meta.isGroup) { if (meta.isGroup) {
await ctx.markGroupMsgAsRead(targetId, meta.sequence); await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence);
} else { } else {
await ctx.markPrivateMsgAsRead(targetId, meta.sequence); await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence);
} }
return okResponse(); return okResponse();
}); });
@@ -258,7 +258,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1, 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(); return okResponse();
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -271,7 +271,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const notices = await ctx.getGroupNotice(groupId); const notices = await ctx.bridge.getGroupNotice(groupId);
return okResponse(notices); return okResponse(notices);
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -288,7 +288,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const success = await ctx.deleteGroupNotice(groupId, fid); const success = await ctx.bridge.deleteGroupNotice(groupId, fid);
if (success) { if (success) {
return okResponse(); return okResponse();
} else { } else {
@@ -427,7 +427,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const cookies = await ctx.getCookiesStr(domain); const cookies = await ctx.bridge.getCookiesStr(domain);
return okResponse({ cookies }); return okResponse({ cookies });
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -437,7 +437,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_csrf_token', async () => { h.registerAction('get_csrf_token', async () => {
try { try {
const token = await ctx.getCsrfToken(); const token = await ctx.bridge.getCsrfToken();
return okResponse({ token }); return okResponse({ token });
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -449,7 +449,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const creds = await ctx.getCredentials(domain); const creds = await ctx.bridge.getCredentials(domain);
return okResponse(creds); return okResponse(creds);
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -480,7 +480,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id); const userId = asNumber(params.user_id);
const remark = asString(params.remark) ?? ''; const remark = asString(params.remark) ?? '';
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.setFriendRemark(userId, remark); await ctx.bridge.setFriendRemark(userId, remark);
return okResponse(); return okResponse();
}); });
@@ -488,7 +488,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id); const groupId = asNumber(params.group_id);
const remark = asString(params.remark) ?? ''; const remark = asString(params.remark) ?? '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupRemark(groupId, remark); await ctx.bridge.setGroupRemark(groupId, remark);
return okResponse(); return okResponse();
}); });
@@ -570,7 +570,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
await ctx.setProfile(nickname, personalNote); await ctx.bridge.setProfile(nickname, personalNote);
return okResponse(); return okResponse();
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -590,7 +590,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
await ctx.setOnlineStatus(status, extStatus, batteryStatus); await ctx.bridge.setOnlineStatus(status, extStatus, batteryStatus);
return okResponse(); return okResponse();
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -653,7 +653,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('fetch_custom_face', async (params) => { h.registerAction('fetch_custom_face', async (params) => {
const count = asNumber(params.count) || 10; const count = asNumber(params.count) || 10;
try { try {
const urls = await ctx.fetchCustomFace(count); const urls = await ctx.bridge.fetchCustomFace(count);
return okResponse(urls); return okResponse(urls);
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -667,7 +667,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const meta = ctx.getMessageMeta(messageId); const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message'); 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: '' })) }); return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) });
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -684,7 +684,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const meta = ctx.getMessageMeta(messageId); const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message'); 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({ return okResponse({
result: 0, result: 0,
errMsg: '', errMsg: '',
@@ -733,7 +733,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const data = await ctx.getGroupAtAllRemain(groupId); const data = await ctx.bridge.getGroupAtAllRemain(groupId);
return okResponse(data); return okResponse(data);
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -743,7 +743,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_unidirectional_friend_list', async () => { h.registerAction('get_unidirectional_friend_list', async () => {
try { try {
const data = await ctx.getUnidirectionalFriendList(); const data = await ctx.bridge.getUnidirectionalFriendList();
return okResponse(data); return okResponse(data);
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -759,7 +759,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
await ctx.setSelfLongNick(longNick); await ctx.bridge.setSelfLongNick(longNick);
return okResponse({}); return okResponse({});
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -780,7 +780,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
await ctx.setAvatar(file); await ctx.bridge.setAvatar(file);
return okResponse(); return okResponse();
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -802,7 +802,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
await ctx.setInputStatus(userId, eventType); await ctx.bridge.setInputStatus(userId, eventType);
return okResponse({}); return okResponse({});
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -820,7 +820,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const translated = await ctx.translateEn2Zh(words); const translated = await ctx.bridge.translateEn2Zh(words);
return okResponse({ words: translated }); return okResponse({ words: translated });
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -828,11 +828,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}); });
h.registerAction('get_clientkey', async () => { h.registerAction('get_clientkey', async () => {
const clientKeyInfo = await ctx.forceFetchClientKey(); const clientKeyInfo = await ctx.bridge.forceFetchClientKey();
if (!clientKeyInfo.clientKey) { if (!clientKeyInfo.clientKey) {
return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error'); return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error');
} }
return okResponse(clientKeyInfo); return okResponse({ ...clientKeyInfo });
}); });
h.registerAction('get_mini_app_ark', async (params) => { h.registerAction('get_mini_app_ark', async (params) => {
@@ -844,7 +844,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const data = await ctx.getMiniAppArk( const data = await ctx.bridge.getMiniAppArk(
String(type), String(type),
String(title), String(title),
String(desc), String(desc),
@@ -870,7 +870,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const data = await ctx.clickInlineKeyboardButton( const data = await ctx.bridge.clickInlineKeyboardButton(
groupId, groupId,
botAppid, botAppid,
String(buttonId), String(buttonId),
@@ -892,7 +892,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
await ctx.sendGroupSign(groupId); await ctx.bridge.sendGroupSign(groupId);
return okResponse({}); return okResponse({});
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e)); return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -42,14 +42,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id); const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type); const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required'); 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(); return okResponse();
}); });
h.registerAction('set_group_search', async (params) => { h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id); const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupSearch(groupId); await ctx.bridge.setGroupSearch(groupId);
return okResponse(); return okResponse();
}); });
@@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id); const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true); const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); 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(); return okResponse();
}); });
@@ -67,7 +67,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id); const userId = asNumber(params.user_id);
const card = asString(params.card); const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); 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(); return okResponse();
}); });
@@ -75,7 +75,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id); const groupId = asNumber(params.group_id);
const name = asString(params.group_name); const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupName(groupId, name); await ctx.bridge.setGroupName(groupId, name);
return okResponse(); return okResponse();
}); });
@@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id); const userId = asNumber(params.user_id);
const title = asString(params.special_title); const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); 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(); return okResponse();
}); });
@@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId) { if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); 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(); return okResponse();
}); });
@@ -70,7 +70,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId || !parentDirectory || !targetDirectory) { if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required'); 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(); return okResponse();
}); });
@@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId) { if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); 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(); return okResponse();
}); });
@@ -102,7 +102,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId || !newName) { if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required'); 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(); return okResponse();
}); });
@@ -68,7 +68,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
} }
try { try {
const honorInfo = await ctx.getGroupHonorInfo(groupId, typeStr as WebHonorType); const honorInfo = await ctx.bridge.getGroupHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo); return okResponse(honorInfo);
} catch (e) { } catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`); return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
+20 -50
View File
@@ -1,5 +1,6 @@
import type { JsonObject, JsonValue, MessageMeta } from './types'; import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { ForwardPreviewMeta } from './modules/message-actions'; import type { ForwardPreviewMeta } from './modules/message-actions';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { RETCODE, failedResponse } from './types'; import { RETCODE, failedResponse } from './types';
import { register as registerInfo } from './actions/info'; import { register as registerInfo } from './actions/info';
@@ -31,6 +32,14 @@ export interface GroupEssenceMsgRet {
} }
export interface ApiActionContext { 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 }; getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean; isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null; getMessage: (messageId: number) => JsonObject | null;
@@ -47,87 +56,48 @@ export interface ApiActionContext {
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>; getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>; getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo: (userId: number) => 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>; setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>; setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>; setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan: (groupId: number, enable: boolean) => 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>; setGroupLeave: (groupId: number) => Promise<void>;
setGroupSpecialTitle: (groupId: number, userId: number, title: string) => Promise<void>; // Group file (adapters: field extraction + Bridge name translation)
getGroupAtAllRemain: (groupId: number) => Promise<any>;
// Group file
uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>; 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>; uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>; getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>; 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>; 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>; 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>; handleFriendRequest: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>; handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Extended // Pokes (adapters: flatten isGroup into bridge.sendPoke signature)
sendLike: (userId: number, times: number) => Promise<void>;
sendFriendPoke: (userId: number, targetId?: number) => Promise<void>; sendFriendPoke: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke: (groupId: number, userId: number) => Promise<void>; sendGroupPoke: (groupId: number, userId: number) => Promise<void>;
// Essence (adapter: bakes the set/unset boolean)
setEssenceMsg: (messageId: number) => Promise<void>; setEssenceMsg: (messageId: number) => Promise<void>;
deleteEssenceMsg: (messageId: number) => Promise<void>; deleteEssenceMsg: (messageId: number) => Promise<void>;
forceFetchClientKey: () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>; // Profile reads with OneBot-specific default args
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>; getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>; getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
getUnidirectionalFriendList: () => Promise<any>; // Friend deletion (adapter: rename + force-boolean)
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>;
handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>; handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>;
// Module wrappers / multi-dep compositions
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>; getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>; getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>; handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
getDownloadRKeys: () => Promise<JsonObject[]>; getDownloadRKeys: () => Promise<JsonObject[]>;
// Forward message
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>; sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: 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 }>; sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>; getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>; forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
// Extended NapCat-compatible
setFriendRemark: (userId: number, remark: string) => Promise<void>;
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>; 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>;
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[]>;
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<{ cookies: string; token: number; csrf_token: number }>;
// Media lookup (populated from previously dispatched message segments) // Media lookup (populated from previously dispatched message segments)
getImageInfo: (file: string) => Promise<JsonObject | null>; getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (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>; type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
+55 -68
View File
@@ -1,6 +1,5 @@
import type { WebHonorType } from '@/bridge/web/group-honor'; import type { WebHonorType } from '@/bridge/web/group-honor';
import type { Bridge } from '../bridge/bridge'; import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext } from './api-handler'; import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter'; import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store'; import type { MediaStore } from './media-store';
@@ -36,6 +35,7 @@ import {
getRecordInfo as getCachedRecordInfo, getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions'; } from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-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 * 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. */ /** Self UIN parsed once, used in event payloads. */
selfId: number; selfId: number;
qqInfo: QQInfo; bridge: BridgeInterface;
bridge: Bridge;
messageStore: MessageStore; messageStore: MessageStore;
mediaStore: MediaStore; mediaStore: MediaStore;
@@ -73,10 +72,25 @@ export interface OneBotInstanceContext {
dispatchEvent(event: JsonObject): void; 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 { export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, qqInfo, messageStore, mediaStore } = ref; const { bridge, messageStore, mediaStore } = ref;
return { return {
bridge,
getLoginInfo: () => getLoginInfo(ref), getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true, isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId), getMessage: (messageId) => messageStore.findEvent(messageId),
@@ -89,29 +103,22 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape), sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta), deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions. // OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge, qqInfo), getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, qqInfo, noCache), getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, qqInfo, groupId, noCache), getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, qqInfo, groupId, noCache), getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache), getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, qqInfo, userId), getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin. // Group admin — names translate to OneBot vocabulary.
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject), setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject), setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration), setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable), 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), 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) => { uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true); const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId; return result.fileId;
@@ -122,45 +129,31 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
}, },
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102), getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId), 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 ?? '/'), 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), getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
// Requests. // Requests — name translation.
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve), handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason), handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Extended. // Pokes — flatten isGroup into the bridge signature.
sendLike: (userId, times) => bridge.sendLike(userId, times),
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId), sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId), sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
// Essence — bake the set/unset boolean.
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true), setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false), 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. // Profile-like / get_group_essence — OneBot-specific defaults that the
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet), // action handlers don't supply.
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block), 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), getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count), getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
// Module wrappers / multi-dep compositions.
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge), handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge), getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta), sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
@@ -168,36 +161,30 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages), sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
getForwardMsg: (resId) => getForwardMessage(ref, resId), getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target), forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
forceFetchClientKey: () => bridge.forceFetchClientKey(), handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId), getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
setMsgEmojiLike: async (messageId, emojiId, set) => { setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId); 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); 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),
// 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),
sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain) => bridge.getCookiesStr(domain),
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain) => bridge.getCredentials(domain),
// Media lookup. // Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file), getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, 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 { 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'; import { createLogger } from '../utils/logger';
const log = createLogger('OneBot'); const log = createLogger('OneBot');
@@ -26,7 +27,7 @@ export class RKeyCache {
private cache = new Map<number, CachedRKey>(); private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0; private lastRefreshAttempt = 0;
warmUp(bridge: Bridge, uin: string): void { warmUp(bridge: BridgeInterface, uin: string): void {
bridge.fetchDownloadRKeys().then( bridge.fetchDownloadRKeys().then(
(rkeys) => { (rkeys) => {
this.updateCache(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 ?? ''; const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url; if (!urlNeedsRKey(url)) return url;
@@ -54,7 +55,7 @@ export class RKeyCache {
* Resolve a URL for video/record/file media elements. * Resolve a URL for video/record/file media elements.
* Appends the correct RKey type based on media kind and group/private context. * 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 ?? ''; const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return 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; const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType); 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 now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => { const tryFind = (type: number): string | null => {
+5 -7
View File
@@ -1,6 +1,5 @@
import path from 'path'; import path from 'path';
import type { Bridge } from '../bridge/bridge'; import type { BridgeInterface } from '../bridge/bridge-interface';
import type { QQInfo } from '../bridge/qq-info';
import { ApiHandler } from './api-handler'; import { ApiHandler } from './api-handler';
import type { ConverterContext } from './event-converter'; import type { ConverterContext } from './event-converter';
import { MediaIndexer } from './media-indexer'; import { MediaIndexer } from './media-indexer';
@@ -27,8 +26,7 @@ const log = createLogger('Event');
export class OneBotInstance { export class OneBotInstance {
readonly uin: string; readonly uin: string;
readonly qqInfo: QQInfo; private readonly bridge: BridgeInterface;
private readonly bridge: Bridge;
private readonly apiHandler: ApiHandler; private readonly apiHandler: ApiHandler;
private readonly converterCtx: ConverterContext; private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore; private readonly messageStore: MessageStore;
@@ -43,9 +41,10 @@ export class OneBotInstance {
private heartbeatTimer: NodeJS.Timeout | null = null; private heartbeatTimer: NodeJS.Timeout | null = null;
private static readonly HEARTBEAT_INTERVAL = 30000; 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.uin = uin;
this.qqInfo = qqInfo;
this.bridge = bridge; this.bridge = bridge;
this.rkeyCache = new RKeyCache(); this.rkeyCache = new RKeyCache();
@@ -75,7 +74,6 @@ export class OneBotInstance {
const ctx: OneBotInstanceContext = { const ctx: OneBotInstanceContext = {
uin: this.uin, uin: this.uin,
selfId: parseInt(this.uin, 10) || 0, selfId: parseInt(this.uin, 10) || 0,
qqInfo: this.qqInfo,
bridge: this.bridge, bridge: this.bridge,
messageStore: this.messageStore, messageStore: this.messageStore,
mediaStore: this.mediaStore, mediaStore: this.mediaStore,
+13 -14
View File
@@ -1,5 +1,4 @@
import type { Bridge } from '../bridge/bridge'; import type { BridgeInterface } from '../bridge/bridge-interface';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeManager } from '../bridge/manager'; import type { BridgeManager } from '../bridge/manager';
import { loadOneBotConfig } from './config'; import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance'; import { OneBotInstance } from './instance';
@@ -12,8 +11,8 @@ export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>(); private readonly instances = new Map<string, OneBotInstance>();
bind(bridgeManager: BridgeManager): void { bind(bridgeManager: BridgeManager): void {
bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => { bridgeManager.setSessionStartedCallback((uin, bridge) => {
this.onSessionStarted(uin, qqInfo, bridge); this.onSessionStarted(uin, bridge);
}); });
bridgeManager.setSessionClosedCallback((uin) => { bridgeManager.setSessionClosedCallback((uin) => {
@@ -49,11 +48,11 @@ export class OneBotManager {
this.instances.clear(); 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; if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin); const config = loadOneBotConfig(uin);
const instance = new OneBotInstance(uin, qqInfo, bridge, config); const instance = new OneBotInstance(uin, bridge, config);
const activePid = bridge.activePid; const activePid = bridge.activePid;
if (activePid !== null) { if (activePid !== null) {
@@ -62,13 +61,13 @@ export class OneBotManager {
// Seed nickname with the UIN so the WebUI never renders blank while // Seed nickname with the UIN so the WebUI never renders blank while
// warmup is in flight or if warmup never resolves a real nickname. // 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); this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin); log.info('session started: UIN=%s', uin);
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state) // 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)); 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; const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false; let selfResolved = false;
// Step 1: Fetch friend list + derive self profile when QQ happens to // Step 1: Fetch friend list + derive self profile when QQ happens to
// include self in the response. Some accounts / versions omit self, // 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. // explicit fallback.
try { try {
const friends = await bridge.fetchFriendList(); const friends = await bridge.fetchFriendList();
@@ -98,12 +97,12 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
for (const f of friends) { for (const f of friends) {
if (f.uin === selfUin) { if (f.uin === selfUin) {
qqInfo.setSelfProfile({ bridge.identity.setSelfProfile({
uin: f.uin, uid: f.uid, uin: f.uin, uid: f.uid,
nickname: f.nickname || uin, nickname: f.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', 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 ?? ''); log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
selfResolved = true; selfResolved = true;
break; break;
@@ -120,8 +119,8 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
if (!selfResolved && selfUin > 0) { if (!selfResolved && selfUin > 0) {
try { try {
const profile = await bridge.fetchUserProfile(selfUin); const profile = await bridge.fetchUserProfile(selfUin);
qqInfo.setSelfProfile(profile); bridge.identity.setSelfProfile(profile);
qqInfo.nickname = profile.nickname || uin; bridge.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s', log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
uin, profile.uid, profile.nickname); uin, profile.uid, profile.nickname);
} catch (e) { } catch (e) {
@@ -12,13 +12,13 @@
// //
// Used as the `mediaUrlResolver` callback in `ConverterContext`. // 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 { MessageElement } from '../bridge/events';
import type { RKeyCache } from './instance-rkey'; import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver { export class MediaUrlResolver {
constructor( constructor(
private readonly bridge: Bridge, private readonly bridge: BridgeInterface,
private readonly rkeyCache: RKeyCache, private readonly rkeyCache: RKeyCache,
) {} ) {}
@@ -1,17 +1,17 @@
import type { Bridge } from '../../bridge/bridge'; import type { BridgeInterface } from '../../bridge/bridge-interface';
import type { QQInfo } from '../../bridge/qq-info'; import type { IdentityService } from '../../bridge/identity-service';
import type { OneBotInstanceContext } from '../instance-context'; import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types'; import type { JsonObject } from '../types';
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } { export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0; 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 }; return { userId, nickname };
} }
// Keep refreshes scoped. A broad "refresh all members in all groups" call can // 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. // 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 { try {
await bridge.fetchGroupMemberList(groupId); await bridge.fetchGroupMemberList(groupId);
} catch { } 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 { try {
const friends = await bridge.fetchFriendList(); const friends = await bridge.fetchFriendList();
return friends.map(f => ({ return friends.map(f => ({
@@ -28,7 +28,7 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
remark: f.remark as any, remark: f.remark as any,
})); }));
} catch { } catch {
return qqInfo.friends.map(f => ({ return bridge.identity.friends.map(f => ({
user_id: f.uin as any, user_id: f.uin as any,
nickname: f.nickname as any, nickname: f.nickname as any,
remark: f.remark 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( export async function getGroupList(
bridge: Bridge, bridge: BridgeInterface,
qqInfo: QQInfo,
noCache?: boolean, noCache?: boolean,
): Promise<JsonObject[]> { ): Promise<JsonObject[]> {
try { try {
if (noCache || qqInfo.groups.length === 0) { if (noCache || bridge.identity.groups.length === 0) {
await bridge.fetchGroupList(); await bridge.fetchGroupList();
} }
} catch { } catch {
// Use cached data. // Use cached data.
} }
return qqInfo.groups.map(g => ({ return bridge.identity.groups.map(g => ({
group_id: g.groupId as any, group_id: g.groupId as any,
group_name: g.groupName as any, group_name: g.groupName as any,
member_count: g.memberCount as any, member_count: g.memberCount as any,
@@ -57,19 +56,18 @@ export async function getGroupList(
} }
export async function getGroupInfo( export async function getGroupInfo(
bridge: Bridge, bridge: BridgeInterface,
qqInfo: QQInfo,
groupId: number, groupId: number,
noCache?: boolean, noCache?: boolean,
): Promise<JsonObject | null> { ): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroup(groupId)) { if (noCache || !bridge.identity.findGroup(groupId)) {
try { try {
await bridge.fetchGroupList(); await bridge.fetchGroupList();
} catch { } catch {
// Use cached data. // Use cached data.
} }
} }
const g = qqInfo.findGroup(groupId); const g = bridge.identity.findGroup(groupId);
if (!g) return null; if (!g) return null;
return { return {
group_id: g.groupId as any, group_id: g.groupId as any,
@@ -80,41 +78,39 @@ export async function getGroupInfo(
} }
export async function getGroupMemberList( export async function getGroupMemberList(
bridge: Bridge, bridge: BridgeInterface,
qqInfo: QQInfo,
groupId: number, groupId: number,
noCache?: boolean, noCache?: boolean,
): Promise<JsonObject[]> { ): Promise<JsonObject[]> {
if (noCache) { if (noCache) {
await refreshSingleGroupMembers(bridge, groupId); await refreshSingleGroupMembers(bridge, groupId);
return getCachedGroupMembers(qqInfo, groupId); return getCachedGroupMembers(bridge.identity, groupId);
} }
try { try {
const members = await bridge.fetchGroupMemberList(groupId); const members = await bridge.fetchGroupMemberList(groupId);
return members.map(m => formatGroupMember(groupId, m)); return members.map(m => formatGroupMember(groupId, m));
} catch { } catch {
return getCachedGroupMembers(qqInfo, groupId); return getCachedGroupMembers(bridge.identity, groupId);
} }
} }
export async function getGroupMemberInfo( export async function getGroupMemberInfo(
bridge: Bridge, bridge: BridgeInterface,
qqInfo: QQInfo,
groupId: number, groupId: number,
userId: number, userId: number,
noCache?: boolean, noCache?: boolean,
): Promise<JsonObject | null> { ): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroupMember(groupId, userId)) { if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
await refreshSingleGroupMembers(bridge, groupId); await refreshSingleGroupMembers(bridge, groupId);
} }
const m = qqInfo.findGroupMember(groupId, userId); const m = bridge.identity.findGroupMember(groupId, userId);
if (!m) return null; if (!m) return null;
return formatGroupMember(groupId, m); return formatGroupMember(groupId, m);
} }
export async function getGroupFiles( export async function getGroupFiles(
bridge: Bridge, bridge: BridgeInterface,
groupId: number, groupId: number,
folderId?: string, folderId?: string,
): Promise<JsonObject> { ): Promise<JsonObject> {
@@ -146,8 +142,7 @@ export async function getGroupFiles(
} }
export async function getStrangerInfo( export async function getStrangerInfo(
bridge: Bridge, bridge: BridgeInterface,
qqInfo: QQInfo,
userId: number, userId: number,
): Promise<JsonObject | null> { ): Promise<JsonObject | null> {
try { try {
@@ -159,7 +154,7 @@ export async function getStrangerInfo(
age: p.age as any, age: p.age as any,
}; };
} catch { } catch {
const p = qqInfo.findUserProfile(userId); const p = bridge.identity.findUserProfile(userId);
if (!p) return null; if (!p) return null;
return { return {
user_id: p.uin as any, 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 { try {
const reqs = await bridge.fetchGroupRequests(); const reqs = await bridge.fetchGroupRequests();
return reqs.map(r => ({ 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 { try {
const rkeys = await bridge.fetchDownloadRKeys(); const rkeys = await bridge.fetchDownloadRKeys();
return rkeys.map(r => ({ return rkeys.map(r => ({
@@ -201,8 +196,8 @@ export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
} }
} }
function getCachedGroupMembers(qqInfo: QQInfo, groupId: number): JsonObject[] { function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
const g = qqInfo.findGroup(groupId); const g = identity.findGroup(groupId);
if (!g) return []; if (!g) return [];
const result: JsonObject[] = []; const result: JsonObject[] = [];
for (const [, member] of g.members) { 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 { createLogger } from '../../utils/logger';
import type { MediaStore } from '../media-store'; import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types'; import type { JsonObject } from '../types';
@@ -21,7 +21,7 @@ export async function getImageInfo(
} }
export async function getRecordInfo( export async function getRecordInfo(
bridge: Bridge, bridge: BridgeInterface,
mediaStore: MediaStore, mediaStore: MediaStore,
file: string, file: string,
): Promise<JsonObject | null> { ): 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 type { ForwardNodePayload, MessageElement } from '../../bridge/events';
import { createLogger } from '../../utils/logger'; import { createLogger } from '../../utils/logger';
import type { MessageSendResult } from '../api-handler'; import type { MessageSendResult } from '../api-handler';
@@ -63,7 +63,7 @@ export async function getFriendMsgHistory(
.map(sanitizeMessageEventForApi); .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) { if (meta.isGroup) {
await bridge.recallGroupMessage(meta.targetId, meta.sequence); await bridge.recallGroupMessage(meta.targetId, meta.sequence);
} else { } else {
@@ -78,7 +78,7 @@ export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise<
} }
export async function setEssenceMessage( export async function setEssenceMessage(
bridge: Bridge, bridge: BridgeInterface,
messageStore: MessageStore, messageStore: MessageStore,
messageId: number, messageId: number,
enable: boolean, enable: boolean,
@@ -1,7 +1,7 @@
import type { Bridge } from '../../bridge/bridge'; import type { BridgeInterface } from '../../bridge/bridge-interface';
export async function handleGroupAddRequest( export async function handleGroupAddRequest(
bridge: Bridge, bridge: BridgeInterface,
flag: string, flag: string,
approve: boolean, approve: boolean,
reason: string, reason: string,
+1 -1
View File
@@ -306,7 +306,7 @@ export async function initWebUI(
app.get('/api/qq-list', (c) => { app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances(); 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 }); return c.json({ list });
}); });
+8 -9
View File
@@ -11,19 +11,19 @@ import { vi } from 'vitest';
import type { SendPacketResult } from '../../src/protocol/packet-sender'; import type { SendPacketResult } from '../../src/protocol/packet-sender';
export interface MockBridge { export interface MockBridge {
qqInfo: { identity: {
uin: string; uin: string;
selfUid: string; selfUid: string;
findGroupMember: ReturnType<typeof vi.fn>; nickname: string;
};
identity: {
findUidByUin: ReturnType<typeof vi.fn>; findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>; findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
}; };
sendRawPacket: ReturnType<typeof vi.fn>; sendRawPacket: ReturnType<typeof vi.fn>;
fetchFriendList: ReturnType<typeof vi.fn>; fetchFriendList: ReturnType<typeof vi.fn>;
fetchGroupMemberList: ReturnType<typeof vi.fn>; fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>; fetchUserProfile: ReturnType<typeof vi.fn>;
resolveUserUid: ReturnType<typeof vi.fn>;
} }
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge { export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
@@ -35,21 +35,20 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
responseData: Buffer.alloc(0), responseData: Buffer.alloc(0),
}; };
return { return {
qqInfo: { identity: {
uin: '10001', uin: '10001',
selfUid: 'self-uid', selfUid: 'self-uid',
findGroupMember: vi.fn(() => null), nickname: 'self-nick',
...(overrides.qqInfo ?? {}),
} as MockBridge['qqInfo'],
identity: {
findUidByUin: vi.fn(() => 'cached-uid'), findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0), findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
...(overrides.identity ?? {}), ...(overrides.identity ?? {}),
} as MockBridge['identity'], } as MockBridge['identity'],
sendRawPacket: vi.fn(async () => defaultResp), sendRawPacket: vi.fn(async () => defaultResp),
fetchFriendList: vi.fn(async () => []), fetchFriendList: vi.fn(async () => []),
fetchGroupMemberList: vi.fn(async () => []), fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })), fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
...overrides, ...overrides,
}; };
} }
+1 -4
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
// element-builder reaches into protoEncode with element-specific schemas // element-builder reaches into protoEncode with element-specific schemas
+15 -19
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,33 +10,32 @@ import { mockBridge } from './_helpers';
describe('actions/friend', () => { describe('actions/friend', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
}); });
it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => { it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, '10001', true); await friend.setFriendAddRequest(bridge as any, '10001', true);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); expect(call.request.value).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
}); });
it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => { it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, 'flag-abc', false); await friend.setFriendAddRequest(bridge as any, 'flag-abc', false);
expect(oidb.resolveUserUid).not.toHaveBeenCalled(); expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); expect(call.request.value).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
}); });
it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.deleteFriend(bridge as any, 10001, true); await friend.deleteFriend(bridge as any, 10001, true);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0x126b_0'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
expect((call[4] as any).field1.block).toBe(true); expect((call.request.value as any).field1.block).toBe(true);
expect(bridge.fetchFriendList).toHaveBeenCalled(); expect(bridge.fetchFriendList).toHaveBeenCalled();
}); });
@@ -54,8 +50,8 @@ describe('actions/friend', () => {
it('setFriendRemark resolves UID and sends 0xb6e_2', async () => { it('setFriendRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.setFriendRemark(bridge as any, 10001, 'best-friend'); await friend.setFriendRemark(bridge as any, 10001, 'best-friend');
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0xb6e_2'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
expect(call[4]).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); expect(call.request.value).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
}); });
}); });
+26 -31
View File
@@ -3,10 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Stub the OIDB shim so we can assert WHICH command + payload each // Stub the OIDB shim so we can assert WHICH command + payload each
// action constructs without booting a real Bridge / native pipe. // action constructs without booting a real Bridge / native pipe.
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -15,21 +12,19 @@ import { mockBridge } from './_helpers';
describe('actions/group-admin', () => { describe('actions/group-admin', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
}); });
it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => { it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.muteGroupMember(bridge as any, 12345, 67890, 600); await admin.muteGroupMember(bridge as any, 12345, 67890, 600);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 67890, 12345); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce(); expect(oidb.runOidb).toHaveBeenCalledOnce();
const args = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(args[1]).toBe('OidbSvcTrpcTcp.0x1253_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1253_1');
expect(args[2]).toBe(0x1253); expect(call.oidbCmd).toBe(0x1253);
expect(args[3]).toBe(1); expect(call.subCmd).toBe(1);
expect(args[4]).toMatchObject({ expect(call.request.value).toMatchObject({
groupUin: 12345, groupUin: 12345,
type: 1, type: 1,
body: { targetUid: 'resolved-uid', duration: 600 }, body: { targetUid: 'resolved-uid', duration: 600 },
@@ -39,13 +34,13 @@ describe('actions/group-admin', () => {
it('muteGroupAll flips the muteState flag based on enable', async () => { it('muteGroupAll flips the muteState flag based on enable', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.muteGroupAll(bridge as any, 12345, true); await admin.muteGroupAll(bridge as any, 12345, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, groupUin: 12345,
muteState: { state: 0xFFFFFFFF }, muteState: { state: 0xFFFFFFFF },
}); });
await admin.muteGroupAll(bridge as any, 12345, false); await admin.muteGroupAll(bridge as any, 12345, false);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value).toMatchObject({
muteState: { state: 0 }, muteState: { state: 0 },
}); });
}); });
@@ -53,8 +48,8 @@ describe('actions/group-admin', () => {
it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => { it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour'); await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour');
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 67890, 12345); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, groupUin: 12345,
targetUid: 'resolved-uid', targetUid: 'resolved-uid',
rejectAddRequest: true, rejectAddRequest: true,
@@ -64,13 +59,13 @@ describe('actions/group-admin', () => {
it('kickGroupMembers resolves each UID in parallel', async () => { it('kickGroupMembers resolves each UID in parallel', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.resolveUserUid) vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('uid-a') .mockResolvedValueOnce('uid-a')
.mockResolvedValueOnce('uid-b'); .mockResolvedValueOnce('uid-b');
await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false); await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false);
expect(oidb.resolveUserUid).toHaveBeenCalledTimes(2); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const payload: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
expect(payload.targetUids).toEqual(['uid-a', 'uid-b']); expect(payload.targetUids).toEqual(['uid-a', 'uid-b']);
expect(payload.rejectAddRequest).toBe(0); expect(payload.rejectAddRequest).toBe(0);
}); });
@@ -78,15 +73,15 @@ describe('actions/group-admin', () => {
it('leaveGroup sends 0x1097_1 with the groupUin', async () => { it('leaveGroup sends 0x1097_1 with the groupUin', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.leaveGroup(bridge as any, 12345); await admin.leaveGroup(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0x1097_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(call[4]).toMatchObject({ groupUin: 12345 }); expect(call.request.value).toMatchObject({ groupUin: 12345 });
}); });
it('setGroupAdmin resolves UID and sends 0x1096_1', async () => { it('setGroupAdmin resolves UID and sends 0x1096_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.setGroupAdmin(bridge as any, 12345, 67890, true); await admin.setGroupAdmin(bridge as any, 12345, 67890, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, uid: 'resolved-uid', isAdmin: true, groupUin: 12345, uid: 'resolved-uid', isAdmin: true,
}); });
}); });
@@ -100,7 +95,7 @@ describe('actions/group-admin', () => {
await admin.setGroupAddOption(bridge as any, 1, 2); await admin.setGroupAddOption(bridge as any, 1, 2);
await admin.setGroupSearch(bridge as any, 1); await admin.setGroupSearch(bridge as any, 1);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
expect(cmds).toEqual([ expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x8fc_3', 'OidbSvcTrpcTcp.0x8fc_3',
'OidbSvcTrpcTcp.0x89a_15', 'OidbSvcTrpcTcp.0x89a_15',
@@ -116,23 +111,23 @@ describe('actions/group-admin', () => {
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false); await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false);
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true); await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
expect(cmds).toEqual([ expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x10c8_1', 'OidbSvcTrpcTcp.0x10c8_1',
'OidbSvcTrpcTcp.0x10c8_2', 'OidbSvcTrpcTcp.0x10c8_2',
]); ]);
const firstBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const firstBody: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
expect(firstBody.accept).toBe(1); expect(firstBody.accept).toBe(1);
expect(firstBody.body.message).toBe('ok'); expect(firstBody.body.message).toBe('ok');
const secondBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4]; const secondBody: any = vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value;
expect(secondBody.accept).toBe(2); expect(secondBody.accept).toBe(2);
}); });
it('getGroupAtAllRemain decodes the response and converts BigInts', async () => { it('getGroupAtAllRemain decodes the response and converts BigInts', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
canAtAll: 1, canAtAll: 1,
groupRemain: 12n, groupRemain: 12n,
uinRemain: 5n, uinRemain: 5n,
@@ -147,7 +142,7 @@ describe('actions/group-admin', () => {
it('getGroupAtAllRemain throws when the response is empty', async () => { it('getGroupAtAllRemain throws when the response is empty', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce(null); vi.mocked(oidb.runOidb).mockResolvedValueOnce(null);
await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/); await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/);
}); });
}); });
+28 -25
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
vi.mock('../../src/bridge/highway/highway-client', () => ({ vi.mock('../../src/bridge/highway/highway-client', () => ({
@@ -28,16 +25,15 @@ import { mockBridge } from './_helpers';
describe('actions/group-file', () => { describe('actions/group-file', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
}); });
it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => { it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
count: { fileCount: 42, maxCount: 1000 }, count: { fileCount: 42, maxCount: 1000 },
}); });
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
@@ -46,14 +42,14 @@ describe('actions/group-file', () => {
it('fetchGroupFileCount falls back to defaults on partial response', async () => { it('fetchGroupFileCount falls back to defaults on partial response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ count: {} }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ count: {} });
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
}); });
it('uploadGroupFile skips highway when boolFileExist is true', async () => { it('uploadGroupFile skips highway when boolFileExist is true', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { upload: {
retCode: 0, retCode: 0,
fileId: 'fid-xyz', fileId: 'fid-xyz',
@@ -68,7 +64,7 @@ describe('actions/group-file', () => {
it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => { it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { upload: {
retCode: 0, retCode: 0,
fileId: 'fid-xyz', fileId: 'fid-xyz',
@@ -86,14 +82,14 @@ describe('actions/group-file', () => {
it('uploadGroupFile throws on missing upload response', async () => { it('uploadGroupFile throws on missing upload response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({}); vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/response missing/); .rejects.toThrow(/response missing/);
}); });
it('uploadGroupFile bubbles up OIDB retCode errors', async () => { it('uploadGroupFile bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 999, retMsg: 'quota exceeded' }, upload: { retCode: 999, retMsg: 'quota exceeded' },
}); });
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
@@ -102,22 +98,29 @@ describe('actions/group-file', () => {
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => { it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({ const bridge = mockBridge({
qqInfo: { uin: '10001', selfUid: '', findGroupMember: vi.fn(() => null) }, identity: {
uin: '10001',
selfUid: '',
nickname: 'self-nick',
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
},
}); });
vi.mocked(oidb.resolveUserUid) vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('target-uid') // target user .mockResolvedValueOnce('target-uid') // target user
.mockResolvedValueOnce('self-uid-resolved'); // self fallback .mockResolvedValueOnce('self-uid-resolved'); // self fallback
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true }, upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true },
}); });
const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file'); const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file');
expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' }); expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' });
expect(oidb.resolveUserUid).toHaveBeenCalledTimes(2); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
}); });
it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { it('fetchGroupFiles paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
list: { list: {
retCode: 0, retCode: 0,
isEnd: true, isEnd: true,
@@ -136,7 +139,7 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => { it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: { download: {
retCode: 0, retCode: 0,
downloadDns: 'cdn.example.com', downloadDns: 'cdn.example.com',
@@ -149,7 +152,7 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl throws when response is missing dns or url', async () => { it('fetchGroupFileUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: { retCode: 0 }, download: { retCode: 0 },
}); });
await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz')) await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'))
@@ -158,29 +161,29 @@ describe('actions/group-file', () => {
it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => { it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ delete: { retCode: 0 } }) .mockResolvedValueOnce({ delete: { retCode: 0 } })
.mockResolvedValueOnce({ move: { retCode: 0 } }); .mockResolvedValueOnce({ move: { retCode: 0 } });
await groupFile.deleteGroupFile(bridge as any, 12345, 'fid'); await groupFile.deleteGroupFile(bridge as any, 12345, 'fid');
await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b'); await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[3])).toEqual([3, 5]); expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].subCmd)).toEqual([3, 5]);
}); });
it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => { it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ create: { retcode: 0 } }) .mockResolvedValueOnce({ create: { retcode: 0 } })
.mockResolvedValueOnce({ delete: { retcode: 0 } }) .mockResolvedValueOnce({ delete: { retcode: 0 } })
.mockResolvedValueOnce({ rename: { retcode: 0 } }); .mockResolvedValueOnce({ rename: { retcode: 0 } });
await groupFile.createGroupFileFolder(bridge as any, 1, 'folder'); await groupFile.createGroupFileFolder(bridge as any, 1, 'folder');
await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid'); await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid');
await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname'); await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[2])).toEqual([0x6D7, 0x6D7, 0x6D7]); expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].oidbCmd)).toEqual([0x6D7, 0x6D7, 0x6D7]);
}); });
it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => { it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValue({ vi.mocked(oidb.runOidb).mockResolvedValue({
respHead: { retCode: 0 }, respHead: { retCode: 0 },
download: { download: {
info: { domain: 'media.example.com', urlPath: '/path/x' }, info: { domain: 'media.example.com', urlPath: '/path/x' },
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,8 +10,7 @@ import { mockBridge } from './_helpers';
describe('actions/group-message', () => { describe('actions/group-message', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
}); });
it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => { it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => {
@@ -42,7 +38,7 @@ describe('actions/group-message', () => {
it('recallPrivateMessage resolves the target UID before dispatch', async () => { it('recallPrivateMessage resolves the target UID before dispatch', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await msg.recallPrivateMessage(bridge as any, 10001, 100, 200, 123, 1700000000); await msg.recallPrivateMessage(bridge as any, 10001, 100, 200, 123, 1700000000);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!; const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg'); expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
}); });
@@ -63,7 +59,7 @@ describe('actions/group-message', () => {
const bridge = mockBridge(); const bridge = mockBridge();
await msg.setGroupEssence(bridge as any, 12345, 5, 7, true); await msg.setGroupEssence(bridge as any, 12345, 5, 7, true);
await msg.setGroupEssence(bridge as any, 12345, 5, 7, false); await msg.setGroupEssence(bridge as any, 12345, 5, 7, false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
}); });
}); });
+13 -16
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,43 +10,43 @@ import { mockBridge } from './_helpers';
describe('actions/interaction', () => { describe('actions/interaction', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockResolvedValue({});
}); });
it('sendPoke group: groupUin set, friendUin=0', async () => { it('sendPoke group: groupUin set, friendUin=0', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.sendPoke(bridge as any, true, 12345, 67890); await inter.sendPoke(bridge as any, true, 12345, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
}); });
it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => { it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.sendPoke(bridge as any, false, 67890); await inter.sendPoke(bridge as any, false, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
}); });
it('sendLike forwards target + count to 0x7e5_104', async () => { it('sendLike forwards target + count to 0x7e5_104', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.sendLike(bridge as any, 10001, 3); await inter.sendLike(bridge as any, 10001, 3);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0x7e5_104'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x7e5_104');
expect(call[4]).toMatchObject({ targetUin: 10001, count: 3 }); expect(call.request.value).toMatchObject({ targetUin: 10001, count: 3 });
}); });
it('setGroupReaction picks _1 for set and _2 for unset', async () => { it('setGroupReaction picks _1 for set and _2 for unset', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true);
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']); expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
}); });
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => { it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
inner: { userInfo: { uin: 10001 } }, inner: { userInfo: { uin: 10001 } },
cookie: new Uint8Array([0xCA, 0xFE]), cookie: new Uint8Array([0xCA, 0xFE]),
}); });
@@ -61,7 +58,7 @@ describe('actions/interaction', () => {
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => { it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({}); vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([]); expect(out.users).toEqual([]);
expect(out.isLast).toBe(true); expect(out.isLast).toBe(true);
+8 -10
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,12 +10,13 @@ import { mockBridge } from './_helpers';
describe('actions/misc', () => { describe('actions/misc', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
}); });
it('translateEn2Zh returns dstWords when present', async () => { it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
translateResp: { dstWords: ['你好', '世界'] }, translateResp: { dstWords: ['你好', '世界'] },
}); });
const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']); const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']);
@@ -27,7 +25,7 @@ describe('actions/misc', () => {
it('translateEn2Zh throws on empty response', async () => { it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({}); vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
await expect(misc.translateEn2Zh(bridge as any, ['hello'])) await expect(misc.translateEn2Zh(bridge as any, ['hello']))
.rejects.toThrow(/empty/); .rejects.toThrow(/empty/);
}); });
@@ -62,7 +60,7 @@ describe('actions/misc', () => {
it('clickInlineKeyboardButton returns shaped result', async () => { it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
result: 1, errMsg: 'ok', promptText: 'hi', result: 1, errMsg: 'ok', promptText: 'hi',
}); });
const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100); const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100);
@@ -72,7 +70,7 @@ describe('actions/misc', () => {
it('sendGroupSign dispatches to 0xEB7_1', async () => { it('sendGroupSign dispatches to 0xEB7_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await misc.sendGroupSign(bridge as any, 12345); await misc.sendGroupSign(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0xEB7_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
}); });
}); });
+15 -19
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
vi.mock('../../src/bridge/highway/highway-client', () => ({ vi.mock('../../src/bridge/highway/highway-client', () => ({
@@ -25,9 +22,8 @@ import { mockBridge } from './_helpers';
describe('actions/profile', () => { describe('actions/profile', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
}); });
@@ -42,30 +38,30 @@ describe('actions/profile', () => {
it('setProfile is a no-op when both arguments are undefined', async () => { it('setProfile is a no-op when both arguments are undefined', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setProfile(bridge as any); await profile.setProfile(bridge as any);
expect(oidb.sendOidbAndCheck).not.toHaveBeenCalled(); expect(oidb.runOidb).not.toHaveBeenCalled();
}); });
it('setProfile only sends non-undefined fields', async () => { it('setProfile only sends non-undefined fields', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setProfile(bridge as any, 'New Nick'); await profile.setProfile(bridge as any, 'New Nick');
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce(); expect(oidb.runOidb).toHaveBeenCalledOnce();
const body: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(body.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); expect((call.request.value as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
}); });
it('setSelfLongNick wraps the long nick in profile tag 102', async () => { it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setSelfLongNick(bridge as any, 'hello world'); await profile.setSelfLongNick(bridge as any, 'hello world');
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect((call[4] as any).profile).toEqual({ tag: 102, value: 'hello world' }); expect((call.request.value as any).profile).toEqual({ tag: 102, value: 'hello world' });
}); });
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setInputStatus(bridge as any, 10001, 1); await profile.setInputStatus(bridge as any, 10001, 1);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0xcd4_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0xcd4_1');
}); });
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
@@ -79,7 +75,7 @@ describe('actions/profile', () => {
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
userLikeInfos: [{ userLikeInfos: [{
uid: 'u', uid: 'u',
time: 1700000000n, time: 1700000000n,
@@ -94,13 +90,13 @@ describe('actions/profile', () => {
it('getProfileLike throws on empty result', async () => { it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ userLikeInfos: [] }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ userLikeInfos: [] });
await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/); await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/);
}); });
it('getUnidirectionalFriendList parses the embedded JSON body', async () => { it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }), jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
}); });
const out = await profile.getUnidirectionalFriendList(bridge as any); const out = await profile.getUnidirectionalFriendList(bridge as any);
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge'; import { Bridge } from '../src/bridge/bridge';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info'; import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events'; import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events';
import type { PacketInfo } from '../src/protocol/types'; import type { PacketInfo } from '../src/protocol/types';
@@ -36,14 +37,14 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
class RefreshingBridge extends Bridge { class RefreshingBridge extends Bridge {
readonly memberFetches: Array<{ groupId: number; force: boolean }> = []; readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
constructor(qqInfo: QQInfo, private readonly refreshedMembers: GroupMemberInfo[]) { constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(qqInfo); super(identity);
} }
override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> { override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
this.memberFetches.push({ groupId, force: Boolean(options.force) }); this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) { for (const member of this.refreshedMembers) {
this.qqInfo.updateGroupMember(groupId, member); this.identity.updateGroupMember(groupId, member);
} }
return this.refreshedMembers; return this.refreshedMembers;
} }
@@ -79,9 +80,9 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
describe('Bridge group member identity refresh', () => { describe('Bridge group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => { it('forces a fresh member list before dispatching an unresolved join event', async () => {
const member = makeGroupMember(22222, 'u_new_member'); const member = makeGroupMember(22222, 'u_new_member');
const qqInfo = new QQInfo(SELF_UIN); const identity = IdentityService.memory(SELF_UIN);
qqInfo.setGroups([makeGroup()]); identity.rememberGroups([makeGroup()]);
const bridge = new RefreshingBridge(qqInfo, [member]); const bridge = new RefreshingBridge(identity, [member]);
const seen: GroupMemberJoin[] = []; const seen: GroupMemberJoin[] = [];
bridge.registerCmd('test.member_join', () => [{ bridge.registerCmd('test.member_join', () => [{
@@ -107,8 +108,7 @@ describe('Bridge group member identity refresh', () => {
}); });
it('remembers UID mappings from realtime request events', () => { it('remembers UID mappings from realtime request events', () => {
const qqInfo = new QQInfo(SELF_UIN); const bridge = new Bridge(IdentityService.memory(SELF_UIN));
const bridge = new Bridge(qqInfo);
const events: QQEventVariant[] = [ const events: QQEventVariant[] = [
{ {
kind: 'friend_request', kind: 'friend_request',
@@ -10,7 +10,7 @@ vi.mock('../src/bridge/element-builder', () => ({
describe('Bridge private media routing', () => { describe('Bridge private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => { it('includes resolved uid in the final c2c send request for media messages', async () => {
const { Bridge } = await import('../src/bridge/bridge'); const { Bridge } = await import('../src/bridge/bridge');
const { QQInfo } = await import('../src/bridge/qq-info'); const { IdentityService } = await import('../src/bridge/identity-service');
class TestBridge extends Bridge { class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null; capturedBody: Uint8Array | null = null;
@@ -37,7 +37,7 @@ describe('Bridge private media routing', () => {
} }
} }
const bridge = new TestBridge(new QQInfo('10000')); const bridge = new TestBridge(IdentityService.memory('10000'));
await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array); expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
@@ -104,7 +104,6 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
const ctx: OneBotInstanceContext = { const ctx: OneBotInstanceContext = {
uin: SELF_UIN, uin: SELF_UIN,
selfId: SELF_ID, selfId: SELF_ID,
qqInfo: {} as never,
bridge: fakeBridge as never, bridge: fakeBridge as never,
messageStore: {} as never, messageStore: {} as never,
mediaStore: {} as never, mediaStore: {} as never,
+86 -31
View File
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it } from 'vitest'; import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { IdentityService } from '../src/bridge/identity-service'; import { IdentityService } from '../src/bridge/identity-service';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info'; import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '../src/bridge/qq-info';
const SELF_UIN = '10001'; const SELF_UIN = '10001';
const GROUP_ID = 123456789; const GROUP_ID = 123456789;
@@ -60,8 +60,7 @@ describe('IdentityService', () => {
const dbPath = tempDbPath('persist'); const dbPath = tempDbPath('persist');
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]); identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]);
identity.rememberGroups([makeGroup()]); identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]); identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
@@ -69,12 +68,11 @@ describe('IdentityService', () => {
} }
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findFriend(22222)?.uid).toBe('u_friend'); expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(qqInfo.findGroup(GROUP_ID)?.groupName).toBe('group'); expect(identity.findGroup(GROUP_ID)?.groupName).toBe('group');
expect(qqInfo.findGroupMember(GROUP_ID, 33333)?.card).toBe('card'); expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member'); expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member');
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333); expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
@@ -88,8 +86,7 @@ describe('IdentityService', () => {
const second = makeMember(44444, 'u_second'); const second = makeMember(44444, 'u_second');
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberGroups([makeGroup()]); identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [first, second]); identity.rememberGroupMembers(GROUP_ID, [first, second]);
identity.rememberGroupMembers(GROUP_ID, [second]); identity.rememberGroupMembers(GROUP_ID, [second]);
@@ -97,11 +94,10 @@ describe('IdentityService', () => {
} }
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findGroupMember(GROUP_ID, first.uin)).toBeNull(); expect(identity.findGroupMember(GROUP_ID, first.uin)).toBeNull();
expect(qqInfo.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid); expect(identity.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
// Historical identity remains available for UID/UIN resolution. // Historical identity remains available for UID/UIN resolution.
expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid); expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid);
@@ -114,8 +110,7 @@ describe('IdentityService', () => {
const member = makeMember(33333, 'u_member'); const member = makeMember(33333, 'u_member');
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]); identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]);
identity.rememberGroups([makeGroup()]); identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]); identity.rememberGroupMembers(GROUP_ID, [member]);
@@ -125,11 +120,10 @@ describe('IdentityService', () => {
} }
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findFriend(22222)).toBeNull(); expect(identity.findFriend(22222)).toBeNull();
expect(qqInfo.findGroup(GROUP_ID)).toBeNull(); expect(identity.findGroup(GROUP_ID)).toBeNull();
// Identity mappings remain useful for historical events/actions. // Identity mappings remain useful for historical events/actions.
expect(identity.findUidByUin(22222)).toBe('u_friend'); expect(identity.findUidByUin(22222)).toBe('u_friend');
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid); expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
@@ -143,8 +137,7 @@ describe('IdentityService', () => {
const member = makeMember(33333, 'u_member'); const member = makeMember(33333, 'u_member');
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberGroups([makeGroup()]); identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]); identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin }); identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
@@ -152,10 +145,9 @@ describe('IdentityService', () => {
} }
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findGroupMember(GROUP_ID, member.uin)).toBeNull(); expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin); expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
identity.close(); identity.close();
@@ -166,8 +158,7 @@ describe('IdentityService', () => {
const dbPath = tempDbPath('request-events'); const dbPath = tempDbPath('request-events');
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberRequestIdentity({ identity.rememberRequestIdentity({
uid: 'u_friend_request', uid: 'u_friend_request',
uin: 55555, uin: 55555,
@@ -183,15 +174,79 @@ describe('IdentityService', () => {
} }
{ {
const qqInfo = new QQInfo(SELF_UIN); const identity = new IdentityService(SELF_UIN, dbPath);
const identity = new IdentityService(qqInfo, dbPath);
expect(identity.findUidByUin(55555)).toBe('u_friend_request'); expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555); expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(qqInfo.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID); expect(identity.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
expect(identity.findUidByUin(66666)).toBe('u_group_request'); expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close(); identity.close();
} }
}); });
}); });
describe('IdentityService.resolveUid', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '' };
}
it('returns the cached uid without invoking the fetcher', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberRequestIdentity({ uid: 'u_known', uin: 12345 });
const fetchProfile = vi.fn(async (uin: number) => makeProfile(uin, 'should-not-be-used'));
identity.setFetcher({ fetchProfile });
await expect(identity.resolveUid(12345)).resolves.toBe('u_known');
expect(fetchProfile).not.toHaveBeenCalled();
});
it('falls back to fetchProfile on miss and returns the resolved uid', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfile = vi.fn(async (uin: number) => {
// Simulate the bridge writing the result back via rememberUserProfile.
identity.rememberUserProfile(makeProfile(uin, 'u_fetched'));
return makeProfile(uin, 'u_fetched');
});
identity.setFetcher({ fetchProfile });
await expect(identity.resolveUid(99999)).resolves.toBe('u_fetched');
expect(fetchProfile).toHaveBeenCalledWith(99999);
});
it('throws when neither cache nor fetcher can produce a uid', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.setFetcher({ fetchProfile: async (uin) => makeProfile(uin, '') });
await expect(identity.resolveUid(99999)).rejects.toThrow(/failed to resolve UID/);
});
it('tries fetchGroupMemberList before fetchProfile when groupId is provided', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([{
groupId: GROUP_ID, groupName: '', remark: '',
memberCount: 0, memberMax: 0, members: new Map(),
}]);
const fetchProfile = vi.fn(async (uin: number) => makeProfile(uin, 'u_via_profile'));
const fetchGroupMemberList = vi.fn(async (groupId: number) => {
// Roster fetch should populate the cache.
identity.rememberGroupMembers(groupId, [makeMember(77777, 'u_via_roster')]);
return [];
});
identity.setFetcher({ fetchProfile, fetchGroupMemberList });
await expect(identity.resolveUid(77777, GROUP_ID)).resolves.toBe('u_via_roster');
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
expect(fetchProfile).not.toHaveBeenCalled();
});
it('throws on invalid (zero / negative) uin without calling fetcher', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfile = vi.fn();
identity.setFetcher({ fetchProfile });
await expect(identity.resolveUid(0)).rejects.toThrow(/invalid uin/);
expect(fetchProfile).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -258,7 +258,7 @@ describe('parseMessage', () => {
}, respSchema); }, respSchema);
const bridge = { const bridge = {
qqInfo: { uin: '10000' }, identity: { uin: '10000' },
sendRawPacket: vi.fn(async () => ({ sendRawPacket: vi.fn(async () => ({
success: true, success: true,
gotResponse: true, gotResponse: true,
+12 -7
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push-handler'; import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push-handler';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info'; import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
import { PushMsgSchema } from '../src/bridge/proto/message'; import { PushMsgSchema } from '../src/bridge/proto/message';
import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify'; import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify';
import type { GroupMemberJoin } from '../src/bridge/events'; import type { GroupMemberJoin } from '../src/bridge/events';
@@ -36,10 +37,11 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
}; };
} }
function makeQqInfo(members: GroupMemberInfo[] = []): QQInfo { function makeIdentity(members: GroupMemberInfo[] = []): IdentityService {
const qqInfo = new QQInfo(SELF_UIN); const identity = IdentityService.memory(SELF_UIN);
qqInfo.setGroups([makeGroup(members)]); identity.rememberGroups([makeGroup(members)]);
return qqInfo; if (members.length) identity.rememberGroupMembers(GROUP_ID, members);
return identity;
} }
function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo { function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo {
@@ -73,7 +75,7 @@ function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin =
describe('parseMsgPush group member increase', () => { describe('parseMsgPush group member increase', () => {
it('does not fall back to the group id when a joining uid is unresolved', () => { it('does not fall back to the group id when a joining uid is unresolved', () => {
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeQqInfo()) as GroupMemberJoin[]; const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeIdentity()) as GroupMemberJoin[];
expect(event.kind).toBe('group_member_join'); expect(event.kind).toBe('group_member_join');
expect(event.groupId).toBe(GROUP_ID); expect(event.groupId).toBe(GROUP_ID);
@@ -85,7 +87,10 @@ describe('parseMsgPush group member increase', () => {
it('resolves joining uid and operator uid from the member cache when available', () => { it('resolves joining uid and operator uid from the member cache when available', () => {
const member = makeGroupMember(22222, 'u_member'); const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator'); const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(makeGroupIncreasePacket(member.uid, operator.uid), makeQqInfo([member, operator])) as GroupMemberJoin[]; const [event] = parseMsgPush(
makeGroupIncreasePacket(member.uid, operator.uid),
makeIdentity([member, operator]),
) as GroupMemberJoin[];
expect(event.userUin).toBe(member.uin); expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(operator.uin); expect(event.operatorUin).toBe(operator.uin);
@@ -0,0 +1,297 @@
// First real OneBot unit test that exercises a module purely through
// BridgeInterface — no concrete Bridge, no SQLite, no native packet
// sender, no BridgeManager. This is the testability win that PR4 + PR5
// were supposed to unlock; the file exists to prove it.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo,
} from '../../src/bridge/qq-info';
import {
getFriendList,
getGroupInfo,
getGroupList,
getGroupMemberInfo,
getGroupMemberList,
getLoginInfo,
getStrangerInfo,
} from '../../src/onebot/modules/contact-actions';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
/**
* A typed BridgeInterface where every property is undefined by default;
* accessing an un-stubbed property throws with a clear message so tests
* fail loudly if they exercise a code path the fake hasn't been told
* about. Tests just spread the methods they care about.
*/
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
/** Same Proxy trick for the IdentityService surface that contact-actions touches. */
function fakeIdentity(overrides: Record<string, unknown> = {}): BridgeInterface['identity'] {
return new Proxy(overrides as any, {
get(target, prop) {
if (prop in target) return target[prop];
throw new Error(`fakeIdentity: '${String(prop)}' was not stubbed for this test`);
},
});
}
// ─── Fixture builders ───
function makeFriend(uin: number, nickname: string, remark = ''): FriendInfo {
return { uin, uid: `u_${uin}`, nickname, remark };
}
function makeGroup(groupId: number, groupName: string, members: GroupMemberInfo[] = []): QQGroupInfo {
return {
groupId, groupName, remark: '',
memberCount: members.length, memberMax: 500,
members: new Map(members.map((m) => [m.uin, m])),
};
}
function makeMember(uin: number, nickname: string, card = ''): GroupMemberInfo {
return {
uin, uid: `u_${uin}`, nickname, card,
role: 'member', level: 1, title: '',
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
};
}
function makeProfile(uin: number, nickname: string, sex: 'male' | 'female' | 'unknown' = 'unknown', age = 0): UserProfileInfo {
return {
uin, uid: `u_${uin}`, nickname, remark: '', qid: '', sex, age, sign: '', avatar: '',
};
}
// ─── Tests ───
describe('onebot/contact-actions / getLoginInfo', () => {
it('returns user_id parsed from uin and nickname from identity', () => {
const ref = {
uin: '10001',
bridge: fakeBridge({ identity: fakeIdentity({ nickname: 'self-nick' }) }),
} as unknown as OneBotInstanceContext;
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: 'self-nick' });
});
it('falls back to the uin string when identity nickname is empty', () => {
const ref = {
uin: '10001',
bridge: fakeBridge({ identity: fakeIdentity({ nickname: '' }) }),
} as unknown as OneBotInstanceContext;
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: '10001' });
});
});
describe('onebot/contact-actions / getFriendList', () => {
it('returns the fetched list mapped to OneBot shape', async () => {
const bridge = fakeBridge({
fetchFriendList: vi.fn(async () => [makeFriend(22222, 'alice', 'best-friend')]),
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
expect(bridge.fetchFriendList).toHaveBeenCalledOnce();
});
it('falls back to identity.friends on fetch failure', async () => {
const cached = [makeFriend(33333, 'bob')];
const bridge = fakeBridge({
fetchFriendList: vi.fn(async () => { throw new Error('network down'); }),
identity: fakeIdentity({ friends: cached }),
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 33333, nickname: 'bob', remark: '' }]);
});
});
describe('onebot/contact-actions / getGroupList', () => {
it('triggers fetch when the in-memory roster is empty', async () => {
const fetched = [makeGroup(100, 'Group A')];
// `groups` starts empty; the fetch callback flips it to mimic
// bridge.fetchGroupList writing back through identity.rememberGroups.
let groups: QQGroupInfo[] = [];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }),
identity: fakeIdentity({
get groups() { return groups; },
}),
});
const out = await getGroupList(bridge);
expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
expect(out).toEqual([{
group_id: 100, group_name: 'Group A',
member_count: 0, max_member_count: 500,
}]);
});
it('skips fetch when cache is populated and noCache is omitted', async () => {
const cached = [makeGroup(200, 'Group B')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge);
expect(bridge.fetchGroupList).not.toHaveBeenCalled();
});
it('forces fetch when noCache=true even with a populated cache', async () => {
const cached = [makeGroup(300, 'Group C')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => cached),
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge, true);
expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
});
it('serves the stale cache when the fetch path throws', async () => {
const cached = [makeGroup(400, 'Group D')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { throw new Error('boom'); }),
identity: fakeIdentity({ groups: cached }),
});
const out = await getGroupList(bridge, true);
expect(out[0]).toMatchObject({ group_id: 400, group_name: 'Group D' });
});
});
describe('onebot/contact-actions / getGroupInfo', () => {
it('returns the cached group without refreshing when group is known and noCache is false', async () => {
const cached = makeGroup(500, 'Group E');
const findGroup = vi.fn((groupId: number) => groupId === 500 ? cached : null);
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ findGroup }),
});
const out = await getGroupInfo(bridge, 500);
expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' });
expect(bridge.fetchGroupList).not.toHaveBeenCalled();
});
it('triggers fetch when the group is unknown to the cache', async () => {
const cached = makeGroup(600, 'Group F');
let known = false;
const findGroup = vi.fn((groupId: number) => (known && groupId === 600) ? cached : null);
const fetchGroupList = vi.fn(async () => { known = true; return [cached]; });
const bridge = fakeBridge({
fetchGroupList,
identity: fakeIdentity({ findGroup }),
});
const out = await getGroupInfo(bridge, 600);
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(out).toMatchObject({ group_id: 600, group_name: 'Group F' });
});
it('returns null when the group remains unknown after fetch', async () => {
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ findGroup: () => null }),
});
expect(await getGroupInfo(bridge, 700)).toBeNull();
});
});
describe('onebot/contact-actions / getGroupMemberList', () => {
it('returns the fetched roster mapped to OneBot shape', async () => {
const members = [makeMember(11, 'alice', 'A'), makeMember(22, 'bob', 'B')];
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => members),
});
const out = await getGroupMemberList(bridge, 800);
expect(out).toHaveLength(2);
expect(out[0]).toMatchObject({ group_id: 800, user_id: 11, nickname: 'alice', card: 'A' });
});
it('falls back to the cached roster when fetch fails', async () => {
const cached = makeGroup(900, '', [makeMember(33, 'cached')]);
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({
findGroup: (gid: number) => gid === 900 ? cached : null,
}),
});
const out = await getGroupMemberList(bridge, 900);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({ user_id: 33, nickname: 'cached' });
});
it('returns [] when no roster is known and fetch fails', async () => {
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({ findGroup: () => null }),
});
expect(await getGroupMemberList(bridge, 999)).toEqual([]);
});
});
describe('onebot/contact-actions / getGroupMemberInfo', () => {
it('returns the cached member when present and noCache is false', async () => {
const member = makeMember(44, 'dave', 'D');
const cached = makeGroup(1000, '', [member]);
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => []),
identity: fakeIdentity({
findGroupMember: (gid: number, uin: number) =>
gid === 1000 && uin === 44 ? member : null,
}),
});
const out = await getGroupMemberInfo(bridge, 1000, 44);
expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' });
expect(bridge.fetchGroupMemberList).not.toHaveBeenCalled();
});
it('triggers fetch when member is unknown and re-queries the cache', async () => {
const member = makeMember(55, 'eve');
let known = false;
const findGroupMember = vi.fn((gid: number, uin: number) =>
(known && gid === 1100 && uin === 55) ? member : null,
);
const fetchGroupMemberList = vi.fn(async () => { known = true; return [member]; });
const bridge = fakeBridge({
fetchGroupMemberList,
identity: fakeIdentity({ findGroupMember }),
});
const out = await getGroupMemberInfo(bridge, 1100, 55);
expect(fetchGroupMemberList).toHaveBeenCalledOnce();
expect(out).toMatchObject({ user_id: 55, nickname: 'eve' });
});
});
describe('onebot/contact-actions / getStrangerInfo', () => {
it('returns a fetched profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => makeProfile(55555, 'Eve', 'female', 25)),
});
const out = await getStrangerInfo(bridge, 55555);
expect(out).toMatchObject({ user_id: 55555, nickname: 'Eve', sex: 'female', age: 25 });
});
it('falls back to identity.findUserProfile when fetch fails but the profile is cached', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({
findUserProfile: (uin: number) =>
uin === 66666 ? makeProfile(66666, 'Frank', 'male', 30) : null,
}),
});
const out = await getStrangerInfo(bridge, 66666);
expect(out).toMatchObject({ user_id: 66666, nickname: 'Frank' });
});
it('returns null when neither fetch nor cache produces a profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({ findUserProfile: () => null }),
});
expect(await getStrangerInfo(bridge, 99999)).toBeNull();
});
});
+19 -22
View File
@@ -3,10 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock the OIDB shim so we can control what `forceFetchClientKey` and // Mock the OIDB shim so we can control what `forceFetchClientKey` and
// `getPSkey` see without standing up a Bridge. // `getPSkey` see without standing up a Bridge.
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndDecode: vi.fn(async () => ({})), runOidb: vi.fn(async () => ({})),
sendOidbAndCheck: vi.fn(async () => undefined),
resolveUserUid: vi.fn(async () => 'uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
// Mock the actual HTTP cookie fetch. // Mock the actual HTTP cookie fetch.
@@ -29,13 +26,13 @@ import {
getCredentials, getCredentials,
} from '../../src/bridge/web-actions/cookies'; } from '../../src/bridge/web-actions/cookies';
const bridge = { qqInfo: { uin: '10001' } } as any; const bridge = { identity: { uin: '10001' } } as any;
describe('cookies — forceFetchClientKey', () => { describe('cookies — forceFetchClientKey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); }); beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => { it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600, clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600,
}); });
const out = await forceFetchClientKey(bridge); const out = await forceFetchClientKey(bridge);
@@ -43,17 +40,17 @@ describe('cookies — forceFetchClientKey', () => {
}); });
it('falls back to default keyIndex/expireTime when the response omits them', async () => { it('falls back to default keyIndex/expireTime when the response omits them', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck' }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck' });
const out = await forceFetchClientKey(bridge); const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' }); expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' });
}); });
}); });
describe('cookies — getPSkey', () => { describe('cookies — getPSkey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); }); beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
it('folds pskeyItems into a domain → pskey Map', async () => { it('folds pskeyItems into a domain → pskey Map', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
pskeyItems: [ pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' }, { domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' }, { domain: 'qzone.qq.com', pskey: 'psk-b' },
@@ -69,12 +66,12 @@ describe('cookies — getPSkey', () => {
describe('cookies — getCookies', () => { describe('cookies — getCookies', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
}); });
it('builds the ptlogin2 jump URL with the right query params', async () => { it('builds the ptlogin2 jump URL with the right query params', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({
p_skey: 'psk', p_skey: 'psk',
skey: 'sk', skey: 'sk',
@@ -91,7 +88,7 @@ describe('cookies — getCookies', () => {
}); });
it('falls back to getPSkey when p_skey is missing in the cookie response', async () => { it('falls back to getPSkey when p_skey is missing in the cookie response', async () => {
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey
.mockResolvedValueOnce({ // getPSkey .mockResolvedValueOnce({ // getPSkey
pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }], pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }],
@@ -103,7 +100,7 @@ describe('cookies — getCookies', () => {
}); });
it('returns whatever cookies it got if getPSkey fallback throws', async () => { it('returns whatever cookies it got if getPSkey fallback throws', async () => {
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('pskey unavailable')); .mockRejectedValueOnce(new Error('pskey unavailable'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' });
@@ -115,23 +112,23 @@ describe('cookies — getCookies', () => {
describe('cookies — getSKey', () => { describe('cookies — getSKey', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
}); });
it('returns skey from the qzone-targeted ptlogin2 jump', async () => { it('returns skey from the qzone-targeted ptlogin2 jump', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' });
expect(await getSKey(bridge)).toBe('the-skey'); expect(await getSKey(bridge)).toBe('the-skey');
}); });
it('throws when clientKey comes back empty', async () => { it('throws when clientKey comes back empty', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: '' }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: '' });
await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/); await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/);
}); });
it('throws when the jump response omits skey', async () => { it('throws when the jump response omits skey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/); await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/);
}); });
@@ -150,21 +147,21 @@ describe('cookies — pure helpers', () => {
}); });
it('getCookiesStr: joins cookies with "; "', async () => { it('getCookiesStr: joins cookies with "; "', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCookiesStr(bridge, 'qun.qq.com'); const out = await getCookiesStr(bridge, 'qun.qq.com');
expect(out).toBe('p_skey=p; skey=s'); expect(out).toBe('p_skey=p; skey=s');
}); });
it('getCsrfToken: combines getSKey + getBknFromSKey', async () => { it('getCsrfToken: combines getSKey + getBknFromSKey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' });
const csrf = await getCsrfToken(bridge); const csrf = await getCsrfToken(bridge);
expect(csrf).toBe(getBknFromSKey('abc')); expect(csrf).toBe(getBknFromSKey('abc'));
}); });
it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => { it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCredentials(bridge, 'qun.qq.com'); const out = await getCredentials(bridge, 'qun.qq.com');
@@ -174,7 +171,7 @@ describe('cookies — pure helpers', () => {
}); });
it('getCredentials: token is 0 when no skey/p_skey available', async () => { it('getCredentials: token is 0 when no skey/p_skey available', async () => {
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('no pskey')); .mockRejectedValueOnce(new Error('no pskey'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@snowluma/runtime", "name": "@snowluma/runtime",
"version": "1.7.9", "version": "1.8.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "index.mjs", "main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven", "name": "MotricSeven",
"email": "[email protected]" "email": "[email protected]"
}, },
"version": "1.7.9", "version": "1.8.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [ "keywords": [
"snowluma", "snowluma",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@snowluma/websocket", "name": "@snowluma/websocket",
"version": "1.7.9", "version": "1.8.0",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "webui", "name": "webui",
"private": true, "private": true,
"version": "1.7.9", "version": "1.8.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env node
// One-shot release driver.
//
// pnpm release <version> # full pipeline: dev → Promote → main → tag
// pnpm release <version> --no-wait # bump+push dev only, do main+tag manually
// pnpm release <version> --dry-run # print plan, change nothing
//
// What it does, in order:
// 1. Sanity-check: on `dev`, clean tree, in sync with origin/dev.
// 2. `pnpm bump <version>` (writes every package.json).
// 3. Commit `chore(release): vX.Y.Z` — that prefix triggers the
// Promote workflow, which opens (or updates) the dev→main PR and
// auto-merges if the GitHub setting allows.
// 4. Push to origin/dev.
// 5. (Unless `--no-wait`) poll the Promote PR via `gh` until it
// merges, then `git fetch && git checkout main && git pull`,
// create `vX.Y.Z` tag, push it — that triggers `release.yml`.
// 6. Switch back to `dev` so the next `git log` view is back where
// you were.
import { execSync, spawnSync } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..');
// ───────────── arg parsing ─────────────
const args = process.argv.slice(2);
const flags = new Set(args.filter(a => a.startsWith('--')));
const positional = args.filter(a => !a.startsWith('--'));
const version = positional[0];
const dryRun = flags.has('--dry-run');
const noWait = flags.has('--no-wait');
if (!version) {
console.error('Usage: pnpm release <version> [--no-wait] [--dry-run]');
console.error('Example: pnpm release 1.8.0');
process.exit(1);
}
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
console.error(`Invalid semver: "${version}"`);
process.exit(1);
}
const tag = `v${version}`;
const releaseCommit = `chore(release): ${tag}`;
// ───────────── shell helpers ─────────────
function sh(cmd, { capture = false, allowFail = false } = {}) {
if (dryRun) {
console.log(`[dry-run] $ ${cmd}`);
return '';
}
if (capture) {
return execSync(cmd, { cwd: repoRoot, encoding: 'utf-8' }).trim();
}
const result = spawnSync(cmd, { cwd: repoRoot, shell: true, stdio: 'inherit' });
if (result.status !== 0 && !allowFail) {
throw new Error(`Command failed: ${cmd}`);
}
return '';
}
function shCapture(cmd) {
return execSync(cmd, { cwd: repoRoot, encoding: 'utf-8' }).trim();
}
function which(bin) {
try {
execSync(`command -v ${bin}`, { stdio: 'ignore' });
return true;
} catch { return false; }
}
function ok(msg) { console.log(`\x1b[32m✓\x1b[0m ${msg}`); }
function info(msg) { console.log(`\x1b[36mi\x1b[0m ${msg}`); }
function warn(msg) { console.log(`\x1b[33m!\x1b[0m ${msg}`); }
// ───────────── step 1: preflight ─────────────
function preflightFail(msg) {
if (dryRun) { warn(`[dry-run] would have aborted: ${msg}`); return; }
console.error(msg);
process.exit(1);
}
function preflight() {
const branch = shCapture('git rev-parse --abbrev-ref HEAD');
if (branch !== 'dev') {
preflightFail(`Must be on \`dev\` to start a release. Current: \`${branch}\``);
}
const dirty = shCapture('git status --porcelain');
if (dirty) {
preflightFail(`Working tree is not clean. Commit or stash first.\n${dirty}`);
}
// Make sure we're up to date with origin/dev so the bump commit doesn't
// collide with someone else's push.
shCapture('git fetch origin dev --quiet');
const local = shCapture('git rev-parse dev');
const remote = shCapture('git rev-parse origin/dev');
if (local !== remote) {
const ahead = shCapture('git rev-list --count origin/dev..dev');
const behind = shCapture('git rev-list --count dev..origin/dev');
preflightFail(`dev is not in sync with origin/dev (ahead=${ahead}, behind=${behind}). Pull / push first.`);
}
if (!dryRun) ok(`on dev, clean, in sync with origin/dev`);
}
// ───────────── step 2-4: bump + commit + push dev ─────────────
function bumpAndPushDev() {
sh(`node tools/bump-version.mjs ${version}`);
ok(`bumped all package.json files to ${version}`);
if (dryRun) {
info(`would commit "${releaseCommit}" and push origin dev`);
return;
}
const changed = shCapture('git status --porcelain');
if (!changed) {
// Already at this version. Probably re-running. Still try to push tag.
warn(`no version changes — package.json already at ${version}, skipping commit`);
return;
}
sh('git add package.json packages/*/package.json');
sh(`git commit -m "${releaseCommit}"`);
ok(`committed ${releaseCommit}`);
sh('git push origin dev');
ok(`pushed to origin/dev — Promote workflow should kick off shortly`);
}
// ───────────── step 5: wait for Promote PR + tag main ─────────────
async function waitAndTag() {
if (!which('gh')) {
warn('`gh` CLI not found — skipping auto-tag.');
info('Once the Promote PR merges, run:');
info(` git fetch && git checkout main && git pull && git tag ${tag} && git push origin ${tag}`);
return;
}
info('waiting for the Promote PR (head: dev → base: main) to merge...');
info('press Ctrl-C if you want to handle main / tag manually.');
const startedAt = Date.now();
const TIMEOUT_MS = 30 * 60 * 1000; // 30 min hard cap
const POLL_MS = 15 * 1000;
let prNumber = null;
while (Date.now() - startedAt < TIMEOUT_MS) {
if (!prNumber) {
try {
const list = shCapture(`gh pr list --base main --head dev --state all --json number,mergedAt,state --limit 5`);
const prs = JSON.parse(list);
// Pick the newest one that's open or merged after we pushed.
const fresh = prs.find(p => p.state === 'OPEN' || (p.mergedAt && Date.parse(p.mergedAt) > startedAt - 2 * POLL_MS));
if (fresh) {
prNumber = fresh.number;
info(`tracking PR #${prNumber}`);
}
} catch (e) {
warn(`gh pr list failed: ${e.message}`);
}
}
if (prNumber) {
try {
const view = shCapture(`gh pr view ${prNumber} --json state,mergedAt`);
const pr = JSON.parse(view);
if (pr.state === 'MERGED') {
ok(`PR #${prNumber} merged at ${pr.mergedAt}`);
break;
}
if (pr.state === 'CLOSED') {
console.error(`PR #${prNumber} was closed without merging — aborting tag step.`);
process.exit(1);
}
} catch (e) {
warn(`gh pr view failed: ${e.message}`);
}
}
await new Promise(r => setTimeout(r, POLL_MS));
}
if (Date.now() - startedAt >= TIMEOUT_MS) {
warn('30-minute timeout reached without seeing the PR merge.');
info(`Once it does, finish manually: git checkout main && git pull && git tag ${tag} && git push origin ${tag}`);
return;
}
sh('git fetch origin main --quiet');
sh('git checkout main');
sh('git pull origin main');
// Sanity: package.json on main matches version
const mainPkg = JSON.parse(await readFile(path.join(repoRoot, 'package.json'), 'utf-8'));
if (mainPkg.version !== version) {
warn(`main package.json is ${mainPkg.version} but you asked for ${version}.`);
warn('Tagging anyway, but the release artifact name may not match.');
}
sh(`git tag ${tag}`);
sh(`git push origin ${tag}`);
ok(`tagged and pushed ${tag} — release workflow will pick it up`);
// Hop back to dev so the user lands where they started.
sh('git checkout dev');
ok('back on dev');
}
// ───────────── go ─────────────
(async () => {
console.log(`Release pipeline → ${tag}${dryRun ? ' (dry-run)' : ''}\n`);
preflight();
bumpAndPushDev();
if (noWait) {
info('--no-wait set; not polling for PR merge.');
info(`Once it merges: git checkout main && git pull && git tag ${tag} && git push origin ${tag}`);
return;
}
await waitAndTag();
})().catch(err => {
console.error(err.stack || err.message);
process.exit(1);
});