diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts new file mode 100644 index 00000000..ff99745d --- /dev/null +++ b/packages/core/src/bridge/actions/forward.ts @@ -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 '../builders/element-builder'; +import { parseMsgPush } from '../handlers/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(); + +async function buildForwardPushBody( + bridge: Bridge, + node: ForwardNodePayload, +): Promise> { + 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 { + 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 { + 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; +} diff --git a/packages/core/src/bridge/actions/friend.ts b/packages/core/src/bridge/actions/friend.ts new file mode 100644 index 00000000..27dfdea5 --- /dev/null +++ b/packages/core/src/bridge/actions/friend.ts @@ -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 { + 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 { + 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 { + const uid = await resolveUserUid(bridge, userId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2, + { targetUid: uid, remark }, OidbSetFriendRemarkSchema); +} diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts new file mode 100644 index 00000000..fcc27fdc --- /dev/null +++ b/packages/core/src/bridge/actions/group-admin.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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( + 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), + }; +} + diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts new file mode 100644 index 00000000..df166eb4 --- /dev/null +++ b/packages/core/src/bridge/actions/group-file.ts @@ -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 { + 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, +): Promise { + const resp = await sendOidbAndDecode( + 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(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 { + 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( + 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 { + 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( + 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 { + 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( + 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 { + const resp = await sendOidbAndDecode( + 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 { + const uid = await resolveUserUid(bridge, userId); + const resp = await sendOidbAndDecode( + 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 { + const resp = await sendOidbAndDecode( + 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 { + const resp = await sendOidbAndDecode( + 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 { + const resp = await sendOidbAndDecode( + 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 { + const resp = await sendOidbAndDecode( + 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 { + const resp = await sendOidbAndDecode( + 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 { + 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 { + 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 { + 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 { + 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 } }, + }, + }); +} diff --git a/packages/core/src/bridge/actions/group-message.ts b/packages/core/src/bridge/actions/group-message.ts new file mode 100644 index 00000000..9d8d7dd0 --- /dev/null +++ b/packages/core/src/bridge/actions/group-message.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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); +} diff --git a/packages/core/src/bridge/actions/interaction.ts b/packages/core/src/bridge/actions/interaction.ts new file mode 100644 index 00000000..df16d73a --- /dev/null +++ b/packages/core/src/bridge/actions/interaction.ts @@ -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 { + 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 { + 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 { + 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(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 }; +} diff --git a/packages/core/src/bridge/actions/misc.ts b/packages/core/src/bridge/actions/misc.ts new file mode 100644 index 00000000..f8bec65e --- /dev/null +++ b/packages/core/src/bridge/actions/misc.ts @@ -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( + 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( + 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( + bridge, + 'OidbSvcTrpcTcp.0xEB7_1', + 0xEB7, + 1, + req, + Oidb0xeb7ReqSchema, + Oidb0xeb7RespSchema, + ); +} diff --git a/packages/core/src/bridge/actions/profile.ts b/packages/core/src/bridge/actions/profile.ts new file mode 100644 index 00000000..30771f23 --- /dev/null +++ b/packages/core/src/bridge/actions/profile.ts @@ -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 { + 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 { + 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( + 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( + bridge, + 'OidbSvcTrpcTcp.0xcd4_1', + 0xCD4, + 1, + req, + Oidb0xcd4ReqSchema, + Oidb0xcd4RespSchema, + ); +} + +export async function setAvatar( + bridge: Bridge, + source: string, +): Promise { + 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( + 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( + 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 { + 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`); +} diff --git a/packages/core/src/bridge/actions/shared.ts b/packages/core/src/bridge/actions/shared.ts new file mode 100644 index 00000000..75628436 --- /dev/null +++ b/packages/core/src/bridge/actions/shared.ts @@ -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 { + 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; +} diff --git a/packages/core/src/bridge/bridge-actions.ts b/packages/core/src/bridge/bridge-actions.ts deleted file mode 100644 index 0266a75f..00000000 --- a/packages/core/src/bridge/bridge-actions.ts +++ /dev/null @@ -1,1814 +0,0 @@ -// Admin / action operations extracted from Bridge. - -import type { Bridge } from './bridge'; -import type { PacketInfo } from '../protocol/types'; -import { protoDecode, protoEncode } from '../protobuf/decode'; -import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from './bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from './highway/highway-client'; -import { computeHashes, computeMd5, loadBinarySource } from './highway/utils'; -import { buildSendElems } from './builders/element-builder'; -import { parseMsgPush } from './handlers/msg-push-handler'; -import type { ForwardNodePayload, MessageElement } from './events'; -import { createLogger } from '../utils/logger'; -import { PushMsgSchema } from './proto/message'; -import { - OidbMuteMemberSchema, - OidbMuteAllSchema, - Oidb0x89a_0AddOptionSchema, - Oidb0x89a_0SearchSchema, - OidbKickMemberSchema, - OidbLeaveGroupSchema, - OidbFriendRequestActionSchema, - OidbDeleteFriendSchema, - OidbGroupRequestActionSchema, - OidbPokeSchema, - OidbEssenceSchema, - OidbSetAdminSchema, - OidbRenameMemberSchema, - OidbRenameGroupSchema, - OidbSpecialTitleSchema, - OidbLikeSchema, - OidbGroupReactionSchema, - OidbSetFriendRemarkSchema, - OidbGroupFileCountViewReqSchema, - OidbGroupFileCountViewRespSchema, - OidbGroupFileViewReqSchema, - OidbGroupFileViewRespSchema, - OidbGroupFileReqSchema, - OidbGroupFileRespSchema, - OidbGroupFileFolderReqSchema, - OidbGroupFileFolderRespSchema, - OidbPrivateFileDownloadReqSchema, - OidbPrivateFileDownloadRespSchema, - OidbPrivateFileUploadReqSchema, - OidbPrivateFileUploadRespSchema, - NTV2RichMediaReqSchema, - NTV2RichMediaRespSchema, - GroupRecallRequestSchema, - C2CRecallRequestSchema, - SsoReadedReportReqSchema, - SetStatusReqSchema, - SetStatusRespSchema, - OidbSetProfileSchema, - Oidb0x7edReqSchema, - Oidb0x7edRespSchema, - Oidb0x8a0ReqSchema, - Oidb0x8a0RespSchema, - Oidb0xf16ReqSchema, - Oidb0xf16RespSchema, - Oidb0x8a7RespSchema, - Oidb0x8a7ReqSchema, - Oidb0xe17RespSchema, - Oidb0xe17ReqSchema, - Oidb0x112aReqSchema, - Oidb0x112aRespSchema, - Oidb0xcd4ReqSchema, - Oidb0xcd4RespSchema, - Oidb0x990ReqSchema, - Oidb0x990RespSchema, - MiniAppShareReqSchema, - MiniAppShareRespSchema, - Oidb0x112eReqSchema, - Oidb0x112eRespSchema, - Oidb0xeb7ReqSchema, - Oidb0xeb7RespSchema, - FaceroamOpReqSchema, - FaceroamOpRespSchema, - Oidb0x9083ReqSchema, - Oidb0x9083RespSchema, -} from './proto/oidb-action'; -import { FileUploadExtSchema } from './proto/highway'; -import { - LongMsgResultSchema, - RecvLongMsgReqSchema, - RecvLongMsgRespSchema, - SendLongMsgReqSchema, - SendLongMsgRespSchema, -} from './proto/longmsg'; -import { gzipSync, gunzipSync } from 'zlib'; - -const log = createLogger('BridgeActions'); - -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; -} - -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; -} - -const forwardResCache = new Map(); - -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; -} - -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}`); -} - -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); -} - -async function resolveSelfUid(bridge: Bridge): Promise { - 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; -} - -function normalizeMediaNode(node: MediaIndexNode): Record { - 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, -): Promise { - const resp = await sendOidbAndDecode( - 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}`; -} - -async function buildForwardPushBody( - bridge: Bridge, - node: ForwardNodePayload, -): Promise> { - 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, - }, - }, - }; -} - -// --------------------------------------------------------------------------- -// Friend actions -// --------------------------------------------------------------------------- - -export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise { - const uid = await resolveUserUid(bridge, userId); - await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2, - { targetUid: uid, remark }, OidbSetFriendRemarkSchema); -} - -export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise { - await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1, - { inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema); -} - -// --------------------------------------------------------------------------- -// Group file count -// --------------------------------------------------------------------------- - -export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { - const resp = await sendOidbAndDecode(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), - }; -} - -// --------------------------------------------------------------------------- -// Group admin actions -// --------------------------------------------------------------------------- - -export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise { - 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 { - await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, - { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema); -} - -export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise { - 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 { - await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, - { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema); -} - -export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise { - 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 { - 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 { - await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1, - { groupUin: groupId }, OidbLeaveGroupSchema); -} - -export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise { - 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 { - 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 { - 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 { - 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); -} - -// --------------------------------------------------------------------------- -// Friend / group add requests -// --------------------------------------------------------------------------- - -export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise { - 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 { - 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. - try { await bridge.fetchFriendList(); } catch { /* ignore */ } -} - -// --------------------------------------------------------------------------- -// Group / private file operations -// --------------------------------------------------------------------------- - -export async function uploadGroupFile( - bridge: Bridge, - groupId: number, - source: string, - name = '', - folderId = '/', - uploadFile = true, -): Promise { - 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( - 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 { - 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( - 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 }; -} - -export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise { - 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( - 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 }; -} - -export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise { - const resp = await sendOidbAndDecode( - 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 deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise { - const resp = await sendOidbAndDecode( - 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 { - const resp = await sendOidbAndDecode( - 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); -} - -export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise { - const resp = await sendOidbAndDecode( - 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 { - const resp = await sendOidbAndDecode( - 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 { - const resp = await sendOidbAndDecode( - 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); -} - -export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise { - const uid = await resolveUserUid(bridge, userId); - const resp = await sendOidbAndDecode( - 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`; -} - -export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise { - 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 { - 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 { - 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 { - 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 } }, - }, - }); -} - -export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise { - 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 { - 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; -} - -export async function setGroupAddRequest( - bridge: Bridge, groupId: number, sequence: number, eventType: number, - approve: boolean, reason = '', filtered = false, -): Promise { - 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); -} - -// --------------------------------------------------------------------------- -// Poke / Like -// --------------------------------------------------------------------------- - -export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise { - 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 { - await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104, - { targetUin: userId, count }, OidbLikeSchema); -} - -// --------------------------------------------------------------------------- -// Essence / Reaction -// --------------------------------------------------------------------------- - -export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise { - 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); -} - -export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise { - 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); -} - -// --------------------------------------------------------------------------- -// Recall messages -// --------------------------------------------------------------------------- - -export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise { - 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 { - 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'); -} - -// --- Mark message as read --- - -export async function markPrivateMessageRead( - bridge: Bridge, - userId: number, - msgSeq: number, - timestamp: number = Math.floor(Date.now() / 1000) -): Promise { - 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 { - 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 setOnlineStatus( - bridge: Bridge, - status: number, - extStatus: number = 0, - batteryStatus: number = 100 -): Promise { - 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 { - 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 getProfileLike( - bridge: Bridge, - userId?: number, - start: number = 0, - limit: number = 10 -) { - - // const isSelf = !userId || userId === bridge.qqInfo.uin; - // const targetUid = isSelf - // ? bridge.qqInfo.uid - // : await bridge.getUidByUinV2(userId!); - - - 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( - 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 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( - bridge, - 'OidbSvcTrpcTcp.0x8a7_0', - 0x8A7, - 0, - req, - Oidb0x8a7ReqSchema, - Oidb0x8a7RespSchema - ); - - if (!result) { - throw new Error('get group at all remain result empty'); - } - - return { - can_at_all: !!result.canAtAll, - remain_at_all_count_for_group: Number(result.groupRemain || 0), // 【修改点】:防止底层库将 uint32 也返回成 BigInt 导致无法被 JSON 序列化 - remain_at_all_count_for_uin: Number(result.uinRemain || 0) // 【修改点】:同上 - }; -} - -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( - 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 setSelfLongNick( - bridge: Bridge, - longNick: string -) { - const req = { - uin: BigInt(bridge.qqInfo.uin), - profile: { - tag: 102, - value: String(longNick) - } - }; - - await sendOidbAndDecode( - 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( - bridge, - 'OidbSvcTrpcTcp.0xcd4_1', - 0xCD4, - 1, - req, - Oidb0xcd4ReqSchema, - Oidb0xcd4RespSchema - ); -} - -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( - 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"; // 默认 bili - 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( - 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( - bridge, - 'OidbSvcTrpcTcp.0xEB7_1', - 0xEB7, - 1, - req, - Oidb0xeb7ReqSchema, - Oidb0xeb7RespSchema - ); -} - -export async function setAvatar( - bridge: Bridge, - source: string, -): Promise { - 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)); -} - -export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise { - 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`); -} - -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(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 }; -} - diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 55ab4e64..fe748ffa 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -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[]; diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts new file mode 100644 index 00000000..998f7a59 --- /dev/null +++ b/packages/core/tests/actions/_helpers.ts @@ -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; + }; + identity: { + findUidByUin: ReturnType; + findUinByUid: ReturnType; + }; + sendRawPacket: ReturnType; + fetchFriendList: ReturnType; + fetchGroupMemberList: ReturnType; + fetchUserProfile: ReturnType; +} + +export function mockBridge(overrides: Partial = {}): 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, + }; +} diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts new file mode 100644 index 00000000..0b2c4a5c --- /dev/null +++ b/packages/core/tests/actions/forward.test.ts @@ -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/builders/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/); + }); +}); diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts new file mode 100644 index 00000000..0ca0f913 --- /dev/null +++ b/packages/core/tests/actions/friend.test.ts @@ -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' }); + }); +}); diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts new file mode 100644 index 00000000..4bd605d6 --- /dev/null +++ b/packages/core/tests/actions/group-admin.test.ts @@ -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/); + }); +}); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts new file mode 100644 index 00000000..57fc39fb --- /dev/null +++ b/packages/core/tests/actions/group-file.test.ts @@ -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'); + }); +}); diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts new file mode 100644 index 00000000..7295301c --- /dev/null +++ b/packages/core/tests/actions/group-message.test.ts @@ -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']); + }); +}); diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts new file mode 100644 index 00000000..152e8810 --- /dev/null +++ b/packages/core/tests/actions/interaction.test.ts @@ -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); + }); +}); diff --git a/packages/core/tests/actions/misc.test.ts b/packages/core/tests/actions/misc.test.ts new file mode 100644 index 00000000..44d6f5d6 --- /dev/null +++ b/packages/core/tests/actions/misc.test.ts @@ -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'); + }); +}); diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts new file mode 100644 index 00000000..f98de1a2 --- /dev/null +++ b/packages/core/tests/actions/profile.test.ts @@ -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 }]); + }); +});