Merge pull request #28 from SnowLuma/dev

chore: promote dev → main (1b2dd83)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-05-12 22:06:52 +08:00
commit 9216b54427
90 files changed
+9448 -4773

No files matched your search

+197
View File
@@ -0,0 +1,197 @@
// Forward-message upload / download via the long-message service.
// Uses gzipped protobufs over `trpc.group.long_msg_interface`.
// An in-memory cache keeps res_ids stable across rapid re-fetches
// from the same OneBot client (avoids re-decoding the same payload).
import type { Bridge } from '../bridge';
import { gunzipSync, gzipSync } from 'zlib';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { buildSendElems } from '../element-builder';
import { parseMsgPush } from '../msg-push-handler';
import type { ForwardNodePayload } from '../events';
import type { PacketInfo } from '../../protocol/types';
import {
LongMsgResultSchema,
RecvLongMsgReqSchema,
RecvLongMsgRespSchema,
SendLongMsgReqSchema,
SendLongMsgRespSchema,
} from '../proto/longmsg';
import { PushMsgSchema } from '../proto/message';
import { resolveSelfUid, toInt } from './shared';
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
): Promise<Record<string, unknown>> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.qqInfo.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin);
const elems = await buildSendElems(node.elements);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
const seq = Math.floor(Math.random() * 9000000) + 1000000;
return {
responseHead: {
fromUin,
toUid: bridge.qqInfo.selfUid ?? '',
forward: {
friendName: nickname,
},
},
contentHead: {
msgType: 9,
subType: 4,
msgId: random,
sequence: seq,
timestamp: now,
divSeq: 0,
},
body: {
richText: {
elems,
},
},
};
}
export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise<string> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node)));
const longMsgResult = protoEncode({
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: msgBody as any },
},
],
}, LongMsgResultSchema);
const selfUid = await resolveSelfUid(bridge);
const info: any = {
type: groupId ? 3 : 1,
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
const request = protoEncode({
info,
settings: {
field1: 4,
field2: 1,
field3: 7,
field4: 0,
},
}, SendLongMsgReqSchema);
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'upload forward message failed');
}
const resp = protoDecode(result.responseData, SendLongMsgRespSchema);
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
if (!resId) {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
})));
return resId;
}
export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<ForwardNodePayload[]> {
const cached = forwardResCache.get(resId);
if (cached) {
return cached.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements] }));
}
const selfUid = await resolveSelfUid(bridge);
const request = protoEncode({
info: {
uid: { uid: selfUid },
resId,
acquire: true,
},
settings: {
field1: 2,
field2: 0,
field3: 0,
field4: 0,
},
}, RecvLongMsgReqSchema);
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'download forward message failed');
}
const resp = protoDecode(result.responseData, RecvLongMsgRespSchema);
const payload = resp?.result?.payload;
if (!(payload instanceof Uint8Array) || payload.length === 0) {
throw new Error('download forward message payload is empty');
}
const inflate = gunzipSync(Buffer.from(payload));
const longMsg = protoDecode(inflate, LongMsgResultSchema);
const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
const nodes: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const pkt: PacketInfo = {
pid: 0,
uin: bridge.qqInfo.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: wrapped,
};
const events = parseMsgPush(pkt, bridge.qqInfo);
const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue;
if (event.kind === 'group_message') {
nodes.push({
userUin: event.senderUin,
nickname: event.senderCard || event.senderNick,
elements: event.elements,
});
} else if (event.kind === 'friend_message') {
nodes.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
});
} else {
nodes.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
});
}
}
if (nodes.length > 0) {
forwardResCache.set(resId, nodes.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements] })));
}
return nodes;
}
@@ -0,0 +1,53 @@
// Friend-list operations: accept/reject add request, delete, set the
// local remark label. Each one resolves a UID first because the OIDB
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
OidbSetFriendRemarkSchema,
} from '../proto/oidb-action';
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await resolveUserUid(bridge, parseInt(uidOrFlag, 10));
}
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb5d_44', 0xB5D, 44,
{ accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema);
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await resolveUserUid(bridge, userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0,
{
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
},
OidbDeleteFriendSchema);
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
// shouldn't make the delete itself look failed.
try { await bridge.fetchFriendList(); } catch { /* ignore */ }
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2,
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema);
}
@@ -0,0 +1,153 @@
// Group admin actions: mute/kick/leave/role/profile + join-request approval.
// Every function ultimately routes through one OIDB schema; the function
// names match the OneBot action names (set_group_kick, set_group_ban, ...)
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
Oidb0x8a0ReqSchema,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
OidbGroupRequestActionSchema,
OidbKickMemberSchema,
OidbLeaveGroupSchema,
OidbMuteAllSchema,
OidbMuteMemberSchema,
OidbRenameGroupSchema,
OidbRenameMemberSchema,
OidbSetAdminSchema,
OidbSpecialTitleSchema,
Oidb0xf16ReqSchema,
} from '../proto/oidb-action';
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1,
{ groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema);
}
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema);
}
// ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema);
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema);
}
export async function setGroupAddRequest(
bridge: Bridge, groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
): Promise<void> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await sendOidbAndCheck(bridge, cmd, 0x10C8, subCmd,
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
OidbGroupRequestActionSchema, true);
}
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema);
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => resolveUserUid(bridge, userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema);
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1,
{ groupUin: groupId }, OidbLeaveGroupSchema);
}
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1,
{ groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema);
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3,
{ groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema);
}
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_15', 0x89A, 15,
{ groupUin: groupId, body: { targetName: name } }, OidbRenameGroupSchema);
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2,
{ groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema);
}
// ─────────────── personal-side metadata ───────────────
// setGroupRemark is the bot's local-only label for the group; it lives
// here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1,
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema);
}
// ─────────────── group-level quota query ───────────────
export async function getGroupAtAllRemain(
bridge: Bridge,
groupId: number,
) {
const req = {
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.qqInfo.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x8a7_0',
0x8A7,
0,
req,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
);
if (!result) {
throw new Error('get group at all remain result empty');
}
// Cast numbers to plain Number: the OIDB layer may surface uint32 as
// BigInt and the WebUI JSON serializer chokes on those.
return {
can_at_all: !!result.canAtAll,
remain_at_all_count_for_group: Number(result.groupRemain || 0),
remain_at_all_count_for_uin: Number(result.uinRemain || 0),
};
}
@@ -0,0 +1,821 @@
// Group + private file operations: upload (with highway fast-path),
// folder management, file listing, file/media URL fetch. All upload
// paths share the same shape (resolve target → OIDB metadata exchange
// → highway HTTP PUT if the server says we must), but the OIDB schemas
// and field layouts differ enough between group and private that they
// stay as separate functions.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import {
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema,
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from '../proto/oidb-action';
import { FileUploadExtSchema } from '../proto/highway';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
fileId: string;
fileName: string;
busId: number;
fileSize: number;
uploadTime: number;
deadTime: number;
modifyTime: number;
downloadTimes: number;
uploader: number;
uploaderName: string;
}
export interface GroupFolderInfo {
folderId: string;
folderName: string;
createTime: number;
creator: number;
creatorName: string;
totalFileCount: number;
}
export interface GroupFilesResult {
files: GroupFileInfo[];
folders: GroupFolderInfo[];
}
export interface UploadFileResult {
fileId: string | null;
fileHash?: string | null;
}
// Re-export so this file is a one-stop-shop for the file API surface
// (bridge.ts imports MediaIndexNode through here for type symmetry).
export type { MediaIndexNode } from './shared';
// ─────────────── file-specific helpers ───────────────
function normalizeDirectory(dir?: string): string {
if (!dir || !dir.trim()) return '/';
return dir;
}
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return Buffer.from(data).toString('hex').toUpperCase();
}
function normalizeUploadFileName(name: string, fallback: string): string {
const trimmed = name.trim();
if (trimmed) return trimmed;
const safeFallback = fallback.trim();
return safeFallback || 'file.bin';
}
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
return computeMd5(bytes.subarray(0, limit));
}
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
checkKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown200: 0,
}, FileUploadExtSchema);
}
function buildPrivateFileUploadExt(
senderUin: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
sha1: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: 0n,
groupCode: 0n,
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey: sha1,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown3: 0,
unknown200: 1,
}, FileUploadExtSchema);
}
function normalizeMediaNode(node: MediaIndexNode): Record<string, unknown> {
const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
if (!fileUuid) throw new Error('media node fileUuid is required');
const info = node.info ?? {};
const type = info.type ?? {};
return {
info: {
fileSize: toInt(info.fileSize),
fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
fileName: typeof info.fileName === 'string' ? info.fileName : '',
type: {
type: toInt(type.type),
picFormat: toInt(type.picFormat),
videoFormat: toInt(type.videoFormat),
voiceFormat: toInt(type.voiceFormat),
},
width: toInt(info.width),
height: toInt(info.height),
time: toInt(info.time),
original: toInt(info.original),
},
fileUuid,
storeId: toInt(node.storeId),
uploadTime: toInt(node.uploadTime),
ttl: toInt(node.ttl),
subType: toInt(node.subType),
};
}
async function fetchNtv2DownloadUrl(
bridge: Bridge,
serviceCmd: string,
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const resp = await sendOidbAndDecode<any>(
bridge,
serviceCmd,
oidbCmd,
200,
payload,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
true,
);
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : '';
const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : '';
if (!domain || !path) {
throw new Error('ntv2 download response invalid');
}
return `https://${domain}${path}${rKeyParam}`;
}
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await sendOidbAndDecode<any>(bridge,
'OidbSvcTrpcTcp.0x6d8_3', 0x6D8, 3,
{ count: { groupUin: groupId, appId: 7, busId: 0 } },
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema);
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
};
}
// ─────────────── upload ───────────────
export async function uploadGroupFile(
bridge: Bridge,
groupId: number,
source: string,
name = '',
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
const loaded = await loadBinarySource(source, 'file');
if (!loaded.bytes.length) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_0',
0x6D6,
0,
{
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(bridge.qqInfo.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
fileName,
loaded.bytes.length,
hashes.md5,
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
}
return { fileId };
}
export async function uploadPrivateFile(
bridge: Bridge,
userId: number,
source: string,
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
const loaded = await loadBinarySource(source, 'file');
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await resolveUserUid(bridge, userId);
let selfUid = bridge.qqInfo.selfUid;
if (!selfUid) {
const selfUin = toInt(bridge.qqInfo.uin);
if (selfUin > 0) {
selfUid = await resolveUserUid(bridge, selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(bridge.qqInfo.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1700',
0xE37,
1700,
{
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
);
const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing');
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
if (!fileId) throw new Error('private file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) {
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('private file upload host is invalid');
}
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
loaded.bytes.length,
hashes.md5,
hashes.sha1,
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
}
return { fileId, fileHash };
}
// ─────────────── list ───────────────
export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise<GroupFilesResult> {
const targetDirectory = normalizeDirectory(folderId);
const files: GroupFileInfo[] = [];
const folders: GroupFolderInfo[] = [];
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d8_1',
0x6D8,
1,
{
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
},
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
true,
);
const list = resp?.list;
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
for (const item of list.items ?? []) {
const type = toInt(item?.type);
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
const uploader = toInt(file.uploaderUin);
const cached = bridge.qqInfo.findGroupMember(groupId, uploader);
files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '',
busId: toInt(file.busId),
fileSize: toInt(file.fileSize),
uploadTime: toInt(file.uploadedTime),
deadTime: toInt(file.expireTime),
modifyTime: toInt(file.modifiedTime),
downloadTimes: toInt(file.downloadedTimes),
uploader,
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|| cached?.card
|| cached?.nickname
|| '',
});
} else if (type === 2 && item?.folderInfo) {
const folder = item.folderInfo;
const creator = toInt(folder.creatorUin);
const cached = bridge.qqInfo.findGroupMember(groupId, creator);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
createTime: toInt(folder.createTime),
creator,
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|| cached?.card
|| cached?.nickname
|| '',
totalFileCount: toInt(folder.totalFileCount),
});
}
}
if (list.isEnd) break;
startIndex += pageSize;
}
return { files, folders };
}
// ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_2',
0x6D6,
2,
{
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|| '';
const hexUrl = bytesToHexUpper(download.downloadUrl);
if (!dns || !hexUrl) {
throw new Error('group file url response invalid');
}
// Keep the same behavior as Lagrange: append file_id after ?fname=
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
}
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await resolveUserUid(bridge, userId);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1200',
0xE37,
1200,
{
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
);
const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : '';
const port = toInt(result?.port);
const url = typeof result?.url === 'string' ? result.url : '';
if (!server || !port || !url) {
throw new Error('private file url response invalid');
}
return `http://${server}:${port}${url}&isthumb=0`;
}
// ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_3',
0x6D6,
3,
{
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
const result = resp?.delete;
if (!result) throw new Error('group file delete response missing');
ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording);
}
export async function moveGroupFile(
bridge: Bridge,
groupId: number,
fileId: string,
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_5',
0x6D6,
5,
{
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
const result = resp?.move;
if (!result) throw new Error('group file move response missing');
ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording);
}
// ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_0',
0x6D7,
0,
{
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
const result = resp?.create;
if (!result) throw new Error('group folder create response missing');
ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
}
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_1',
0x6D7,
1,
{
delete: {
groupUin: groupId,
folderId,
},
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing');
ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording);
}
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_2',
0x6D7,
2,
{
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing');
ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording);
}
// ─────────────── rich-media URL by node ───────────────
export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, {
reqHead: {
common: { requestId: 4, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
@@ -0,0 +1,101 @@
// Operations targeting an existing message: recall (group / private),
// mark-as-read (group / private), and the "essence" highlight toggle.
// All of these take a message identifier and modify server-side state
// without producing a downstream observable event.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
OidbEssenceSchema,
SsoReadedReportReqSchema,
} from '../proto/oidb-action';
export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise<void> {
const request = protoEncode({
type: 1,
groupUin: groupId,
info: { sequence, random: 0, field3: 0 },
settings: { field1: 0 },
}, GroupRecallRequestSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
}
export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number,
): Promise<void> {
const targetUid = await resolveUserUid(bridge, userUin);
const request = protoEncode({
type: 1,
targetUid,
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
},
settings: { field1: false, field2: false },
field6: false,
}, C2CRecallRequestSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
export async function markPrivateMessageRead(
bridge: Bridge,
userId: number,
msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
const request = protoEncode({
c2cList: [
{
uid,
lastReadTime: BigInt(timestamp),
lastReadSeq: BigInt(msgSeq),
},
],
}, SsoReadedReportReqSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
}
}
export async function markGroupMessageRead(
bridge: Bridge,
groupId: number,
msgSeq: number,
): Promise<void> {
const request = protoEncode({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(msgSeq),
},
],
}, SsoReadedReportReqSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
}
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await sendOidbAndCheck(bridge, cmd, 0xEAC, subCmd,
{ groupUin: groupId, sequence, random }, OidbEssenceSchema);
}
@@ -0,0 +1,61 @@
// Lightweight social-interaction actions: poke, like, emoji reaction,
// and the related read-side "who reacted with X" query. None of these
// edit message content — they're purely social signals.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb';
import {
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
OidbGroupReactionSchema,
OidbLikeSchema,
OidbPokeSchema,
} from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xed3_1', 0xED3, 1,
{
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
}, OidbPokeSchema);
}
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104,
{ targetUin: userId, count }, OidbLikeSchema);
}
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd,
{ groupUin: groupId, sequence, code }, OidbGroupReactionSchema);
}
export async function getEmojiLikes(
bridge: Bridge,
groupId: number,
sequence: number,
emojiId: string,
emojiType: number = 1,
count: number = 10,
cookie: string = '',
): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> {
const req = {
groupId: BigInt(groupId),
sequence,
emojiType,
emojiId,
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
field7: 0,
count,
field12: 1,
};
const resp = await sendOidbAndDecode<any>(bridge, 'OidbSvcTrpcTcp.0x9083_1', 0x9083, 1, req, Oidb0x9083ReqSchema, Oidb0x9083RespSchema);
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
return { users, cookie: respCookie, isLast: !respCookie };
}
+173
View File
@@ -0,0 +1,173 @@
// Grab-bag: action verbs that don't share a theme with anything else.
// Kept together so the directory stays small; if any of these grow new
// related siblings, lift the whole group out into its own file.
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode } from '../bridge-oidb';
import {
MiniAppShareReqSchema,
MiniAppShareRespSchema,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
} from '../proto/oidb-action';
export async function translateEn2Zh(
bridge: Bridge,
words: string[],
) {
const req = {
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words: words,
},
tag10: 1,
tag12: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x990_2',
0x990,
2,
req,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
);
const resp = result?.translateResp;
if (!resp) {
throw new Error('translate response empty');
}
return resp.dstWords || [];
}
export async function getMiniAppArk(
bridge: Bridge,
type: string,
title: string,
desc: string,
picUrl: string,
jumpUrl: string,
) {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
if (type === 'weibo') {
appid = '1109224783';
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
}
const request = protoEncode({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: {
appid,
title,
desc,
picUrl,
jumpUrl,
iconUrl,
},
}, MiniAppShareReqSchema);
const result = await bridge.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
}
const decoded = protoDecode(result.responseData, MiniAppShareRespSchema);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr);
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
export async function clickInlineKeyboardButton(
bridge: Bridge,
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
) {
const req = {
botAppid: BigInt(botAppid),
msgSeq: BigInt(msgSeq),
buttonId: String(buttonId),
callbackData: String(callbackData || ''),
unknown7: 0,
groupId: BigInt(groupId),
unknown9: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112e_1',
0x112E,
1,
req,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
);
if (!result) {
throw new Error('click inline keyboard button result empty');
}
return {
result: Number(result.result || 0),
errMsg: result.errMsg || '',
status: 0,
promptText: result.promptText || '',
promptType: 0,
promptIcon: 0,
};
}
export async function sendGroupSign(
bridge: Bridge,
groupId: number,
) {
const req = {
signInInfo: {
uin: String(bridge.qqInfo.uin),
groupId: String(groupId),
version: '9.0.90',
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xEB7_1',
0xEB7,
1,
req,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
);
}
+269
View File
@@ -0,0 +1,269 @@
// Operations that touch the bot's own profile / status, plus the
// related queries about my profile likes and unidirectional friends.
// All of these read/write fields on the self-uin via OIDB.
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
FaceroamOpReqSchema,
FaceroamOpRespSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
OidbSetProfileSchema,
SetStatusReqSchema,
SetStatusRespSchema,
} from '../proto/oidb-action';
import { resolveSelfUid } from './shared';
// ─────────────── status / profile setters ───────────────
export async function setOnlineStatus(
bridge: Bridge,
status: number,
extStatus: number = 0,
batteryStatus: number = 100,
): Promise<void> {
const request = protoEncode({
status,
extStatus,
batteryStatus,
}, SetStatusReqSchema);
const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request);
if (!result.success) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (result.responseData && result.responseData.length > 0) {
const resp = protoDecode(result.responseData, SetStatusRespSchema);
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
}
}
}
export async function setProfile(
bridge: Bridge,
nickname?: string,
personalNote?: string,
): Promise<void> {
const uin = BigInt(bridge.qqInfo.uin);
const stringProfiles: any[] = [];
const intProfiles: any[] = [];
if (nickname !== undefined) {
stringProfiles.push({ fieldId: 20002, value: nickname });
}
if (personalNote !== undefined) {
stringProfiles.push({ fieldId: 102, value: personalNote });
}
if (stringProfiles.length === 0 && intProfiles.length === 0) {
return;
}
const req = {
uin,
stringProfiles,
};
await sendOidbAndCheck(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
OidbSetProfileSchema,
);
}
export async function setSelfLongNick(
bridge: Bridge,
longNick: string,
) {
const req = {
uin: BigInt(bridge.qqInfo.uin),
profile: {
tag: 102,
value: String(longNick),
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
);
}
export async function setInputStatus(
bridge: Bridge,
userId: number,
eventType: number,
) {
const targetUid = await resolveUserUid(bridge, userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
reqBody: {
uid: targetUid,
chatType: 0,
eventType: eventType,
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xcd4_1',
0xCD4,
1,
req,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
);
}
export async function setAvatar(
bridge: Bridge,
source: string,
): Promise<void> {
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
}
// ─────────────── queries on me / my contacts ───────────────
export async function getProfileLike(
bridge: Bridge,
userId?: number,
start: number = 0,
limit: number = 10,
) {
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
targetUid: targetUid,
basic: 1,
vote: 1,
favorite: 1,
start: start,
limit: limit,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x7ed_12',
0x7ED,
12,
req,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
);
const data = result?.userLikeInfos?.[0];
if (!data) {
throw new Error('get profile like info empty');
}
return {
uid: data.uid,
time: Number(data.time),
favoriteInfo: {
total_count: data.favoriteInfo?.totalCount || 0,
last_time: Number(data.favoriteInfo?.lastTime || 0),
today_count: data.favoriteInfo?.newCount || 0,
userInfos: [],
},
voteInfo: {
total_count: data.voteInfo?.totalCount || 0,
new_count: data.voteInfo?.newCount || 0,
new_nearby_count: 0,
last_visit_time: Number(data.voteInfo?.lastTime || 0),
userInfos: [],
},
};
}
export async function getUnidirectionalFriendList(
bridge: Bridge,
) {
const reqObj = {
uint64_uin: String(bridge.qqInfo.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
};
const req = {
jsonBody: JSON.stringify(reqObj),
};
const result = await sendOidbAndDecode<any>(
bridge,
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
0xE17,
0,
req,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
);
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
}
const parsed = JSON.parse(result.jsonBody);
return parsed.rpt_block_list || [];
}
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.qqInfo.uin),
field3: 1,
field6: 1,
};
const request = protoEncode(req, FaceroamOpReqSchema);
const result = await bridge.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protoDecode(result.responseData, FaceroamOpRespSchema);
if (!resp || (resp as any).retCode !== 0) {
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
}
const faceIds = (resp as any).item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.qqInfo.uin}/${id}/0`);
}
@@ -0,0 +1,82 @@
// Shared private helpers for the action modules. None of this is part
// of the public Bridge API; keeping it here avoids re-importing the
// same five-line utility from every themed file.
import type { Bridge } from '../bridge';
import { resolveUserUid } from '../bridge-oidb';
/**
* Coerce numbers, strings, and bigints to a plain integer.
* Returns 0 for anything we can't interpret — every action that
* threads this through OIDB has an explicit `<=0` validation later.
*/
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
}
/**
* Standard OIDB response check: throw a typed Error if retCode != 0.
* Prefers `wording` over `msg` for the human-facing message, falling
* back to a generic string. All themed action modules use this for
* their OIDB error-path uniformity.
*/
export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void {
const retCode = toInt(code);
if (retCode === 0) return;
const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error';
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
}
/**
* Look up the bot's own UID. Cached on QQInfo when warmed up, but
* forward/profile actions need a fast path before warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.qqInfo.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.qqInfo.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await resolveUserUid(bridge, selfUin);
return selfUid;
}
/**
* Index describing a server-side rich-media object (image / video /
* voice). Returned by message parsers, consumed by the media-URL
* fetchers in group-file.ts.
*/
export interface MediaIndexNode {
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}
File diff suppressed because it is too large. Load diff
+36 -22
View File
@@ -6,10 +6,10 @@ import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push-handler';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './builders/element-builder';
import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service';
import { createLogger } from '../utils/logger';
import {
@@ -33,6 +33,7 @@ import {
muteGroupAll as muteGroupAll_,
setGroupAddOption as setGroupAddOption_,
setGroupSearch as setGroupSearch_,
setGroupAddRequest as setGroupAddRequest_,
kickGroupMember as kickGroupMember_,
kickGroupMembers as kickGroupMembers_,
leaveGroup as leaveGroup_,
@@ -40,8 +41,10 @@ import {
setGroupCard as setGroupCard_,
setGroupName as setGroupName_,
setGroupSpecialTitle as setGroupSpecialTitle_,
setFriendAddRequest as setFriendAddRequest_,
deleteFriend as deleteFriend_,
setGroupRemark as setGroupRemark_,
getGroupAtAllRemain as getGroupAtAllRemain_,
} from './actions/group-admin';
import {
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
fetchGroupFiles as fetchGroupFiles_,
@@ -51,40 +54,51 @@ import {
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
uploadForwardNodes as uploadForwardNodes_,
fetchForwardNodes as fetchForwardNodes_,
deleteGroupFile as deleteGroupFile_,
moveGroupFile as moveGroupFile_,
createGroupFileFolder as createGroupFileFolder_,
deleteGroupFileFolder as deleteGroupFileFolder_,
renameGroupFileFolder as renameGroupFileFolder_,
setGroupAddRequest as setGroupAddRequest_,
sendPoke as sendPoke_,
sendLike as sendLike_,
setGroupEssence as setGroupEssence_,
setGroupReaction as setGroupReaction_,
fetchGroupFileCount as fetchGroupFileCount_,
} from './actions/group-file';
import {
recallGroupMessage as recallGroupMessage_,
recallPrivateMessage as recallPrivateMessage_,
markPrivateMessageRead as markGroupMsgAsRead_,
markGroupMessageRead as markPrivateMsgAsRead_,
setGroupEssence as setGroupEssence_,
} from './actions/group-message';
import {
sendPoke as sendPoke_,
sendLike as sendLike_,
setGroupReaction as setGroupReaction_,
getEmojiLikes as getEmojiLikes_,
} from './actions/interaction';
import {
uploadForwardNodes as uploadForwardNodes_,
fetchForwardNodes as fetchForwardNodes_,
} from './actions/forward';
import {
setFriendAddRequest as setFriendAddRequest_,
deleteFriend as deleteFriend_,
setFriendRemark as setFriendRemark_,
setGroupRemark as setGroupRemark_,
fetchGroupFileCount as fetchGroupFileCount_,
} from './actions/friend';
import {
setOnlineStatus as setOnlineStatus_,
setProfile as setProfile_,
getProfileLike as getProfileLike_,
getGroupAtAllRemain as getGroupAtAllRemain_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
setAvatar as setAvatar_,
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
} from './actions/profile';
import {
translateEn2Zh as translateEn2Zh_,
getMiniAppArk as getMiniAppArk_,
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
setAvatar as setAvatar_,
fetchCustomFace as fetchCustomFace_,
getEmojiLikes as getEmojiLikes_,
} from './bridge-actions';
} from './actions/misc';
import {
getGroupHonorInfo as getGroupHonorInfo_,
forceFetchClientKey as forceFetchClientKey_,
@@ -97,8 +111,8 @@ import {
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
} from './web-actions';
import type { GroupFilesResult } from './bridge-actions';
import type { MediaIndexNode } from './bridge-actions';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
@@ -2,20 +2,20 @@
// for encoding with protoEncode(SendMessageRequestSchema).
// Port of src/bridge/src/bridge_messages.cpp build_send_elems()
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import type { ProtoDecoded } from '../../protobuf/decode';
import { protoEncode } from '../../protobuf/decode';
import type { Bridge } from './bridge';
import type { MessageElement } from './events';
import type { ProtoDecoded } from '../protobuf/decode';
import { protoEncode } from '../protobuf/decode';
import {
ElemSchema,
} from '../proto/element';
} from './proto/element';
import {
MentionExtraSendSchema,
MarkdownDataSchema,
} from '../proto/action';
import { uploadImageMsgInfo } from '../highway/image-upload';
import { uploadPttMsgInfo } from '../highway/ptt-upload';
import { uploadVideoMsgInfo } from '../highway/video-upload';
} from './proto/action';
import { uploadImageMsgInfo } from './highway/image-upload';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
+10
View File
@@ -27,6 +27,16 @@ export interface MessageElement {
flash?: boolean;
resId?: string;
fileHash?: string;
// Server-side fingerprints carried from receive side so a forward can do a
// pure md5/sha1 fast-upload without re-downloading the original bytes.
// Set together with `noByteFallback: true` to make the upload modules throw
// instead of falling back to fetch(url).
md5Hex?: string;
sha1Hex?: string;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
noByteFallback?: boolean;
mediaNode?: {
fileUuid?: string;
storeId?: number;
+97 -129
View File
@@ -1,38 +1,65 @@
// Image upload pipeline: load image, OIDB upload request, highway upload, build message element.
// Port of src/bridge/src/highway_upload_req.cpp + highway_client.cpp (image parts)
// Image upload: load the source, run NTV2 upload + (optional) Highway PUT,
// return the encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file just supplies the image-specific bits (format
// detection, picFormat, bizType, command ids).
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import {
loadBinarySource, computeHashes, detectImageFormat,
} from './utils';
import {
fetchHighwaySession, uploadHighwayHttp, buildHighwayExtend,
PRIVATE_IMAGE_CMD_ID, GROUP_IMAGE_CMD_ID,
} from './highway-client';
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
interface ImageData {
/** Empty when the caller is forwarding from cached fingerprints. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
fileSize: number;
summary: string;
subType: number;
width: number;
height: number;
picFormat: number;
/** True when `bytes` is empty; runNtv2Upload throws fastOnlyError if
* the server demands the bytes anyway. */
fastOnly: boolean;
}
function imageDataFromFingerprint(element: MessageElement): ImageData {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`,
fileSize: element.fileSize ?? 0,
summary: element.summary || (element.subType === 0 ? '[image]' : '[sticker]'),
subType: element.subType ?? 0,
width: element.width ?? 0,
height: element.height ?? 0,
picFormat: element.picFormat ?? 1000,
fastOnly: true,
};
}
function loadImage(element: MessageElement): Promise<ImageData> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
return Promise.reject(new Error('image fast-upload requires md5Hex + sha1Hex'));
}
return Promise.resolve(imageDataFromFingerprint(element));
}
return loadImageFromSource(
element.url || element.fileId || '',
element.fileName ?? '',
@@ -59,119 +86,19 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: finalName,
fileSize: loaded.bytes.length,
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
subType,
width: fmt.width,
height: fmt.height,
picFormat: fmt.format,
fastOnly: false,
};
}
async function startImageUpload(bridge: Bridge, isGroup: boolean, targetIdOrUid: string | number, image: ImageData): Promise<any> {
const body: any = {
reqHead: {
common: { requestId: 1, command: 100 },
scene: {
requestType: 2,
businessType: 1,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: [{
fileInfo: {
fileSize: image.bytes.length,
fileHash: image.md5Hex,
fileSha1: image.sha1Hex,
fileName: image.fileName,
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
width: image.width,
height: image.height,
time: 0,
original: 1,
},
subFileType: 0,
}],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: BigInt(Math.floor(Math.random() * 0x7FFFFFFFFFFFFFFF)),
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { reserveTroop: { subType: image.subType } }
: { reserveC2c: { subType: image.subType } }),
},
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const oidbCmd = isGroup ? 0x11C4 : 0x11C5;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'image upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'image upload failed');
}
return uploadBody.upload;
}
function finalizeImageMsgInfo(upload: any, image: ImageData): Uint8Array {
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) {
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? image.subType;
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? image.summary;
} else {
extBizInfo.pic = { bizType: image.subType, textSummary: image.summary };
}
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload an image and return the encoded MsgInfo bytes to embed in a CommonElem.
* Upload an image and return the encoded MsgInfo bytes for the outgoing
* commonElem.
*/
export async function uploadImageMsgInfo(
bridge: Bridge,
@@ -180,16 +107,57 @@ export async function uploadImageMsgInfo(
element: MessageElement,
): Promise<Uint8Array> {
const image = await loadImage(element);
const upload = await startImageUpload(bridge, isGroup, targetIdOrUid, image);
// Upload binary if uKey is present (not fast-uploaded)
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
const session = await fetchHighwaySession(bridge);
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], image.sha1);
const commandId = isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID;
await uploadHighwayHttp(bridge, session, commandId, image.bytes, image.md5, extend);
}
const uploads: MediaSubFileUpload[] = [{
source: 'top',
cmdId: isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID,
bytes: image.bytes,
md5: image.md5,
sha1: image.sha1,
fastOnlyError: 'image fast-upload not available (server requires bytes)',
}];
return finalizeImageMsgInfo(upload, image);
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
requestId: 1,
businessType: 1,
uploadInfo: [{
fileInfo: {
fileSize: image.fileSize,
fileHash: image.md5Hex,
fileSha1: image.sha1Hex,
fileName: image.fileName,
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
width: image.width,
height: image.height,
time: 0,
original: 1,
},
subFileType: 0,
}],
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { reserveTroop: { subType: image.subType } }
: { reserveC2c: { subType: image.subType } }),
},
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
uploads,
label: 'image',
});
return finalizeMediaMsgInfo(upload, { bizType: image.subType, textSummary: image.summary });
}
@@ -0,0 +1,249 @@
// Shared NTV2 rich-media upload pipeline.
//
// Image, PTT, and video all follow the same three-step shape:
// 1. send a NTV2UploadRichMediaReq OIDB packet describing the file(s),
// 2. for any sub-file the server signals it wants (uKey present in the
// response), do a Highway HTTP PUT of the bytes,
// 3. encode the returned msgInfo into the bytes that go inside a
// commonElem on the outgoing message.
//
// The per-format files (image-upload, ptt-upload, video-upload) used to
// each implement steps 1 / 2 / 3 inline with subtle drift between them.
// This module pulls the envelope, response decoding, error handling, and
// the Highway PUT loop into one place, leaving each format file with
// only: how to load the file, how to fill the type-specific fileInfo +
// extBizInfo, and which command ids to use.
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
EncodableMediaMsgInfoSchema,
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
} from '../proto/highway';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
// ─────────────── public types ───────────────
/**
* Highway upload spec for one sub-file of an NTV2 upload response.
* The server returns 0..N sub-files; for each we either fast-path (skip)
* or do an HTTP PUT.
*/
export interface MediaSubFileUpload {
/**
* Where to read uKey + ipv4s from on the OIDB response:
* 'top' -> `upload.uKey` + `upload.ipv4s` (main file)
* N (int) -> `upload.subFileInfos[N].uKey` + `.ipv4s` (sub-file)
*
* Image and PTT use 'top' only. Video uses 'top' (main) and 0 (thumb).
*/
source: 'top' | number;
/** Highway command id for this sub-file. */
cmdId: number;
/** Bytes to upload. Empty when the caller is forwarding from cached
* fingerprints; in that case set fastOnlyError so we throw with a
* typed message when the server actually demands the bytes. */
bytes: Uint8Array;
/** md5 used for the highway request. */
md5: Uint8Array;
/** sha1 — single buffer or per-1MB block array. Passed verbatim to
* buildHighwayExtend. */
sha1: Uint8Array | Uint8Array[];
/** subFileIndex argument for buildHighwayExtend. Defaults to 0;
* video thumb passes 1. */
subFileIndex?: number;
/** Error message to throw when uKey is present but `bytes.length === 0`.
* Omit if the caller guarantees bytes always exist (e.g. video thumb
* always has FALLBACK_THUMB bytes). */
fastOnlyError?: string;
}
export interface NtV2UploadParams {
bridge: Bridge;
isGroup: boolean;
/** Group uin when isGroup, otherwise the recipient's uid string. */
targetIdOrUid: string | number;
/** OIDB command id (e.g. 0x11C4 / 0x11C5 / 0x126E / 0x126D / 0x11EA / 0x11E9). */
oidbCmd: number;
/** Service cmd (e.g. 'OidbSvcTrpcTcp.0x11c4_100'). */
serviceCmd: string;
/** `reqHead.common.requestId`. NTV2 sub-protocols use different values
* here (image=1, video=3, ptt = group:1 / c2c:4). */
requestId: number;
/** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */
businessType: number;
/** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */
uploadInfo: unknown[];
/** `upload.compatQmsgSceneType`. */
compatQmsgSceneType: number;
/** `upload.extBizInfo` — type-specific bytes/flags. */
extBizInfo: unknown;
/** Sub-file Highway PUTs to perform after the OIDB response. */
uploads: MediaSubFileUpload[];
/** Used in error messages. Defaults to 'media'. */
label?: string;
}
// ─────────────── helpers ───────────────
/**
* 8 random bytes masked into the positive int64 range so the resulting
* BigInt survives signed-int64 protobuf encoding without surprises.
* Mirrors NapCat.
*/
export function makeClientRandomId(): bigint {
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
/** Hex string -> Uint8Array. Used by every format's fingerprint path. */
export function hexToBytes(hex: string): Uint8Array {
const clean = hex.length % 2 === 0 ? hex : '0' + hex;
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
// ─────────────── main entrypoint ───────────────
/**
* Send a NTV2UploadRichMediaReq and run any Highway PUTs the server asks
* for. Returns the decoded `upload` object so the caller can pass it to
* `finalizeMediaMsgInfo`.
*
* Sessions are cached across sub-file uploads — video does two PUTs but
* only fetches the Highway session once.
*/
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
const label = params.label ?? 'media';
// Build the full body once. Pulling this in here means each format file
// only specifies the seven fields that actually vary.
const body: any = {
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
requestType: 2,
businessType: params.businessType,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: params.uploadInfo,
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error(`${label} upload response body missing`);
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
}
const upload = uploadBody.upload;
if (!upload) throw new Error(`${label} upload response body missing`);
// Highway PUTs. Session is lazily fetched and cached — video does two
// PUTs (main + thumb) and shouldn't pay for two sessions.
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
session ??= await fetchHighwaySession(bridge);
return session;
};
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// Either the server fast-pathed this sub-file (no uKey) or msgInfo is
// missing entirely; either way nothing to push.
if (!uKey || !upload.msgInfo) continue;
if (sub.bytes.length === 0) {
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
continue;
}
const extend = buildHighwayExtend(
uKey,
upload.msgInfo,
target.ipv4s ?? [],
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
sub.subFileIndex ?? 0,
);
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
}
return upload;
}
// ─────────────── shared finalize ───────────────
/**
* Build the encoded MsgInfo bytes that go inside the outgoing commonElem.
*
* `defaultPic` is the image-only fall-back: image uploads inject
* `bizType` + `textSummary` defaults when the server response omits the
* `pic` ext-biz-info. PTT and video pass `undefined` here — they leave
* pic alone unless the server populates it.
*/
export function finalizeMediaMsgInfo(
upload: any,
defaultPic?: { bizType: number; textSummary: string },
): Uint8Array {
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) {
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
if (defaultPic) {
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? defaultPic.bizType;
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? defaultPic.textSummary;
}
} else if (defaultPic) {
extBizInfo.pic = { bizType: defaultPic.bizType, textSummary: defaultPic.textSummary };
}
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
+84 -136
View File
@@ -1,12 +1,10 @@
// Voice (PTT) upload pipeline:
// 1. resolve / fetch the source audio bytes,
// 2. convert to NT SILK via the ffmpegAddon (skip if already silk),
// 3. NTV2 OIDB upload request — 0x126E (group) / 0x126D (private),
// 4. highway HTTP upload — commandId 1008 (group) / 1007 (private),
// 5. return the encoded `MsgInfo` bytes ready for the commonElem.
// Voice (PTT) upload: stage the audio bytes (convert to NT silk if
// necessary), run NTV2 upload + (optional) Highway PUT, return the
// encoded MsgInfo for the outgoing commonElem.
//
// Port of NapCat's `UploadGroupPtt` / `UploadPrivatePtt` transformer + the
// `uploadGroupPtt` / `uploadC2CPtt` paths in `PacketHighwayContext`.
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file owns the silk transcoding, the temp-file
// cleanup hooks, and the PTT-specific OIDB fields.
import fs from 'fs';
import path from 'path';
@@ -14,21 +12,15 @@ import crypto from 'crypto';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import { loadBinarySource, computeHashes, resolveLocalFilePath } from './utils';
import {
fetchHighwaySession,
uploadHighwayHttp,
buildHighwayExtend,
} from './highway-client';
import { encodeSilk, defaultPttTempDir } from './ffmpeg-addon';
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
const log = createLogger('Ptt');
@@ -36,26 +28,56 @@ export const PRIVATE_PTT_CMD_ID = 1007;
export const GROUP_PTT_CMD_ID = 1008;
interface PttPayload {
/** Silk bytes that get uploaded to highway. */
/** Silk bytes uploaded to Highway. Empty when forwarding from cached fingerprints. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
fileSize: number;
/** Whole seconds, >= 1. */
duration: number;
/** Cleanup hooks invoked once the OIDB request + highway upload finish. */
voiceFormat: number;
/** True when bytes is empty; pipeline throws fastOnlyError if the
* server demands the bytes anyway. */
fastOnly: boolean;
/** Cleanup hooks for any temp silk files staged during loadPtt. */
cleanups: Array<() => void>;
}
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'record'}.amr`,
fileSize: element.fileSize ?? 0,
duration: element.duration ?? 1,
// Voice format: 1 = silk (NTV2 standard). Honour any fingerprint that
// declares a different format; legacy NTQQ paths all use 1.
voiceFormat: element.voiceFormat || 1,
fastOnly: true,
cleanups: [],
};
}
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('record fast-upload requires md5Hex + sha1Hex');
}
return pttPayloadFromFingerprint(element);
}
const source = element.url || element.fileId || '';
if (!source) throw new Error('record source is empty');
const cleanups: Array<() => void> = [];
// Run all queued cleanups; callable both on the success path (via the
// returned `cleanups` array) and the failure path (try/catch below).
// Run all queued cleanups; called both on the success path (via the
// returned `cleanups` array) and on the failure path (try/catch below).
const runCleanups = () => {
while (cleanups.length > 0) {
const fn = cleanups.pop();
@@ -97,7 +119,10 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: `${hashes.md5Hex}.amr`,
fileSize: silkBytes.length,
duration: silk.duration,
voiceFormat: 1,
fastOnly: false,
cleanups: [...cleanups],
};
} catch (err) {
@@ -106,42 +131,44 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
}
}
function makeClientRandomId(): bigint {
// Same trick NapCat uses: 8 random bytes, masked into the positive int64
// range so it survives proto signed-int64 encoding without surprises.
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
async function startPttUpload(
/**
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
ptt: PttPayload,
): Promise<any> {
const body: any = {
reqHead: {
element: MessageElement,
): Promise<Uint8Array> {
const tempDir = defaultPttTempDir();
const ptt = await loadPtt(element, tempDir);
try {
const uploads: MediaSubFileUpload[] = [{
source: 'top',
cmdId: isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID,
bytes: ptt.bytes,
md5: ptt.md5,
sha1: ptt.sha1,
fastOnlyError: 'record fast-upload not available (server requires bytes)',
}];
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x126E : 0x126D,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100',
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
common: { requestId: isGroup ? 1 : 4, command: 100 },
scene: {
requestType: 2,
businessType: 3,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
requestId: isGroup ? 1 : 4,
businessType: 3,
uploadInfo: [{
fileInfo: {
fileSize: ptt.bytes.length,
fileSize: ptt.fileSize,
fileHash: ptt.md5Hex,
fileSha1: ptt.sha1Hex,
fileName: ptt.fileName,
// type=3 voice, voiceFormat=1 (silk).
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: 1 },
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: ptt.voiceFormat },
width: 0,
height: 0,
time: ptt.duration,
@@ -149,9 +176,6 @@ async function startPttUpload(
},
subFileType: 0,
}],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
// NapCat fills in a placeholder textSummary so the legacy compat
@@ -168,87 +192,11 @@ async function startPttUpload(
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
uploads,
label: 'ptt',
});
const oidbCmd = isGroup ? 0x126E : 0x126D;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode ptt upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('ptt upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'ptt upload failed');
}
return uploadBody.upload;
}
function finalizePttMsgInfo(upload: any): Uint8Array {
if (!upload?.msgInfo) throw new Error('ptt upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) extBizInfo.pic = upload.msgInfo.extBizInfo.pic;
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload a voice clip and return the encoded `MsgInfo` bytes that go inside
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const tempDir = defaultPttTempDir();
const ptt = await loadPtt(element, tempDir);
try {
const upload = await startPttUpload(bridge, isGroup, targetIdOrUid, ptt);
// Highway upload only happens when the server didn't fast-path the file
// (uKey present == "we want the bytes"). Otherwise we just embed the
// returned MsgInfo and trust the dedupe.
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
log.debug('highway upload: bytes=%d md5=%s scene=%s', ptt.bytes.length, ptt.md5Hex, isGroup ? 'group' : 'c2c');
const session = await fetchHighwaySession(bridge);
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], ptt.sha1);
const commandId = isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID;
await uploadHighwayHttp(bridge, session, commandId, ptt.bytes, ptt.md5, extend);
} else {
log.debug('ptt fast-uploaded (server already has md5=%s)', ptt.md5Hex);
}
return finalizePttMsgInfo(upload);
return finalizeMediaMsgInfo(upload);
} finally {
for (const fn of ptt.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
+127 -140
View File
@@ -1,12 +1,11 @@
// Video upload pipeline:
// 1. resolve / fetch the source video and optional thumbnail,
// 2. generate a thumbnail via ffmpegAddon when needed,
// 3. NTV2 OIDB upload request - 0x11EA (group) / 0x11E9 (private),
// 4. highway HTTP upload for video + thumbnail,
// 5. return the encoded `MsgInfo` bytes ready for the commonElem.
// Video upload: stage the source video and a thumbnail (extracted via
// ffmpeg if not supplied), run NTV2 upload + (optional) Highway PUTs for
// both files, return the encoded MsgInfo for the outgoing commonElem.
//
// Port of NapCat's UploadGroupVideo / UploadPrivateVideo transformers and
// the uploadGroupVideo / uploadC2CVideo paths in PacketHighwayContext.
// Shared OIDB envelope + response handling + Highway PUT loop live in
// pipeline.ts; this file owns the ffmpeg thumb extraction, the 1 MB
// streaming sha1 used by main-video Highway uploads, and the
// video-specific OIDB fields (uploadInfo has TWO entries — main + thumb).
import fs from 'fs';
import os from 'os';
@@ -15,26 +14,20 @@ import crypto from 'crypto';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import {
loadBinarySource,
computeHashes,
detectImageFormat,
loadBinarySource,
resolveLocalFilePath,
} from './utils';
import {
fetchHighwaySession,
uploadHighwayHttp,
buildHighwayExtend,
} from './highway-client';
import { getFFmpegAddon } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
const log = createLogger('Video');
@@ -52,6 +45,7 @@ const FALLBACK_THUMB = Buffer.from(
);
interface VideoPayload {
/** Video bytes. Empty when forwarding from cached fingerprints. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
@@ -60,13 +54,55 @@ interface VideoPayload {
sha1Hex: string;
fileName: string;
filePath: string;
fileSize: number;
width: number;
height: number;
duration: number;
videoFormat: number;
thumb: ThumbPayload;
/** When true, video bytes are empty; pipeline throws fastOnlyError
* for the main file if the server demands the bytes. The thumb is
* always present (FALLBACK_THUMB at worst) so its sub-file uploads
* normally regardless. */
fastOnly: boolean;
cleanups: Array<() => void>;
}
function makeFallbackThumb(): ThumbPayload {
const bytes = new Uint8Array(FALLBACK_THUMB);
const hashes = computeHashes(bytes);
return {
bytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width: 1,
height: 1,
};
}
function videoPayloadFromFingerprint(element: MessageElement): VideoPayload {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
sha1Blocks: [],
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'video'}.mp4`,
filePath: '',
fileSize: element.fileSize ?? 0,
width: element.width ?? 0,
height: element.height ?? 0,
duration: element.duration ?? 1,
videoFormat: element.videoFormat ?? 0,
thumb: makeFallbackThumb(),
fastOnly: true,
cleanups: [],
};
}
interface ThumbPayload {
bytes: Uint8Array;
md5: Uint8Array;
@@ -77,6 +113,12 @@ interface ThumbPayload {
height: number;
}
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
// Highway expects sha1 computed over each 1 MB block of the file, plus
// the final overall sha1. This is a streaming implementation that doesn't
// reuse Node's crypto because Node only exposes the final digest.
class Sha1StreamState {
readonly blockSize = 64;
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
@@ -213,6 +255,8 @@ function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
return blocks;
}
// ─────────────── source staging + thumb extraction ───────────────
function defaultVideoTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-video');
}
@@ -226,11 +270,6 @@ function sourceExtension(fileName: string, source: string): string {
return fromSource || '.mp4';
}
function makeClientRandomId(): bigint {
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
bytes: Uint8Array;
filePath: string;
@@ -321,6 +360,13 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
}
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
throw new Error('video fast-upload requires md5Hex + sha1Hex');
}
return videoPayloadFromFingerprint(element);
}
const tempDir = defaultVideoTempDir();
const cleanups: Array<() => void> = [];
fs.mkdirSync(tempDir, { recursive: true });
@@ -344,10 +390,13 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
sha1Hex: hashes.sha1Hex,
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
filePath: staged.filePath,
fileSize: staged.bytes.length,
width,
height,
duration,
videoFormat: 0,
thumb,
fastOnly: false,
cleanups: [...cleanups],
};
} catch (err) {
@@ -358,37 +407,63 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
}
}
async function startVideoUpload(
// ─────────────── exported entry ───────────────
/**
* Upload a video and return the encoded MsgInfo bytes that go inside a
* `commonElem { serviceType: 48, businessType: 21 }`.
*
* Two highway PUTs run when the server doesn't fast-path: the main video
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
*/
export async function uploadVideoMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
video: VideoPayload,
): Promise<any> {
const body: any = {
reqHead: {
common: { requestId: 3, command: 100 },
scene: {
requestType: 2,
businessType: 2,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
element: MessageElement,
): Promise<Uint8Array> {
const video = await loadVideo(element);
try {
const uploads: MediaSubFileUpload[] = [
{
source: 'top',
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
bytes: video.bytes,
md5: video.md5,
sha1: video.sha1Blocks,
subFileIndex: 0,
fastOnlyError: 'video fast-upload not available (server requires bytes)',
},
client: { agentType: 2 },
},
upload: {
{
source: 0, // upload.subFileInfos[0]
cmdId: isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID,
bytes: video.thumb.bytes,
md5: video.thumb.md5,
sha1: video.thumb.sha1,
subFileIndex: 1,
// No fastOnlyError: thumb always has bytes (FALLBACK_THUMB at worst).
},
];
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x11EA : 0x11E9,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100',
requestId: 3,
businessType: 2,
uploadInfo: [
{
fileInfo: {
fileSize: video.bytes.length,
fileSize: video.fileSize,
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
height: 0,
width: 0,
time: 0,
type: { type: 2, picFormat: 0, videoFormat: video.videoFormat, voiceFormat: 0 },
height: video.height,
width: video.width,
time: video.duration,
original: 0,
},
subFileType: 0,
@@ -408,9 +483,6 @@ async function startVideoUpload(
subFileType: 100,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: 2,
extBizInfo: {
pic: { bizType: 0, textSummary: 'Nya~' },
@@ -421,97 +493,12 @@ async function startVideoUpload(
bytesGeneralFlags: new Uint8Array(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
uploads,
label: 'video',
});
const oidbCmd = isGroup ? 0x11EA : 0x11E9;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'video upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode video upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('video upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'video upload failed');
}
return uploadBody.upload;
}
function finalizeVideoMsgInfo(upload: any): Uint8Array {
if (!upload?.msgInfo) throw new Error('video upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) extBizInfo.pic = upload.msgInfo.extBizInfo.pic;
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload a video and return the encoded `MsgInfo` bytes that go inside
* a `commonElem { serviceType: 48, businessType: 21 }`.
*/
export async function uploadVideoMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const video = await loadVideo(element);
try {
const upload = await startVideoUpload(bridge, isGroup, targetIdOrUid, video);
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
session ??= await fetchHighwaySession(bridge);
return session;
};
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
log.debug('highway video upload: bytes=%d md5=%s scene=%s', video.bytes.length, video.md5Hex, isGroup ? 'group' : 'c2c');
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], video.sha1Blocks, 0);
const commandId = isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID;
await uploadHighwayHttp(bridge, await getSession(), commandId, video.bytes, video.md5, extend);
} else {
log.debug('video fast-uploaded (server already has md5=%s)', video.md5Hex);
}
const subFile = upload?.subFileInfos?.[0];
if (subFile?.uKey && upload?.msgInfo) {
log.debug('highway video thumb upload: bytes=%d md5=%s scene=%s', video.thumb.bytes.length, video.thumb.md5Hex, isGroup ? 'group' : 'c2c');
const extend = buildHighwayExtend(subFile.uKey, upload.msgInfo, subFile.ipv4s ?? [], video.thumb.sha1, 1);
const commandId = isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID;
await uploadHighwayHttp(bridge, await getSession(), commandId, video.thumb.bytes, video.thumb.md5, extend);
} else {
log.debug('video thumb fast-uploaded (server already has md5=%s)', video.thumb.md5Hex);
}
return finalizeVideoMsgInfo(upload);
log.debug('video upload completed: md5=%s scene=%s', video.md5Hex, isGroup ? 'group' : 'c2c');
return finalizeMediaMsgInfo(upload);
} finally {
for (const fn of video.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
@@ -71,7 +71,6 @@ export class IdentityService {
private readonly uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>();
private inTransaction = false;
private writeFailed = false;
constructor(
private readonly qqInfo: QQInfo,
@@ -106,10 +105,6 @@ export class IdentityService {
return this.db !== null;
}
get hasWriteFailure(): boolean {
return this.writeFailed;
}
rememberFriends(friends: FriendInfo[]): void {
this.qqInfo.setFriends(friends);
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
@@ -693,7 +688,6 @@ export class IdentityService {
try {
fn();
} catch (err) {
this.writeFailed = true;
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
}
}
+3 -7
View File
@@ -1,8 +1,8 @@
// BridgeManager — manages per-UIN Bridge sessions.
// Wires NtqqHandler packets to appropriate Bridge instances.
// onPacket() is the single entry point for parsed hook packets;
// HookManager wires it as the default packet sink for every HookSession.
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
import type { NtqqHandler } from '../protocol/ntqq-handler';
import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
@@ -31,10 +31,6 @@ export class BridgeManager {
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
bind(ntqq: NtqqHandler): void {
ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt));
}
onPidDisconnected(pid: number): void {
this.pidPacketClients_.delete(pid);
const uin = this.pidToUin_.get(pid);
@@ -76,7 +72,7 @@ export class BridgeManager {
}
}
private onPacket(pkt: PacketInfo): void {
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
const uin = pkt.uin;
@@ -2,31 +2,31 @@
// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp
import { inflateSync } from 'zlib';
import { protoDecode } from '../../protobuf/decode';
import { WireMessage } from '../../protobuf/wire';
import { PushMsgSchema } from '../proto/message';
import { protoDecode } from '../protobuf/decode';
import { WireMessage } from '../protobuf/wire';
import { PushMsgSchema } from './proto/message';
import {
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
} from '../proto/element';
import { FileExtraSchema } from '../proto/message';
} from './proto/element';
import { FileExtraSchema } from './proto/message';
import {
GroupChangeSchema, GroupAdminSchema, GroupJoinSchema,
GroupInvitationSchema, GroupInviteSchema,
FriendRequestSchema, FriendRecallSchema,
GroupMuteSchema, NotifyMessageBodySchema,
GeneralGrayTipInfoSchema, OperatorInfoSchema,
} from '../proto/notify';
import type { QQInfo } from '../qq-info';
import type { PacketInfo } from '../../protocol/types';
} from './proto/notify';
import type { QQInfo } from './qq-info';
import type { PacketInfo } from '../protocol/types';
import type {
QQEventVariant, MessageElement,
FriendMessage, GroupMessage, TempMessage,
GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent,
FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent,
FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent,
} from '../events';
import type { ProtoDecoded, ProtoSchema } from '../../protobuf/decode';
} from './events';
import type { ProtoDecoded, ProtoSchema } from '../protobuf/decode';
// --- PkgType enum ---
const enum PkgType {
@@ -147,7 +147,7 @@ function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
// --- Element conversion ---
type ElemDecoded = ProtoDecoded<typeof import('../proto/element').ElemSchema>;
type ElemDecoded = ProtoDecoded<typeof import('./proto/element').ElemSchema>;
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
@@ -217,6 +217,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: bytesToHex(img.picMd5),
});
}
}
@@ -234,6 +235,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: bytesToHex(img.md5),
});
}
}
@@ -397,6 +399,9 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
height: fi.height ?? 0, imageUrl: url,
};
if (fi.fileHash) me.md5Hex = fi.fileHash;
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
if (info.extBizInfo?.pic) {
me.subType = info.extBizInfo.pic.bizType ?? 0;
me.summary = info.extBizInfo.pic.textSummary || '[image]';
@@ -408,6 +413,10 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
type: 'record', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
voiceFormat: fi.type?.voiceFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
@@ -439,6 +448,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
width: fi.width ?? 0,
height: fi.height ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
videoFormat: fi.type?.videoFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
@@ -483,17 +497,20 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
}
function extractRichtextExtras(
rt: ProtoDecoded<typeof import('../proto/message').RichTextSchema>,
rt: ProtoDecoded<typeof import('./proto/message').RichTextSchema>,
elements: MessageElement[],
isGroup = false
): void {
// Ptt (voice)
if (rt.ptt) {
const p = rt.ptt;
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '';
const me: MessageElement = {
type: 'record', fileName: p.fileName ?? '',
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
fileHash: md5Hex,
md5Hex,
voiceFormat: p.format ?? 0,
};
if (isGroup && (p.fileId ?? 0n) !== 0n) {
me.fileId = p.groupFileKey ?? '';
-331
View File
@@ -1,331 +0,0 @@
// Web API operations extracted from Bridge.
import type { Bridge } from './bridge';
import { sendOidbAndDecode } from './bridge-oidb';
import { resolveUserUid } from './bridge-oidb';
import {
OidbClientKeyRespSchema,
OidbClientKeyReqSchema,
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema
} from './proto/oidb-action';
import { RequestUtil } from './web/request-util';
import { getHonorListWebAPI, WebHonorType } from './web/group-honor';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from './web/group-essence';
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI, uploadGroupNoticeImage, deleteGroupNotice } from './web/group-notice';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_1',
0x102A,
1,
{},
OidbClientKeyReqSchema,
OidbClientKeyRespSchema
);
const clientKey = resp?.clientKey || '';
const keyIndex = String(resp?.keyIndex || '19'); // 不知道是什么
return {
clientKey,
keyIndex,
expireTime: String(resp?.expireTime || '1800')
};
}
export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_0',
0x102A,
0,
{ domainList },
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema
);
const domainPskeyMap = new Map<string, string>();
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
for (const item of resp.pskeyItems) {
if (item.domain && item.pskey) {
domainPskeyMap.set(item.domain, item.pskey);
}
}
}
return {
domainPskeyMap,
};
}
export async function getCookies(bridge: Bridge, domain: string) {
const ClientKeyData = await forceFetchClientKey(bridge);
// 构造 ptlogin2 跳转 URL
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data['p_skey'] || data['p_skey'].length === 0) {
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
}
}
return data;
}
export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: any = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
}
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
}
return honorInfo;
}
export async function getSKey(bridge: Bridge): Promise<string> {
const ClientKeyData = await forceFetchClientKey(bridge);
if (!ClientKeyData.clientKey) {
throw new Error('getClientKey Error: clientKey is empty');
}
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.qqInfo.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
if (!skey) {
throw new Error('SKey is Empty');
}
return skey;
}
/**
* 分页获取群精华消息
*/
export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
/**
* 获取所有群精华消息
*/
export async function getGroupEssenceAll(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode);
return essenceDataAll;
}
export async function sendGroupNotice(
bridge: Bridge,
groupId: number,
content: string,
options?: {
image?: string; // 未来如果要发图片,传路径进来
pinned?: number;
type?: number;
confirm_required?: number;
}
) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
options?.pinned ?? 0,
options?.type ?? 1,
1,
1,
options?.confirm_required ?? 1,
picId,
imgWidth,
imgHeight
);
if (!ret || ret.ec !== 0) {
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
}
return ret;
}
export async function getGroupNotice(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
if (!ret) {
throw new Error('获取公告失败');
}
const retNotices: any[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
const feed = ret.feeds[key];
if (!feed) continue;
const image = feed.msg?.pics?.map((pic) => ({
id: pic.id,
height: pic.h,
width: pic.w,
})) || [];
retNotices.push({
notice_id: feed.fid,
sender_id: feed.u,
publish_time: feed.pubt,
message: {
text: feed.msg?.text || '',
image: image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
}
export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise<boolean> {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNotice(cookieObject, groupCode, fid);
}
/**
* 提取的公共算法:根据 skey/p_skey 计算 bkn (也就是 token / csrf_token)
*/
export function getBknFromSKey(skey: string): number {
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
}
/**
* 获取 Cookies (字符串格式)
*/
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
const cookieObject = await getCookies(bridge, domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/**
* 获取 CSRF Token (即 BKN)
*/
export async function getCsrfToken(bridge: Bridge): Promise<number> {
const skey = await getSKey(bridge);
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/**
* 获取凭证 (Cookies 字符串 + Token)
*/
export async function getCredentials(bridge: Bridge, domain: string) {
const cookieObject = await getCookies(bridge, domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
return {
cookies: cookiesStr,
token: token,
csrf_token: token
};
}
@@ -0,0 +1,161 @@
// Web-cookie / credential primitives — every other web-action in this
// directory builds on these. Each Bridge-level web call ends up doing
// roughly: forceFetchClientKey -> ptlogin2 jump -> cookie dict ->
// thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge';
import { sendOidbAndDecode } from '../bridge-oidb';
import {
OidbClientKeyRespSchema,
OidbClientKeyReqSchema,
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
} from '../proto/oidb-action';
import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_1',
0x102A,
1,
{},
OidbClientKeyReqSchema,
OidbClientKeyRespSchema,
);
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
// every NapCat-derived implementation uses when the server omits it.
const keyIndex = String(resp?.keyIndex || '19');
return {
clientKey,
keyIndex,
expireTime: String(resp?.expireTime || '1800'),
};
}
export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_0',
0x102A,
0,
{ domainList },
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
);
const domainPskeyMap = new Map<string, string>();
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
for (const item of resp.pskeyItems) {
if (item.domain && item.pskey) {
domainPskeyMap.set(item.domain, item.pskey);
}
}
}
return { domainPskeyMap };
}
export async function getCookies(bridge: Bridge, domain: string) {
const ClientKeyData = await forceFetchClientKey(bridge);
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data['p_skey'] || data['p_skey'].length === 0) {
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
// for the same domain. Errors are swallowed so the caller can
// still proceed with whatever cookies it did get.
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
}
}
return data;
}
export async function getSKey(bridge: Bridge): Promise<string> {
const ClientKeyData = await forceFetchClientKey(bridge);
if (!ClientKeyData.clientKey) {
throw new Error('getClientKey Error: clientKey is empty');
}
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.qqInfo.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
if (!skey) {
throw new Error('SKey is Empty');
}
return skey;
}
/**
* Standard QQ bkn hash (also known as token / csrf_token) derived from
* skey or p_skey. djb2 hash truncated to 31 bits.
*/
export function getBknFromSKey(skey: string): number {
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
const cookieObject = await getCookies(bridge, domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
export async function getCsrfToken(bridge: Bridge): Promise<number> {
const skey = await getSKey(bridge);
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
export async function getCredentials(bridge: Bridge, domain: string) {
const cookieObject = await getCookies(bridge, domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
return {
cookies: cookiesStr,
token: token,
csrf_token: token,
};
}
@@ -0,0 +1,27 @@
// `get_essence_msg_list` — group essence (highlighted) messages.
// Two flavors: paginated (`getGroupEssence`) and the convenience
// fetch-everything (`getGroupEssenceAll`).
import type { Bridge } from '../bridge';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence';
import { getCookies } from './cookies';
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
/** Walks every page and returns the concatenated result. */
export async function getGroupEssenceAll(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode);
return essenceDataAll;
}
@@ -0,0 +1,45 @@
// `get_group_honor_info` — queries the per-group honor leaderboards
// (talkative / performer / legend / emotion / strong_newbie).
// Each honor type is a separate web call; ALL fetches all four
// non-newbie lists and folds them into one response.
import type { Bridge } from '../bridge';
import { getHonorListWebAPI, WebHonorType } from '../web/group-honor';
import { getCookies } from './cookies';
export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: any = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
}
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
}
return honorInfo;
}
@@ -0,0 +1,118 @@
// Group notice (`群公告`) web actions: send / list / delete.
// `sendGroupNotice` can attach an optional image; when present it
// stages the bytes (HTTP URL or local file) and uploads via the
// notice-image endpoint before posting the notice itself.
import type { Bridge } from '../bridge';
import {
setGroupNoticeWebAPI,
getGroupNoticeWebAPI,
uploadGroupNoticeImage,
deleteGroupNotice,
} from '../web/group-notice';
import { getCookies } from './cookies';
export async function sendGroupNotice(
bridge: Bridge,
groupId: number,
content: string,
options?: {
image?: string; // local path, http URL, or undefined (text-only)
pinned?: number;
type?: number;
confirm_required?: number;
},
) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
options?.pinned ?? 0,
options?.type ?? 1,
1,
1,
options?.confirm_required ?? 1,
picId,
imgWidth,
imgHeight,
);
if (!ret || ret.ec !== 0) {
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
}
return ret;
}
export async function getGroupNotice(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
if (!ret) {
throw new Error('获取公告失败');
}
const retNotices: any[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
const feed = ret.feeds[key];
if (!feed) continue;
const image = feed.msg?.pics?.map((pic) => ({
id: pic.id,
height: pic.h,
width: pic.w,
})) || [];
retNotices.push({
notice_id: feed.fid,
sender_id: feed.u,
publish_time: feed.pubt,
message: {
text: feed.msg?.text || '',
image: image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
}
export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise<boolean> {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNotice(cookieObject, groupCode, fid);
}
@@ -0,0 +1,27 @@
// Barrel for the web-action themed split. `bridge.ts` imports
// everything from this directory as if it were a single file; the
// per-theme files keep the implementation discoverable.
export {
forceFetchClientKey,
getPSkey,
getCookies,
getSKey,
getBknFromSKey,
getCookiesStr,
getCsrfToken,
getCredentials,
} from './cookies';
export { getGroupHonorInfo } from './group-honor';
export {
getGroupEssence,
getGroupEssenceAll,
} from './group-essence';
export {
sendGroupNotice,
getGroupNotice,
deleteGroupNoticeByFid,
} from './group-notice';
+19
View File
@@ -3,6 +3,10 @@ import path from 'path';
export interface RuntimeConfig {
webuiPort?: number;
/** When true, every newly-discovered QQ process gets auto-injected by
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
* Defaults to false; the Docker image flips it on in supervisord.conf. */
hookAutoLoad?: boolean;
}
const CONFIG_DIR = 'config';
@@ -10,6 +14,7 @@ const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
webuiPort: 5099,
hookAutoLoad: false,
};
export function loadRuntimeConfig(): RuntimeConfig {
@@ -23,10 +28,12 @@ export function loadRuntimeConfig(): RuntimeConfig {
const normalized: RuntimeConfig = {
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
};
if (
normalized.webuiPort !== loaded.webuiPort
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
) {
saveRuntimeConfig(normalized);
}
@@ -44,6 +51,7 @@ function tryLoadRuntimeConfig(): RuntimeConfig | null {
return {
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
};
} catch {
return null;
@@ -70,6 +78,17 @@ function normalizePort(value: unknown, fallback: number): number {
return fallback;
}
function normalizeBool(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
const v = value.trim().toLowerCase();
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
}
return fallback;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+199 -468
View File
@@ -1,514 +1,245 @@
import type { BridgeManager } from '../bridge/manager';
import type { NtqqHandler } from '../protocol/ntqq-handler';
import { createLogger } from '../utils/logger';
import { HookPacketClient } from './hook-packet-client';
import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector';
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
import type { PacketSink } from '../protocol/types';
import { createLogger, type Logger } from '../utils/logger';
import {
injectHookProcess,
listHookProcesses,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { HookSession, type HookSessionDeps } from './hook-session';
import { PipeWatcher } from './pipe-watcher';
import { QqHookClient } from './qq-hook-client';
import type { HookProcessInfo } from './types';
const log = createLogger('Hook');
const DEFAULT_WATCHER_INTERVAL_MS = 1500;
const MIN_WATCHER_INTERVAL_MS = 250;
export type { HookProcessInfo, HookProcessStatus } from './types';
export type { HookProcessBaseInfo } from './injector';
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
}
interface HookProcessState extends HookProcessInfo {
client: QqHookClient | null;
sender: HookPacketClient | null;
injectResult: HookInjectResult | null;
bound: boolean;
}
export interface HookManagerOptions {
/** Background pipe-watcher polling interval. Lower = faster reconnect but
* more frequent named-pipe directory listings. Defaults to 1500 ms. */
export type HookManagerDeps = {
bridgeManager: BridgeManager;
/** Sink for parsed packets from any live HookSession. Defaults to
* `bridgeManager.onPacket` — every packet flows straight into the
* per-UIN bridge dispatcher with no intermediate event emitter. */
onPacket?: PacketSink;
/** Native injector entrypoints. Defaults to the real native addon. */
injector?: HookSessionDeps['injector'];
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
makeClient?: HookSessionDeps['makeClient'];
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
pipeWatcher?: PipeWatcher;
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
watcherIntervalMs?: number;
}
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
listProcesses?: () => HookProcessBaseInfo[];
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state. */
autoLoadOnDiscovery?: boolean;
log?: Logger;
};
/**
* Manages SnowLuma hook injection and bridge connectivity for QQ.exe processes.
* HookManager — thin orchestrator over a per-PID HookSession map and a
* singleton PipeWatcher.
*
* Lifecycle: load -> inject DLL only (returns fast) -> background watcher
* detects the named pipe coming up and connects -> on QQ login the bridge is
* notified. The watcher also handles reconnect after a pipe drop and detects
* hooks that survived a previous SnowLuma restart.
* Responsibilities:
* - Route user commands (load/unload/refresh) to the matching session.
* - Route watcher diff events to the matching session.
* - Forward session events ('login' / 'disconnected') to BridgeManager.
* - Retry stuck-in-connecting sessions on every watcher tick (so a
* failed connect eventually recovers without a manual refresh).
*
* Concurrency: every per-PID mutation (load / unload / refresh / connect /
* close-handler / watcher reconcile) goes through a per-PID promise chain so
* users can spam buttons without races.
* The native injector, native pipe-client, and native process/pipe
* listings are all swappable dependencies so tests can run without a
* real QQ.exe or a native addon.
*/
export class HookManager {
private readonly states = new Map<number, HookProcessState>();
private readonly opsByPid = new Map<number, Promise<unknown>>();
private readonly watcherIntervalMs: number;
private watcherTimer: NodeJS.Timeout | null = null;
private watcherTicking = false;
private readonly bridgeManager: BridgeManager;
private readonly onPacket: PacketSink;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
private readonly listProcessesNative: () => HookProcessBaseInfo[];
private readonly autoLoadOnDiscovery: boolean;
private readonly log: Logger;
private readonly sessions = new Map<number, HookSession>();
private readonly startPromise: Promise<void>;
private disposed = false;
constructor(
private readonly ntqq: NtqqHandler,
private readonly bridgeManager: BridgeManager,
options: HookManagerOptions = {},
) {
this.watcherIntervalMs = Math.max(
MIN_WATCHER_INTERVAL_MS,
options.watcherIntervalMs ?? DEFAULT_WATCHER_INTERVAL_MS,
);
// Boot the watcher on the next tick so callers can attach listeners first.
this.scheduleWatcher(0);
constructor(deps: HookManagerDeps) {
this.bridgeManager = deps.bridgeManager;
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
inject: injectHookProcess,
unload: (pid, handle) => {
if (!handle) return;
unloadHookProcess(pid, handle);
},
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.listProcessesNative,
listLivePipes: () => QqHookClient.listLivePipes(),
intervalMs: deps.watcherIntervalMs,
log: this.log,
});
this.ownsPipeWatcher = true;
}
this.bindWatcher();
this.startPromise = this.pipeWatcher.start();
}
// ─────────────── public API (unchanged from prior HookManager) ───────────────
async listProcesses(): Promise<HookProcessInfo[]> {
const processes = listHookProcesses();
for (const proc of processes) {
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
await this.startPromise;
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcessesNative();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
result.push(session.toInfo());
}
return result.sort((a, b) => a.pid - b.pid);
}
loadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.loadProcessInternal(pid));
async loadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
const info = await session.load();
// Pull the next tick forward so a freshly-injected pipe gets noticed
// within the next event-loop turn instead of after the full interval.
this.pipeWatcher.wake();
return info;
}
unloadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.unloadProcessInternal(pid));
async unloadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.unload();
}
/**
* Re-probe the named pipe for `pid`, reconnect if it became available,
* or tear down a stale connection if it disappeared. Safe to call at any
* time; serialised against load/unload/watcher actions on the same PID.
*/
refreshProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.refreshProcessInternal(pid));
async refreshProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.refresh();
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
if (this.watcherTimer) {
clearTimeout(this.watcherTimer);
this.watcherTimer = null;
for (const session of this.sessions.values()) {
session.dispose();
}
for (const state of this.states.values()) {
this.tearDownClient(state);
state.status = state.injected ? 'disconnected' : 'available';
this.sessions.clear();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
}
}
// ───────────────────────── per-PID serialization ─────────────────────────
// ─────────────── wiring ───────────────
/**
* Serialise an operation against a per-PID promise chain. Guarantees that
* load / unload / refresh / watcher-driven connects for the same PID never
* interleave even if the user mashes buttons.
*/
private async serialize<T>(pid: number, op: () => Promise<T>): Promise<T> {
const previous = this.opsByPid.get(pid) ?? Promise.resolve();
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
const chained = previous.then(() => completion);
this.opsByPid.set(pid, chained);
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
// Drop the chain entry once nothing else is waiting on it.
if (this.opsByPid.get(pid) === chained) this.opsByPid.delete(pid);
}
}
// ──────────────────────────── load / unload ──────────────────────────────
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.error = '';
state.status = 'loading';
try {
if (!state.injected) {
// Fast path: a previous SnowLuma run may have left the hook DLL
// resident in QQ.exe. If the control pipe is already listed we skip
// re-injection and let the watcher reconnect instead.
const livePipes = await QqHookClient.listLivePipes();
if (livePipes.has(pid)) {
state.injected = true;
state.method = state.method || 'reconnect';
log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid);
} else {
state.injectResult = injectHookProcess(pid);
state.injected = true;
state.method = state.injectResult.method;
}
}
state.status = state.connected
? (state.loggedIn ? 'online' : 'loaded')
: 'connecting';
} catch (error) {
state.status = 'error';
state.error = error instanceof Error ? error.message : String(error);
log.error('load failed: PID=%d err=%s', pid, state.error);
}
// Wake the watcher so it can pick up the freshly-injected pipe asap
// instead of waiting up to one full interval.
this.scheduleWatcher(0);
return this.toPublicInfo(state);
}
private async unloadProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.error = '';
try {
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
const handle = state.injectResult?.handle;
if (state.injected && handle) {
unloadHookProcess(pid, handle);
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
}
// Clear injection state first
state.injected = false;
state.injectResult = null;
state.method = '';
state.uin = '0';
// Verify unload succeeded by checking if pipe still exists
const livePipes = await QqHookClient.listLivePipes();
if (livePipes.has(pid)) {
// Pipe still exists - unload failed, but let watcher handle reconnection
state.error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
state.status = 'connecting'; // Let watcher pick it up and reconnect
log.warn('unload verification failed: PID=%d pipe still exists after unloadModuleManual, watcher will reconnect', pid);
} else {
// Successfully unloaded
state.status = 'available';
state.error = '';
}
} catch (error) {
state.status = 'error';
state.error = error instanceof Error ? error.message : String(error);
log.error('unload failed: PID=%d err=%s', pid, state.error);
}
return this.toPublicInfo(state);
}
private async refreshProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.error = '';
try {
const livePipes = await QqHookClient.listLivePipes();
const pipeUp = livePipes.has(pid);
if (pipeUp) {
// A live pipe means a SnowLuma DLL is resident — even if we did not
// inject it ourselves (e.g. left over from a prior run).
if (!state.injected) {
state.injected = true;
state.method = state.method || 'reconnect';
}
if (state.client?.isClosed) this.tearDownClient(state);
if (!state.connected) {
await this.attemptConnect(state);
} else {
state.status = state.loggedIn ? 'online' : 'loaded';
}
} else {
// Pipe is gone; if we still hold a client, drop it and surface the
// appropriate disconnected/available state to the UI.
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
state.status = state.injected ? 'disconnected' : 'available';
}
} catch (error) {
state.error = error instanceof Error ? error.message : String(error);
state.status = state.injected ? 'disconnected' : 'error';
log.warn('refresh failed: PID=%d err=%s', pid, state.error);
}
return this.toPublicInfo(state);
}
private ensureState(pid: number): HookProcessState {
let state = this.states.get(pid);
if (!state) {
state = {
pid,
name: 'QQ.exe',
path: '',
injected: false,
connected: false,
loggedIn: false,
uin: '0',
status: 'available',
error: '',
method: '',
client: null,
sender: null,
injectResult: null,
bound: false,
};
this.states.set(pid, state);
}
return state;
}
// ───────────────────────────── pipe watcher ──────────────────────────────
private scheduleWatcher(delayMs: number): void {
if (this.disposed) return;
if (this.watcherTimer) {
clearTimeout(this.watcherTimer);
this.watcherTimer = null;
}
this.watcherTimer = setTimeout(() => {
this.watcherTimer = null;
void this.tickWatcher();
}, Math.max(0, delayMs));
}
private async tickWatcher(): Promise<void> {
if (this.disposed) return;
if (this.watcherTicking) {
this.scheduleWatcher(this.watcherIntervalMs);
return;
}
this.watcherTicking = true;
try {
const livePipes = await QqHookClient.listLivePipes();
const processes = listHookProcesses();
const runningSet = new Set(processes.map(p => p.pid));
// Refresh metadata + ensure a state entry exists for each known PID.
for (const proc of processes) {
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
}
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
for (const pid of livePipes) {
if (!runningSet.has(pid)) continue;
const state = this.ensureState(pid);
if (!state.injected) {
state.injected = true;
state.method = state.method || 'reconnect';
if (state.status === 'available') state.status = 'connecting';
log.info('Detected pre-existing SnowLuma pipe in PID=%d', pid);
}
}
const tasks: Promise<unknown>[] = [];
for (const state of [...this.states.values()]) {
const alivePipe = livePipes.has(state.pid);
const aliveProc = runningSet.has(state.pid);
if (!aliveProc) {
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(state.pid);
this.states.delete(state.pid);
continue;
}
// Pipe vanished but we still hold a client → schedule a teardown.
if (state.connected && !alivePipe) {
tasks.push(this.serialize(state.pid, async () => this.reconcileLostPipe(state.pid))
.catch(err => log.warn('watcher teardown failed: PID=%d err=%s', state.pid, this.errMsg(err))));
continue;
}
// Injected & pipe up but not connected → schedule a connect.
if (state.injected && !state.connected && alivePipe) {
tasks.push(this.serialize(state.pid, async () => this.reconcileConnect(state.pid))
.catch(err => log.warn('watcher connect failed: PID=%d err=%s', state.pid, this.errMsg(err))));
continue;
}
// Injected but pipe still pending → keep status visible to the UI.
if (state.injected && !state.connected && !alivePipe) {
if (state.status !== 'error' && state.status !== 'disconnected' && state.status !== 'loading') {
state.status = 'connecting';
}
}
}
await Promise.all(tasks);
} finally {
this.watcherTicking = false;
this.scheduleWatcher(this.watcherIntervalMs);
}
}
/** Re-check pipe and connect under the per-PID lock. */
private async reconcileConnect(pid: number): Promise<void> {
const state = this.states.get(pid);
if (!state || !state.injected || state.connected) return;
if (state.client?.isClosed) this.tearDownClient(state);
const live = await QqHookClient.listLivePipes();
if (!live.has(pid)) return;
await this.attemptConnect(state);
}
/** Tear down a client whose pipe disappeared. */
private async reconcileLostPipe(pid: number): Promise<void> {
const state = this.states.get(pid);
if (!state || !state.connected) return;
const live = await QqHookClient.listLivePipes();
if (live.has(pid)) return;
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
state.status = state.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available';
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
}
// ───────────────────────────── client plumbing ───────────────────────────
private async attemptConnect(state: HookProcessState): Promise<void> {
if (state.connected) return;
if (state.client?.isClosed) this.tearDownClient(state);
if (!state.client) {
state.client = new QqHookClient(state.pid);
state.sender = new HookPacketClient(state.client);
state.bound = false;
}
if (!state.bound) {
this.bindClient(state, state.client);
state.bound = true;
}
const client = state.client;
try {
await client.connectAll({ recv: true });
state.connected = true;
state.status = client.isLoggedIn ? 'online' : 'loaded';
state.error = '';
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(state, loginState);
log.info('pipe connected: PID=%d', state.pid);
} catch (error) {
state.error = this.errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient(state);
state.status = state.injected ? 'connecting' : 'available';
}
}
private bindClient(state: HookProcessState, client: QqHookClient): void {
client.on('packet', packet => this.handlePacket(state, packet));
client.on('loginState', loginState => this.handleLoginState(state, loginState));
client.on('error', error => {
const msg = this.errMsg(error);
state.error = msg;
log.warn('pipe error: PID=%d err=%s', state.pid, msg);
});
client.on('close', () => {
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) return;
// Only the client that is currently registered should drive a reconcile;
// listeners may fire for an already-replaced client.
if (state.client !== client) return;
void this.serialize(state.pid, async () => {
if (state.client !== client) return;
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (!state.injected) {
state.status = 'available';
} else if (wasLoggedIn) {
state.status = 'disconnected';
this.bridgeManager.onPidDisconnected(state.pid);
} else {
state.status = 'connecting';
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery) {
void session.load().catch((err) => {
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
});
}
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.onPipeUp();
});
this.pipeWatcher.on('pipe-down', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.onPipeDown();
});
// After every tick, retry sessions that are stuck in 'connecting'
// while the pipe is up. Mirrors the original tickWatcher's per-tick
// reconcileConnect pass; onPipeUp is idempotent so calling it for an
// already-connected session is harmless.
this.pipeWatcher.on('tick', () => {
if (this.disposed) return;
for (const session of this.sessions.values()) {
if (session.status === 'connecting' && this.pipeWatcher.isPipeLive(session.pid)) {
session.onPipeUp();
}
}).catch(err => log.warn('close reconcile failed: PID=%d err=%s', state.pid, this.errMsg(err)));
}
});
}
/** Detach + close the current client and reset its associated fields. */
private tearDownClient(state: HookProcessState): void {
const client = state.client;
if (client) {
client.removeAllListeners();
try { client.close(); } catch { /* ignore */ }
}
state.client = null;
state.sender = null;
state.bound = false;
state.connected = false;
state.loggedIn = false;
private ensureSession(pid: number): HookSession {
let session = this.sessions.get(pid);
if (session) return session;
session = new HookSession(pid, {
injector: this.injector,
makeClient: this.makeClient,
pipeWatcher: this.pipeWatcher,
onPacket: this.onPacket,
log: this.log,
});
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
this.bridgeManager.onHookLogin(pid, uin, sender);
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
});
session.on('disposed', () => {
this.sessions.delete(pid);
});
this.sessions.set(pid, session);
return session;
}
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
const wasLoggedIn = state.loggedIn;
const previousUin = state.uin;
state.uin = loginState.uin || loginState.uinNumber.toString();
state.loggedIn = loginState.loggedIn && isRealUin(state.uin);
state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status);
if (!state.loggedIn || !state.sender) return;
if (wasLoggedIn && previousUin === state.uin) return;
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
}
private handlePacket(state: HookProcessState, packet: QqHookPacket): void {
if (!state.loggedIn) return;
const uin = packet.uin || state.uin;
if (!isRealUin(uin)) return;
this.ntqq.onHookPacket(state.pid, { ...packet, uin });
}
private toPublicInfo(state: HookProcessState): HookProcessInfo {
return {
pid: state.pid,
name: state.name,
path: state.path,
injected: state.injected,
connected: state.connected,
loggedIn: state.loggedIn,
uin: state.uin,
status: state.status,
error: state.error,
method: state.method,
};
}
private errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
private assertValidPid(pid: number): void {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+431
View File
@@ -0,0 +1,431 @@
import { EventEmitter } from 'events';
import type { PacketSender } from '../protocol/packet-sender';
import type { PacketSink } from '../protocol/types';
import { createLogger, type Logger } from '../utils/logger';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import type { HookProcessInfo, HookProcessStatus } from './types';
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. */
pipeWatcher: { isPipeLive: (pid: number) => boolean };
/** Sink for parsed packets. Called with the BridgeManager-shaped
* PacketInfo for every packet received while logged in. If omitted,
* packets are dropped (useful in unit tests that don't care). */
onPacket?: PacketSink;
log?: Logger;
};
/**
* HookSession — owns the lifecycle of one QQ.exe process: injection,
* pipe client, login state, and the public status field.
*
* Concurrency: every state-mutating method goes through a per-session
* promise chain so user clicks (load/unload/refresh) and watcher-driven
* events (onPipeUp/onPipeDown) never interleave.
*
* Communication: emits high-level events instead of calling BridgeManager
* directly, so HookManager forwards them and tests can attach spies.
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
*/
export class HookSession extends EventEmitter {
readonly pid: number;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
private _status: HookProcessStatus = 'available';
private _error = '';
private _uin = '0';
private _method = '';
private _name = '';
private _path = '';
private injected = false;
private connected = false;
private loggedIn = false;
private injectResult: HookInjectResult | null = null;
private client: QqHookClient | null = null;
private sender: HookPacketClient | null = null;
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
}
// ─────────────── readonly public surface ───────────────
get status(): HookProcessStatus { return this._status; }
get error(): string { return this._error; }
get uin(): string { return this._uin; }
get method(): string { return this._method; }
get isDisposed(): boolean { return this.disposed; }
attachProcessInfo(info: { name?: string; path?: string }): void {
if (info.name) this._name = info.name;
if (info.path) this._path = info.path;
}
toInfo(): HookProcessInfo {
return {
pid: this.pid,
name: this._name,
path: this._path,
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
uin: this._uin,
status: this._status,
error: this._error,
method: this._method,
};
}
// ─────────────── user-facing commands ───────────────
load(): Promise<HookProcessInfo> {
return this.serialize(() => this.loadInternal());
}
unload(): Promise<HookProcessInfo> {
return this.serialize(() => this.unloadInternal());
}
refresh(): Promise<HookProcessInfo> {
return this.serialize(() => this.refreshInternal());
}
// ─────────────── watcher-driven events (called by manager) ───────────────
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
* every watcher tick where the pipe is live. */
onPipeUp(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
// Adopt a DLL that survived a SnowLuma restart.
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}
onPipeDown(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
if (!this.connected) {
// Nothing to tear down; just keep status visible.
if (this.injected) this.setStatus('connecting', this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
'',
);
if (wasLoggedIn) this.emit('disconnected', true);
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}
/** Called by the manager when the watcher reports the QQ.exe process is
* gone. Cleans up and signals the manager to remove this session. */
notifyProcessGone(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.removeAllListeners();
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.tearDownClient();
this.removeAllListeners();
}
// ─────────────── per-session serialization ───────────────
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
this.opChain = previous.then(() => completion);
return (async () => {
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
}
})();
}
// ─────────────── internal transitions ───────────────
private async loadInternal(): Promise<HookProcessInfo> {
this._error = '';
this.setStatus('loading', '');
try {
if (!this.injected) {
// Fast path: a previous SnowLuma run may have left the hook DLL
// resident in QQ.exe. If the watcher already sees a live pipe,
// skip re-injection and let onPipeUp drive the reconnect.
if (this.pipeWatcher.isPipeLive(this.pid)) {
this.injected = true;
this._method = this._method || 'reconnect';
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
} else {
this.injectResult = this.injector.inject(this.pid);
this.injected = true;
this._method = this.injectResult.method;
}
}
this.setStatus(
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
'',
);
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async unloadInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (wasLoggedIn) this.emit('disconnected', true);
const handle = this.injectResult?.handle;
if (this.injected && handle) {
this.injector.unload(this.pid, handle);
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
}
this.injected = false;
this.injectResult = null;
this._method = '';
this._uin = '0';
// Verify the unload took: if the pipe is still up the DLL is still
// resident. Drop back to 'connecting' and let the watcher reconnect.
if (this.pipeWatcher.isPipeLive(this.pid)) {
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
this.setStatus('connecting', this._error);
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
} else {
this.setStatus('available', '');
}
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async refreshInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
if (pipeUp) {
// Adopt an unknown DLL the same way onPipeUp would.
if (!this.injected) {
this.injected = true;
this._method = this._method || 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
} else {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(this.injected ? 'disconnected' : 'available', '');
if (wasLoggedIn) this.emit('disconnected', true);
}
} catch (error) {
this._error = errMsg(error);
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) return;
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.bound = false;
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(loginState);
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient();
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
}
}
private bindClient(client: QqHookClient): void {
client.on('packet', packet => this.handlePacket(packet));
client.on('loginState', state => this.handleLoginState(state));
client.on('error', error => {
const msg = errMsg(error);
this._error = msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
client.on('close', () => {
if (this.disposed) return;
// Only the currently-registered client should drive a reconcile;
// listeners may fire for an already-replaced client.
if (this.client !== client) return;
void this.serialize(async () => {
if (this.disposed) return;
if (this.client !== client) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (!this.injected) {
this.setStatus('available', '');
} else if (wasLoggedIn) {
this.setStatus('disconnected', '');
} else {
this.setStatus('connecting', '');
}
if (wasLoggedIn) this.emit('disconnected', true);
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
});
}
private tearDownClient(): void {
const client = this.client;
if (client) {
client.removeAllListeners();
try { client.close(); } catch { /* ignore */ }
}
this.client = null;
this.sender = null;
this.bound = false;
this.connected = false;
this.loggedIn = false;
}
private handleLoginState(state: QqHookLoginState): void {
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
if (this.loggedIn) {
this.setStatus('online', '');
} else if (this.connected) {
this.setStatus('loaded', this._error);
}
if (!this.loggedIn || !this.sender) return;
if (wasLoggedIn && previousUin === this._uin) return;
this.emit('login', this._uin, this.sender);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
if (!isRealUin(uin)) return;
if (!this.onPacket) return;
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
// renaming was that module's entire purpose, so it lives at the source
// now (no need for a single-listener event-emitter in between).
this.onPacket({
pid: this.pid,
uin,
serviceCmd: packet.cmd,
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
body: Buffer.from(packet.body),
});
}
private setStatus(status: HookProcessStatus, error: string): void {
if (this._status === status && this._error === error) return;
this._status = status;
this._error = error;
this.emit('status-changed', status, error);
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+208
View File
@@ -0,0 +1,208 @@
import { EventEmitter } from 'events';
import { createLogger, type Logger } from '../utils/logger';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. */
listProcesses: () => HookProcessBaseInfo[];
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
};
/**
* PipeWatcher — the only module that polls the OS for QQ.exe processes
* and live SnowLuma named pipes. Subscribers consume diffs as events.
*
* Lifecycle: start() runs one tick synchronously, then schedules a poll
* every `intervalMs`. tickNow() drains a single tick on demand. wake()
* pulls the next scheduled tick forward to the next event-loop turn.
*
* Emitted events:
* 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared
* 'process-gone' (pid: number) — a QQ.exe disappeared
* 'pipe-up' (pid: number) — named pipe came up
* 'pipe-down' (pid: number) — named pipe dropped
* 'tick' () — fired after every poll
*
* Within a single tick the order is: process-discovered, pipe-up,
* pipe-down, process-gone, tick. That ordering lets HookManager create
* a session before it gets a pipe event and run disconnect logic before
* dispose logic when QQ.exe is killed with a live pipe.
*/
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
constructor(deps: PipeWatcherDeps) {
super();
this.listProcesses = deps.listProcesses;
this.listLivePipes = deps.listLivePipes;
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
if (this.startPromise) return this.startPromise;
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
}
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) return;
this.scheduleNext(0);
}
/** Force a single tick now. Resolves after diff events have been emitted. */
tickNow(): Promise<void> {
return this.tickOnce();
}
stop(): void {
this.stopped = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
dispose(): void {
this.stop();
this.removeAllListeners();
}
private scheduleNext(delayMs: number): void {
if (this.stopped) return;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, Math.max(0, delayMs));
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
return;
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
}
let livePipes: Set<number>;
try {
livePipes = await this.listLivePipes();
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = new Set();
}
const newKnownPids = new Set<number>();
for (const proc of processes) newKnownPids.add(proc.pid);
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => { void this.tickOnce(); });
}
}
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+27
View File
@@ -0,0 +1,27 @@
import type { HookProcessBaseInfo } from './injector';
/**
* Lifecycle status of a single per-PID HookSession.
*
* Transitions live inside HookSession; this union only enumerates the
* states visible to API callers (WebUI, manager.listProcesses()).
*/
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
/** Public-facing snapshot of a per-PID HookSession. */
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
}
+21 -5
View File
@@ -1,4 +1,3 @@
import { NtqqHandler } from './protocol/ntqq-handler';
import { BridgeManager } from './bridge/manager';
import { OneBotManager } from './onebot/manager';
import { loadRuntimeConfig } from './common/runtime';
@@ -11,13 +10,20 @@ const log = createLogger('App');
async function main() {
log.info('SnowLuma starting');
const ntqq = new NtqqHandler();
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const hookManager = new HookManager(ntqq, bridgeManager);
// HookManager defaults its packet sink to bridgeManager.onPacket, so
// every parsed hook packet reaches the per-UIN bridge dispatcher with
// no intermediate layer.
// Env var SNOWLUMA_HOOK_AUTOLOAD wins over runtime.json so Docker /
// headless deployments can flip auto-injection on without touching the
// persisted user config volume.
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
if (autoLoadOnDiscovery) {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
// Bind bridge manager to NTQQ handler (receives all parsed packets)
bridgeManager.bind(ntqq);
oneBotManager.bind(bridgeManager);
if (
@@ -41,6 +47,16 @@ async function main() {
});
}
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
if (typeof envRaw === 'string' && envRaw.trim()) {
const v = envRaw.trim().toLowerCase();
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true;
if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false;
}
return fromConfig === true;
}
main().catch((error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
process.exit(1);
+22 -88
View File
@@ -9,7 +9,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const times = asNumber(params.times) || 1;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.sendLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendLike(userId, times);
return okResponse();
});
@@ -18,7 +17,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const targetId = asNumber(params.target_id) || undefined;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendFriendPoke(userId, targetId);
return okResponse();
});
@@ -27,7 +25,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendGroupPoke(groupId, userId);
return okResponse();
});
@@ -37,10 +34,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (groupId) {
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendGroupPoke(groupId, userId);
} else {
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendFriendPoke(userId);
}
return okResponse();
@@ -53,7 +48,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
if (!ctx.setEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setEssenceMsg(messageId);
return okResponse();
});
@@ -63,7 +57,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
if (!ctx.deleteEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.deleteEssenceMsg(messageId);
return okResponse();
});
@@ -72,9 +65,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.getGroupEssenceAll) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const essenceDataAll = await ctx.getGroupEssenceAll(groupId);
@@ -108,7 +98,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
if (!ctx.setGroupReaction) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
return okResponse();
});
@@ -120,7 +109,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const messageId = asNumber(params.message_id) || 0;
const count = asNumber(params.count) || 20;
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.getGroupMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const messages = await ctx.getGroupMsgHistory(groupId, messageId, count);
return okResponse({ messages });
});
@@ -130,7 +118,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const messageId = asNumber(params.message_id) || 0;
const count = asNumber(params.count) || 20;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.getFriendMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const messages = await ctx.getFriendMsgHistory(userId, messageId, count);
return okResponse({ messages });
});
@@ -153,7 +140,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
if (!ctx.markGroupMsgAsRead) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.markGroupMsgAsRead(groupId, meta.sequence);
return okResponse();
@@ -177,7 +163,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
}
if (!ctx.markPrivateMsgAsRead) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.markPrivateMsgAsRead(userId, meta.sequence);
return okResponse();
@@ -198,8 +183,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session');
}
if (!(ctx.markPrivateMsgAsRead && ctx.markGroupMsgAsRead)) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
if (meta.isGroup) {
await ctx.markGroupMsgAsRead(targetId, meta.sequence);
} else {
@@ -239,9 +222,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required');
}
if (!ctx.sendGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const options = {
@@ -262,9 +242,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.getGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const notices = await ctx.getGroupNotice(groupId);
@@ -282,9 +259,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required');
}
if (!ctx.deleteGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const success = await ctx.deleteGroupNotice(groupId, fid);
@@ -304,7 +278,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const messages = asMessage(params.messages ?? params.message);
const groupId = asNumber(params.group_id);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendForwardMsg(messages);
const data: Record<string, unknown> = {
@@ -319,7 +292,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('upload_foward_msg', async (params) => {
const messages = asMessage(params.messages ?? params.message);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendForwardMsg(messages);
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
});
@@ -344,7 +316,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
}
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendForwardMsg(messages);
return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId });
});
@@ -354,7 +325,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const messages = asMessage(params.messages ?? params.message);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendGroupForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendGroupForwardMsg(groupId, messages);
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
@@ -365,7 +335,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const messages = asMessage(params.messages ?? params.message);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendPrivateForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendPrivateForwardMsg(userId, messages);
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
@@ -400,7 +369,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
if (!ctx.getForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const messages = await ctx.getForwardMsg(id);
return okResponse({ messages });
@@ -411,7 +379,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_image', async (params) => {
const file = asString(params.file) || asString(params.file_id);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
if (!ctx.getImageInfo) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const info = await ctx.getImageInfo(file);
if (info) return okResponse(info);
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
@@ -420,7 +387,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_record', async (params) => {
const file = asString(params.file) || asString(params.file_id);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
if (!ctx.getRecordInfo) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const info = await ctx.getRecordInfo(file);
if (info) return okResponse(info);
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
@@ -431,7 +397,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_cookies', async (params) => {
const domain = asString(params.domain) || 'qun.qq.com';
if (!ctx.getCookiesStr) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
try {
const cookies = await ctx.getCookiesStr(domain);
@@ -442,7 +407,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
h.registerAction('get_csrf_token', async () => {
if (!ctx.getCsrfToken) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
try {
const token = await ctx.getCsrfToken();
@@ -455,7 +419,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_credentials', async (params) => {
const domain = asString(params.domain) || 'qun.qq.com';
if (!ctx.getCredentials) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
try {
const creds = await ctx.getCredentials(domain);
@@ -489,7 +452,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const remark = asString(params.remark) ?? '';
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.setFriendRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setFriendRemark(userId, remark);
return okResponse();
});
@@ -498,7 +460,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const remark = asString(params.remark) ?? '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupRemark(groupId, remark);
return okResponse();
});
@@ -510,7 +471,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
}
if (!ctx.setMsgEmojiLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setMsgEmojiLike(messageId, emojiId, set);
return okResponse();
});
@@ -580,9 +540,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const nickname = params.nickname !== undefined ? asString(params.nickname) : undefined;
const personalNote = params.personal_note !== undefined ? asString(params.personal_note) : undefined;
if (!ctx.setProfile) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setProfile(nickname, personalNote);
@@ -603,9 +560,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'status is required');
}
if (!ctx.setOnlineStatus) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setOnlineStatus(status, extStatus, batteryStatus);
@@ -623,12 +577,30 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse([]);
});
h.registerAction('forward_friend_single_msg', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('forward_friend_single_msg', async (params) => {
const messageId = asNumber(params.message_id);
const userId = asNumber(params.user_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
try {
const result = await ctx.forwardSingleMsg(messageId, { userId });
return okResponse({ message_id: result.messageId });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
h.registerAction('forward_group_single_msg', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('forward_group_single_msg', async (params) => {
const messageId = asNumber(params.message_id);
const groupId = asNumber(params.group_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
try {
const result = await ctx.forwardSingleMsg(messageId, { groupId });
return okResponse({ message_id: result.messageId });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
// todo 我的建议是引入数据库api 纯协议我不知道这种api怎么实现,ntQQ在实现这个方法的时候只进行了数据库查询,完全没碰网络
@@ -641,9 +613,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const start = asNumber(params.start) || 0;
const count = asNumber(params.count) || 10;
if (!ctx.getProfileLike) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getProfileLike(userId, start, count);
@@ -655,9 +624,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('fetch_custom_face', async (params) => {
const count = asNumber(params.count) || 10;
if (!ctx.fetchCustomFace) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const urls = await ctx.fetchCustomFace(count);
return okResponse(urls);
@@ -670,7 +636,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const messageId = asNumber(params.message_id);
const emojiId = asString(params.emoji_id) || '';
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
if (!ctx.getEmojiLikes) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
@@ -688,7 +653,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const count = asNumber(params.count) || 10;
const cookie = asString(params.cookie) || '';
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required');
if (!ctx.getEmojiLikes) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
@@ -739,9 +703,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
if (!ctx.getGroupAtAllRemain) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getGroupAtAllRemain(groupId);
@@ -752,9 +713,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
h.registerAction('get_unidirectional_friend_list', async () => {
if (!ctx.getUnidirectionalFriendList) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getUnidirectionalFriendList();
@@ -771,9 +729,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
}
if (!ctx.setSelfLongNick) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setSelfLongNick(longNick);
@@ -795,9 +750,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const file = asString(params.file);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
if (!ctx.setAvatar) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setAvatar(file);
@@ -820,9 +772,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type');
}
if (!ctx.setInputStatus) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setInputStatus(userId, eventType);
@@ -841,9 +790,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const words = rawWords.map(w => String(w));
if (!ctx.translateEn2Zh) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const translated = await ctx.translateEn2Zh(words);
@@ -854,9 +800,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
h.registerAction('get_clientkey', async () => {
if (!ctx.forceFetchClientKey) {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
}
const clientKeyInfo = await ctx.forceFetchClientKey();
if (!clientKeyInfo.clientKey) {
return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error');
@@ -871,9 +814,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const picUrl = params.picUrl || params.pic_url || '';
const jumpUrl = params.jumpUrl || params.jump_url || '';
if (!ctx.getMiniAppArk) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getMiniAppArk(
@@ -900,9 +840,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters');
}
if (!ctx.clickInlineKeyboardButton) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.clickInlineKeyboardButton(
@@ -925,9 +862,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
if (!ctx.sendGroupSign) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.sendGroupSign(groupId);
@@ -24,7 +24,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const block = asBoolean(params.block, false);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.handleDeleteFriend) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.handleDeleteFriend(userId, block);
return okResponse();
});
@@ -8,7 +8,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupKick) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupKick(groupId, userId, reject);
return okResponse();
});
@@ -18,7 +17,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
if (!ctx.setGroupKickMembers) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupKickMembers(groupId, userIds, reject);
return okResponse();
});
@@ -28,7 +26,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const duration = asNumber(params.duration) || 1800;
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupBan(groupId, userId, duration);
return okResponse();
});
@@ -37,7 +34,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const enable = asBoolean(params.enable, true);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupWholeBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupWholeBan(groupId, enable);
return okResponse();
});
@@ -46,7 +42,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
if (!ctx.setGroupAddOption) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupAddOption(groupId, addType);
return okResponse();
});
@@ -54,7 +49,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupSearch) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupSearch(groupId);
return okResponse();
});
@@ -64,7 +58,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupAdmin) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupAdmin(groupId, userId, enable);
return okResponse();
});
@@ -74,7 +67,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupCard) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupCard(groupId, userId, card);
return okResponse();
});
@@ -83,7 +75,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupName) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupName(groupId, name);
return okResponse();
});
@@ -91,7 +82,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_group_leave', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupLeave) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupLeave(groupId);
return okResponse();
});
@@ -101,7 +91,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupSpecialTitle) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupSpecialTitle(groupId, userId, title);
return okResponse();
});
@@ -11,7 +11,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
const uploadFile = asBoolean(params.upload_file, true);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
if (!ctx.uploadGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile);
return okResponse({ file_id: fileId });
});
@@ -22,7 +21,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const name = asString(params.name);
const uploadFile = asBoolean(params.upload_file, true);
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
if (!ctx.uploadPrivateFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile);
return okResponse({ file_id: fileId });
});
@@ -34,7 +32,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
if (!ctx.getGroupFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) });
});
@@ -43,7 +40,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse(await ctx.getGroupFiles(groupId, '/'));
});
@@ -53,7 +49,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse(await ctx.getGroupFiles(groupId, folderId));
});
@@ -63,7 +58,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
if (!ctx.deleteGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.deleteGroupFile(groupId, fileId);
return okResponse();
});
@@ -76,7 +70,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
if (!ctx.moveGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
@@ -88,7 +81,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !name) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
}
if (!ctx.createGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.createGroupFileFolder(groupId, name, parentId);
return okResponse();
});
@@ -99,7 +91,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
if (!ctx.deleteGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.deleteGroupFileFolder(groupId, folderId);
return okResponse();
});
@@ -111,7 +102,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
if (!ctx.renameGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.renameGroupFileFolder(groupId, folderId, newName);
return okResponse();
});
@@ -123,7 +113,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!userId || !fileId || !fileHash) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
}
if (!ctx.getPrivateFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
});
}
@@ -61,9 +61,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.getGroupHonorInfo) {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
}
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
@@ -18,9 +18,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.sendGroupMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
}
@@ -29,9 +26,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
if (!ctx.sendPrivateMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
@@ -47,9 +41,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (!ctx.sendPrivateMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
@@ -66,9 +57,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (!ctx.sendGroupMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
@@ -97,9 +85,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
if (!ctx.deleteMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'delete_msg is not implemented');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) {
@@ -7,7 +7,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const flag = asString(params.flag);
const approve = asBoolean(params.approve, true);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
if (!ctx.handleFriendRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.handleFriendRequest(flag, approve);
return okResponse();
});
@@ -18,7 +17,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const approve = asBoolean(params.approve, true);
const reason = asString(params.reason);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
if (!ctx.handleGroupRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.handleGroupRequest(flag, subType, approve, reason);
return okResponse();
});
+82 -81
View File
@@ -34,98 +34,99 @@ export interface ApiActionContext {
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
sendPrivateMessage?: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
sendGroupMessage?: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
deleteMessage?: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage?: () => boolean;
canSendRecord?: () => boolean;
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage: () => boolean;
canSendRecord: () => boolean;
// Info retrieval (async — triggers OIDB fetch)
getFriendList?: () => Promise<JsonObject[]>;
getGroupList?: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo?: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList?: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo?: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo?: (userId: number) => Promise<JsonObject | null>;
getFriendList: () => Promise<JsonObject[]>;
getGroupList: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo: (userId: number) => Promise<JsonObject | null>;
// Group admin
setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers?: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan?: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan?: (groupId: number, enable: boolean) => Promise<void>;
setGroupAddOption?: (groupId: number, addType: number) => Promise<void>;
setGroupSearch?: (groupId: number) => Promise<void>;
setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise<void>;
setGroupCard?: (groupId: number, userId: number, card: string) => Promise<void>;
setGroupName?: (groupId: number, name: string) => Promise<void>;
setGroupLeave?: (groupId: number) => Promise<void>;
setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise<void>;
getGroupAtAllRemain?: (groupId: number) => Promise<any>;
setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan: (groupId: number, enable: boolean) => Promise<void>;
setGroupAddOption: (groupId: number, addType: number) => Promise<void>;
setGroupSearch: (groupId: number) => Promise<void>;
setGroupAdmin: (groupId: number, userId: number, enable: boolean) => Promise<void>;
setGroupCard: (groupId: number, userId: number, card: string) => Promise<void>;
setGroupName: (groupId: number, name: string) => Promise<void>;
setGroupLeave: (groupId: number) => Promise<void>;
setGroupSpecialTitle: (groupId: number, userId: number, title: string) => Promise<void>;
getGroupAtAllRemain: (groupId: number) => Promise<any>;
// Group file
uploadGroupFile?: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile?: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl?: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles?: (groupId: number, folderId?: string) => Promise<JsonObject>;
deleteGroupFile?: (groupId: number, fileId: string) => Promise<void>;
moveGroupFile?: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
createGroupFileFolder?: (groupId: number, name: string, parentId?: string) => Promise<void>;
deleteGroupFileFolder?: (groupId: number, folderId: string) => Promise<void>;
renameGroupFileFolder?: (groupId: number, folderId: string, newName: string) => Promise<void>;
getPrivateFileUrl?: (userId: number, fileId: string, fileHash: string) => Promise<string>;
uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>;
deleteGroupFile: (groupId: number, fileId: string) => Promise<void>;
moveGroupFile: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
createGroupFileFolder: (groupId: number, name: string, parentId?: string) => Promise<void>;
deleteGroupFileFolder: (groupId: number, folderId: string) => Promise<void>;
renameGroupFileFolder: (groupId: number, folderId: string, newName: string) => Promise<void>;
getPrivateFileUrl: (userId: number, fileId: string, fileHash: string) => Promise<string>;
// Requests
handleFriendRequest?: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest?: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
handleFriendRequest: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Extended
sendLike?: (userId: number, times: number) => Promise<void>;
sendFriendPoke?: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke?: (groupId: number, userId: number) => Promise<void>;
setEssenceMsg?: (messageId: number) => Promise<void>;
deleteEssenceMsg?: (messageId: number) => Promise<void>;
forceFetchClientKey? : () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
setOnlineStatus?: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile?: (nickname?: string, personalNote?: string) => Promise<void>;
getUnidirectionalFriendList?: () => Promise<any>;
setSelfLongNick?: (longNick: string) => Promise<void>;
setInputStatus?: (userId: number, eventType: number) => Promise<void>;
translateEn2Zh?: (words: string[]) => Promise<string[]>;
getMiniAppArk?: (type: string, title: string, desc: string, picUrl: string, jumpUrl: string) => Promise<any>;
clickInlineKeyboardButton?: (groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) => Promise<any>;
sendGroupSign?: (groupId: number) => Promise<void>;
sendLike: (userId: number, times: number) => Promise<void>;
sendFriendPoke: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke: (groupId: number, userId: number) => Promise<void>;
setEssenceMsg: (messageId: number) => Promise<void>;
deleteEssenceMsg: (messageId: number) => Promise<void>;
forceFetchClientKey: () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
getUnidirectionalFriendList: () => Promise<any>;
setSelfLongNick: (longNick: string) => Promise<void>;
setInputStatus: (userId: number, eventType: number) => Promise<void>;
translateEn2Zh: (words: string[]) => Promise<string[]>;
getMiniAppArk: (type: string, title: string, desc: string, picUrl: string, jumpUrl: string) => Promise<any>;
clickInlineKeyboardButton: (groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) => Promise<any>;
sendGroupSign: (groupId: number) => Promise<void>;
// New context methods
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
getGroupMsgHistory?: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory?: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg?: () => Promise<JsonObject[]>;
getDownloadRKeys?: () => Promise<JsonObject[]>;
setGroupReaction: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>;
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
getDownloadRKeys: () => Promise<JsonObject[]>;
// Forward message
sendGroupForwardMsg?: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg?: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg?: (messages: JsonValue) => Promise<{ forwardId: string }>;
getForwardMsg?: (resId: string) => Promise<JsonObject[]>;
sendGroupForwardMsg: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
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>;
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 }>;
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>;
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 }>;
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)
getImageInfo?: (file: string) => Promise<JsonObject | null>;
getRecordInfo?: (file: string) => Promise<JsonObject | null>;
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
// Avatar
setAvatar?: (source: string) => Promise<void>;
setAvatar: (source: string) => Promise<void>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
-542
View File
@@ -1,542 +0,0 @@
import type { MessageElement, QQEventVariant } from '../bridge/events';
import type { JsonArray, JsonObject } from './types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id';
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
/**
* Side-channel callback invoked every time an image/record segment is
* produced, so that callers can keep a lookup index (e.g. for `get_image` /
* `get_record`) without having to re-scan the persisted message store.
*/
export type MediaSegmentSink = (
mediaType: 'image' | 'record',
element: MessageElement,
data: JsonObject,
isGroup: boolean,
sessionId: number,
) => void;
export class EventConverter {
private imageUrlResolver_: ImageUrlResolver | null = null;
private mediaUrlResolver_: MediaUrlResolver | null = null;
private messageIdResolver_: MessageIdResolver | null = null;
private mediaSegmentSink_: MediaSegmentSink | null = null;
setImageUrlResolver(resolver: ImageUrlResolver): void {
this.imageUrlResolver_ = resolver;
}
setMediaUrlResolver(resolver: MediaUrlResolver): void {
this.mediaUrlResolver_ = resolver;
}
setMessageIdResolver(resolver: MessageIdResolver): void {
this.messageIdResolver_ = resolver;
}
setMediaSegmentSink(sink: MediaSegmentSink): void {
this.mediaSegmentSink_ = sink;
}
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
const selfId = parseSelfId(instanceUin);
switch (event.kind) {
case 'friend_message':
{
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
return {
time: event.time,
self_id: selfId,
post_type: postType,
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
case 'group_message':
{
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
return {
time: event.time,
self_id: selfId,
post_type: postType,
message_type: 'group',
sub_type: 'normal',
message_id: messageId,
message_seq: event.msgSeq,
group_id: event.groupId,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
card: event.senderCard,
role: event.senderRole || 'member',
sex: 'unknown',
age: 0,
},
anonymous: null,
};
}
case 'temp_message':
{
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
return {
time: event.time,
self_id: selfId,
post_type: postType,
message_type: 'private',
sub_type: 'group',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
case 'group_member_join':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_increase',
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
case 'group_member_leave':
{
let subType: string;
if (event.isKick) {
subType = event.userUin === parseSelfId(instanceUin) ? 'kick_me' : 'kick';
} else {
subType = 'leave';
}
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_decrease',
sub_type: subType,
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
}
case 'group_mute':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_ban',
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
duration: event.duration,
};
case 'group_admin':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_admin',
sub_type: event.set ? 'set' : 'unset',
group_id: event.groupId,
user_id: event.userUin,
};
case 'friend_recall':
{
const messageId = this.resolveMessageId(false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'friend_recall',
user_id: event.userUin,
message_id: messageId,
};
}
case 'group_recall':
{
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_recall',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.authorUin,
message_id: messageId,
};
}
case 'friend_request':
return {
time: event.time,
self_id: selfId,
post_type: 'request',
request_type: 'friend',
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
case 'group_invite':
return {
time: event.time,
self_id: selfId,
post_type: 'request',
request_type: 'group',
sub_type: event.subType || 'invite',
group_id: event.groupId,
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
case 'friend_poke':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
case 'group_poke':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
group_id: event.groupId,
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
case 'group_essence':
{
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'essence',
sub_type: event.set ? 'add' : 'delete',
group_id: event.groupId,
user_id: event.senderUin,
sender_id: event.senderUin,
operator_id: event.operatorUin,
message_id: messageId,
message_seq: event.msgSeq,
random: event.random,
};
}
case 'group_file_upload':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_upload',
group_id: event.groupId,
user_id: event.userUin,
file: {
id: event.fileId,
name: event.fileName,
size: event.fileSize,
busid: event.busId,
},
};
case 'friend_add':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'friend_add',
user_id: event.userUin,
};
default:
return null;
}
}
private resolveMessageId(isGroup: boolean, sessionId: number, sequence: number, eventName: string): number {
if (this.messageIdResolver_) {
const resolved = this.messageIdResolver_(isGroup, sessionId, sequence, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
const seq = Math.trunc(sequence);
return seq === 0 ? 0 : seq;
}
}
function parseSelfId(instanceUin: string): number {
const parsed = Number.parseInt(instanceUin, 10);
return Number.isNaN(parsed) ? 0 : parsed;
}
function isSameActor(leftUin: number, leftUid: string | undefined, rightUin: number, rightUid: string | undefined): boolean {
if (leftUin > 0 && rightUin > 0) return leftUin === rightUin;
return Boolean(leftUid) && leftUid === rightUid;
}
async function elementsToJson(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSink?: MediaSegmentSink | null,
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver, mediaSink));
}
return result;
}
export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSink?: MediaSegmentSink | null,
): Promise<JsonArray> {
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver, mediaSink);
}
async function elementToSegment(
element: MessageElement,
isGroup: boolean,
sessionId: number,
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSink?: MediaSegmentSink | null,
): Promise<JsonObject> {
if (element.type === 'text') {
return { type: 'text', data: { text: element.text ?? '' } };
}
if (element.type === 'face') {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
}
if (element.type === 'image') {
const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
const data: JsonObject = {
url,
file: element.fileId ?? '',
};
if (mediaSink) mediaSink('image', element, data, isGroup, sessionId);
return { type: 'image', data };
}
if (element.type === 'at') {
const qq = (element.uid === 'all' || element.targetUin === 0)
? 'all'
: String(element.targetUin ?? 0);
return { type: 'at', data: { qq } };
}
if (element.type === 'reply') {
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
return { type: 'reply', data: { id: String(id) } };
}
if (element.type === 'record') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSink) mediaSink('record', element, data, isGroup, sessionId);
return { type: 'record', data };
}
if (element.type === 'video') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'video',
data: {
file: element.fileName ?? element.fileId ?? '',
url,
},
};
}
if (element.type === 'json') {
return { type: 'json', data: { data: element.text ?? '' } };
}
if (element.type === 'xml') {
return {
type: 'xml',
data: {
data: element.text ?? '',
resid: element.subType ?? 35,
},
};
}
if (element.type === 'file') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'file',
data: {
name: element.fileName ?? '',
size: element.fileSize ?? 0,
id: element.fileId ?? '',
url,
file_hash: element.fileHash ?? '',
},
};
}
if (element.type === 'mface') {
return {
type: 'mface',
data: {
name: element.text ?? '',
tab_id: element.faceId ?? 0,
sub_type: element.subType ?? 0,
},
};
}
if (element.type === 'poke') {
return {
type: 'poke',
data: {
type: element.subType ?? 0,
},
};
}
if (!isGroup && element.type === 'at') {
return { type: 'text', data: { text: element.text ?? '' } };
}
return { type: element.type, data: {} };
}
// --- CQ code raw_message generation (from already-resolved JSON segments) ---
function cqEscape(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;').replace(/,/g, '&#44;');
}
function segmentsToRawMessage(segments: JsonArray): string {
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
}
function segmentToCQ(seg: JsonObject): string {
const type = String(seg.type ?? '');
const data = (seg.data ?? {}) as Record<string, unknown>;
switch (type) {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
return `[CQ:at,qq=${data.qq ?? ''}]`;
case 'reply':
return `[CQ:reply,id=${data.id ?? 0}]`;
case 'record':
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'video':
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'json':
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
case 'xml':
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
case 'forward':
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
case 'mface':
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
case 'poke':
return `[CQ:poke,type=${data.type ?? 0}]`;
case 'file':
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
default:
return `[CQ:${type}]`;
}
}
function resolveReplyId(
isGroup: boolean,
sessionId: number,
sequence: number,
resolver?: MessageIdResolver | null,
): number {
const seq = Math.trunc(sequence);
if (seq === 0) return 0;
if (resolver) {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const resolved = resolver(isGroup, sessionId, seq, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
return seq;
}
@@ -0,0 +1,133 @@
// Bridge event -> OneBot top-level event conversion.
//
// Replaces the old `EventConverter` class. The class held four
// resolver fields (image-url / media-url / message-id / media-segment
// sink) wired in lazily via setters; the new shape passes them as a
// `ConverterContext` object so each case is a pure function and the
// per-case test setup is two lines, not a class instance plus four
// setter calls.
import type { MessageElement, QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import {
convertFriendMessage,
convertGroupMessage,
convertTempMessage,
} from './to-message';
import {
convertFriendAdd,
convertFriendPoke,
convertFriendRecall,
convertGroupAdmin,
convertGroupEssence,
convertGroupFileUpload,
convertGroupMemberJoin,
convertGroupMemberLeave,
convertGroupMute,
convertGroupPoke,
convertGroupRecall,
} from './to-notice';
import {
convertFriendRequest,
convertGroupInvite,
} from './to-request';
import { elementsToJson } from './to-segment';
// ─────────────── resolver callback types ───────────────
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
/**
* Side-channel callback invoked every time an image / record / video
* segment is produced, so callers can keep a lookup index (e.g. for
* `get_image` / `get_record`) without re-scanning the message store.
*/
export type MediaSegmentSink = (
mediaType: 'image' | 'record' | 'video',
element: MessageElement,
data: JsonObject,
isGroup: boolean,
sessionId: number,
) => void;
// ─────────────── context ───────────────
/**
* Everything `convertEvent` needs that isn't on the bridge event itself.
* Built once per OneBotInstance and passed through unchanged. Resolvers
* are nullable because tests routinely omit them; when missing, the
* converter falls back to the bridge event's own fields (e.g. raw
* `element.url`, raw `event.msgSeq`).
*/
export interface ConverterContext {
/** Self uin parsed once into a Number for inclusion in `self_id`. */
selfId: number;
imageUrlResolver: ImageUrlResolver | null;
mediaUrlResolver: MediaUrlResolver | null;
messageIdResolver: MessageIdResolver | null;
mediaSegmentSink: MediaSegmentSink | null;
}
// ─────────────── dispatcher ───────────────
/**
* Convert a bridge `QQEventVariant` to the OneBot wire-shape JSON.
* Returns null for kinds we don't surface (so callers can skip them
* without an explicit allow-list).
*/
export async function convertEvent(
ctx: ConverterContext,
event: QQEventVariant,
): Promise<JsonObject | null> {
switch (event.kind) {
// Messages.
case 'friend_message': return convertFriendMessage(ctx, event);
case 'group_message': return convertGroupMessage(ctx, event);
case 'temp_message': return convertTempMessage(ctx, event);
// Notices.
case 'group_member_join': return convertGroupMemberJoin(ctx, event);
case 'group_member_leave': return convertGroupMemberLeave(ctx, event);
case 'group_mute': return convertGroupMute(ctx, event);
case 'group_admin': return convertGroupAdmin(ctx, event);
case 'friend_recall': return convertFriendRecall(ctx, event);
case 'group_recall': return convertGroupRecall(ctx, event);
case 'friend_poke': return convertFriendPoke(ctx, event);
case 'group_poke': return convertGroupPoke(ctx, event);
case 'group_essence': return convertGroupEssence(ctx, event);
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
case 'friend_add': return convertFriendAdd(ctx, event);
// Requests.
case 'friend_request': return convertFriendRequest(ctx, event);
case 'group_invite': return convertGroupInvite(ctx, event);
default:
return null;
}
}
// ─────────────── side-channel re-export ───────────────
/**
* Element-array -> OneBot segment-array helper. Used by
* `modules/message-actions.ts` for forward-message rebuilding (where
* we already know the elements but want the OneBot segment shape).
* The signature stays backwards-compatible: each resolver is an
* optional positional argument.
*/
export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
imageUrlResolver?: ImageUrlResolver | null,
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
) {
return elementsToJson(
elements, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
);
}
@@ -0,0 +1,112 @@
// Message-kind handlers: friend_message, group_message, temp_message.
// Each takes a ConverterContext (which carries selfId + the four
// resolver/sink callbacks) and the typed bridge event, and returns the
// OneBot top-level event JSON.
import type { QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { ConverterContext } from './index';
import { elementsToJson } from './to-segment';
import { applyMessageIdResolver, segmentsToRawMessage } from './utils';
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type TempMessage = Extract<QQEventVariant, { kind: 'temp_message' }>;
export async function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, false, event.senderUin,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
export async function convertGroupMessage(ctx: ConverterContext, event: GroupMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, true, event.groupId,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'group',
sub_type: 'normal',
message_id: messageId,
message_seq: event.msgSeq,
group_id: event.groupId,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
card: event.senderCard,
role: event.senderRole || 'member',
sex: 'unknown',
age: 0,
},
anonymous: null,
};
}
export async function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, false, event.senderUin,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'private',
sub_type: 'group',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
@@ -0,0 +1,189 @@
// Notice-kind handlers (10 cases). These produce OneBot `notice` events
// with no message body / no element conversion — pure field projections
// from the bridge event into the OneBot wire shape. None of them call
// resolvers except the two recall handlers and group_essence, which
// need a message-id resolution.
import type { QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { ConverterContext } from './index';
import { applyMessageIdResolver, isSameActor } from './utils';
type GroupMemberJoin = Extract<QQEventVariant, { kind: 'group_member_join' }>;
type GroupMemberLeave = Extract<QQEventVariant, { kind: 'group_member_leave' }>;
type GroupMute = Extract<QQEventVariant, { kind: 'group_mute' }>;
type GroupAdmin = Extract<QQEventVariant, { kind: 'group_admin' }>;
type FriendRecall = Extract<QQEventVariant, { kind: 'friend_recall' }>;
type GroupRecall = Extract<QQEventVariant, { kind: 'group_recall' }>;
type FriendPoke = Extract<QQEventVariant, { kind: 'friend_poke' }>;
type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_increase',
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
}
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
let subType: string;
if (event.isKick) {
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
} else {
subType = 'leave';
}
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_decrease',
sub_type: subType,
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
}
export function convertGroupMute(ctx: ConverterContext, event: GroupMute): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_ban',
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
duration: event.duration,
};
}
export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_admin',
sub_type: event.set ? 'set' : 'unset',
group_id: event.groupId,
user_id: event.userUin,
};
}
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'friend_recall',
user_id: event.userUin,
message_id: messageId,
};
}
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_recall',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.authorUin,
message_id: messageId,
};
}
export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
}
export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
group_id: event.groupId,
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
}
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'essence',
sub_type: event.set ? 'add' : 'delete',
group_id: event.groupId,
user_id: event.senderUin,
sender_id: event.senderUin,
operator_id: event.operatorUin,
message_id: messageId,
message_seq: event.msgSeq,
random: event.random,
};
}
export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUpload): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_upload',
group_id: event.groupId,
user_id: event.userUin,
file: {
id: event.fileId,
name: event.fileName,
size: event.fileSize,
busid: event.busId,
},
};
}
export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'friend_add',
user_id: event.userUin,
};
}
@@ -0,0 +1,37 @@
// Request-kind handlers (2 cases). OneBot `request` events for friend
// adds and group invites/joins — both carry the bridge-supplied `flag`
// that the caller later passes back to `set_friend_add_request` /
// `set_group_add_request`.
import type { QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
type FriendRequest = Extract<QQEventVariant, { kind: 'friend_request' }>;
type GroupInvite = Extract<QQEventVariant, { kind: 'group_invite' }>;
export function convertFriendRequest(ctx: ConverterContext, event: FriendRequest): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'request',
request_type: 'friend',
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
}
export function convertGroupInvite(ctx: ConverterContext, event: GroupInvite): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'request',
request_type: 'group',
sub_type: event.subType || 'invite',
group_id: event.groupId,
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
}
@@ -0,0 +1,145 @@
// Per-element converter: 13 element types -> one OneBot message segment.
// Used by message-events (friend/group/temp) for inline elements AND by
// modules/message-actions.ts for forward-message rebuilding (re-exported
// from this module via the index barrel as `elementsToOneBotSegments`).
import type { MessageElement } from '../../bridge/events';
import type { JsonArray, JsonObject } from '../types';
import type {
ImageUrlResolver,
MediaSegmentSink,
MediaUrlResolver,
MessageIdResolver,
} from './index';
import { resolveReplyId } from './utils';
export async function elementsToJson(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
imageUrlResolver?: ImageUrlResolver | null,
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
result.push(await elementToSegment(
element, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
));
}
return result;
}
async function elementToSegment(
element: MessageElement,
isGroup: boolean,
sessionId: number,
imageUrlResolver?: ImageUrlResolver | null,
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
): Promise<JsonObject> {
if (element.type === 'text') {
return { type: 'text', data: { text: element.text ?? '' } };
}
if (element.type === 'face') {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
}
if (element.type === 'image') {
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
const data: JsonObject = {
url,
file: element.fileId ?? '',
};
if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId);
return { type: 'image', data };
}
if (element.type === 'at') {
const qq = (element.uid === 'all' || element.targetUin === 0)
? 'all'
: String(element.targetUin ?? 0);
return { type: 'at', data: { qq } };
}
if (element.type === 'reply') {
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
return { type: 'reply', data: { id: String(id) } };
}
if (element.type === 'record') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSegmentSink) mediaSegmentSink('record', element, data, isGroup, sessionId);
return { type: 'record', data };
}
if (element.type === 'video') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSegmentSink) mediaSegmentSink('video', element, data, isGroup, sessionId);
return { type: 'video', data };
}
if (element.type === 'json') {
return { type: 'json', data: { data: element.text ?? '' } };
}
if (element.type === 'xml') {
return {
type: 'xml',
data: {
data: element.text ?? '',
resid: element.subType ?? 35,
},
};
}
if (element.type === 'file') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'file',
data: {
name: element.fileName ?? '',
size: element.fileSize ?? 0,
id: element.fileId ?? '',
url,
file_hash: element.fileHash ?? '',
},
};
}
if (element.type === 'mface') {
return {
type: 'mface',
data: {
name: element.text ?? '',
tab_id: element.faceId ?? 0,
sub_type: element.subType ?? 0,
},
};
}
if (element.type === 'poke') {
return {
type: 'poke',
data: {
type: element.subType ?? 0,
},
};
}
// Unknown / unmapped element type — emit an empty segment to keep the
// outgoing message length consistent with the bridge event.
return { type: element.type, data: {} };
}
@@ -0,0 +1,111 @@
// Pure helpers shared across the per-post_type converter modules.
//
// Nothing here touches I/O or class state; everything is a small
// function so the per-event tests can import what they need without
// dragging in resolver wiring.
import type { JsonArray, JsonObject } from '../types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { MessageIdResolver } from './index';
export function parseSelfId(instanceUin: string): number {
const parsed = Number.parseInt(instanceUin, 10);
return Number.isNaN(parsed) ? 0 : parsed;
}
/**
* Two QQEvent actors are "the same" when their uins match, or their
* uids match when uins aren't available. Used by the group_member_join
* sub-type calculation (self-approve vs. invite).
*/
export function isSameActor(
leftUin: number,
leftUid: string | undefined,
rightUin: number,
rightUid: string | undefined,
): boolean {
if (leftUin > 0 && rightUin > 0) return leftUin === rightUin;
return Boolean(leftUid) && leftUid === rightUid;
}
/**
* Run the optional MessageId resolver, falling back to the raw
* sequence when no resolver is wired or it returns 0.
*/
export function applyMessageIdResolver(
resolver: MessageIdResolver | null,
isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
): number {
if (resolver) {
const resolved = resolver(isGroup, sessionId, sequence, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
const seq = Math.trunc(sequence);
return seq === 0 ? 0 : seq;
}
export function resolveReplyId(
isGroup: boolean,
sessionId: number,
sequence: number,
resolver?: MessageIdResolver | null,
): number {
const seq = Math.trunc(sequence);
if (seq === 0) return 0;
if (resolver) {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const resolved = resolver(isGroup, sessionId, seq, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
return seq;
}
// ─────────────── raw_message (CQ string) generation ───────────────
function cqEscape(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;').replace(/,/g, '&#44;');
}
export function segmentsToRawMessage(segments: JsonArray): string {
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
}
function segmentToCQ(seg: JsonObject): string {
const type = String(seg.type ?? '');
const data = (seg.data ?? {}) as Record<string, unknown>;
switch (type) {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
return `[CQ:at,qq=${data.qq ?? ''}]`;
case 'reply':
return `[CQ:reply,id=${data.id ?? 0}]`;
case 'record':
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'video':
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'json':
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
case 'xml':
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
case 'forward':
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
case 'mface':
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
case 'poke':
return `[CQ:poke,type=${data.type ?? 0}]`;
case 'file':
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
default:
return `[CQ:${type}]`;
}
}
+2 -1
View File
@@ -7,6 +7,7 @@
// dispatch) compose cleanly without one giant switch statement.
import type { OneBotInstanceContext } from './instance-context';
import { convertEvent } from './event-converter';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { QQEventVariant } from '../bridge/events';
@@ -75,7 +76,7 @@ const NOTICE_KINDS = [
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
const converted = await ctx.eventConverter.convert(ctx.uin, event);
const converted = await convertEvent(ctx.converterCtx, event);
if (!converted) return;
ctx.dispatchEvent(converted);
}
+106 -731
View File
@@ -1,27 +1,50 @@
import type { WebHonorType } from '@/bridge/web/group-honor';
import type { Bridge } from '../bridge/bridge';
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import type { EventConverter } from './event-converter';
import { elementsToOneBotSegments } from './event-converter';
import { MessageStore } from './message-store';
import { parseMessage } from './message-parser';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
import {WebHonorType} from "@/bridge/web/group-honor";
const log = createLogger('OneBot');
import type { MessageStore } from './message-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import {
getDownloadRKeys,
getFriendList,
getGroupFiles,
getGroupInfo,
getGroupList,
getGroupMemberInfo,
getGroupMemberList,
getGroupSystemMessages,
getLoginInfo,
getStrangerInfo,
} from './modules/contact-actions';
import {
deleteMessage,
forwardSingleMessage,
getForwardMessage,
getFriendMsgHistory,
getGroupMsgHistory,
sendGroupForwardMessage,
sendGroupMessage,
sendPrivateForwardMessage,
sendPrivateMessage,
setEssenceMessage,
uploadForwardMessage,
} from './modules/message-actions';
import {
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
/**
* Single shared context bag that flows through every OneBot instance-internal
* subsystem: API builder and the per-kind event pipeline.
*
* Only fields that are actually read through this bag live here — the api
* Only fields that are actually read through this bag live here. The API
* handler and network manager are owned by `OneBotInstance` directly because
* nothing reads them via ctx, and including them here would force a
* chicken-and-egg `late-bound` field dance during construction.
* chicken-and-egg late-bound field dance during construction.
*
* `dispatchEvent` is the indirection used by the event pipeline to hand a
* converted OneBot event back to the instance for caching + adapter fan-out;
@@ -39,7 +62,7 @@ export interface OneBotInstanceContext {
messageStore: MessageStore;
mediaStore: MediaStore;
eventConverter: EventConverter;
converterCtx: ConverterContext;
config: OneBotConfig;
musicSignUrl?: string;
@@ -60,17 +83,21 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
canSendImage: () => true,
canSendRecord: () => true,
sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape),
deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta),
// Info retrieval (async, triggers OIDB fetch)
getFriendList: () => handleGetFriendList(bridge, qqInfo),
getGroupList: (noCache) => handleGetGroupList(bridge, qqInfo, noCache),
getGroupInfo: (groupId, noCache) => handleGetGroupInfo(bridge, qqInfo, groupId, noCache),
getGroupMemberList: (groupId, noCache) => handleGetGroupMemberList(bridge, qqInfo, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => handleGetGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId),
// Group admin
// OneBot11 message actions.
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions.
getFriendList: () => getFriendList(bridge, qqInfo),
getGroupList: (noCache) => getGroupList(bridge, qqInfo, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, qqInfo, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, qqInfo, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, qqInfo, userId),
// Group admin.
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
@@ -83,7 +110,8 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
getGroupAtAllRemain: (groupId) => bridge.getGroupAtAllRemain(groupId),
// Group file
// Group file.
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
@@ -93,71 +121,54 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
return result.fileId;
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => handleGetGroupFiles(bridge, groupId, folderId),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory),
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => {
return bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
},
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
// Requests
// Requests.
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Extended
// Extended.
sendLike: (userId, times) => bridge.sendLike(userId, times),
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
getProfileLike: (userId?: number, start: number = 0, limit: number = 10) => bridge.getProfileLike(userId, start, limit),
fetchCustomFace: (count?: number) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => {
return bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie);
},
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
translateEn2Zh: (words) => bridge.translateEn2Zh(words),
getMiniAppArk: (type, title, desc, picUrl, jumpUrl) => bridge.getMiniAppArk(type, title, desc, picUrl, jumpUrl),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => {
return bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq);
},
sendGroupSign: (groupId) => bridge.sendGroupSign(groupId),
// New extended
// NapCat-compatible extended actions.
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
getGroupMsgHistory: (groupId, messageId, count) => handleGetGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => handleGetFriendMsgHistory(messageStore, userId, messageId, count),
handleGetGroupSystemMsg: async () => {
try {
const reqs = await bridge.fetchGroupRequests();
return reqs.map(r => ({
group_id: r.groupId, group_name: r.groupName,
request_id: r.sequence, requester_uin: r.targetUin,
requester_nick: r.targetName, message: r.comment,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
} as JsonObject));
} catch { return []; }
},
getDownloadRKeys: async () => {
try {
const rkeys = await bridge.fetchDownloadRKeys();
return rkeys.map(r => ({
rkey: r.rkey, type: r.type, ttl: r.ttlSeconds, create_time: r.createTime,
} as JsonObject));
} catch { return []; }
},
sendGroupForwardMsg: async (groupId, messages) => {
return handleSendGroupForward(ref, groupId, messages);
},
sendPrivateForwardMsg: async (userId, messages) => {
return handleSendPrivateForward(ref, userId, messages);
},
sendForwardMsg: async (messages) => {
return handleUploadForward(ref, messages);
},
getForwardMsg: async (resId) => {
return handleGetForward(ref, resId);
},
forceFetchClientKey: async () => bridge.forceFetchClientKey(),
// Extended NapCat-compatible
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages) => sendGroupForwardMessage(ref, groupId, messages),
sendPrivateForwardMsg: (userId, messages) => sendPrivateForwardMessage(ref, userId, messages),
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
forceFetchClientKey: () => bridge.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
@@ -166,663 +177,27 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId: number, sequence: number) => bridge.markGroupMsgAsRead(groupId, sequence),
markPrivateMsgAsRead: (userId: number, sequence: number) => bridge.markPrivateMsgAsRead(userId, sequence),
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote),
// web
getGroupHonorInfo: (groupId: number, type: WebHonorType | string)=> bridge.getGroupHonorInfo(groupId, type),
getGroupEssence: (groupId: number, pageStart: number = 0, pageLimit: number = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
getGroupEssenceAll: (groupId: number) => bridge.getGroupEssenceAll(groupId),
sendGroupNotice: (groupId: number, content: string, options?: any) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId: number) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId: number, fid: string) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain: string) => bridge.getCookiesStr(domain),
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: string) => bridge.getCredentials(domain),
// Media lookup
getImageInfo: (file) => handleGetImageInfo(mediaStore, file),
getRecordInfo: (file) => handleGetRecordInfo(bridge, mediaStore, file),
// Avatar
setAvatar: (source: string) => bridge.setAvatar(source),
getCredentials: (domain) => bridge.getCredentials(domain),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
// Avatar.
setAvatar: (source) => bridge.setAvatar(source),
};
}
// --- Media lookup ---
async function handleGetImageInfo(
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findImage(file);
if (!cached) return null;
const url = cached.url || cached.imageUrl || '';
return {
file: url || cached.file,
url,
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
async function handleGetRecordInfo(
bridge: Bridge,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findRecord(file);
if (!cached) return null;
// Re-resolve via OIDB if the cached URL is missing or empty.
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
let url = cached.url;
if (!url && cached.mediaNode) {
try {
url = cached.isGroup
? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode)
: await bridge.fetchPrivatePttUrlByNode(cached.mediaNode);
if (url) {
mediaStore.updateRecordUrl(file, url);
}
} catch (err) {
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
}
}
return {
file: url || cached.file,
url: url || '',
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
// --- Login info ---
function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
return { userId, nickname };
}
// NOTE: do NOT iterate all groups here. Calling fetchGroupMemberList for
// every group on demand causes a fan-out (1 incoming request -> N OIDB
// 0xfe7_3 calls where N = group count). When a busy OneBot client (e.g.
// MaiBot) issues `get_group_member_info(no_cache=true)` per inbound
// message, this amplifier produced ~hundreds of OIDB calls per chat
// message and triggered Tencent risk-control / 7-day account ban.
// Each handler below now refreshes only the resource it actually needs.
async function refreshGroupListOnly(bridge: Bridge, qqInfo: QQInfo): Promise<void> {
try {
await bridge.fetchGroupList();
} catch { /* use cached */ }
void qqInfo;
}
async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promise<void> {
try {
await bridge.fetchGroupMemberList(groupId);
} catch { /* use cached */ }
}
function normalizeHistoryCount(count?: number): number {
if (!Number.isFinite(count)) return 20;
const n = Math.trunc(count as number);
if (n <= 0) return 20;
if (n > 200) return 200;
return n;
}
function sanitizeMessageEventForApi(event: JsonObject): JsonObject {
const result: JsonObject = { ...event };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? 0) as JsonValue;
return result;
}
// --- Info retrieval ---
async function handleGetFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
try {
const friends = await bridge.fetchFriendList();
return friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
} catch {
return qqInfo.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
}
}
async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: boolean): Promise<JsonObject[]> {
try {
if (noCache || qqInfo.groups.length === 0) {
await bridge.fetchGroupList();
}
} catch { /* use cached */ }
return qqInfo.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
}));
}
async function handleGetGroupInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroup(groupId)) {
try { await bridge.fetchGroupList(); } catch { /* use cached */ }
}
const g = qqInfo.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
};
}
async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject[]> {
if (noCache) {
await refreshSingleGroupMembers(bridge, groupId);
const g = qqInfo.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, m] of g.members) {
result.push({
group_id: groupId as any, user_id: m.uin as any,
nickname: m.nickname as any, card: m.card as any,
sex: 'unknown' as any, age: 0 as any,
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
level: String(m.level) as any, role: m.role as any, title: m.title as any,
});
}
return result;
}
try {
const members = await bridge.fetchGroupMemberList(groupId);
return members.map(m => ({
group_id: groupId as any,
user_id: m.uin as any,
nickname: m.nickname as any,
card: m.card as any,
sex: 'unknown' as any,
age: 0 as any,
join_time: m.joinTime as any,
last_sent_time: m.lastSentTime as any,
level: String(m.level) as any,
role: m.role as any,
title: m.title as any,
}));
} catch {
const g = qqInfo.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, m] of g.members) {
result.push({
group_id: groupId as any, user_id: m.uin as any,
nickname: m.nickname as any, card: m.card as any,
sex: 'unknown' as any, age: 0 as any,
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
level: String(m.level) as any, role: m.role as any, title: m.title as any,
});
}
return result;
}
}
async function handleGetGroupMemberInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, userId: number, noCache?: boolean): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroupMember(groupId, userId)) {
await refreshSingleGroupMembers(bridge, groupId);
}
const m = qqInfo.findGroupMember(groupId, userId);
if (!m) return null;
return {
group_id: groupId as any, user_id: m.uin as any,
nickname: m.nickname as any, card: m.card as any,
sex: 'unknown' as any, age: 0 as any,
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
level: String(m.level) as any, role: m.role as any, title: m.title as any,
};
}
async function handleGetGroupFiles(bridge: Bridge, groupId: number, folderId?: string): Promise<JsonObject> {
const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/');
return {
files: result.files.map((file) => ({
group_id: groupId as any,
file_id: file.fileId as any,
file_name: file.fileName as any,
busid: file.busId as any,
file_size: file.fileSize as any,
upload_time: file.uploadTime as any,
dead_time: file.deadTime as any,
modify_time: file.modifyTime as any,
download_times: file.downloadTimes as any,
uploader: file.uploader as any,
uploader_name: file.uploaderName as any,
} as JsonObject)) as any,
folders: result.folders.map((folder) => ({
group_id: groupId as any,
folder_id: folder.folderId as any,
folder_name: folder.folderName as any,
create_time: folder.createTime as any,
creator: folder.creator as any,
create_name: folder.creatorName as any,
total_file_count: folder.totalFileCount as any,
} as JsonObject)) as any,
};
}
async function handleGetStrangerInfo(bridge: Bridge, qqInfo: QQInfo, userId: number): Promise<JsonObject | null> {
try {
const p = await bridge.fetchUserProfile(userId);
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
};
} catch {
const p = qqInfo.findUserProfile(userId);
if (!p) return null;
return { user_id: p.uin as any, nickname: p.nickname as any, sex: p.sex as any, age: p.age as any };
}
}
// --- Message history ---
async function handleGetGroupMsgHistory(
messageStore: MessageStore,
groupId: number,
messageId?: number,
count?: number,
): Promise<JsonObject[]> {
if (!Number.isInteger(groupId) || groupId <= 0) return [];
const limit = normalizeHistoryCount(count);
let anchorSequence: number | undefined;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence);
return events
.filter((event) => {
if (event.message_type !== 'group') return false;
const gid = Number(event.group_id ?? 0);
return Number.isFinite(gid) && Math.trunc(gid) === groupId;
})
.map(sanitizeMessageEventForApi);
}
async function handleGetFriendMsgHistory(
messageStore: MessageStore,
userId: number,
messageId?: number,
count?: number,
): Promise<JsonObject[]> {
if (!Number.isInteger(userId) || userId <= 0) return [];
const limit = normalizeHistoryCount(count);
let anchorSequence: number | undefined;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence);
return events
.filter((event) => {
if (event.message_type !== 'private') return false;
const uid = Number(event.user_id ?? 0);
return Number.isFinite(uid) && Math.trunc(uid) === userId;
})
.map(sanitizeMessageEventForApi);
}
// --- Delete message ---
async function handleDeleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
if (meta.isGroup) {
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
} else {
await bridge.recallPrivateMessage(
meta.targetId, meta.clientSequence, meta.sequence, meta.random, meta.timestamp);
}
}
// --- Group request ---
async function handleGroupAddRequest(bridge: Bridge, flag: string, approve: boolean, reason: string): Promise<void> {
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
const parts = flag.split(':');
if (parts.length < 3) throw new Error('invalid group request flag');
const groupId = parseInt(parts[1], 10);
if (!groupId) throw new Error('invalid group_id in flag');
// We need sequence and eventType -- fetch from group requests
const requests = await bridge.fetchGroupRequests();
const matching = requests.find(r => r.groupId === groupId);
if (matching) {
await bridge.setGroupAddRequest(groupId, matching.sequence, matching.eventType, approve, reason, matching.filtered);
} else {
throw new Error('matching group request not found');
}
}
// --- Essence ---
async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, messageId: number, enable: boolean): Promise<void> {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
}
// --- Send message logging ---
function logSentMessage(isGroup: boolean, targetId: number, elements: MessageElement[]): void {
const type = isGroup ? '群聊' : '私聊';
const parts: string[] = [];
// Check for reply element
const replyElem = elements.find(e => e.type === 'reply');
if (replyElem && replyElem.replyMessageId) {
parts.push(`[回复:${replyElem.replyMessageId}]`);
}
// Build message content preview
for (const elem of elements) {
if (elem.type === 'reply') continue; // Already handled
switch (elem.type) {
case 'text':
if (elem.text) {
const preview = elem.text.length > 50 ? elem.text.substring(0, 50) + '...' : elem.text;
parts.push(preview);
}
break;
case 'image':
parts.push('[图片]');
break;
case 'face':
parts.push('[表情]');
break;
case 'at':
if (elem.text) parts.push(elem.text.trim());
break;
case 'record':
parts.push('[语音]');
break;
case 'video':
parts.push('[视频]');
break;
case 'json':
parts.push('[JSON消息]');
break;
case 'xml':
parts.push('[XML消息]');
break;
case 'markdown':
parts.push('[Markdown]');
break;
case 'forward':
parts.push('[转发消息]');
break;
case 'poke':
parts.push('[戳一戳]');
break;
default:
break;
}
}
const content = parts.join(' ').trim() || '[空消息]';
log.info(`${type} ${targetId} | 发送:${content}`);
}
// --- Send message ---
async function handleSendPrivate(
ref: OneBotInstanceContext,
userId: number,
message: JsonValue,
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: meta.targetId, // For received messages, targetId is the sender
time: meta.timestamp,
random: meta.random,
};
}
return null;
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin),
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
// Log sent message
logSentMessage(false, userId, elements);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId };
}
async function handleSendGroup(
ref: OneBotInstanceContext,
groupId: number,
message: JsonValue,
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
return {
senderUin: typeof event.user_id === 'number' ? event.user_id : parseInt(String(event.user_id || '0'), 10),
time: typeof event.time === 'number' ? event.time : parseInt(String(event.time || '0'), 10),
random: 0, // Group messages might not have random field in event
};
}
return null;
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
// Log sent message
logSentMessage(true, groupId, elements);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId };
}
async function handleSendGroupForward(
ref: OneBotInstanceContext,
groupId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId, forwardId };
}
async function handleSendPrivateForward(
ref: OneBotInstanceContext,
userId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId, forwardId };
}
async function handleUploadForward(
ref: OneBotInstanceContext,
messages: JsonValue,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
return { forwardId };
}
async function handleGetForward(
ref: OneBotInstanceContext,
resId: string,
): Promise<JsonObject[]> {
const nodes = await ref.bridge.fetchForwardNodes(resId);
const results: JsonObject[] = [];
for (const node of nodes) {
results.push({
type: 'node' as any,
data: {
user_id: node.userUin as any,
nickname: node.nickname as any,
uin: String(node.userUin) as any,
name: node.nickname as any,
content: await elementsToOneBotSegments(node.elements, false, node.userUin) as any,
} as any,
} as JsonObject);
}
return results;
}
async function parseForwardNodes(ref: OneBotInstanceContext, messages: JsonValue): Promise<ForwardNodePayload[]> {
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}
const nodes: ForwardNodePayload[] = [];
for (const item of messages) {
const segment = asJsonObject(item);
if (!segment) continue;
let nodeData: JsonObject | null = null;
if (String(segment.type ?? '') === 'node') {
nodeData = asJsonObject(segment.data);
} else if (segment.content !== undefined || segment.message !== undefined) {
nodeData = segment;
}
if (!nodeData) continue;
const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id);
if (messageId > 0) {
const event = ref.messageStore.findEvent(messageId);
if (!event) throw new Error(`forward node message_id not found: ${messageId}`);
const eventSender = asJsonObject(event.sender) ?? {};
const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? '');
const userUin = toPositiveInt(event.user_id);
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (userUin > 0 && elements.length > 0) {
nodes.push({ userUin, nickname: nickname || String(userUin), elements });
}
continue;
}
const userUin = toPositiveInt(nodeData.user_id ?? nodeData.uin);
if (userUin <= 0) throw new Error('forward node user_id/uin is required');
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`);
nodes.push({ userUin, nickname, elements });
}
if (nodes.length === 0) {
throw new Error('forward node list is empty');
}
return nodes;
}
function asJsonObject(value: JsonValue | undefined): JsonObject | null {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
return value as JsonObject;
}
function toPositiveInt(value: JsonValue | undefined): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.max(0, Math.trunc(parsed));
}
return 0;
}
+23 -65
View File
@@ -2,9 +2,11 @@ import path from 'path';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import { ApiHandler } from './api-handler';
import { EventConverter } from './event-converter';
import { MessageStore } from './message-store';
import type { ConverterContext } from './event-converter';
import { MediaIndexer } from './media-indexer';
import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
import { MessageStore } from './message-store';
import { RKeyCache } from './instance-rkey';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
import { registerEventPipeline } from './event-pipeline';
@@ -28,7 +30,7 @@ export class OneBotInstance {
readonly qqInfo: QQInfo;
private readonly bridge: Bridge;
private readonly apiHandler: ApiHandler;
private readonly eventConverter: EventConverter;
private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore;
private readonly mediaStore: MediaStore;
private readonly networkManager: OneBotNetworkManager;
@@ -46,71 +48,27 @@ export class OneBotInstance {
this.qqInfo = qqInfo;
this.bridge = bridge;
this.eventConverter = new EventConverter();
this.rkeyCache = new RKeyCache();
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.eventConverter.setImageUrlResolver((element, isGroup) =>
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup));
this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => {
// Fetch URL from bridge if not already present
if (!element.url) {
try {
if (element.type === 'file' && element.fileId) {
element.url = isGroup
? await this.bridge.fetchGroupFileUrl(sessionId, element.fileId)
: element.fileHash
? await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash)
: '';
} else if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
if (isGroup) {
element.url = element.type === 'record'
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
} else {
element.url = element.type === 'record'
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
}
}
} catch { /* best-effort */ }
}
// Then apply RKey if needed
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
});
this.eventConverter.setMediaSegmentSink((mediaType, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (mediaType === 'image') {
this.mediaStore.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
});
return;
}
this.mediaStore.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
});
});
this.eventConverter.setMessageIdResolver((isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
// The converter context's four callbacks delegate to small, focused
// modules so this constructor doesn't carry the bridge-URL fetch
// branching or the mediaStore field-mapping fanout inline.
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
const mediaIndexer = new MediaIndexer(this.mediaStore);
this.converterCtx = {
selfId: parseInt(this.uin, 10) || 0,
imageUrlResolver: (element, isGroup) =>
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
// Shared instance context. Only carries fields that are actually read
// through it — api handler and network manager stay as direct fields on
// the instance because nothing reads them via ctx.
@@ -121,7 +79,7 @@ export class OneBotInstance {
bridge: this.bridge,
messageStore: this.messageStore,
mediaStore: this.mediaStore,
eventConverter: this.eventConverter,
converterCtx: this.converterCtx,
config,
musicSignUrl: config.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
+90
View File
@@ -0,0 +1,90 @@
// Side-channel observer that watches every image / record / video
// segment emitted by the event converter and writes a row into the
// MediaStore so later `get_image` / `get_record` OneBot actions can
// resolve the original `data.file` back to a URL + metadata.
//
// Used as the `mediaSegmentSink` callback in `ConverterContext`.
//
// The fan-out is uniform (always one rememberX call per segment), but
// each mediaType maps to a slightly different MediaStore record shape;
// keeping the three field maps in one place makes the divergence
// visible at a glance.
import type { MessageElement } from '../bridge/events';
import type { JsonObject } from './types';
import type { MediaStore } from './media-store';
export type MediaType = 'image' | 'record' | 'video';
export class MediaIndexer {
constructor(private readonly mediaStore: MediaStore) {}
remember(
mediaType: MediaType,
element: MessageElement,
data: JsonObject,
isGroup: boolean,
sessionId: number,
): void {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (mediaType === 'image') {
this.mediaStore.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
width: element.width,
height: element.height,
picFormat: element.picFormat,
});
return;
}
if (mediaType === 'record') {
this.mediaStore.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
voiceFormat: element.voiceFormat,
});
return;
}
// video
this.mediaStore.rememberVideo({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
width: element.width,
height: element.height,
videoFormat: element.videoFormat,
});
}
}
+51 -2
View File
@@ -38,6 +38,13 @@ export interface CachedImage {
sessionId: number;
/** Original imageUrl from the MessageElement, used for RKey re-appending. */
imageUrl: string;
/** Fingerprints used for md5/sha1 fast-upload on forward. Optional because
* legacy CustomFace / NotOnlineImage only carry md5. */
md5Hex?: string;
sha1Hex?: string;
width?: number;
height?: number;
picFormat?: number;
}
export interface CachedRecord {
@@ -56,10 +63,34 @@ export interface CachedRecord {
/** Conversation the media originated from (group vs private path). */
isGroup: boolean;
sessionId: number;
/** Fingerprints used for md5/sha1 fast-upload on forward. */
md5Hex?: string;
sha1Hex?: string;
voiceFormat?: number;
}
export interface CachedVideo {
file: string;
fileId: string;
url: string;
fileSize: number;
fileName: string;
duration: number;
fileHash: string;
mediaNode?: MessageElement['mediaNode'];
isGroup: boolean;
sessionId: number;
/** Fingerprints used for md5/sha1 fast-upload on forward. */
md5Hex?: string;
sha1Hex?: string;
width?: number;
height?: number;
videoFormat?: number;
}
const TYPE_IMAGE = 'image';
const TYPE_RECORD = 'record';
const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export class MediaStore {
@@ -145,6 +176,12 @@ export class MediaStore {
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
rememberVideo(info: CachedVideo): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_VIDEO, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
findImage(key: string): CachedImage | null {
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
}
@@ -153,6 +190,10 @@ export class MediaStore {
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
}
findVideo(key: string): CachedVideo | null {
return this.findByAnyKey<CachedVideo>(TYPE_VIDEO, key);
}
updateImageUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findImage(key);
@@ -167,11 +208,19 @@ export class MediaStore {
this.rememberRecord({ ...cached, url });
}
updateVideoUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findVideo(key);
if (!cached || cached.url === url) return;
this.rememberVideo({ ...cached, url });
}
/** Snapshot count of distinct entries per type; mostly used by tests. */
size(): { images: number; records: number } {
size(): { images: number; records: number; videos: number } {
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
return { images: img?.n ?? 0, records: rec?.n ?? 0 };
const vid = this.countByType.get(TYPE_VIDEO) as { n: number } | undefined;
return { images: img?.n ?? 0, records: rec?.n ?? 0, videos: vid?.n ?? 0 };
}
// --- internals ---
@@ -0,0 +1,64 @@
// Resolves the URL for an image / record / video / file element on its
// way out of the bridge into an OneBot segment.
//
// Two steps:
// 1. If the bridge event arrived without a `url` (the receive path
// sometimes does), fetch a fresh URL from the right Bridge API
// based on element.type + isGroup, mutating the element in-place
// so any downstream cache sees the URL too.
// 2. Apply the cached RKey (the per-UIN signed download key) the
// RKeyCache knows about — both to brand-new URLs from step 1 and
// to URLs that came in with the event already.
//
// Used as the `mediaUrlResolver` callback in `ConverterContext`.
import type { Bridge } from '../bridge/bridge';
import type { MessageElement } from '../bridge/events';
import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver {
constructor(
private readonly bridge: Bridge,
private readonly rkeyCache: RKeyCache,
) {}
async resolve(element: MessageElement, isGroup: boolean, sessionId: number): Promise<string> {
if (!element.url) {
try {
await this.populateUrl(element, isGroup, sessionId);
} catch {
// Best-effort: a URL fetch hiccup should never block the
// outgoing segment. The RKey pass below still runs.
}
}
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
}
/** Branches by element.type + isGroup to pick the right Bridge API.
* Mutates `element.url` in-place so the caller sees the same URL
* the downstream rkey/media-store path will see. */
private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise<void> {
if (element.type === 'file' && element.fileId) {
if (isGroup) {
element.url = await this.bridge.fetchGroupFileUrl(sessionId, element.fileId);
} else if (element.fileHash) {
element.url = await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash);
} else {
element.url = '';
}
return;
}
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
if (isGroup) {
element.url = element.type === 'record'
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
} else {
element.url = element.type === 'record'
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
}
}
}
}
@@ -0,0 +1,240 @@
import type { Bridge } from '../../bridge/bridge';
import type { QQInfo } from '../../bridge/qq-info';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
return { userId, nickname };
}
// Keep refreshes scoped. A broad "refresh all members in all groups" call can
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promise<void> {
try {
await bridge.fetchGroupMemberList(groupId);
} catch {
// Use cached data.
}
}
export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
try {
const friends = await bridge.fetchFriendList();
return friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
} catch {
return qqInfo.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
}
}
export async function getGroupList(
bridge: Bridge,
qqInfo: QQInfo,
noCache?: boolean,
): Promise<JsonObject[]> {
try {
if (noCache || qqInfo.groups.length === 0) {
await bridge.fetchGroupList();
}
} catch {
// Use cached data.
}
return qqInfo.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
}));
}
export async function getGroupInfo(
bridge: Bridge,
qqInfo: QQInfo,
groupId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroup(groupId)) {
try {
await bridge.fetchGroupList();
} catch {
// Use cached data.
}
}
const g = qqInfo.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
};
}
export async function getGroupMemberList(
bridge: Bridge,
qqInfo: QQInfo,
groupId: number,
noCache?: boolean,
): Promise<JsonObject[]> {
if (noCache) {
await refreshSingleGroupMembers(bridge, groupId);
return getCachedGroupMembers(qqInfo, groupId);
}
try {
const members = await bridge.fetchGroupMemberList(groupId);
return members.map(m => formatGroupMember(groupId, m));
} catch {
return getCachedGroupMembers(qqInfo, groupId);
}
}
export async function getGroupMemberInfo(
bridge: Bridge,
qqInfo: QQInfo,
groupId: number,
userId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroupMember(groupId, userId)) {
await refreshSingleGroupMembers(bridge, groupId);
}
const m = qqInfo.findGroupMember(groupId, userId);
if (!m) return null;
return formatGroupMember(groupId, m);
}
export async function getGroupFiles(
bridge: Bridge,
groupId: number,
folderId?: string,
): Promise<JsonObject> {
const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/');
return {
files: result.files.map((file) => ({
group_id: groupId as any,
file_id: file.fileId as any,
file_name: file.fileName as any,
busid: file.busId as any,
file_size: file.fileSize as any,
upload_time: file.uploadTime as any,
dead_time: file.deadTime as any,
modify_time: file.modifyTime as any,
download_times: file.downloadTimes as any,
uploader: file.uploader as any,
uploader_name: file.uploaderName as any,
} as JsonObject)) as any,
folders: result.folders.map((folder) => ({
group_id: groupId as any,
folder_id: folder.folderId as any,
folder_name: folder.folderName as any,
create_time: folder.createTime as any,
creator: folder.creator as any,
create_name: folder.creatorName as any,
total_file_count: folder.totalFileCount as any,
} as JsonObject)) as any,
};
}
export async function getStrangerInfo(
bridge: Bridge,
qqInfo: QQInfo,
userId: number,
): Promise<JsonObject | null> {
try {
const p = await bridge.fetchUserProfile(userId);
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
};
} catch {
const p = qqInfo.findUserProfile(userId);
if (!p) return null;
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
};
}
}
export async function getGroupSystemMessages(bridge: Bridge): Promise<JsonObject[]> {
try {
const reqs = await bridge.fetchGroupRequests();
return reqs.map(r => ({
group_id: r.groupId,
group_name: r.groupName,
request_id: r.sequence,
requester_uin: r.targetUin,
requester_nick: r.targetName,
message: r.comment,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
} as JsonObject));
} catch {
return [];
}
}
export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
try {
const rkeys = await bridge.fetchDownloadRKeys();
return rkeys.map(r => ({
rkey: r.rkey,
type: r.type,
ttl: r.ttlSeconds,
create_time: r.createTime,
} as JsonObject));
} catch {
return [];
}
}
function getCachedGroupMembers(qqInfo: QQInfo, groupId: number): JsonObject[] {
const g = qqInfo.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, member] of g.members) {
result.push(formatGroupMember(groupId, member));
}
return result;
}
function formatGroupMember(
groupId: number,
member: {
uin: number;
nickname: string;
card: string;
joinTime: number;
lastSentTime: number;
level: number;
role: string;
title: string;
},
): JsonObject {
return {
group_id: groupId as any,
user_id: member.uin as any,
nickname: member.nickname as any,
card: member.card as any,
sex: 'unknown' as any,
age: 0 as any,
join_time: member.joinTime as any,
last_sent_time: member.lastSentTime as any,
level: String(member.level) as any,
role: member.role as any,
title: member.title as any,
};
}
@@ -0,0 +1,53 @@
import type { Bridge } from '../../bridge/bridge';
import { createLogger } from '../../utils/logger';
import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types';
const log = createLogger('OneBot');
export async function getImageInfo(
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findImage(file);
if (!cached) return null;
const url = cached.url || cached.imageUrl || '';
return {
file: url || cached.file,
url,
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
export async function getRecordInfo(
bridge: Bridge,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findRecord(file);
if (!cached) return null;
// Re-resolve via OIDB if the cached URL is missing or empty.
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
let url = cached.url;
if (!url && cached.mediaNode) {
try {
url = cached.isGroup
? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode)
: await bridge.fetchPrivatePttUrlByNode(cached.mediaNode);
if (url) {
mediaStore.updateRecordUrl(file, url);
}
} catch (err) {
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
}
}
return {
file: url || cached.file,
url: url || '',
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
@@ -0,0 +1,545 @@
import type { Bridge } from '../../bridge/bridge';
import type { ForwardNodePayload, MessageElement } from '../../bridge/events';
import { createLogger } from '../../utils/logger';
import type { MessageSendResult } from '../api-handler';
import { elementsToOneBotSegments } from '../event-converter';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import { parseMessage } from '../message-parser';
import type { MessageStore } from '../message-store';
import type { JsonObject, JsonValue, MessageMeta } from '../types';
import type { OneBotInstanceContext } from '../instance-context';
const log = createLogger('OneBot');
export async function getGroupMsgHistory(
messageStore: MessageStore,
groupId: number,
messageId?: number,
count?: number,
): Promise<JsonObject[]> {
if (!Number.isInteger(groupId) || groupId <= 0) return [];
const limit = normalizeHistoryCount(count);
let anchorSequence: number | undefined;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence);
return events
.filter((event) => {
if (event.message_type !== 'group') return false;
const gid = Number(event.group_id ?? 0);
return Number.isFinite(gid) && Math.trunc(gid) === groupId;
})
.map(sanitizeMessageEventForApi);
}
export async function getFriendMsgHistory(
messageStore: MessageStore,
userId: number,
messageId?: number,
count?: number,
): Promise<JsonObject[]> {
if (!Number.isInteger(userId) || userId <= 0) return [];
const limit = normalizeHistoryCount(count);
let anchorSequence: number | undefined;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence);
return events
.filter((event) => {
if (event.message_type !== 'private') return false;
const uid = Number(event.user_id ?? 0);
return Number.isFinite(uid) && Math.trunc(uid) === userId;
})
.map(sanitizeMessageEventForApi);
}
export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
if (meta.isGroup) {
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
} else {
await bridge.recallPrivateMessage(
meta.targetId,
meta.clientSequence,
meta.sequence,
meta.random,
meta.timestamp,
);
}
}
export async function setEssenceMessage(
bridge: Bridge,
messageStore: MessageStore,
messageId: number,
enable: boolean,
): Promise<void> {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
}
export async function sendPrivateMessage(
ref: OneBotInstanceContext,
userId: number,
message: JsonValue,
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: meta.targetId,
time: meta.timestamp,
random: meta.random,
};
}
return null;
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin),
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
logSentMessage(false, userId, elements);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId };
}
export async function sendGroupMessage(
ref: OneBotInstanceContext,
groupId: number,
message: JsonValue,
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
return {
senderUin: typeof event.user_id === 'number'
? event.user_id
: parseInt(String(event.user_id || '0'), 10),
time: typeof event.time === 'number'
? event.time
: parseInt(String(event.time || '0'), 10),
random: 0,
};
}
return null;
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
logSentMessage(true, groupId, elements);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId };
}
export async function sendGroupForwardMessage(
ref: OneBotInstanceContext,
groupId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId, forwardId };
}
export async function sendPrivateForwardMessage(
ref: OneBotInstanceContext,
userId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId, forwardId };
}
export async function uploadForwardMessage(
ref: OneBotInstanceContext,
messages: JsonValue,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
return { forwardId };
}
/**
* Forward a previously-received message to another peer.
*
* We look up the cached event + media fingerprints, then re-send via the
* normal send pipeline with `noByteFallback` set on media elements so the
* upload modules fast-path through OIDB md5/sha1 instead of re-downloading
* the original CDN bytes. Fails fast if a media segment has no cached
* fingerprints or contains a file segment (file forwarding has its own
* separate protocol and is not in scope here).
*/
export async function forwardSingleMessage(
ref: OneBotInstanceContext,
messageId: number,
target: { groupId?: number; userId?: number },
): Promise<{ messageId: number }> {
if (!target.groupId && !target.userId) {
throw new Error('forward target group_id or user_id is required');
}
const event = ref.messageStore.findEvent(messageId);
if (!event) throw new Error(`message not found: ${messageId}`);
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const parsed = await parseMessage(content, false);
if (parsed.length === 0) throw new Error('message has no content');
const elements = parsed.map((el) => enrichForForward(ref, el));
let receipt;
let messageIdOut: number;
if (target.groupId) {
receipt = await ref.bridge.sendGroupMessage(target.groupId, elements);
messageIdOut = hashMessageIdInt32(receipt.sequence, target.groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageIdOut, {
isGroup: true,
targetId: target.groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
} else {
receipt = await ref.bridge.sendPrivateMessage(target.userId!, elements);
messageIdOut = hashMessageIdInt32(receipt.sequence, target.userId!, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageIdOut, {
isGroup: false,
targetId: target.userId!,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
}
return { messageId: messageIdOut };
}
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement): MessageElement {
// The send path takes care of these as-is; nothing extra to do.
if (element.type === 'text' || element.type === 'face' || element.type === 'at'
|| element.type === 'reply' || element.type === 'json' || element.type === 'xml'
|| element.type === 'poke' || element.type === 'forward' || element.type === 'mface') {
return element;
}
// The `file` segment is its own upload pipeline (FtnUpload / OfflineFile)
// and is not supported by the fast-upload forward path.
if (element.type === 'file') {
throw new Error('forward of file segment is not supported');
}
// For images/records/videos we look up the cached fingerprints by any of
// the keys MediaStore aliases under. After parseMessage, the segment's
// `data.file` lands on `element.url` for all three types.
const lookupKey = element.url || element.fileName || element.fileId || '';
if (!lookupKey) {
throw new Error(`forward ${element.type} missing cache key`);
}
if (element.type === 'image') {
const cached = ref.mediaStore.findImage(lookupKey);
if (!cached || !cached.md5Hex || !cached.sha1Hex || !cached.width || !cached.height || !cached.picFormat) {
throw new Error('forward image fingerprint not cached (legacy image or expired)');
}
return {
...element,
type: 'image',
noByteFallback: true,
md5Hex: cached.md5Hex,
sha1Hex: cached.sha1Hex,
fileSize: cached.fileSize,
fileName: cached.fileName,
subType: cached.subType,
summary: cached.summary,
width: cached.width,
height: cached.height,
picFormat: cached.picFormat,
};
}
if (element.type === 'record') {
const cached = ref.mediaStore.findRecord(lookupKey);
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('forward record fingerprint not cached');
}
return {
...element,
type: 'record',
noByteFallback: true,
md5Hex: cached.md5Hex,
sha1Hex: cached.sha1Hex,
fileSize: cached.fileSize,
fileName: cached.fileName,
fileId: cached.fileId,
duration: cached.duration,
voiceFormat: cached.voiceFormat ?? 1,
};
}
if (element.type === 'video') {
const cached = ref.mediaStore.findVideo(lookupKey);
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('forward video fingerprint not cached');
}
log.warn('video forward uses a fallback thumbnail (original thumb not cached)');
return {
...element,
type: 'video',
noByteFallback: true,
md5Hex: cached.md5Hex,
sha1Hex: cached.sha1Hex,
fileSize: cached.fileSize,
fileName: cached.fileName,
fileId: cached.fileId,
duration: cached.duration,
width: cached.width ?? 0,
height: cached.height ?? 0,
videoFormat: cached.videoFormat ?? 0,
};
}
return element;
}
export async function getForwardMessage(
ref: OneBotInstanceContext,
resId: string,
): Promise<JsonObject[]> {
const nodes = await ref.bridge.fetchForwardNodes(resId);
const results: JsonObject[] = [];
for (const node of nodes) {
results.push({
type: 'node' as any,
data: {
user_id: node.userUin as any,
nickname: node.nickname as any,
uin: String(node.userUin) as any,
name: node.nickname as any,
content: await elementsToOneBotSegments(node.elements, false, node.userUin) as any,
} as any,
} as JsonObject);
}
return results;
}
function normalizeHistoryCount(count?: number): number {
if (!Number.isFinite(count)) return 20;
const n = Math.trunc(count as number);
if (n <= 0) return 20;
if (n > 200) return 200;
return n;
}
function sanitizeMessageEventForApi(event: JsonObject): JsonObject {
const result: JsonObject = { ...event };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? 0) as JsonValue;
return result;
}
function logSentMessage(isGroup: boolean, targetId: number, elements: MessageElement[]): void {
const type = isGroup ? '群聊' : '私聊';
const parts: string[] = [];
const replyElem = elements.find(e => e.type === 'reply');
if (replyElem?.replyMessageId) {
parts.push(`[回复:${replyElem.replyMessageId}]`);
}
for (const elem of elements) {
if (elem.type === 'reply') continue;
switch (elem.type) {
case 'text':
if (elem.text) {
const preview = elem.text.length > 50 ? `${elem.text.substring(0, 50)}...` : elem.text;
parts.push(preview);
}
break;
case 'image':
parts.push('[图片]');
break;
case 'face':
parts.push('[表情]');
break;
case 'at':
if (elem.text) parts.push(elem.text.trim());
break;
case 'record':
parts.push('[语音]');
break;
case 'video':
parts.push('[视频]');
break;
case 'json':
parts.push('[JSON消息]');
break;
case 'xml':
parts.push('[XML消息]');
break;
case 'markdown':
parts.push('[Markdown]');
break;
case 'forward':
parts.push('[转发消息]');
break;
case 'poke':
parts.push('[戳一戳]');
break;
default:
break;
}
}
const content = parts.join(' ').trim() || '[空消息]';
log.info(`${type} ${targetId} | 发送:${content}`);
}
async function parseForwardNodes(
ref: OneBotInstanceContext,
messages: JsonValue,
): Promise<ForwardNodePayload[]> {
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}
const nodes: ForwardNodePayload[] = [];
for (const item of messages) {
const segment = asJsonObject(item);
if (!segment) continue;
let nodeData: JsonObject | null = null;
if (String(segment.type ?? '') === 'node') {
nodeData = asJsonObject(segment.data);
} else if (segment.content !== undefined || segment.message !== undefined) {
nodeData = segment;
}
if (!nodeData) continue;
const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id);
if (messageId > 0) {
const event = ref.messageStore.findEvent(messageId);
if (!event) throw new Error(`forward node message_id not found: ${messageId}`);
const eventSender = asJsonObject(event.sender) ?? {};
const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? '');
const userUin = toPositiveInt(event.user_id);
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (userUin > 0 && elements.length > 0) {
nodes.push({ userUin, nickname: nickname || String(userUin), elements });
}
continue;
}
const userUin = toPositiveInt(nodeData.user_id ?? nodeData.uin);
if (userUin <= 0) throw new Error('forward node user_id/uin is required');
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`);
nodes.push({ userUin, nickname, elements });
}
if (nodes.length === 0) {
throw new Error('forward node list is empty');
}
return nodes;
}
function asJsonObject(value: JsonValue | undefined): JsonObject | null {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
return value as JsonObject;
}
function toPositiveInt(value: JsonValue | undefined): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.max(0, Math.trunc(parsed));
}
return 0;
}
@@ -0,0 +1,29 @@
import type { Bridge } from '../../bridge/bridge';
export async function handleGroupAddRequest(
bridge: Bridge,
flag: string,
approve: boolean,
reason: string,
): Promise<void> {
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
const parts = flag.split(':');
if (parts.length < 3) throw new Error('invalid group request flag');
const groupId = parseInt(parts[1], 10);
if (!groupId) throw new Error('invalid group_id in flag');
const requests = await bridge.fetchGroupRequests();
const matching = requests.find(r => r.groupId === groupId);
if (!matching) {
throw new Error('matching group request not found');
}
await bridge.setGroupAddRequest(
groupId,
matching.sequence,
matching.eventType,
approve,
reason,
matching.filtered,
);
}
@@ -1,54 +0,0 @@
import { createLogger } from '../utils/logger';
import type { PacketInfo } from './types';
const log = createLogger('NTQQ');
export type CmdCallback = (pkt: PacketInfo) => void;
export interface HookPacketInput {
seq: number;
error: number;
cmd: string;
uin: string;
body: Uint8Array;
}
export class NtqqHandler {
private cmdHandlers = new Map<string, CmdCallback[]>();
private cmdAllHandlers: CmdCallback[] = [];
registerCmd(cmd: string, cb: CmdCallback): void {
const arr = this.cmdHandlers.get(cmd) ?? [];
arr.push(cb);
this.cmdHandlers.set(cmd, arr);
}
registerCmdAll(cb: CmdCallback): void { this.cmdAllHandlers.push(cb); }
onHookPacket(pid: number, packet: HookPacketInput): void {
this.dispatchPacket({
pid,
uin: packet.uin,
serviceCmd: packet.cmd,
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
body: Buffer.from(packet.body),
});
}
private dispatchPacket(pkt: PacketInfo): void {
const specific = this.cmdHandlers.get(pkt.serviceCmd);
if (specific) {
for (const cb of specific) {
try { cb(pkt); } catch (e) {
log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
for (const cb of this.cmdAllHandlers) {
try { cb(pkt); } catch (e) {
log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
}
+6
View File
@@ -8,3 +8,9 @@ export interface PacketInfo {
fromClient: boolean;
body: Uint8Array;
}
/**
* Packet sink injected into HookSession / HookManager. The default
* wiring forwards to BridgeManager.onPacket, but tests inject spies.
*/
export type PacketSink = (packet: PacketInfo) => void;
+55
View File
@@ -0,0 +1,55 @@
// Shared fixtures for the per-theme bridge-action tests.
//
// Each action test file mocks `../src/bridge/bridge-oidb` and (where
// needed) `../src/bridge/highway/*` so we can assert what the action
// asked the OIDB / Highway layer to do without booting a real Bridge.
//
// `mockBridge()` returns a minimal stand-in: enough state for the
// actions to thread but no real packet/event machinery.
import { vi } from 'vitest';
import type { SendPacketResult } from '../../src/protocol/packet-sender';
export interface MockBridge {
qqInfo: {
uin: string;
selfUid: string;
findGroupMember: ReturnType<typeof vi.fn>;
};
identity: {
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
};
sendRawPacket: ReturnType<typeof vi.fn>;
fetchFriendList: ReturnType<typeof vi.fn>;
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
}
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
const defaultResp: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.alloc(0),
};
return {
qqInfo: {
uin: '10001',
selfUid: 'self-uid',
findGroupMember: vi.fn(() => null),
...(overrides.qqInfo ?? {}),
} as MockBridge['qqInfo'],
identity: {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
sendRawPacket: vi.fn(async () => defaultResp),
fetchFriendList: vi.fn(async () => []),
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
...overrides,
};
}
+107
View File
@@ -0,0 +1,107 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
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
// that we don't want to construct manually in tests; stub it to return
// a benign placeholder.
vi.mock('../../src/bridge/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
import { protoEncode } from '../../src/protobuf/decode';
import { SendLongMsgRespSchema } from '../../src/bridge/proto/longmsg';
import * as forward from '../../src/bridge/actions/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
const encoded = protoEncode({ result: { resId } }, SendLongMsgRespSchema);
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(encoded),
};
}
describe('actions/forward', () => {
it('uploadForwardNodes rejects empty arrays', async () => {
const bridge = mockBridge();
await expect(forward.uploadForwardNodes(bridge as any, []))
.rejects.toThrow(/required/);
});
it('uploadForwardNodes dispatches to SsoSendLongMsg with a non-empty body and returns the res_id', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-001')) as any,
});
const resId = await forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'alice', elements: [] },
]);
expect(resId).toBe('res-001');
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg');
expect((body as Uint8Array).length).toBeGreaterThan(0);
});
it('uploadForwardNodes throws when sendRawPacket reports failure', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'pipe broken', responseData: null,
})) as any,
});
await expect(forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'a', elements: [] },
])).rejects.toThrow(/pipe broken/);
});
it('uploadForwardNodes throws when the response is missing res_id', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('')) as any,
});
await expect(forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'a', elements: [] },
])).rejects.toThrow(/missing res_id/);
});
it('fetchForwardNodes serves from cache after a successful upload (no second sendRawPacket)', async () => {
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-cache')) as any;
const bridge = mockBridge({ sendRawPacket });
const nodes = [
{ userUin: 10001, nickname: 'alice', elements: [] },
{ userUin: 10002, nickname: 'bob', elements: [] },
];
const resId = await forward.uploadForwardNodes(bridge as any, nodes);
expect(resId).toBe('res-cache');
const fetched = await forward.fetchForwardNodes(bridge as any, 'res-cache');
// Same nicknames + uins; elements have been deep-copied so the shape
// is preserved but the array reference is different.
expect(fetched).toHaveLength(2);
expect(fetched.map(n => n.nickname)).toEqual(['alice', 'bob']);
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
it('fetchForwardNodes throws on transport failure when nothing is cached', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'down', responseData: null,
})) as any,
});
await expect(forward.fetchForwardNodes(bridge as any, 'cold-cache-miss'))
.rejects.toThrow(/download forward message failed|down/);
});
});
@@ -0,0 +1,61 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
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 friend from '../../src/bridge/actions/friend';
import { mockBridge } from './_helpers';
describe('actions/friend', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
});
it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, '10001', true);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
});
it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, 'flag-abc', false);
expect(oidb.resolveUserUid).not.toHaveBeenCalled();
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
});
it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge();
await friend.deleteFriend(bridge as any, 10001, true);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0x126b_0');
expect((call[4] as any).field1.block).toBe(true);
expect(bridge.fetchFriendList).toHaveBeenCalled();
});
it('deleteFriend still succeeds when the friend-list refresh throws', async () => {
const bridge = mockBridge({
fetchFriendList: vi.fn(async () => { throw new Error('cache miss'); }),
});
await expect(friend.deleteFriend(bridge as any, 10001))
.resolves.toBeUndefined();
});
it('setFriendRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge();
await friend.setFriendRemark(bridge as any, 10001, 'best-friend');
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xb6e_2');
expect(call[4]).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});
@@ -0,0 +1,153 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Stub the OIDB shim so we can assert WHICH command + payload each
// action constructs without booting a real Bridge / native pipe.
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
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 admin from '../../src/bridge/actions/group-admin';
import { mockBridge } from './_helpers';
describe('actions/group-admin', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
});
it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge();
await admin.muteGroupMember(bridge as any, 12345, 67890, 600);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 67890, 12345);
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce();
const args = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(args[1]).toBe('OidbSvcTrpcTcp.0x1253_1');
expect(args[2]).toBe(0x1253);
expect(args[3]).toBe(1);
expect(args[4]).toMatchObject({
groupUin: 12345,
type: 1,
body: { targetUid: 'resolved-uid', duration: 600 },
});
});
it('muteGroupAll flips the muteState flag based on enable', async () => {
const bridge = mockBridge();
await admin.muteGroupAll(bridge as any, 12345, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({
groupUin: 12345,
muteState: { state: 0xFFFFFFFF },
});
await admin.muteGroupAll(bridge as any, 12345, false);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4]).toMatchObject({
muteState: { state: 0 },
});
});
it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => {
const bridge = mockBridge();
await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour');
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 67890, 12345);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({
groupUin: 12345,
targetUid: 'resolved-uid',
rejectAddRequest: true,
reason: 'bad behaviour',
});
});
it('kickGroupMembers resolves each UID in parallel', async () => {
const bridge = mockBridge();
vi.mocked(oidb.resolveUserUid)
.mockResolvedValueOnce('uid-a')
.mockResolvedValueOnce('uid-b');
await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false);
expect(oidb.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload.targetUids).toEqual(['uid-a', 'uid-b']);
expect(payload.rejectAddRequest).toBe(0);
});
it('leaveGroup sends 0x1097_1 with the groupUin', async () => {
const bridge = mockBridge();
await admin.leaveGroup(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(call[4]).toMatchObject({ groupUin: 12345 });
});
it('setGroupAdmin resolves UID and sends 0x1096_1', async () => {
const bridge = mockBridge();
await admin.setGroupAdmin(bridge as any, 12345, 67890, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({
groupUin: 12345, uid: 'resolved-uid', isAdmin: true,
});
});
it('setGroupCard / setGroupName / setGroupSpecialTitle / setGroupRemark / setGroupAddOption / setGroupSearch dispatch the right command', async () => {
const bridge = mockBridge();
await admin.setGroupCard(bridge as any, 1, 2, 'newCard');
await admin.setGroupName(bridge as any, 1, 'newName');
await admin.setGroupSpecialTitle(bridge as any, 1, 2, 'newTitle');
await admin.setGroupRemark(bridge as any, 1, 'newRemark');
await admin.setGroupAddOption(bridge as any, 1, 2);
await admin.setGroupSearch(bridge as any, 1);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x8fc_3',
'OidbSvcTrpcTcp.0x89a_15',
'OidbSvcTrpcTcp.0x8fc_2',
'OidbSvcTrpcTcp.0xf16_1',
'OidbSvcTrpcTcp.0x89a_0',
'OidbSvcTrpcTcp.0x89a_0',
]);
});
it('setGroupAddRequest picks _1 / _2 based on filtered flag', async () => {
const bridge = mockBridge();
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false);
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x10c8_1',
'OidbSvcTrpcTcp.0x10c8_2',
]);
const firstBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(firstBody.accept).toBe(1);
expect(firstBody.body.message).toBe('ok');
const secondBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4];
expect(secondBody.accept).toBe(2);
});
it('getGroupAtAllRemain decodes the response and converts BigInts', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
canAtAll: 1,
groupRemain: 12n,
uinRemain: 5n,
});
const out = await admin.getGroupAtAllRemain(bridge as any, 12345);
expect(out).toEqual({
can_at_all: true,
remain_at_all_count_for_group: 12,
remain_at_all_count_for_uin: 5,
});
});
it('getGroupAtAllRemain throws when the response is empty', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce(null);
await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/);
});
});
@@ -0,0 +1,193 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
}));
vi.mock('../../src/bridge/highway/highway-client', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
}));
vi.mock('../../src/bridge/highway/utils', () => ({
loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({
bytes: new Uint8Array([1, 2, 3]),
fileName: `${fallback}.bin`,
})),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
import * as highwayClient from '../../src/bridge/highway/highway-client';
import * as groupFile from '../../src/bridge/actions/group-file';
import { mockBridge } from './_helpers';
describe('actions/group-file', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
count: { fileCount: 42, maxCount: 1000 },
});
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 42, maxCount: 1000 });
});
it('fetchGroupFileCount falls back to defaults on partial response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ count: {} });
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
});
it('uploadGroupFile skips highway when boolFileExist is true', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
upload: {
retCode: 0,
fileId: 'fid-xyz',
boolFileExist: true,
},
});
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
upload: {
retCode: 0,
fileId: 'fid-xyz',
boolFileExist: false,
uploadIp: '1.2.3.4',
uploadPort: 8080,
fileKey: new Uint8Array([9]),
checkKey: new Uint8Array([8]),
},
});
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadGroupFile throws on missing upload response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({});
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/response missing/);
});
it('uploadGroupFile bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
upload: { retCode: 999, retMsg: 'quota exceeded' },
});
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/code=999/);
});
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({
qqInfo: { uin: '10001', selfUid: '', findGroupMember: vi.fn(() => null) },
});
vi.mocked(oidb.resolveUserUid)
.mockResolvedValueOnce('target-uid') // target user
.mockResolvedValueOnce('self-uid-resolved'); // self fallback
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true },
});
const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file');
expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' });
expect(oidb.resolveUserUid).toHaveBeenCalledTimes(2);
});
it('fetchGroupFiles paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
list: {
retCode: 0,
isEnd: true,
items: [
{ type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } },
{ type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } },
],
},
});
const out = await groupFile.fetchGroupFiles(bridge as any, 12345);
expect(out.files).toHaveLength(1);
expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' });
expect(out.folders).toHaveLength(1);
expect(out.folders[0]).toMatchObject({ folderId: 'd1', folderName: 'dir', creator: 2, creatorName: 'bob' });
});
it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
download: {
retCode: 0,
downloadDns: 'cdn.example.com',
downloadUrl: new Uint8Array([0x01, 0x02]),
},
});
const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz');
expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz');
});
it('fetchGroupFileUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
download: { retCode: 0 },
});
await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'))
.rejects.toThrow(/invalid/);
});
it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ delete: { retCode: 0 } })
.mockResolvedValueOnce({ move: { retCode: 0 } });
await groupFile.deleteGroupFile(bridge as any, 12345, 'fid');
await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[3])).toEqual([3, 5]);
});
it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ create: { retcode: 0 } })
.mockResolvedValueOnce({ delete: { retcode: 0 } })
.mockResolvedValueOnce({ rename: { retcode: 0 } });
await groupFile.createGroupFileFolder(bridge as any, 1, 'folder');
await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid');
await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[2])).toEqual([0x6D7, 0x6D7, 0x6D7]);
});
it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValue({
respHead: { retCode: 0 },
download: {
info: { domain: 'media.example.com', urlPath: '/path/x' },
rKeyParam: '?rkey=abc',
},
});
const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' });
expect(url).toBe('https://media.example.com/path/x?rkey=abc');
});
});
@@ -0,0 +1,69 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
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 msg from '../../src/bridge/actions/group-message';
import { mockBridge } from './_helpers';
describe('actions/group-message', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
});
it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => {
const bridge = mockBridge();
await msg.recallGroupMessage(bridge as any, 12345, 999);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg');
});
it('recallGroupMessage throws when sendRawPacket reports failure', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'network down',
responseData: null,
})) as any,
});
await expect(msg.recallGroupMessage(bridge as any, 12345, 999))
.rejects.toThrow(/network down/);
});
it('recallPrivateMessage resolves the target UID before dispatch', async () => {
const bridge = mockBridge();
await msg.recallPrivateMessage(bridge as any, 10001, 100, 200, 123, 1700000000);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
});
it('markGroupMessageRead and markPrivateMessageRead both hit SsoReadedReport', async () => {
const bridge = mockBridge();
await msg.markGroupMessageRead(bridge as any, 12345, 50);
await msg.markPrivateMessageRead(bridge as any, 10001, 60);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
const cmds = bridge.sendRawPacket.mock.calls.map((c: any) => c[0]);
expect(cmds).toEqual([
'trpc.msg.msg_svc.MsgService.SsoReadedReport',
'trpc.msg.msg_svc.MsgService.SsoReadedReport',
]);
});
it('setGroupEssence picks _1 for enable and _2 for disable', async () => {
const bridge = mockBridge();
await msg.setGroupEssence(bridge as any, 12345, 5, 7, true);
await msg.setGroupEssence(bridge as any, 12345, 5, 7, false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
});
});
@@ -0,0 +1,69 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
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 inter from '../../src/bridge/actions/interaction';
import { mockBridge } from './_helpers';
describe('actions/interaction', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
});
it('sendPoke group: groupUin set, friendUin=0', async () => {
const bridge = mockBridge();
await inter.sendPoke(bridge as any, true, 12345, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
});
it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => {
const bridge = mockBridge();
await inter.sendPoke(bridge as any, false, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
});
it('sendLike forwards target + count to 0x7e5_104', async () => {
const bridge = mockBridge();
await inter.sendLike(bridge as any, 10001, 3);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0x7e5_104');
expect(call[4]).toMatchObject({ targetUin: 10001, count: 3 });
});
it('setGroupReaction picks _1 for set and _2 for unset', async () => {
const bridge = mockBridge();
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true);
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
});
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
inner: { userInfo: { uin: 10001 } },
cookie: new Uint8Array([0xCA, 0xFE]),
});
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([{ uin: 10001 }]);
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
expect(out.isLast).toBe(false);
});
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({});
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([]);
expect(out.isLast).toBe(true);
});
});
+78
View File
@@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
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 misc from '../../src/bridge/actions/misc';
import { mockBridge } from './_helpers';
describe('actions/misc', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockClear();
});
it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
translateResp: { dstWords: ['你好', '世界'] },
});
const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']);
expect(out).toEqual(['你好', '世界']);
});
it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({});
await expect(misc.translateEn2Zh(bridge as any, ['hello']))
.rejects.toThrow(/empty/);
});
it('getMiniAppArk rejects unsupported types', async () => {
const bridge = mockBridge();
await expect(
misc.getMiniAppArk(bridge as any, 'youtube', 't', 'd', 'p', 'u'),
).rejects.toThrow(/unsupported type/);
});
it('getMiniAppArk routes to LightAppSvc with the encoded body', async () => {
// sendRawPacket is what the action calls; we need a deterministic
// successful response with a decodable body. Easiest: stub the
// raw packet with the encoded response we expect to come back.
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: null,
})) as any,
});
// With null responseData, the action should throw on decode — that
// still proves the right serviceCmd was used.
await expect(misc.getMiniAppArk(bridge as any, 'bili', 't', 'd', 'p', 'u')).rejects.toThrow();
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket.mock.calls[0]![0])
.toBe('LightAppSvc.mini_app_share.AdaptShareInfo');
});
it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
result: 1, errMsg: 'ok', promptText: 'hi',
});
const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100);
expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 });
});
it('sendGroupSign dispatches to 0xEB7_1', async () => {
const bridge = mockBridge();
await misc.sendGroupSign(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xEB7_1');
});
});
+109
View File
@@ -0,0 +1,109 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
}));
vi.mock('../../src/bridge/highway/highway-client', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
}));
vi.mock('../../src/bridge/highway/utils', () => ({
loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'avatar.bin' })),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
import * as highwayClient from '../../src/bridge/highway/highway-client';
import * as profile from '../../src/bridge/actions/profile';
import { mockBridge } from './_helpers';
describe('actions/profile', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => {
const bridge = mockBridge();
await profile.setOnlineStatus(bridge as any, 11, 0, 100);
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
});
it('setProfile is a no-op when both arguments are undefined', async () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any);
expect(oidb.sendOidbAndCheck).not.toHaveBeenCalled();
});
it('setProfile only sends non-undefined fields', async () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any, 'New Nick');
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce();
const body: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(body.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
});
it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
const bridge = mockBridge();
await profile.setSelfLongNick(bridge as any, 'hello world');
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect((call[4] as any).profile).toEqual({ tag: 102, value: 'hello world' });
});
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge();
await profile.setInputStatus(bridge as any, 10001, 1);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
const bridge = mockBridge();
await profile.setAvatar(bridge as any, '/some/avatar.png');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
const [, , cmdId] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
expect(cmdId).toBe(90);
});
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
userLikeInfos: [{
uid: 'u',
time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
});
const out = await profile.getProfileLike(bridge as any);
expect(out.favoriteInfo.total_count).toBe(5);
expect(out.voteInfo.total_count).toBe(7);
});
it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ userLikeInfos: [] });
await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/);
});
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
const out = await profile.getUnidirectionalFriendList(bridge as any);
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
});
@@ -3,7 +3,7 @@ import type { SendPacketResult } from '../src/protocol/packet-sender';
import { protoDecode, protoEncode } from '../src/protobuf/decode';
import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action';
vi.mock('../src/bridge/builders/element-builder', () => ({
vi.mock('../src/bridge/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
}));
+391 -29
View File
@@ -1,16 +1,39 @@
import { describe, expect, it } from 'vitest';
import { EventConverter } from '../src/onebot/event-converter';
import {
convertEvent,
elementsToOneBotSegments,
type ConverterContext,
} from '../src/onebot/event-converter';
import {
buildDispatchPayload,
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
} from '../src/onebot/event-filter';
import type { FriendMessage, GroupMessage, TempMessage } from '../src/bridge/events';
import type {
FriendMessage,
GroupMessage,
MessageElement,
QQEventVariant,
TempMessage,
} from '../src/bridge/events';
const SELF_UIN = '10001';
const SELF_ID = 10001;
const PEER_UIN = 22222;
const GROUP_ID = 99999;
/** Minimal ConverterContext with no resolvers (all null). Per-test
* helpers override individual fields when they need a stub. */
function bareCtx(overrides: Partial<ConverterContext> = {}): ConverterContext {
return {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
...overrides,
};
}
function makeFriendMessage(senderUin: number): FriendMessage {
return {
@@ -54,39 +77,378 @@ function makeTempMessage(senderUin: number): TempMessage {
};
}
describe('EventConverter post_type tagging', () => {
it('tags self friend_message as message_sent', async () => {
const conv = new EventConverter();
const result = await conv.convert(SELF_UIN, makeFriendMessage(SELF_ID));
expect(result).not.toBeNull();
expect(result!.post_type).toBe('message_sent');
expect(result!.message_type).toBe('private');
expect(result!.user_id).toBe(SELF_ID);
expect(result!.self_id).toBe(SELF_ID);
describe('convertEvent — message kinds', () => {
it('friend_message peer → post_type "message", sub_type "friend"', async () => {
const out = await convertEvent(bareCtx(), makeFriendMessage(PEER_UIN));
expect(out).not.toBeNull();
expect(out!.post_type).toBe('message');
expect(out!.message_type).toBe('private');
expect(out!.sub_type).toBe('friend');
expect(out!.user_id).toBe(PEER_UIN);
expect(out!.self_id).toBe(SELF_ID);
expect(out!.raw_message).toBe('hi');
});
it('tags self group_message as message_sent', async () => {
const conv = new EventConverter();
const result = await conv.convert(SELF_UIN, makeGroupMessage(SELF_ID));
expect(result!.post_type).toBe('message_sent');
expect(result!.message_type).toBe('group');
it('friend_message self → post_type "message_sent"', async () => {
const out = await convertEvent(bareCtx(), makeFriendMessage(SELF_ID));
expect(out!.post_type).toBe('message_sent');
});
it('tags self temp_message as message_sent', async () => {
const conv = new EventConverter();
const result = await conv.convert(SELF_UIN, makeTempMessage(SELF_ID));
expect(result!.post_type).toBe('message_sent');
expect(result!.sub_type).toBe('group');
it('group_message peer → post_type "message", sub_type "normal", group_id set', async () => {
const out = await convertEvent(bareCtx(), makeGroupMessage(PEER_UIN));
expect(out!.post_type).toBe('message');
expect(out!.message_type).toBe('group');
expect(out!.sub_type).toBe('normal');
expect(out!.group_id).toBe(GROUP_ID);
});
it('keeps incoming peer messages tagged as plain message', async () => {
const conv = new EventConverter();
const friend = await conv.convert(SELF_UIN, makeFriendMessage(PEER_UIN));
expect(friend!.post_type).toBe('message');
expect(friend!.user_id).toBe(PEER_UIN);
it('group_message self → post_type "message_sent"', async () => {
const out = await convertEvent(bareCtx(), makeGroupMessage(SELF_ID));
expect(out!.post_type).toBe('message_sent');
});
const group = await conv.convert(SELF_UIN, makeGroupMessage(PEER_UIN));
expect(group!.post_type).toBe('message');
it('temp_message peer → post_type "message", sub_type "group"', async () => {
const out = await convertEvent(bareCtx(), makeTempMessage(PEER_UIN));
expect(out!.post_type).toBe('message');
expect(out!.sub_type).toBe('group');
});
it('temp_message self → post_type "message_sent"', async () => {
const out = await convertEvent(bareCtx(), makeTempMessage(SELF_ID));
expect(out!.post_type).toBe('message_sent');
expect(out!.sub_type).toBe('group');
});
it('messageIdResolver overrides the raw msgSeq', async () => {
const ctx = bareCtx({ messageIdResolver: (_g, _s, seq) => seq * 10 });
const out = await convertEvent(ctx, makeFriendMessage(PEER_UIN));
expect(out!.message_id).toBe(10);
});
});
describe('convertEvent — notice kinds', () => {
it('group_member_join: same-actor approve, else invite', async () => {
const approve = await convertEvent(bareCtx(), {
kind: 'group_member_join',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: PEER_UIN,
} as QQEventVariant);
expect(approve!.notice_type).toBe('group_increase');
expect(approve!.sub_type).toBe('approve');
const invite = await convertEvent(bareCtx(), {
kind: 'group_member_join',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333,
} as QQEventVariant);
expect(invite!.sub_type).toBe('invite');
});
it('group_member_leave: leave / kick / kick_me', async () => {
const leave = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 0, isKick: false,
} as QQEventVariant);
expect(leave!.sub_type).toBe('leave');
const kick = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, isKick: true,
} as QQEventVariant);
expect(kick!.sub_type).toBe('kick');
const kickMe = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: SELF_ID, operatorUin: 33333, isKick: true,
} as QQEventVariant);
expect(kickMe!.sub_type).toBe('kick_me');
});
it('group_mute: ban vs lift_ban driven by duration', async () => {
const ban = await convertEvent(bareCtx(), {
kind: 'group_mute', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, duration: 600,
} as QQEventVariant);
expect(ban!.sub_type).toBe('ban');
expect(ban!.duration).toBe(600);
const lift = await convertEvent(bareCtx(), {
kind: 'group_mute', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, duration: 0,
} as QQEventVariant);
expect(lift!.sub_type).toBe('lift_ban');
});
it('group_admin: set vs unset', async () => {
const set = await convertEvent(bareCtx(), {
kind: 'group_admin', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, set: true,
} as QQEventVariant);
expect(set!.notice_type).toBe('group_admin');
expect(set!.sub_type).toBe('set');
const unset = await convertEvent(bareCtx(), {
kind: 'group_admin', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, set: false,
} as QQEventVariant);
expect(unset!.sub_type).toBe('unset');
});
it('friend_recall: passes through user + sequence-as-message_id', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_recall', time: 1, selfUin: SELF_ID,
userUin: PEER_UIN, msgSeq: 77,
} as QQEventVariant);
expect(out!.notice_type).toBe('friend_recall');
expect(out!.user_id).toBe(PEER_UIN);
expect(out!.message_id).toBe(77);
});
it('group_recall: carries operator, author, message_id', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_recall', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
operatorUin: 33333, authorUin: PEER_UIN, msgSeq: 99,
} as QQEventVariant);
expect(out!.notice_type).toBe('group_recall');
expect(out!.operator_id).toBe(33333);
expect(out!.user_id).toBe(PEER_UIN);
expect(out!.message_id).toBe(99);
});
it('friend_poke: notice/notify/poke with target_id + action fields', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_poke', time: 1, selfUin: SELF_ID,
userUin: PEER_UIN, targetUin: SELF_ID,
action: '戳了戳', suffix: '一下', actionImgUrl: 'http://x',
} as QQEventVariant);
expect(out!.notice_type).toBe('notify');
expect(out!.sub_type).toBe('poke');
expect(out!.target_id).toBe(SELF_ID);
expect(out!.action).toBe('戳了戳');
});
it('group_poke: same shape as friend_poke + group_id', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_poke', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, targetUin: SELF_ID,
action: '戳', suffix: '', actionImgUrl: '',
} as QQEventVariant);
expect(out!.notice_type).toBe('notify');
expect(out!.sub_type).toBe('poke');
expect(out!.group_id).toBe(GROUP_ID);
});
it('group_essence: add vs delete + carries random + sequence', async () => {
const add = await convertEvent(bareCtx(), {
kind: 'group_essence', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
senderUin: PEER_UIN, operatorUin: 33333, msgSeq: 50, random: 123,
set: true,
} as QQEventVariant);
expect(add!.notice_type).toBe('essence');
expect(add!.sub_type).toBe('add');
expect(add!.random).toBe(123);
expect(add!.message_seq).toBe(50);
const del = await convertEvent(bareCtx(), {
kind: 'group_essence', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
senderUin: PEER_UIN, operatorUin: 33333, msgSeq: 50, random: 123,
set: false,
} as QQEventVariant);
expect(del!.sub_type).toBe('delete');
});
it('group_file_upload: emits group_upload with file metadata', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_file_upload', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, fileId: 'f1', fileName: 'doc.txt',
fileSize: 1024, busId: 102,
} as QQEventVariant);
expect(out!.notice_type).toBe('group_upload');
expect((out!.file as Record<string, unknown>).id).toBe('f1');
expect((out!.file as Record<string, unknown>).size).toBe(1024);
});
it('friend_add: emits friend_add notice', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_add', time: 1, selfUin: SELF_ID, userUin: PEER_UIN,
} as QQEventVariant);
expect(out!.notice_type).toBe('friend_add');
expect(out!.user_id).toBe(PEER_UIN);
});
});
describe('convertEvent — request kinds', () => {
it('friend_request: request/friend with comment + flag', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_request', time: 1, selfUin: SELF_ID,
fromUin: PEER_UIN, message: '加个好友', flag: 'flag-abc',
} as QQEventVariant);
expect(out!.post_type).toBe('request');
expect(out!.request_type).toBe('friend');
expect(out!.comment).toBe('加个好友');
expect(out!.flag).toBe('flag-abc');
});
it('group_invite: request/group with sub_type defaulting to "invite"', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_invite', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
fromUin: PEER_UIN, message: '邀请', flag: 'gflag', subType: '',
} as QQEventVariant);
expect(out!.post_type).toBe('request');
expect(out!.request_type).toBe('group');
expect(out!.sub_type).toBe('invite');
const withSubType = await convertEvent(bareCtx(), {
kind: 'group_invite', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
fromUin: PEER_UIN, message: '', flag: 'gflag', subType: 'add',
} as QQEventVariant);
expect(withSubType!.sub_type).toBe('add');
});
});
describe('convertEvent — message elements (13 segment types)', () => {
// Round-trips one element through elementsToOneBotSegments and
// asserts the OneBot segment shape. Resolvers are wired only when
// the element type needs them. JsonArray's index type is JsonValue
// (a union); cast back to the segment shape so test bodies can read
// `.type` and `.data` without typeguarding every line.
type Segment = { type: string; data: Record<string, unknown> };
async function segment(element: MessageElement, opts: Partial<ConverterContext> = {}): Promise<Segment> {
const ctx = bareCtx(opts);
const segments = await elementsToOneBotSegments(
[element], false, PEER_UIN,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return segments[0] as unknown as Segment;
}
it('text -> { type:"text", data:{ text } }', async () => {
const seg = await segment({ type: 'text', text: 'hello' });
expect(seg).toEqual({ type: 'text', data: { text: 'hello' } });
});
it('face -> { type:"face", data:{ id: stringified } }', async () => {
const seg = await segment({ type: 'face', faceId: 12 });
expect(seg).toEqual({ type: 'face', data: { id: '12' } });
});
it('image: uses imageUrlResolver when wired, falls back to element.imageUrl', async () => {
const seg = await segment(
{ type: 'image', fileId: 'fid', imageUrl: 'http://fallback' },
{ imageUrlResolver: () => 'http://resolved' },
);
expect(seg.type).toBe('image');
expect((seg.data as Record<string, unknown>).url).toBe('http://resolved');
expect((seg.data as Record<string, unknown>).file).toBe('fid');
});
it('image without resolver uses element.imageUrl', async () => {
const seg = await segment({ type: 'image', fileId: 'fid', imageUrl: 'http://x' });
expect((seg.data as Record<string, unknown>).url).toBe('http://x');
});
it('at: targetUin -> qq string', async () => {
const seg = await segment({ type: 'at', targetUin: PEER_UIN });
expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } });
});
it('at all: uid="all" -> qq:"all"', async () => {
const seg = await segment({ type: 'at', uid: 'all', targetUin: 0 });
expect((seg.data as Record<string, unknown>).qq).toBe('all');
});
it('reply: replySeq is resolved through messageIdResolver when wired', async () => {
const seg = await segment(
{ type: 'reply', replySeq: 5 },
{ messageIdResolver: () => 9999 },
);
expect(seg).toEqual({ type: 'reply', data: { id: '9999' } });
});
it('reply: replySeq=0 -> id "0", no resolver call', async () => {
let resolverCalls = 0;
const seg = await segment(
{ type: 'reply', replySeq: 0 },
{ messageIdResolver: () => { resolverCalls++; return 1; } },
);
expect((seg.data as Record<string, unknown>).id).toBe('0');
expect(resolverCalls).toBe(0);
});
it('record: uses mediaUrlResolver for url', async () => {
const seg = await segment(
{ type: 'record', fileName: 'a.silk', fileId: 'fid', url: 'fallback' },
{ mediaUrlResolver: async () => 'resolved' },
);
expect(seg.type).toBe('record');
expect((seg.data as Record<string, unknown>).url).toBe('resolved');
expect((seg.data as Record<string, unknown>).file).toBe('a.silk');
});
it('video: same shape as record', async () => {
const seg = await segment(
{ type: 'video', fileName: 'a.mp4', fileId: 'fid', url: 'fallback' },
{ mediaUrlResolver: async () => 'resolved' },
);
expect(seg.type).toBe('video');
expect((seg.data as Record<string, unknown>).url).toBe('resolved');
});
it('json: text is forwarded as data.data', async () => {
const seg = await segment({ type: 'json', text: '{"a":1}' });
expect(seg).toEqual({ type: 'json', data: { data: '{"a":1}' } });
});
it('xml: text + resid (defaults to 35)', async () => {
const seg = await segment({ type: 'xml', text: '<x/>' });
expect((seg.data as Record<string, unknown>).resid).toBe(35);
const seg2 = await segment({ type: 'xml', text: '<x/>', subType: 50 });
expect((seg2.data as Record<string, unknown>).resid).toBe(50);
});
it('file: name + size + id + url + file_hash, url via mediaUrlResolver', async () => {
const seg = await segment(
{ type: 'file', fileName: 'doc.pdf', fileSize: 7, fileId: 'fid', fileHash: 'h' },
{ mediaUrlResolver: async () => 'http://download' },
);
expect(seg.type).toBe('file');
expect(seg.data).toEqual({
name: 'doc.pdf', size: 7, id: 'fid', url: 'http://download', file_hash: 'h',
});
});
it('mface: text + tab_id + sub_type', async () => {
const seg = await segment({ type: 'mface', text: 'sticker', faceId: 7, subType: 2 });
expect(seg).toEqual({ type: 'mface', data: { name: 'sticker', tab_id: 7, sub_type: 2 } });
});
it('poke: subType forwarded as data.type', async () => {
const seg = await segment({ type: 'poke', subType: 3 });
expect(seg).toEqual({ type: 'poke', data: { type: 3 } });
});
it('mediaSegmentSink fires once per image/record/video segment', async () => {
const calls: string[] = [];
const sink = (mediaType: string) => { calls.push(mediaType); };
const ctx = bareCtx({
mediaSegmentSink: sink as ConverterContext['mediaSegmentSink'],
mediaUrlResolver: async () => '',
});
await elementsToOneBotSegments(
[
{ type: 'image', fileId: 'i', imageUrl: '' },
{ type: 'record', fileName: 'r.silk', fileId: 'r' },
{ type: 'video', fileName: 'v.mp4', fileId: 'v' },
{ type: 'text', text: 'not media' },
],
true, GROUP_ID,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
expect(calls).toEqual(['image', 'record', 'video']);
});
});
+22 -8
View File
@@ -1,6 +1,15 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '../src/bridge/event-bus';
import { EventConverter } from '../src/onebot/event-converter';
// Wrap convertEvent in a vi.fn that delegates to the real impl by
// default, so one test can override it to return null without making
// the others lose the real conversion behavior.
vi.mock('../src/onebot/event-converter', async () => {
const actual = await vi.importActual<typeof import('../src/onebot/event-converter')>('../src/onebot/event-converter');
return { ...actual, convertEvent: vi.fn(actual.convertEvent) };
});
import { convertEvent, type ConverterContext } from '../src/onebot/event-converter';
import { registerEventPipeline } from '../src/onebot/event-pipeline';
import type { OneBotInstanceContext } from '../src/onebot/instance-context';
import type {
@@ -82,7 +91,13 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
} {
const bus = new BridgeEventBus();
const fakeBridge: FakeBridge = { events: bus };
const eventConverter = new EventConverter();
const converterCtx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
};
const metaCalls: Array<{ id: number; meta: MessageMeta }> = [];
const dispatchCalls: JsonObject[] = [];
@@ -93,7 +108,7 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
bridge: fakeBridge as never,
messageStore: {} as never,
mediaStore: {} as never,
eventConverter,
converterCtx,
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
dispatchEvent: (event) => { dispatchCalls.push(event); },
@@ -180,11 +195,10 @@ describe('registerEventPipeline', () => {
});
it('skips dispatch for kinds without a converter mapping (no crash)', async () => {
// Stub `convert` on a real EventConverter instance so the type stays
// honest -- no structural casts.
const stubbed = new EventConverter();
stubbed.convert = vi.fn().mockResolvedValue(null);
const { ctx, bus, dispatchCalls } = makeContext({ eventConverter: stubbed });
// Force convertEvent to return null for one call; assert the pipeline
// honours the `if (!converted) return;` guard.
vi.mocked(convertEvent).mockResolvedValueOnce(null);
const { ctx, bus, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
@@ -0,0 +1,98 @@
// image-upload tests: with the pipeline mocked out, these check the
// shape of the params each call passes — oidbCmd / serviceCmd / pic
// extBizInfo, the Highway cmdId mapping for group vs c2c, and the
// fast-upload (fingerprint) path.
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xCA, 0xFE])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
vi.mock('../../src/bridge/highway/utils', () => ({
loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'src.jpg' })),
computeHashes: vi.fn(() => ({
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
md5Hex: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
sha1Hex: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
})),
detectImageFormat: vi.fn(() => ({ format: 1000, width: 800, height: 600 })),
}));
import * as pipeline from '../../src/bridge/highway/pipeline';
import { uploadImageMsgInfo } from '../../src/bridge/highway/image-upload';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '../../src/bridge/highway/highway-client';
describe('image-upload', () => {
beforeEach(() => {
vi.mocked(pipeline.runNtv2Upload).mockClear();
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
});
it('group: uses 0x11C4_100 + GROUP_IMAGE_CMD_ID and tags scene as group', async () => {
const out = await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x' } as any);
expect(out).toEqual(new Uint8Array([0xCA, 0xFE]));
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x11C4);
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x11c4_100');
expect(args.requestId).toBe(1);
expect(args.businessType).toBe(1);
expect(args.compatQmsgSceneType).toBe(2);
expect(args.uploads[0]!.cmdId).toBe(GROUP_IMAGE_CMD_ID);
expect((args.extBizInfo as any).pic.reserveTroop).toBeDefined();
expect((args.extBizInfo as any).pic.reserveC2c).toBeUndefined();
});
it('c2c: uses 0x11C5_100 + PRIVATE_IMAGE_CMD_ID and tags scene as c2c', async () => {
await uploadImageMsgInfo({} as any, false, 'recipient-uid', { url: 'http://x' } as any);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x11C5);
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x11c5_100');
expect(args.compatQmsgSceneType).toBe(1);
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_IMAGE_CMD_ID);
expect((args.extBizInfo as any).pic.reserveC2c).toBeDefined();
expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined();
});
it('encodes the detected picFormat and image dimensions into fileInfo', async () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x' } as any);
const fileInfo = (vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo[0] as any).fileInfo;
expect(fileInfo.type.picFormat).toBe(1000);
expect(fileInfo.width).toBe(800);
expect(fileInfo.height).toBe(600);
expect(fileInfo.original).toBe(1);
});
it('forwards subType into bizType and ${subType}-aware textSummary', async () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 1 } as any);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect((args.extBizInfo as any).pic.bizType).toBe(1);
expect((args.extBizInfo as any).pic.textSummary).toBe('[sticker]');
});
it('fingerprint path (noByteFallback): zero bytes, fastOnly error message ready', async () => {
await uploadImageMsgInfo({} as any, true, 12345, {
noByteFallback: true, md5Hex: 'aa', sha1Hex: 'bb', summary: '[image]',
} as any);
const sub = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads[0]!;
expect(sub.bytes.length).toBe(0);
expect(sub.fastOnlyError).toMatch(/fast-upload not available/);
});
it('fingerprint path rejects when md5Hex or sha1Hex is missing', async () => {
await expect(uploadImageMsgInfo({} as any, true, 12345, {
noByteFallback: true,
} as any)).rejects.toThrow(/requires md5Hex/);
});
it('finalize is invoked with pic defaults for image', async () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 0 } as any);
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[image]' });
});
});
@@ -0,0 +1,370 @@
// Pipeline tests: runNtv2Upload + finalizeMediaMsgInfo.
//
// Highway transport (fetchHighwaySession / uploadHighwayHttp /
// buildHighwayExtend) is mocked so tests run without a real session.
// The OIDB response is built with real protobuf encoding so we exercise
// the actual decode path inside the pipeline.
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/highway/highway-client', () => ({
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
uploadHighwayHttp: vi.fn(async () => undefined),
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
PRIVATE_IMAGE_CMD_ID: 1003,
GROUP_IMAGE_CMD_ID: 1004,
}));
import * as highway from '../../src/bridge/highway/highway-client';
import {
finalizeMediaMsgInfo,
hexToBytes,
makeClientRandomId,
runNtv2Upload,
type MediaSubFileUpload,
} from '../../src/bridge/highway/pipeline';
import { protoDecode, protoEncode } from '../../src/protobuf/decode';
import { makeOidbBaseSchema } from '../../src/bridge/proto/oidb';
import {
EncodableMediaMsgInfoSchema,
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
} from '../../src/bridge/proto/highway';
interface FakeUploadResponse {
upload?: {
uKey?: string;
ipv4s?: Array<{ ipv4?: string; port?: number }>;
msgInfo?: {
msgInfoBody?: Array<Record<string, unknown>>;
extBizInfo?: Record<string, unknown>;
};
subFileInfos?: Array<{
uKey?: string;
ipv4s?: Array<{ ipv4?: string; port?: number }>;
}>;
};
respHead?: { retCode?: number; message?: string };
}
function encodeOidbResponse(body: FakeUploadResponse, opts: { errorCode?: number; errorMsg?: string } = {}): Buffer {
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
return Buffer.from(protoEncode({
command: 0x11C4,
subCommand: 100,
errorCode: opts.errorCode ?? 0,
// The OIDB base schema types `body` as a generic ProtoDecoded record;
// the test shape is more specific, so we cast through unknown.
body: body as unknown as Record<string, unknown>,
errorMsg: opts.errorMsg ?? '',
reserved: 1,
}, baseSchema));
}
type SendPacketResult = {
success: boolean;
gotResponse: boolean;
errorCode: number;
errorMessage: string;
responseData: Buffer | null;
};
function makeBridge(opts: {
responseData?: Buffer | null;
success?: boolean;
errorMessage?: string;
} = {}) {
// Explicit two-arg signature so `mock.calls[0]` typechecks as
// [string, Uint8Array] rather than the inferred empty tuple.
const sendRawPacket = vi.fn<(cmd: string, body: Uint8Array) => Promise<SendPacketResult>>(
async () => ({
success: opts.success ?? true,
gotResponse: opts.responseData !== null,
errorCode: 0,
errorMessage: opts.errorMessage ?? '',
responseData: opts.responseData ?? Buffer.alloc(0),
}),
);
return { sendRawPacket };
}
function baseParams(overrides: Record<string, unknown> = {}) {
return {
bridge: makeBridge() as any,
isGroup: true,
targetIdOrUid: 12345,
oidbCmd: 0x11C4,
serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
requestId: 1,
businessType: 1,
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
compatQmsgSceneType: 2,
extBizInfo: { pic: {} },
uploads: [] as MediaSubFileUpload[],
...overrides,
};
}
describe('pipeline — runNtv2Upload', () => {
beforeEach(() => {
vi.mocked(highway.fetchHighwaySession).mockClear();
vi.mocked(highway.uploadHighwayHttp).mockClear();
vi.mocked(highway.buildHighwayExtend).mockClear();
});
it('builds an NTV2 request body and dispatches to the configured serviceCmd', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
});
await runNtv2Upload(baseParams({ bridge }));
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [serviceCmd, requestBytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('OidbSvcTrpcTcp.0x11c4_100');
expect((requestBytes as Uint8Array).length).toBeGreaterThan(0);
// The request roundtrips through the real OIDB envelope and carries
// the requestId / businessType / scene fields we passed.
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const decoded: any = protoDecode(requestBytes as Uint8Array, baseSchema);
expect(decoded.command).toBe(0x11C4);
expect(decoded.body.reqHead.common.requestId).toBe(1);
expect(decoded.body.reqHead.scene.businessType).toBe(1);
expect(decoded.body.reqHead.scene.sceneType).toBe(2); // isGroup -> 2
expect(decoded.body.reqHead.scene.group.groupUin).toBe(12345);
});
it('builds a c2c body when isGroup is false', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
});
await runNtv2Upload(baseParams({ bridge, isGroup: false, targetIdOrUid: 'recipient-uid' }));
const requestBytes = bridge.sendRawPacket.mock.calls[0]![1];
const decoded: any = protoDecode(requestBytes as Uint8Array, makeOidbBaseSchema(NTV2UploadRichMediaReqSchema));
expect(decoded.body.reqHead.scene.sceneType).toBe(1);
expect(decoded.body.reqHead.scene.c2c.targetUid).toBe('recipient-uid');
});
it('returns the decoded `upload` object on success', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'fake-ukey',
msgInfo: { msgInfoBody: [{ fileExist: true }], extBizInfo: {} },
},
}),
});
const upload = await runNtv2Upload(baseParams({ bridge }));
expect(upload.uKey).toBe('fake-ukey');
expect(upload.msgInfo.msgInfoBody).toHaveLength(1);
});
it('throws on transport failure', async () => {
const bridge = makeBridge({ success: false, errorMessage: 'pipe broken', responseData: null });
await expect(runNtv2Upload(baseParams({ bridge })))
.rejects.toThrow(/pipe broken/);
});
it('throws on OIDB errorCode != 0', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({}, { errorCode: 42, errorMsg: 'boom' }),
});
await expect(runNtv2Upload(baseParams({ bridge })))
.rejects.toThrow(/OIDB error 42/);
});
it('throws on body.respHead.retCode != 0', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
respHead: { retCode: 7, message: 'rate-limited' },
}),
});
await expect(runNtv2Upload(baseParams({ bridge })))
.rejects.toThrow(/rate-limited/);
});
it('throws "response body missing" when body.upload is absent', async () => {
const bridge = makeBridge({ responseData: encodeOidbResponse({}) });
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
.rejects.toThrow(/image upload response body missing/);
});
it('does NOT run Highway PUT when the server omits uKey (fast-path)', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } /* no uKey */ },
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
}],
}));
expect(highway.fetchHighwaySession).not.toHaveBeenCalled();
expect(highway.uploadHighwayHttp).not.toHaveBeenCalled();
});
it('runs Highway PUT for the top-level uKey', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'ukey-xyz',
ipv4s: [{ ipv4: '1.2.3.4', port: 8080 }],
msgInfo: { msgInfoBody: [], extBizInfo: {} },
},
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
}],
}));
expect(highway.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highway.buildHighwayExtend).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('routes sub-file uploads via upload.subFileInfos[N]', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'main-ukey',
ipv4s: [{ ipv4: '1.1.1.1', port: 80 }],
msgInfo: { msgInfoBody: [], extBizInfo: {} },
subFileInfos: [
{ uKey: 'thumb-ukey', ipv4s: [{ ipv4: '2.2.2.2', port: 81 }] },
],
},
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [
{ source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20), subFileIndex: 0 },
{ source: 0, cmdId: 1002, bytes: new Uint8Array([2]), md5: new Uint8Array(16), sha1: new Uint8Array(20), subFileIndex: 1 },
],
}));
// Both Highway PUTs ran; only ONE Highway session was fetched.
expect(highway.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledTimes(2);
expect(highway.buildHighwayExtend).toHaveBeenCalledTimes(2);
// The two Highway PUTs received the right uKeys.
const extendCalls = vi.mocked(highway.buildHighwayExtend).mock.calls;
expect(extendCalls[0]![0]).toBe('main-ukey');
expect(extendCalls[1]![0]).toBe('thumb-ukey');
});
it('throws fastOnlyError when uKey is present but bytes are empty', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'ukey-xyz',
msgInfo: { msgInfoBody: [], extBizInfo: {} },
},
}),
});
await expect(runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array(0),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
fastOnlyError: 'image fast-upload not available',
}],
}))).rejects.toThrow(/image fast-upload not available/);
});
it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => {
// This mirrors the video-thumb path where bytes are always synthesised
// (FALLBACK_THUMB) so we don't expect the check to fire even if the
// server returns an empty thumb uKey alongside a present main uKey.
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'main-ukey',
msgInfo: { msgInfoBody: [], extBizInfo: {} },
subFileInfos: [{ uKey: 'thumb-ukey' }],
},
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [
{ source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20) },
{ source: 0, cmdId: 1002, bytes: new Uint8Array(0), md5: new Uint8Array(16), sha1: new Uint8Array(20) },
],
}));
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce(); // only main
});
});
describe('pipeline — finalizeMediaMsgInfo', () => {
it('throws when msgInfo is missing', () => {
expect(() => finalizeMediaMsgInfo({})).toThrow(/missing msgInfo/);
});
it('encodes msgInfoBody + extBizInfo from the server response', () => {
const out = finalizeMediaMsgInfo({
msgInfo: {
msgInfoBody: [{ index: { fileType: 1 }, fileExist: true }],
extBizInfo: { busiType: 1 },
},
});
expect(out).toBeInstanceOf(Uint8Array);
expect(out.length).toBeGreaterThan(0);
});
it('with defaultPic, fills missing pic.bizType + pic.textSummary', () => {
// Encode the result and decode it back via the same schema to inspect
// what actually landed in the proto.
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: {} },
}, { bizType: 7, textSummary: '[image]' });
const decoded: any = protoDecode(out, EncodableMediaMsgInfoSchema);
expect(decoded.extBizInfo.pic.bizType).toBe(7);
expect(decoded.extBizInfo.pic.textSummary).toBe('[image]');
});
it('without defaultPic, leaves pic untouched when server omits it', () => {
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: {} },
});
const decoded: any = protoDecode(out, EncodableMediaMsgInfoSchema);
// An empty extBizInfo proto roundtrips to undefined; either way the
// pic field never got materialised.
expect(decoded?.extBizInfo?.pic).toBeUndefined();
});
});
describe('pipeline — helpers', () => {
it('hexToBytes roundtrips even-length hex', () => {
expect([...hexToBytes('deadbeef')]).toEqual([0xDE, 0xAD, 0xBE, 0xEF]);
});
it('hexToBytes left-pads odd-length hex with a leading zero', () => {
expect([...hexToBytes('abc')]).toEqual([0x0A, 0xBC]);
});
it('makeClientRandomId produces a non-zero positive BigInt', () => {
const id = makeClientRandomId();
expect(typeof id).toBe('bigint');
expect(id).toBeGreaterThan(0n);
expect(id).toBeLessThan(0x8000000000000000n);
});
});
@@ -0,0 +1,88 @@
// ptt-upload tests focus on the fingerprint (fast-upload) path: the
// regular load path goes through ffmpeg's silk encoder + the OS temp
// directory, which we don't want to exercise in a unit test. The
// fingerprint path covers most of what makes ptt-upload distinct
// (group/c2c requestId difference, command id mapping, NapCat-style
// bytesGeneralFlags, voiceFormat honouring).
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
import * as pipeline from '../../src/bridge/highway/pipeline';
import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '../../src/bridge/highway/ptt-upload';
const FINGERPRINT = {
noByteFallback: true,
md5Hex: 'aa',
sha1Hex: 'bb',
fileSize: 1234,
duration: 5,
} as any;
describe('ptt-upload', () => {
beforeEach(() => {
vi.mocked(pipeline.runNtv2Upload).mockClear();
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
});
it('group: 0x126E_100 + GROUP_PTT_CMD_ID + group-flavored bytesGeneralFlags', async () => {
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x126E);
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x126e_100');
expect(args.requestId).toBe(1); // group
expect(args.businessType).toBe(3);
expect(args.uploads[0]!.cmdId).toBe(GROUP_PTT_CMD_ID);
const groupFlags = (args.extBizInfo as any).ptt.bytesGeneralFlags;
expect(groupFlags).toEqual(
new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00]),
);
});
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + c2c-flavored flags', async () => {
await uploadPttMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x126D);
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x126d_100');
expect(args.requestId).toBe(4);
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_PTT_CMD_ID);
const c2cFlags = (args.extBizInfo as any).ptt.bytesGeneralFlags;
expect(c2cFlags.length).toBe(14);
expect(c2cFlags[0]).toBe(0x9a);
});
it('fingerprint payload: zero bytes, fastOnlyError ready, voiceFormat defaults to 1', async () => {
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.uploads[0]!.bytes.length).toBe(0);
expect(args.uploads[0]!.fastOnlyError).toMatch(/record fast-upload not available/);
const fileInfo: any = (args.uploadInfo[0] as any).fileInfo;
expect(fileInfo.type.voiceFormat).toBe(1);
expect(fileInfo.time).toBe(5);
});
it('honours an explicit voiceFormat from the fingerprint', async () => {
await uploadPttMsgInfo({} as any, true, 12345, { ...FINGERPRINT, voiceFormat: 2 });
const fileInfo: any = (vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo[0] as any).fileInfo;
expect(fileInfo.type.voiceFormat).toBe(2);
});
it('fingerprint mode rejects when md5Hex or sha1Hex is missing', async () => {
await expect(
uploadPttMsgInfo({} as any, true, 12345, { noByteFallback: true } as any),
).rejects.toThrow(/requires md5Hex/);
});
it('finalize is called without a defaultPic (ptt copies pic from server only)', async () => {
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(args[1]).toBeUndefined();
});
});
@@ -0,0 +1,118 @@
// video-upload tests cover the fingerprint (fast-upload) path. The
// regular load path exercises ffmpeg + the OS temp dir + a streaming
// SHA1 implementation; that machinery has its own seams worth testing
// separately, and isn't what makes video-upload distinct at the API
// surface.
//
// What we're checking here: the two-sub-file shape (main + thumb), the
// thumb's source routing (`upload.subFileInfos[0]`), the per-sub-file
// fastOnlyError difference (main has it; thumb doesn't — FALLBACK_THUMB
// always provides bytes), and the video-specific OIDB fields.
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0x12, 0x34])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
import * as pipeline from '../../src/bridge/highway/pipeline';
import {
uploadVideoMsgInfo,
GROUP_VIDEO_CMD_ID,
GROUP_VIDEO_THUMB_CMD_ID,
PRIVATE_VIDEO_CMD_ID,
PRIVATE_VIDEO_THUMB_CMD_ID,
} from '../../src/bridge/highway/video-upload';
const FINGERPRINT = {
noByteFallback: true,
md5Hex: 'aa',
sha1Hex: 'bb',
fileSize: 1024,
width: 320,
height: 240,
duration: 10,
videoFormat: 0,
} as any;
describe('video-upload', () => {
beforeEach(() => {
vi.mocked(pipeline.runNtv2Upload).mockClear();
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
});
it('group: 0x11EA_100 + GROUP_VIDEO_CMD_ID for main, GROUP_VIDEO_THUMB_CMD_ID for thumb', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x11EA);
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x11ea_100');
expect(args.requestId).toBe(3);
expect(args.businessType).toBe(2);
expect(args.compatQmsgSceneType).toBe(2);
expect(args.uploads).toHaveLength(2);
expect(args.uploads[0]!.cmdId).toBe(GROUP_VIDEO_CMD_ID);
expect(args.uploads[1]!.cmdId).toBe(GROUP_VIDEO_THUMB_CMD_ID);
});
it('c2c: 0x11E9_100 + PRIVATE cmd ids', async () => {
await uploadVideoMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x11E9);
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_VIDEO_CMD_ID);
expect(args.uploads[1]!.cmdId).toBe(PRIVATE_VIDEO_THUMB_CMD_ID);
});
it('main file routes via "top", thumb routes via subFileInfos[0]', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
expect(uploads[0]!.source).toBe('top');
expect(uploads[0]!.subFileIndex).toBe(0);
expect(uploads[1]!.source).toBe(0);
expect(uploads[1]!.subFileIndex).toBe(1);
});
it('main fastOnlyError is set; thumb is silent (FALLBACK_THUMB always has bytes)', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
expect(uploads[0]!.fastOnlyError).toMatch(/video fast-upload not available/);
expect(uploads[1]!.fastOnlyError).toBeUndefined();
});
it('uploadInfo carries TWO entries (main mp4 + thumb jpg) with subFileType 0 and 100', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploadInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
expect(uploadInfo).toHaveLength(2);
expect((uploadInfo[0] as any).subFileType).toBe(0);
expect((uploadInfo[1] as any).subFileType).toBe(100);
expect((uploadInfo[0] as any).fileInfo.type.type).toBe(2); // video
expect((uploadInfo[1] as any).fileInfo.type.type).toBe(1); // pic (thumb)
});
it('thumb falls back to a synthesized 1x1 PNG with real bytes', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
expect(uploads[1]!.bytes.length).toBeGreaterThan(0); // FALLBACK_THUMB is non-empty
});
it('main file uses per-1MB-block sha1 (an Uint8Array[]) — fingerprint path uses an empty array', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
// The fingerprint payload sets sha1Blocks: [] (no real bytes to chunk).
expect(Array.isArray(uploads[0]!.sha1)).toBe(true);
expect((uploads[0]!.sha1 as Uint8Array[]).length).toBe(0);
});
it('fingerprint mode rejects when md5Hex or sha1Hex is missing', async () => {
await expect(
uploadVideoMsgInfo({} as any, true, 12345, { noByteFallback: true } as any),
).rejects.toThrow(/requires md5Hex/);
});
it('finalize is called without a defaultPic', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(args[1]).toBeUndefined();
});
});
+104
View File
@@ -0,0 +1,104 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook/hook-manager';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { ManualMapHandle } from '../src/hook/injector';
import type { BridgeManager } from '../src/bridge/manager';
import type { QqHookClient } from '../src/hook/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
// FakeClient — never connected; just needs to satisfy EventEmitter +
// a minimal subset of QqHookClient for HookSession.tearDownClient().
const makeClient = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManager;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
});
return {
manager,
inject,
pipeWatcher,
setProcesses: (next: number[]) => { pids = next; },
};
}
describe('HookManager.autoLoadOnDiscovery', () => {
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
expect(ctx.inject).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('injects every newly-discovered PID when flag is on', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
await ctx.pipeWatcher.start();
// session.load() is queued via a per-session promise chain; flush twice
// so the auto-load runs to completion before we assert.
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
expect(ctx.inject).toHaveBeenCalledWith(4242);
// A second PID appearing mid-flight should also trigger an inject.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
ctx.manager.dispose();
});
it('swallows inject errors so the watcher keeps running', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
await ctx.pipeWatcher.start();
await flush();
await flush();
// Second PID should still be auto-loaded — the failure on 4242 must
// not leak out of the listener and break the watcher's emit loop.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
ctx.manager.dispose();
});
});
+418
View File
@@ -0,0 +1,418 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook/hook-session';
import type { ManualMapHandle } from '../src/hook/injector';
import type { QqHookClient, QqHookPacket } from '../src/hook/qq-hook-client';
import type { PacketSink } from '../src/protocol/types';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
/** Minimal stand-in for QqHookClient. Tests drive login/packet/error/close
* events directly via fire* helpers. connectAll succeeds unless told otherwise. */
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
shouldFailConnect = false;
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.shouldFailConnect) throw new Error('connect failed');
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { ...this.loginState }; }
close(): void {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
fireLogin(uin: string): void {
this.isLoggedIn = true;
this.loginState = { loggedIn: true, uin, uinNumber: BigInt(uin) };
this.emit('loginState', { ...this.loginState });
}
firePacket(packet: QqHookPacket): void {
this.emit('packet', packet);
}
}
function makeSession(opts: {
pid?: number;
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
const clients: FakeClient[] = [];
const injector = {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
const session = new HookSession(pid, {
injector,
makeClient: () => {
const c = new FakeClient();
if (opts.clientFailsConnect) c.shouldFailConnect = true;
clients.push(c);
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
return {
session,
injector,
clients,
currentClient: () => clients[clients.length - 1]!,
setPipeLive: (v: boolean) => { pipeLive = v; },
};
}
const flush = () => new Promise<void>(r => setImmediate(r));
describe('HookSession — load', () => {
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
const { session, injector } = makeSession({ pipeLive: false });
const info = await session.load();
expect(injector.inject).toHaveBeenCalledOnce();
expect(info.status).toBe('connecting');
expect(info.method).toBe('loadModuleManual');
expect(info.injected).toBe(true);
});
it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => {
const { session, injector } = makeSession({ pipeLive: true });
const info = await session.load();
expect(injector.inject).not.toHaveBeenCalled();
expect(info.method).toBe('reconnect');
expect(info.injected).toBe(true);
expect(info.status).toBe('connecting');
});
it('inject failure → status error, error message captured', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
unload: vi.fn(),
};
const session = new HookSession(1234, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
const info = await session.load();
expect(info.status).toBe('error');
expect(info.error).toBe('inject boom');
});
});
describe('HookSession — pipe up/down → connect lifecycle', () => {
it('onPipeUp after load: client connects → status loaded', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('loaded');
expect(ctx.clients).toHaveLength(1);
});
it('emits "login" with (uin, sender) after client signals loggedIn', async () => {
const ctx = makeSession({ pipeLive: true });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
expect(loginSpy).toHaveBeenCalledOnce();
const [uin, sender] = loginSpy.mock.calls[0]!;
expect(uin).toBe('10001');
expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
});
it('does not re-emit "login" on duplicate loginState with same uin', async () => {
const ctx = makeSession({ pipeLive: true });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('10001');
expect(loginSpy).toHaveBeenCalledOnce();
});
it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => {
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('connecting');
expect(ctx.session.error).toBe('connect failed');
});
it('onPipeDown while logged in: emits disconnected(true), status disconnected', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.session.onPipeDown();
await flush();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.session.status).toBe('disconnected');
});
it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
// No login fired — we're connected but not logged in.
ctx.session.onPipeDown();
await flush();
// disconnected(false) is currently NOT emitted — disconnect events are
// reserved for "we owe BridgeManager a disconnect notification". This
// preserves the original behaviour.
expect(discSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('connecting');
});
it('repeated pipe down → up cycles reach consistent state', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
expect(ctx.session.status).toBe('online');
ctx.session.onPipeDown();
await flush();
expect(ctx.session.status).toBe('disconnected');
// Pipe returns — session builds a fresh client.
ctx.session.onPipeUp();
await flush();
expect(ctx.clients.length).toBeGreaterThan(1);
expect(ctx.session.status).toBe('loaded');
});
});
describe('HookSession — unload', () => {
it('while logged in: emits disconnected(true), calls unload, status available', async () => {
const ctx = makeSession({ pipeLive: false });
await ctx.session.load();
ctx.setPipeLive(true);
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
ctx.setPipeLive(false); // unload verification will see the pipe gone
await ctx.session.unload();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.injector.unload).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('available');
});
it('when pipe stays live after unload: status connecting with retry message', async () => {
const ctx = makeSession({ pipeLive: false });
await ctx.session.load();
// Simulate the unload-failed scenario: pipe is still up after unload.
ctx.setPipeLive(true);
const info = await ctx.session.unload();
expect(info.status).toBe('connecting');
expect(info.error).toContain('命名管道仍然存在');
});
});
describe('HookSession — serialization', () => {
it('user mashing load → unload → load runs in order, end state consistent', async () => {
const ctx = makeSession({ pipeLive: false });
const p1 = ctx.session.load();
const p2 = ctx.session.unload();
const p3 = ctx.session.load();
await Promise.all([p1, p2, p3]);
expect(ctx.injector.inject).toHaveBeenCalledTimes(2);
expect(ctx.injector.unload).toHaveBeenCalledTimes(1);
expect(ctx.session.status).toBe('connecting');
});
it('onPipeUp queued behind in-flight load resolves correctly', async () => {
const ctx = makeSession({ pipeLive: true });
const loadPromise = ctx.session.load();
ctx.session.onPipeUp(); // queued behind load
await loadPromise;
await flush();
expect(ctx.session.status).toBe('loaded');
});
});
describe('HookSession — process gone', () => {
it('emits disconnected(true) then disposed when killed while logged in', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const events: string[] = [];
ctx.session.on('disconnected', () => events.push('disconnected'));
ctx.session.on('disposed', () => events.push('disposed'));
ctx.session.notifyProcessGone();
await flush();
expect(events).toEqual(['disconnected', 'disposed']);
expect(ctx.session.isDisposed).toBe(true);
});
it('emits only disposed when killed before login', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
const events: string[] = [];
ctx.session.on('disconnected', () => events.push('disconnected'));
ctx.session.on('disposed', () => events.push('disposed'));
ctx.session.notifyProcessGone();
await flush();
expect(events).toEqual(['disposed']);
});
});
describe('HookSession — packet forwarding', () => {
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
// we can exercise the transformation with a plain vi.fn() sink, no
// event-emitter machinery required.
it('forwards parsed packets to onPacket sink with PacketInfo shape', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket({
seq: 42,
error: 0,
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
uin: '10001',
body: Buffer.from([0x01, 0x02, 0x03]),
});
expect(onPacket).toHaveBeenCalledOnce();
const pkt = onPacket.mock.calls[0]![0];
expect(pkt).toMatchObject({
pid: 1234,
uin: '10001',
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 42,
retCode: 0,
fromClient: false,
});
expect(Buffer.isBuffer(pkt.body)).toBe(true);
expect([...pkt.body]).toEqual([1, 2, 3]);
});
it('falls back to session uin when packet.uin is empty', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0),
});
expect(onPacket.mock.calls[0]![0].uin).toBe('10001');
});
it('drops packets received before login', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
// No login fired yet.
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0),
});
expect(onPacket).not.toHaveBeenCalled();
});
it('drops packets whose uin is non-real ("0" / too short / non-numeric)', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
// Packet uin '0' falls back to session uin '10001' — that one passes.
// Force a bad uin via the packet AND null out session uin by simulating
// a logout? Simpler: send a packet with uin '42' (numeric but <5 chars).
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '42', body: Buffer.alloc(0),
});
expect(onPacket).not.toHaveBeenCalled();
});
it('is a no-op when no onPacket sink is provided', async () => {
const ctx = makeSession({ pipeLive: true }); // no onPacket
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
// Should not throw / crash.
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]),
});
});
});
+127
View File
@@ -0,0 +1,127 @@
import { describe, it, expect, vi } from 'vitest';
import { MediaIndexer } from '../src/onebot/media-indexer';
import type { MessageElement } from '../src/bridge/events';
function makeMediaStore() {
return {
rememberImage: vi.fn(),
rememberRecord: vi.fn(),
rememberVideo: vi.fn(),
};
}
describe('MediaIndexer', () => {
it('image: maps element fields into rememberImage with file fallback to fileId', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = {
type: 'image',
fileId: 'img-fid',
fileSize: 1024,
subType: 1,
summary: '[image]',
imageUrl: 'http://orig',
md5Hex: 'abcd',
sha1Hex: 'efgh',
width: 800,
height: 600,
picFormat: 1000,
};
indexer.remember('image', element, { url: 'http://x', file: '' }, true, 99999);
expect(store.rememberImage).toHaveBeenCalledOnce();
const arg = store.rememberImage.mock.calls[0]![0];
expect(arg).toMatchObject({
file: 'img-fid', // data.file was '', fell back to element.fileId
url: 'http://x',
fileSize: 1024,
subType: 1,
summary: '[image]',
imageUrl: 'http://orig',
isGroup: true,
sessionId: 99999,
md5Hex: 'abcd',
sha1Hex: 'efgh',
width: 800,
height: 600,
picFormat: 1000,
});
});
it('record: maps element fields into rememberRecord with file fallback chain', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = {
type: 'record',
fileId: 'rec-fid',
fileName: 'voice.amr',
fileSize: 2048,
duration: 5,
fileHash: 'h',
mediaNode: { fileUuid: 'uuid' },
md5Hex: 'm',
sha1Hex: 's',
voiceFormat: 1,
};
indexer.remember('record', element, { url: 'http://r', file: '' }, false, 12345);
const arg = store.rememberRecord.mock.calls[0]![0];
expect(arg.file).toBe('voice.amr'); // data.file '' → element.fileName
expect(arg.fileId).toBe('rec-fid');
expect(arg.duration).toBe(5);
expect(arg.isGroup).toBe(false);
expect(arg.sessionId).toBe(12345);
expect(arg.voiceFormat).toBe(1);
});
it('video: maps element fields into rememberVideo', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = {
type: 'video',
fileId: 'vid-fid',
fileName: 'clip.mp4',
fileSize: 99999,
duration: 30,
width: 1920,
height: 1080,
videoFormat: 2,
};
indexer.remember('video', element, { url: 'http://v', file: 'override.mp4' }, true, 11111);
const arg = store.rememberVideo.mock.calls[0]![0];
expect(arg.file).toBe('override.mp4'); // data.file used when non-empty
expect(arg.fileId).toBe('vid-fid');
expect(arg.duration).toBe(30);
expect(arg.width).toBe(1920);
expect(arg.videoFormat).toBe(2);
});
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = { type: 'record', fileId: 'only-fid' };
indexer.remember('record', element, { url: '', file: '' }, false, 1);
expect(store.rememberRecord.mock.calls[0]![0].file).toBe('only-fid');
});
it('defaults missing numeric fields to 0 / missing strings to ""', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
const arg = store.rememberImage.mock.calls[0]![0];
expect(arg.fileSize).toBe(0);
expect(arg.subType).toBe(0);
expect(arg.summary).toBe('');
expect(arg.imageUrl).toBe('');
});
it('only the matching rememberX is called', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
expect(store.rememberImage).toHaveBeenCalledOnce();
expect(store.rememberRecord).not.toHaveBeenCalled();
expect(store.rememberVideo).not.toHaveBeenCalled();
});
});
+59 -46
View File
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import path from 'path';
import { MediaStore } from '../src/onebot/media-store';
import { EventConverter } from '../src/onebot/event-converter';
import { convertEvent, type ConverterContext } from '../src/onebot/event-converter';
import type { GroupMessage, FriendMessage, MessageElement } from '../src/bridge/events';
const SELF_UIN = '10001';
@@ -208,7 +208,7 @@ describe('MediaStore basic semantics', () => {
});
});
describe('EventConverter media segment sink → MediaStore wiring', () => {
describe('convertEvent media segment sink → MediaStore wiring', () => {
const dbs: string[] = [];
afterEach(() => {
@@ -221,14 +221,19 @@ describe('EventConverter media segment sink → MediaStore wiring', () => {
});
it('emits sink invocations for image segments with the right context', async () => {
const conv = new EventConverter();
const sinkCalls: Array<{ type: string; isGroup: boolean; sessionId: number; file: string }> = [];
conv.setMediaSegmentSink((type, _element, data, isGroup, sessionId) => {
sinkCalls.push({ type, isGroup, sessionId, file: String(data.file ?? '') });
});
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: (type, _element, data, isGroup, sessionId) => {
sinkCalls.push({ type, isGroup, sessionId, file: String(data.file ?? '') });
},
};
await conv.convert(SELF_UIN, makeGroupMessage([imageElement()]));
await conv.convert(SELF_UIN, makeFriendMessage([recordElement()]));
await convertEvent(ctx, makeGroupMessage([imageElement()]));
await convertEvent(ctx, makeFriendMessage([recordElement()]));
expect(sinkCalls).toEqual([
{ type: 'image', isGroup: true, sessionId: GROUP_ID, file: 'abc.png' },
@@ -241,42 +246,45 @@ describe('EventConverter media segment sink → MediaStore wiring', () => {
dbs.push(dbPath);
const store = new MediaStore(dbPath);
const conv = new EventConverter();
conv.setImageUrlResolver((element) => element.imageUrl ?? '');
conv.setMediaUrlResolver(async (element) => element.url ?? '');
conv.setMediaSegmentSink((type, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (type === 'image') {
store.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
});
} else {
store.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
});
}
});
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: (element) => element.imageUrl ?? '',
mediaUrlResolver: async (element) => element.url ?? '',
messageIdResolver: null,
mediaSegmentSink: (type, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (type === 'image') {
store.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
});
} else {
store.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
});
}
},
};
await conv.convert(SELF_UIN, makeGroupMessage([imageElement()]));
await conv.convert(SELF_UIN, makeFriendMessage([recordElement()]));
await convertEvent(ctx, makeGroupMessage([imageElement()]));
await convertEvent(ctx, makeFriendMessage([recordElement()]));
const img = store.findImage('abc.png');
expect(img).not.toBeNull();
@@ -297,10 +305,15 @@ describe('EventConverter media segment sink → MediaStore wiring', () => {
});
it('does not invoke the sink when no media segments are present', async () => {
const conv = new EventConverter();
let calls = 0;
conv.setMediaSegmentSink(() => { calls++; });
await conv.convert(SELF_UIN, makeGroupMessage([{ type: 'text', text: 'hello' }]));
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: () => { calls++; },
};
await convertEvent(ctx, makeGroupMessage([{ type: 'text', text: 'hello' }]));
expect(calls).toBe(0);
});
});
@@ -0,0 +1,138 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MediaUrlResolver } from '../src/onebot/media-url-resolver';
import type { MessageElement } from '../src/bridge/events';
// Minimal stand-ins for the two collaborators. Each test wires whatever
// subset of Bridge methods the element type exercises.
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
return {
fetchGroupFileUrl: vi.fn(async () => 'http://group/file'),
fetchPrivateFileUrl: vi.fn(async () => 'http://private/file'),
fetchGroupPttUrlByNode: vi.fn(async () => 'http://group/ptt'),
fetchPrivatePttUrlByNode: vi.fn(async () => 'http://private/ptt'),
fetchGroupVideoUrlByNode: vi.fn(async () => 'http://group/video'),
fetchPrivateVideoUrlByNode: vi.fn(async () => 'http://private/video'),
...overrides,
};
}
function makeRkey(overrides: { resolveMediaUrl?: ReturnType<typeof vi.fn> } = {}) {
return {
resolveMediaUrl: overrides.resolveMediaUrl ?? vi.fn(async (_bridge, el: MessageElement) => el.url ?? ''),
};
}
const MEDIA_NODE = { fileUuid: 'uuid-1' };
describe('MediaUrlResolver — file element', () => {
let bridge: ReturnType<typeof makeBridge>;
let rkey: ReturnType<typeof makeRkey>;
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
it('group + fileId: uses fetchGroupFileUrl, then applies rkey', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
const out = await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupFileUrl).toHaveBeenCalledWith(12345, 'fid-x');
expect(element.url).toBe('http://group/file');
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
expect(out).toBe('http://group/file');
});
it('c2c + fileId + fileHash: uses fetchPrivateFileUrl', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivateFileUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y');
expect(element.url).toBe('http://private/file');
});
it('c2c + fileId but no fileHash: sets url to empty string (no bridge call)', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivateFileUrl).not.toHaveBeenCalled();
expect(element.url).toBe('');
});
});
describe('MediaUrlResolver — record / video element', () => {
let bridge: ReturnType<typeof makeBridge>;
let rkey: ReturnType<typeof makeRkey>;
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
it('group record: uses fetchGroupPttUrlByNode', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupPttUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(element.url).toBe('http://group/ptt');
});
it('c2c record: uses fetchPrivatePttUrlByNode (no sessionId argument)', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivatePttUrlByNode).toHaveBeenCalledWith(MEDIA_NODE);
expect(element.url).toBe('http://private/ptt');
});
it('group video: uses fetchGroupVideoUrlByNode', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupVideoUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(element.url).toBe('http://group/video');
});
it('c2c video: uses fetchPrivateVideoUrlByNode', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
await resolver.resolve(element, false, 67890);
expect(bridge.fetchPrivateVideoUrlByNode).toHaveBeenCalledWith(MEDIA_NODE);
expect(element.url).toBe('http://private/video');
});
it('record without mediaNode: no bridge call, url untouched', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record' };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupPttUrlByNode).not.toHaveBeenCalled();
expect(element.url).toBeUndefined();
});
});
describe('MediaUrlResolver — short-circuits and resilience', () => {
it('element.url already set: no bridge call, just rkey pass', async () => {
const bridge = makeBridge();
const rkey = makeRkey();
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' };
await resolver.resolve(element, true, 12345);
expect(bridge.fetchGroupFileUrl).not.toHaveBeenCalled();
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
});
it('bridge throws: swallowed, rkey still applied', async () => {
const bridge = makeBridge({
fetchGroupFileUrl: vi.fn(async () => { throw new Error('network down'); }),
});
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid' };
const out = await resolver.resolve(element, true, 12345);
expect(out).toBe('rkey-fallback');
expect(element.url).toBeUndefined(); // bridge threw before assignment
});
it('always calls rkey.resolveMediaUrl at the end', async () => {
const bridge = makeBridge();
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'http://signed') });
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'image' };
const out = await resolver.resolve(element, true, 12345);
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
expect(out).toBe('http://signed');
});
});
+1 -1
View File
@@ -3,7 +3,7 @@ import os from 'os';
import path from 'path';
import { describe, it, expect, vi } from 'vitest';
import { parseMessage } from '../src/onebot/message-parser';
import { buildSendElems } from '../src/bridge/builders/element-builder';
import { buildSendElems } from '../src/bridge/element-builder';
import { MentionExtraSendSchema } from '../src/bridge/proto/action';
import { makeOidbBaseSchema } from '../src/bridge/proto/oidb';
import { NTV2UploadRichMediaRespSchema } from '../src/bridge/proto/highway';
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/handlers/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 { PushMsgSchema } from '../src/bridge/proto/message';
import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify';
+197
View File
@@ -0,0 +1,197 @@
import { describe, it, expect } from 'vitest';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/hook/injector';
const flush = () => new Promise<void>(r => setImmediate(r));
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
let processes = initial.processes;
let live = initial.live;
const watcher = new PipeWatcher({
listProcesses: () => processes,
// Defensively copy so the watcher can't mutate the test's reference.
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
});
return {
watcher,
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
setLive: (s: Set<number>) => { live = s; },
};
}
type EventRow = [string, unknown];
function captureEvents(watcher: PipeWatcher): EventRow[] {
const events: EventRow[] = [];
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
watcher.on('process-gone', pid => events.push(['gone', pid]));
watcher.on('pipe-up', pid => events.push(['up', pid]));
watcher.on('pipe-down', pid => events.push(['down', pid]));
return events;
}
describe('PipeWatcher', () => {
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(events).toEqual([
['discovered', 1234],
['up', 1234],
]);
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
ctx.watcher.stop();
});
it('pipe-down emitted when a previously-live pipe disappears', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['down', 1234]]);
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
ctx.watcher.stop();
});
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setProcesses([]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
ctx.watcher.stop();
});
it('ignores live pipes whose process is not running', async () => {
const ctx = setupWatcher({
processes: [],
live: new Set([9999]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(events).toEqual([]);
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
ctx.watcher.stop();
});
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234]]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234], ['down', 1234]]);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
ctx.watcher.stop();
});
it('does not double-emit on idempotent ticks (no state change)', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
await ctx.watcher.tickNow();
await ctx.watcher.tickNow();
expect(events).toEqual([]);
ctx.watcher.stop();
});
it('emits "tick" after every poll', async () => {
const ctx = setupWatcher({ processes: [], live: new Set() });
let ticks = 0;
ctx.watcher.on('tick', () => { ticks++; });
await ctx.watcher.start();
expect(ticks).toBe(1);
await ctx.watcher.tickNow();
expect(ticks).toBe(2);
ctx.watcher.stop();
});
it('wake() pulls the next tick forward', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
// Wait on 'tick' rather than guessing how many event-loop turns
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
ctx.setLive(new Set([1234]));
ctx.watcher.wake();
await nextTick;
expect(events).toEqual([['up', 1234]]);
ctx.watcher.stop();
});
it('survives a throwing listProcesses without crashing the watcher', async () => {
let processes: HookProcessBaseInfo[] = [];
let live = new Set<number>();
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
if (shouldThrow) throw new Error('boom');
return processes;
},
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(false);
shouldThrow = false;
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
live = new Set([1234]);
const events = captureEvents(watcher);
await watcher.tickNow();
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
watcher.stop();
});
});
@@ -0,0 +1,186 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock the OIDB shim so we can control what `forceFetchClientKey` and
// `getPSkey` see without standing up a Bridge.
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndDecode: 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.
vi.mock('../../src/bridge/web/request-util', () => ({
RequestUtil: {
HttpsGetCookies: vi.fn(async () => ({}) as Record<string, string>),
},
}));
import * as oidb from '../../src/bridge/bridge-oidb';
import { RequestUtil } from '../../src/bridge/web/request-util';
import {
forceFetchClientKey,
getPSkey,
getCookies,
getSKey,
getBknFromSKey,
getCookiesStr,
getCsrfToken,
getCredentials,
} from '../../src/bridge/web-actions/cookies';
const bridge = { qqInfo: { uin: '10001' } } as any;
describe('cookies — forceFetchClientKey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600,
});
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck-xyz', keyIndex: '42', expireTime: '3600' });
});
it('falls back to default keyIndex/expireTime when the response omits them', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck' });
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' });
});
});
describe('cookies — getPSkey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
it('folds pskeyItems into a domain → pskey Map', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' },
{ domain: 'corrupt', pskey: '' },
],
});
const { domainPskeyMap } = await getPSkey(bridge, ['qun.qq.com', 'qzone.qq.com']);
expect(domainPskeyMap.get('qun.qq.com')).toBe('psk-a');
expect(domainPskeyMap.get('qzone.qq.com')).toBe('psk-b');
expect(domainPskeyMap.has('corrupt')).toBe(false); // empty pskey skipped
});
});
describe('cookies — getCookies', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('builds the ptlogin2 jump URL with the right query params', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({
p_skey: 'psk',
skey: 'sk',
});
const out = await getCookies(bridge, 'qun.qq.com');
expect(out).toEqual({ p_skey: 'psk', skey: 'sk' });
const url = vi.mocked(RequestUtil.HttpsGetCookies).mock.calls[0]![0];
expect(url).toContain('ssl.ptlogin2.qq.com/jump');
expect(url).toContain('clientuin=10001');
expect(url).toContain('clientkey=ck');
expect(url).toContain('keyindex=19');
});
it('falls back to getPSkey when p_skey is missing in the cookie response', async () => {
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey
.mockResolvedValueOnce({ // getPSkey
pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }],
});
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
const out = await getCookies(bridge, 'qun.qq.com');
expect(out['p_skey']).toBe('psk-from-oidb');
});
it('returns whatever cookies it got if getPSkey fallback throws', async () => {
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('pskey unavailable'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' });
const out = await getCookies(bridge, 'qun.qq.com');
expect(out).toEqual({ skey: 'sk' }); // no p_skey, but no throw
});
});
describe('cookies — getSKey', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('returns skey from the qzone-targeted ptlogin2 jump', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' });
expect(await getSKey(bridge)).toBe('the-skey');
});
it('throws when clientKey comes back empty', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: '' });
await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/);
});
it('throws when the jump response omits skey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/);
});
});
describe('cookies — pure helpers', () => {
it('getBknFromSKey: deterministic djb2 truncated to 31 bits', () => {
// Two calls on the same input → same number; different input → different.
const a = getBknFromSKey('hello');
const b = getBknFromSKey('hello');
const c = getBknFromSKey('world');
expect(a).toBe(b);
expect(a).not.toBe(c);
expect(a).toBeGreaterThanOrEqual(0);
expect(a).toBeLessThanOrEqual(2147483647);
});
it('getCookiesStr: joins cookies with "; "', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCookiesStr(bridge, 'qun.qq.com');
expect(out).toBe('p_skey=p; skey=s');
});
it('getCsrfToken: combines getSKey + getBknFromSKey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' });
const csrf = await getCsrfToken(bridge);
expect(csrf).toBe(getBknFromSKey('abc'));
});
it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCredentials(bridge, 'qun.qq.com');
expect(out.cookies).toBe('p_skey=p; skey=s');
expect(out.token).toBe(getBknFromSKey('p'));
expect(out.csrf_token).toBe(out.token);
});
it('getCredentials: token is 0 when no skey/p_skey available', async () => {
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('no pskey'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
const out = await getCredentials(bridge, 'qun.qq.com');
expect(out.token).toBe(0);
expect(out.cookies).toBe('');
});
});
@@ -0,0 +1,68 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/web-actions/cookies', () => ({
getCookies: vi.fn(async () => ({ p_skey: 'psk' })),
}));
vi.mock('../../src/bridge/web/group-essence', () => ({
getGroupEssenceMsg: vi.fn(async () => null),
getGroupEssenceMsgAll: vi.fn(async () => []),
}));
import * as cookies from '../../src/bridge/web-actions/cookies';
import * as essenceWeb from '../../src/bridge/web/group-essence';
import {
getGroupEssence,
getGroupEssenceAll,
} from '../../src/bridge/web-actions/group-essence';
const bridge = {} as any;
describe('group-essence', () => {
beforeEach(() => {
vi.mocked(cookies.getCookies).mockClear();
vi.mocked(essenceWeb.getGroupEssenceMsg).mockReset();
vi.mocked(essenceWeb.getGroupEssenceMsgAll).mockReset();
});
it('getGroupEssence: passes pageStart + pageLimit through to the web API', async () => {
vi.mocked(essenceWeb.getGroupEssenceMsg).mockResolvedValueOnce({
retcode: 0,
data: { is_end: true, msg_list: [{ a: 1 }] },
} as any);
const out = await getGroupEssence(bridge, 12345, 10, 20);
const args = vi.mocked(essenceWeb.getGroupEssenceMsg).mock.calls[0]!;
expect(args[1]).toBe('12345'); // groupCode
expect(args[2]).toBe(10); // pageStart
expect(args[3]).toBe(20); // pageLimit
expect((out as any).data.msg_list).toHaveLength(1);
});
it('getGroupEssence: defaults pageStart=0 + pageLimit=50', async () => {
vi.mocked(essenceWeb.getGroupEssenceMsg).mockResolvedValueOnce({
retcode: 0,
data: { is_end: true, msg_list: [] },
} as any);
await getGroupEssence(bridge, 12345);
const args = vi.mocked(essenceWeb.getGroupEssenceMsg).mock.calls[0]!;
expect(args[2]).toBe(0);
expect(args[3]).toBe(50);
});
it('getGroupEssence: falls back to an empty result envelope when the API returns null', async () => {
vi.mocked(essenceWeb.getGroupEssenceMsg).mockResolvedValueOnce(null as any);
const out = await getGroupEssence(bridge, 12345);
expect(out).toEqual({ retcode: -1, data: { is_end: true, msg_list: [] } });
});
it('getGroupEssenceAll: delegates to the all-pages web helper', async () => {
vi.mocked(essenceWeb.getGroupEssenceMsgAll).mockResolvedValueOnce([
{ retcode: 0, data: { is_end: false, msg_list: [{}] } },
{ retcode: 0, data: { is_end: true, msg_list: [{}, {}] } },
] as any);
const out = await getGroupEssenceAll(bridge, 12345);
expect(out).toHaveLength(2);
expect(vi.mocked(essenceWeb.getGroupEssenceMsgAll).mock.calls[0]![1]).toBe('12345');
});
});
@@ -0,0 +1,86 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/web-actions/cookies', () => ({
getCookies: vi.fn(async () => ({ p_skey: 'psk' })),
}));
vi.mock('../../src/bridge/web/group-honor', async () => {
// Keep the real WebHonorType enum so the function-under-test still
// sees the same constants as production code; only the network call
// (`getHonorListWebAPI`) is faked.
const actual = await vi.importActual<typeof import('../../src/bridge/web/group-honor')>('../../src/bridge/web/group-honor');
return {
...actual,
getHonorListWebAPI: vi.fn(async () => [] as Array<unknown>),
};
});
import * as cookies from '../../src/bridge/web-actions/cookies';
import * as honorWeb from '../../src/bridge/web/group-honor';
import { WebHonorType } from '../../src/bridge/web/group-honor';
import { getGroupHonorInfo } from '../../src/bridge/web-actions/group-honor';
const bridge = {} as any;
describe('group-honor — getGroupHonorInfo', () => {
beforeEach(() => {
vi.mocked(cookies.getCookies).mockClear();
vi.mocked(honorWeb.getHonorListWebAPI).mockReset();
});
it('TALKATIVE: calls API only for type=1, populates current_talkative + talkative_list', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([
{ uin: 10001, nick: 'alice', avatar: '', desc: '' },
{ uin: 10002, nick: 'bob', avatar: '', desc: '' },
]);
const out = await getGroupHonorInfo(bridge, 12345, WebHonorType.TALKATIVE);
expect(honorWeb.getHonorListWebAPI).toHaveBeenCalledTimes(1);
expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(1);
expect(out.current_talkative).toEqual({ uin: 10001, nick: 'alice', avatar: '', desc: '' });
expect(out.talkative_list).toHaveLength(2);
expect(out.performer_list).toEqual([]);
expect(out.legend_list).toEqual([]);
expect(out.emotion_list).toEqual([]);
});
it('TALKATIVE with empty list: current_talkative stays null', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]);
const out = await getGroupHonorInfo(bridge, 12345, WebHonorType.TALKATIVE);
expect(out.current_talkative).toBeNull();
expect(out.talkative_list).toEqual([]);
});
it('PERFORMER: dispatches API with type=2 only', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([{ uin: 1, nick: 'p', avatar: '', desc: '' }]);
const out = await getGroupHonorInfo(bridge, 12345, WebHonorType.PERFORMER);
expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(2);
expect(out.performer_list).toHaveLength(1);
expect(out.talkative_list).toEqual([]);
});
it('LEGEND: type=3', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]);
await getGroupHonorInfo(bridge, 12345, WebHonorType.LEGEND);
expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(3);
});
it('EMOTION: type=6', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]);
await getGroupHonorInfo(bridge, 12345, WebHonorType.EMOTION);
expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(6);
});
it('ALL: fetches talkative + performer + legend + emotion (4 calls)', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValue([]);
await getGroupHonorInfo(bridge, 12345, WebHonorType.ALL);
expect(honorWeb.getHonorListWebAPI).toHaveBeenCalledTimes(4);
expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls.map(c => c[2])).toEqual([1, 2, 3, 6]);
});
it('groupId is stringified to groupCode', async () => {
vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]);
await getGroupHonorInfo(bridge, 99999, WebHonorType.TALKATIVE);
expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![1]).toBe('99999');
});
});
@@ -0,0 +1,155 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/web-actions/cookies', () => ({
getCookies: vi.fn(async () => ({ p_skey: 'psk' })),
}));
vi.mock('../../src/bridge/web/group-notice', () => ({
setGroupNoticeWebAPI: vi.fn(async () => ({ ec: 0 })),
getGroupNoticeWebAPI: vi.fn(async () => ({ feeds: {} })),
uploadGroupNoticeImage: vi.fn(async () => null),
deleteGroupNotice: vi.fn(async () => true),
}));
import * as cookies from '../../src/bridge/web-actions/cookies';
import * as noticeWeb from '../../src/bridge/web/group-notice';
import {
sendGroupNotice,
getGroupNotice,
deleteGroupNoticeByFid,
} from '../../src/bridge/web-actions/group-notice';
const bridge = {} as any;
describe('group-notice — sendGroupNotice', () => {
beforeEach(() => {
vi.mocked(cookies.getCookies).mockClear();
vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockReset();
vi.mocked(noticeWeb.uploadGroupNoticeImage).mockReset();
});
it('text-only: dispatches with empty picId and default image dims (540x300)', async () => {
vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 0 } as any);
await sendGroupNotice(bridge, 12345, 'hello');
expect(noticeWeb.uploadGroupNoticeImage).not.toHaveBeenCalled();
const args = vi.mocked(noticeWeb.setGroupNoticeWebAPI).mock.calls[0]!;
expect(args[1]).toBe('12345'); // groupCode
expect(args[2]).toBe('hello'); // content
expect(args[3]).toBe(0); // pinned default
expect(args[4]).toBe(1); // type default
expect(args[7]).toBe(1); // confirm_required default
expect(args[8]).toBe(''); // picId
expect(args[9]).toBe(540); // imgWidth default
expect(args[10]).toBe(300); // imgHeight default
});
it('with options: forwards pinned / type / confirm_required overrides', async () => {
vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 0 } as any);
await sendGroupNotice(bridge, 12345, 'pinned!', {
pinned: 1,
type: 2,
confirm_required: 0,
});
const args = vi.mocked(noticeWeb.setGroupNoticeWebAPI).mock.calls[0]!;
expect(args[3]).toBe(1);
expect(args[4]).toBe(2);
expect(args[7]).toBe(0);
});
it('with http image: fetches bytes, uploads, threads pic info into the post', async () => {
const realFetch = global.fetch;
global.fetch = vi.fn(async () => ({
ok: true,
arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer,
})) as any;
vi.mocked(noticeWeb.uploadGroupNoticeImage).mockResolvedValueOnce({
id: 'pic-xyz', width: 1024, height: 768,
} as any);
vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 0 } as any);
await sendGroupNotice(bridge, 12345, 'image notice', { image: 'https://example.com/x.png' });
expect(global.fetch).toHaveBeenCalledOnce();
expect(noticeWeb.uploadGroupNoticeImage).toHaveBeenCalledOnce();
const args = vi.mocked(noticeWeb.setGroupNoticeWebAPI).mock.calls[0]!;
expect(args[8]).toBe('pic-xyz');
expect(args[9]).toBe(1024);
expect(args[10]).toBe(768);
global.fetch = realFetch;
});
it('image fetch failure: throws "Failed to download image"', async () => {
const realFetch = global.fetch;
global.fetch = vi.fn(async () => ({ ok: false, status: 503 })) as any;
await expect(sendGroupNotice(bridge, 12345, 'x', { image: 'https://bad' }))
.rejects.toThrow(/Failed to download image: 503/);
global.fetch = realFetch;
});
it('throws when the web API returns non-zero ec', async () => {
vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({
ec: 42, em: 'permission denied',
} as any);
await expect(sendGroupNotice(bridge, 12345, 'x'))
.rejects.toThrow(/permission denied/);
});
it('throws with a generic message when ec≠0 and em is missing', async () => {
vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 7 } as any);
await expect(sendGroupNotice(bridge, 12345, 'x'))
.rejects.toThrow(/Cookie过期或权限不足/);
});
});
describe('group-notice — getGroupNotice', () => {
beforeEach(() => { vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockReset(); });
it('flattens feeds into OneBot-shaped notice list', async () => {
vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockResolvedValueOnce({
feeds: {
f1: {
fid: 'f1', u: 10001, pubt: 1700000000,
msg: { text: 'first', pics: [{ id: 'p1', h: 100, w: 200 }] },
settings: {}, read_num: 5,
} as any,
f2: {
fid: 'f2', u: 10002, pubt: 1700000100,
msg: { text: 'second' } as any,
settings: {}, read_num: 0,
} as any,
},
} as any);
const out = await getGroupNotice(bridge, 12345);
expect(out).toHaveLength(2);
expect(out[0]!.notice_id).toBe('f1');
expect(out[0]!.message.text).toBe('first');
expect(out[0]!.message.image).toEqual([{ id: 'p1', height: 100, width: 200 }]);
expect(out[0]!.message.images).toEqual(out[0]!.message.image); // alias
expect(out[1]!.message.image).toEqual([]); // no pics → empty
});
it('throws when the underlying web API returns null', async () => {
vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockResolvedValueOnce(null as any);
await expect(getGroupNotice(bridge, 12345)).rejects.toThrow(/获取公告失败/);
});
it('returns an empty array when feeds is empty', async () => {
vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockResolvedValueOnce({ feeds: {} } as any);
expect(await getGroupNotice(bridge, 12345)).toEqual([]);
});
});
describe('group-notice — deleteGroupNoticeByFid', () => {
it('delegates to deleteGroupNotice with cookieObject + groupCode + fid', async () => {
vi.mocked(noticeWeb.deleteGroupNotice).mockResolvedValueOnce(true);
const ok = await deleteGroupNoticeByFid(bridge, 12345, 'fid-abc');
expect(ok).toBe(true);
const args = vi.mocked(noticeWeb.deleteGroupNotice).mock.calls[0]!;
expect(args[1]).toBe('12345');
expect(args[2]).toBe('fid-abc');
});
});
+7
View File
@@ -21,8 +21,11 @@ export const SNOWLUMA_ACTIONS = [
'get_group_honor_info',
'get_group_system_msg',
'set_group_kick',
'set_group_kick_members',
'set_group_ban',
'set_group_whole_ban',
'set_group_add_option',
'set_group_search',
'set_group_admin',
'set_group_card',
'set_group_name',
@@ -78,6 +81,7 @@ export const SNOWLUMA_ACTIONS = [
'clean_cache',
'.handle_quick_operation',
'set_friend_remark',
'set_group_remark',
'set_msg_emoji_like',
'_mark_all_as_read',
'get_group_file_system_info',
@@ -91,6 +95,9 @@ export const SNOWLUMA_ACTIONS = [
'forward_group_single_msg',
'get_recent_contact',
'get_profile_like',
'fetch_custom_face',
'get_emoji_likes',
'fetch_emoji_like',
'get_friends_with_category',
'get_online_clients',
'_get_model_show',
+13
View File
@@ -6,8 +6,11 @@ import type {
DeleteGroupFileParams,
DomainParams,
DownloadFileParams,
FetchCustomFaceParams,
FetchEmojiLikeParams,
ForwardMessageParams,
FriendPokeParams,
GetEmojiLikesParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupFilesParams,
@@ -39,11 +42,14 @@ import type {
SetFriendAddRequestParams,
SetFriendRemarkParams,
SetGroupAddRequestParams,
SetGroupAddOptionParams,
SetGroupAdminParams,
SetGroupBanParams,
SetGroupCardParams,
SetGroupKickParams,
SetGroupKickMembersParams,
SetGroupNameParams,
SetGroupRemarkParams,
SetGroupReactionParams,
SetGroupSpecialTitleParams,
SetGroupWholeBanParams,
@@ -103,8 +109,11 @@ export interface SnowLumaActionMap {
get_group_honor_info: { params: GetGroupHonorInfoParams; data: JsonValue };
get_group_system_msg: { params: JsonObject; data: JsonObject[] };
set_group_kick: { params: SetGroupKickParams; data: EmptyData };
set_group_kick_members: { params: SetGroupKickMembersParams; data: EmptyData };
set_group_ban: { params: SetGroupBanParams; data: EmptyData };
set_group_whole_ban: { params: SetGroupWholeBanParams; data: EmptyData };
set_group_add_option: { params: SetGroupAddOptionParams; data: EmptyData };
set_group_search: { params: GroupIdParams; data: EmptyData };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };
@@ -160,6 +169,7 @@ export interface SnowLumaActionMap {
clean_cache: { params: JsonObject; data: EmptyData };
'.handle_quick_operation': { params: QuickOperationParams; data: EmptyData };
set_friend_remark: { params: SetFriendRemarkParams; data: EmptyData };
set_group_remark: { params: SetGroupRemarkParams; data: EmptyData };
set_msg_emoji_like: { params: SetMsgEmojiLikeParams; data: EmptyData };
_mark_all_as_read: { params: JsonObject; data: EmptyData };
get_group_file_system_info: { params: GroupIdParams; data: GroupFileSystemInfo };
@@ -173,6 +183,9 @@ export interface SnowLumaActionMap {
forward_group_single_msg: { params: JsonObject; data: JsonValue };
get_recent_contact: { params: JsonObject; data: JsonArray };
get_profile_like: { params: JsonObject; data: JsonObject };
fetch_custom_face: { params: FetchCustomFaceParams; data: string[] };
get_emoji_likes: { params: GetEmojiLikesParams; data: JsonObject };
fetch_emoji_like: { params: FetchEmojiLikeParams; data: JsonObject };
get_friends_with_category: { params: JsonObject; data: JsonObject[] };
get_online_clients: { params: JsonObject; data: OnlineClientsInfo };
_get_model_show: { params: JsonObject; data: { variants: JsonArray } };
+28
View File
@@ -64,6 +64,11 @@ export interface SetGroupKickParams extends GroupIdParams {
reject_add_request?: boolean;
}
export interface SetGroupKickMembersParams extends GroupIdParams {
user_id: number[];
reject_add_request?: boolean;
}
export interface SetGroupBanParams extends GroupIdParams {
user_id: number;
duration?: number;
@@ -73,6 +78,10 @@ export interface SetGroupWholeBanParams extends GroupIdParams {
enable?: boolean;
}
export interface SetGroupAddOptionParams extends GroupIdParams {
add_type: number;
}
export interface SetGroupAdminParams extends GroupIdParams {
user_id: number;
enable?: boolean;
@@ -254,12 +263,31 @@ export interface SetFriendRemarkParams extends UserIdParams {
remark: string;
}
export interface SetGroupRemarkParams extends GroupIdParams {
remark: string;
}
export interface SetMsgEmojiLikeParams extends JsonObject {
message_id: number;
emoji_id: string;
set?: boolean;
}
export interface FetchCustomFaceParams extends JsonObject {
count?: number;
}
export interface GetEmojiLikesParams extends MessageIdParams {
emoji_id: string;
}
export interface FetchEmojiLikeParams extends MessageIdParams {
emojiId: string;
emojiType?: number;
count?: number;
cookie?: string;
}
export interface DownloadFileParams extends JsonObject {
url?: string;
base64?: string;