From dad501ebc01e14caa9787dd6e0f2e516766504a1 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 23:08:50 +0800 Subject: [PATCH] refactor(api): move 17 group-file methods to GroupFileApi (#6 commit 4/13) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inlines `actions/group-file.ts` into `apis/group-file.ts::GroupFileApi`, deletes the old action file, removes the matching 17 facade methods off `Bridge`, and slims `BridgeInterface` accordingly. Method renaming follows the same "strip the redundant suffix" rule we applied to GroupAdminApi: uploadGroupFile → upload uploadPrivateFile → uploadPrivate sendGroupFileMessage → publish (OIDB 0x6d9_4) fetchGroupFiles → list fetchGroupFileCount → getCount fetchGroupFileUrl → getUrl fetchPrivateFileUrl → getPrivateUrl fetchGroupPttUrlByNode → getPttUrl fetchPrivatePttUrlByNode → getPrivatePttUrl fetchGroupVideoUrlByNode → getVideoUrl fetchPrivateVideoUrlByNode → getPrivateVideoUrl deleteGroupFile → delete moveGroupFile → move createGroupFileFolder → createFolder deleteGroupFileFolder → deleteFolder renameGroupFileFolder → renameFolder `upload`'s atomic upload+publish flow now calls `this.publish(...)` directly instead of going through `bridge.sendGroupFileMessage`, and `uploadPrivate` calls `this.ctx.apis.message.sendC2cFile(...)`. Callers updated: `instance-context.ts`, `media-url-resolver.ts`, `actions/group-file.ts` (onebot), `actions/extended.ts`, `modules/{contact,media,message}-actions.ts`. Tests: `group-file.test.ts` rewritten to use `new GroupFileApi(bridge as any).method(...)`. The "verify publish was called" assertions now use `vi.spyOn(api, 'publish').mockResolvedValue()` since `publish` is an instance method on the same Api. `_helpers.ts` gains `mockGroupFileApi()` for cross-Api callers and drops the flat `sendGroupFileMessage` shim. `media-url-resolver.test.ts` and `send-group-file.test.ts` switched to `bridge.apis.groupFile.*`; the extended-actions `APIS_ROUTING` map now carries a `[area, newName]` tuple so renamed methods auto-promote. 587/587 tests pass. The network-manager file remains as the only failing test file (pre-existing infrastructure issue unrelated to #6). --- .../core/src/bridge/actions/group-file.ts | 980 ---------------- packages/core/src/bridge/apis/group-file.ts | 1006 +++++++++++++++++ packages/core/src/bridge/apis/index.ts | 6 +- packages/core/src/bridge/bridge-interface.ts | 30 +- packages/core/src/bridge/bridge.ts | 52 +- packages/core/src/onebot/actions/extended.ts | 4 +- .../core/src/onebot/actions/group-file.ts | 8 +- packages/core/src/onebot/instance-context.ts | 12 +- .../core/src/onebot/media-url-resolver.ts | 12 +- .../src/onebot/modules/contact-actions.ts | 2 +- .../core/src/onebot/modules/media-actions.ts | 4 +- .../src/onebot/modules/message-actions.ts | 2 +- packages/core/tests/actions/_helpers.ts | 48 +- .../core/tests/actions/group-file.test.ts | 146 +-- .../core/tests/media-url-resolver.test.ts | 45 +- .../tests/onebot/extended-actions.test.ts | 31 +- .../core/tests/onebot/send-group-file.test.ts | 38 +- 17 files changed, 1241 insertions(+), 1185 deletions(-) delete mode 100644 packages/core/src/bridge/actions/group-file.ts create mode 100644 packages/core/src/bridge/apis/group-file.ts diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts deleted file mode 100644 index 8649da60..00000000 --- a/packages/core/src/bridge/actions/group-file.ts +++ /dev/null @@ -1,980 +0,0 @@ -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import { toHexUpper } from '../../utils/hex'; -import { createLogger } from '../../utils/logger'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '../bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; -import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; -import type { FileUploadExt } from '@snowluma/proto-defs/highway'; -import { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - OidbGroupFileCountViewReq, - OidbGroupFileCountViewResp, - OidbGroupFileFolderReq, - OidbGroupFileFolderResp, - OidbGroupFileReq, - OidbGroupFileResp, - OidbGroupFileViewReq, - OidbGroupFileViewResp, - OidbGroupSendFileReq, -} from '@snowluma/proto-defs/oidb-actions/group-file'; -import type { - NTV2RichMediaReq, - NTV2RichMediaResp, - OidbPrivateFileDownloadReq, - OidbPrivateFileDownloadResp, - OidbPrivateFileUploadReq, - OidbPrivateFileUploadResp, -} from '@snowluma/proto-defs/oidb-actions/media'; -import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; - -const log = createLogger('GroupFile'); - -// ─────────────── 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 toHexUpper(data); -} - -// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives -// little-endian-packed (byte0 = first dotted octet) and we unpack it the -// same way. Force-unsigned the shift to keep negative ints (high bit set) -// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000 -// into a negative number. -function int32ToIpv4Dotted(value: number): string { - const b1 = value & 0xFF; - const b2 = (value >>> 8) & 0xFF; - const b3 = (value >>> 16) & 0xFF; - const b4 = (value >>> 24) & 0xFF; - return `${b1}.${b2}.${b3}.${b4}`; -} - -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 protobuf_encode({ - 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, - }); -} - -function buildPrivateFileUploadExt( - senderUin: number, - fileName: string, - fileSize: number, - md5: Uint8Array, - sha1: Uint8Array, - fileId: string, - uploadKey: Uint8Array, - uploadHost: string, - uploadPort: number, -): Uint8Array { - return protobuf_encode({ - 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, - }); -} - -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 env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); - const respBytes = await runOidb(bridge, serviceCmd, protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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}`; -} - -// ─────────────── publish (group file → chat) ─────────────── - -/** - * Publish a previously-uploaded group file as a chat message. - * - * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`. - * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes - * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells - * the QQ server "now publish that staged blob as a chat message" so - * everyone in the group can see the file bubble. - * - * The old approach — wrap the file as `TransElem(elemType=24)` inside - * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING - * messages (the receive decoder unpacks transElem(24) into a - * FileEntity) but the QQ-NT server REJECTS it on outgoing with - * `result=79` ("invalid element on send-side"). Mirror Lagrange's - * dedicated GroupSendFileService instead. - * - * The unused `field4` slot and the `field3=random` value match - * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the - * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5 - * is the `Field5=true` flag the receiver's deserializer expects. - */ -export async function sendGroupFileMessage(bridge: Bridge, groupId: number, fileId: string): Promise { - if (!fileId) throw new Error('sendGroupFileMessage requires fileId'); - const env = makeOidbEnvelope(0x6D9, 4, { - body: { - groupUin: groupId, - type: 2, - info: { - busiType: 102, - fileId, - field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, - field5: true, - }, - }, - }); - // The envelope-level errorCode peek inside `runOidb` covers the - // happy-path validation; failures surface as a thrown OIDB error. - await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', protobuf_encode>(env)); -} - -// ─────────────── file count ─────────────── - -export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { - const env = makeOidbEnvelope( - 0x6D8, 3, - { count: { groupUin: groupId, appId: 7, busId: 0 } }, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - 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 { - // Group/private files may legitimately be up to 4 GiB on QQ's wire, - // so override the default 1 GiB cap with the protocol ceiling. - const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); - if (!loaded.bytes.length) throw new Error('group file is empty'); - - const fileName = normalizeUploadFileName(name, loaded.fileName); - const hashes = computeHashes(loaded.bytes); - - const env = makeOidbEnvelope( - 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, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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'); - - // Remember the upload so a later `send_group_msg` carrying just the - // file_id can route via `sendGroupFileMessage` without forcing the - // OneBot caller to thread fileName/size/md5 separately. For groups - // the wire publish (OIDB 0x6d9_4) only needs the file_id itself, so - // this is mainly for log-line correctness; the c2c counterpart in - // `uploadPrivateFile` is where the cache is actually load-bearing. - bridge.rememberUploadedFile({ - fileId, - scope: 'group', - groupId, - fileName, - fileSize: loaded.bytes.length, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - rememberedAt: Date.now(), - }); - - if (!upload.boolFileExist && uploadFile) { - const senderUin = toInt(bridge.identity.uin); - if (senderUin <= 0) throw new Error('invalid self uin for group file upload'); - - const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) - || (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); - } - - // Stage 3: file is on the server, now publish it as a chat message. - // - // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes — - // the chat shows nothing. The publish step goes via a dedicated OIDB - // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) - // payload — the QQ-NT server rejects that with `result=79`. Mirrors - // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the - // caller opts out via `uploadFile=false` (treat that as "I only - // wanted the slot allocated, hold the chat post"). Routes through - // the public bridge method (rather than the local `sendGroupFileMessage`) - // so tests can mock at the bridge boundary, matching the pattern - // `uploadPrivateFile` uses with `bridge.sendC2cFileMessage`. - if (uploadFile) { - try { - await bridge.sendGroupFileMessage(groupId, fileId); - } catch (err) { - // The bytes are already on the server and the fileId is valid — - // fail loud but don't lose the upload result the action handler - // committed to returning. Callers can still resolve the file by - // id; they'll just have to re-publish it themselves. - log.warn('group file uploaded (fileId=%s) but chat post failed: %s', - fileId, err instanceof Error ? err.message : String(err)); - } - } - - return { fileId }; -} - -export async function uploadPrivateFile( - bridge: Bridge, - userId: number, - source: string, - name = '', - uploadFile = true, -): Promise { - // Group/private files may legitimately be up to 4 GiB on QQ's wire, - // so override the default 1 GiB cap with the protocol ceiling. - const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); - if (!loaded.bytes.length) throw new Error('private file is empty'); - - const targetUid = await bridge.resolveUserUid(userId); - let selfUid = bridge.identity.selfUid; - if (!selfUid) { - const selfUin = toInt(bridge.identity.uin); - if (selfUin > 0) { - selfUid = await bridge.resolveUserUid(selfUin); - } - } - if (!selfUid) throw new Error('self uid is unavailable'); - - const senderUin = toInt(bridge.identity.uin); - if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); - - const fileName = normalizeUploadFileName(name, loaded.fileName); - const hashes = computeHashes(loaded.bytes); - - const env = makeOidbEnvelope(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, - }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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'); - - // Cache the metadata so a later `send_private_msg` carrying just - // `{type:'file', file_id}` can resurrect the full c2c-file packet - // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without - // this the recipient sees a 0-byte file because the OneBot send path - // has no way to recover those fields from the file_id alone. - bridge.rememberUploadedFile({ - fileId, - scope: 'private', - userId, - fileName, - fileSize: loaded.bytes.length, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - fileHash: fileHash ?? '', - rememberedAt: Date.now(), - }); - - if (!upload.boolFileExist && uploadFile) { - // Host selection. - // - // Current QQ-NT server rollout has stopped populating the legacy - // `uploadIp` (field 60) entirely. The host now arrives as the first - // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated - // IPv4 message) — same place acidify reads it from since their - // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` - // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); - // acidify uses `inIP`/`inPort` exclusively and so do we, because - // that's the address the highway PUT actually needs to reach. - // - // The 32-bit IPs are little-endian-packed (byte0 = first octet) - // per acidify's `Int.toIpString()`. Cross-checked the byte order - // by inspecting their highway flow — there's no separate htonl - // step, so the integer is already in network-octet-first order. - // - // Older server versions still populate the legacy string fields - // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / - // uploadDns), so we fall through to those after rtpMediaPlatform. - // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's - // what we picked. - const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress) - && upload.rtpMediaPlatformUploadAddress[0]) - ? upload.rtpMediaPlatformUploadAddress[0] : null; - const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 - ? int32ToIpv4Dotted(rtpFirst.inIP) : ''; - const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number' - ? rtpFirst.inPort : 0; - const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) - ? upload.uploadIpList[0] : ''; - const uploadHost = (rtpInIP) - || (typeof upload.uploadIp === 'string' && upload.uploadIp) - || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) - || (ipListFirst) - || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) - || (typeof upload.uploadDns === 'string' && upload.uploadDns) - || ''; - const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst - && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; - const uploadPort = rtpInIP && rtpInPort > 0 - ? rtpInPort - : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 - ? toInt(upload.uploadHttpsPort) - : toInt(upload.uploadPort); - if (!uploadHost || uploadPort <= 0) { - // Surface every host-bearing field we know about so a user - // hitting this can show us exactly which slot the server filled - // (or whether it returned nothing at all — which would point at - // a request mismatch rather than a missing decoder). - const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) - ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e: any) => ({ - outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, - iPType: e.iPType, - }))) - : '[]'; - log.warn( - 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', - rtpDump, - upload.uploadIp ?? '', upload.uploadDomain ?? '', - JSON.stringify(upload.uploadIpList ?? []), - upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', - upload.uploadLanip ?? '', upload.uploadPort ?? 0, - upload.uploadHttpsPort ?? 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); - } - - // Stage 3: publish the file as a c2c chat message. C2C files use - // `RichText.notOnlineFile` (parallel to `elems`), so we go through - // the dedicated `sendC2cFileMessage` instead of `sendPrivateMessage` - // which only knows about elems[]. NapCat does the same atomic - // upload+send dance — without it the file sits on the server and - // the recipient sees nothing. - if (uploadFile) { - try { - await bridge.apis.message.sendC2cFile(userId, targetUid, { - fileId, - fileName, - fileSize: loaded.bytes.length, - fileMd5: hashes.md5, - fileHash: fileHash ?? '', - }); - } catch (err) { - log.warn('private file uploaded (fileId=%s) but chat post failed: %s', - fileId, err instanceof Error ? err.message : String(err)); - } - } - - 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 env = makeOidbEnvelope( - 0x6D8, 1, - { - list: { - groupUin: groupId, - appId: 7, - targetDirectory, - fileCount: pageSize, - sortBy: 1, - startIndex, - field17: 2, - field18: 0, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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.identity.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.identity.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 env = makeOidbEnvelope( - 0x6D6, 2, - { - download: { - groupUin: groupId, - appId: 7, - busId, - fileId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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 selfUid = await resolveSelfUid(bridge); - void userId; - const env = makeOidbEnvelope(0xE37, 1200, { - subCommand: 1200, - field2: 1, - body: { - receiverUid: selfUid, - fileUuid: fileId, - type: 2, - fileHash, - t2: 0, - }, - field101: 3, - field102: 103, - field200: 1, - field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), - }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', protobuf_encode>(env), 5000); - const resp = protobuf_decode>(respBytes).body; - - 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 env = makeOidbEnvelope( - 0x6D6, 3, - { - delete: { - groupUin: groupId, - busId: 102, - fileId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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 env = makeOidbEnvelope( - 0x6D6, 5, - { - move: { - groupUin: groupId, - appId: 7, - busId: 102, - fileId, - parentDirectory, - targetDirectory, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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 env = makeOidbEnvelope( - 0x6D7, 0, - { - create: { - groupUin: groupId, - rootDirectory: normalizeDirectory(parentId), - folderName: name, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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 env = makeOidbEnvelope( - 0x6D7, 1, - { - delete: { - groupUin: groupId, - folderId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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 env = makeOidbEnvelope( - 0x6D7, 2, - { - rename: { - groupUin: groupId, - folderId, - newFolderName, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - 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/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts new file mode 100644 index 00000000..58113db4 --- /dev/null +++ b/packages/core/src/bridge/apis/group-file.ts @@ -0,0 +1,1006 @@ +// GroupFileApi — group file CRUD + private (c2c) file upload + media +// download URL resolvers. Inlined from `actions/group-file.ts` +// (deleted alongside the rest of actions/* in commit 13). +// +// Naming: methods drop the redundant `Group`/`File` suffix where the +// area name already says it. The `Private`/`Group` axis stays +// explicit because some methods only exist for one side +// (`publish` only makes sense for group, `getPrivateUrl` only for +// c2c) — keeping them in one Api lets the few shared private helpers +// (`fetchNtv2DownloadUrl`, the upload-ext builder) live in one file. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { toHexUpper } from '../../utils/hex'; +import { createLogger } from '../../utils/logger'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '../bridge-oidb'; +import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; +import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; +import type { FileUploadExt } from '@snowluma/proto-defs/highway'; +import { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileCountViewReq, + OidbGroupFileCountViewResp, + OidbGroupFileFolderReq, + OidbGroupFileFolderResp, + OidbGroupFileReq, + OidbGroupFileResp, + OidbGroupFileViewReq, + OidbGroupFileViewResp, + OidbGroupSendFileReq, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { + NTV2RichMediaReq, + NTV2RichMediaResp, + OidbPrivateFileDownloadReq, + OidbPrivateFileDownloadResp, + OidbPrivateFileUploadReq, + OidbPrivateFileUploadResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from '../actions/shared'; + +const log = createLogger('GroupFile'); + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +// ─────────────── 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 callers don't have to dig into actions/shared. +export type { MediaIndexNode } from '../actions/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 toHexUpper(data); +} + +// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives +// little-endian-packed (byte0 = first dotted octet) and we unpack it the +// same way. Force-unsigned the shift to keep negative ints (high bit set) +// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000 +// into a negative number. +function int32ToIpv4Dotted(value: number): string { + const b1 = value & 0xFF; + const b2 = (value >>> 8) & 0xFF; + const b3 = (value >>> 16) & 0xFF; + const b4 = (value >>> 24) & 0xFF; + return `${b1}.${b2}.${b3}.${b4}`; +} + +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 protobuf_encode({ + 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, + }); +} + +function buildPrivateFileUploadExt( + senderUin: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + sha1: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + uploadHost: string, + uploadPort: number, +): Uint8Array { + return protobuf_encode({ + 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, + }); +} + +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 env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); + const respBytes = await runOidb(bridge, serviceCmd, protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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}`; +} + +export class GroupFileApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── publish (group file → chat) ─────────────── + + /** + * Publish a previously-uploaded group file as a chat message. + * + * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`. + * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes + * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells + * the QQ server "now publish that staged blob as a chat message" so + * everyone in the group can see the file bubble. + * + * The old approach — wrap the file as `TransElem(elemType=24)` inside + * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING + * messages (the receive decoder unpacks transElem(24) into a + * FileEntity) but the QQ-NT server REJECTS it on outgoing with + * `result=79` ("invalid element on send-side"). Mirror Lagrange's + * dedicated GroupSendFileService instead. + * + * The unused `field4` slot and the `field3=random` value match + * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the + * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5 + * is the `Field5=true` flag the receiver's deserializer expects. + */ + async publish(groupId: number, fileId: string): Promise { + if (!fileId) throw new Error('publish requires fileId'); + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x6D9, 4, { + body: { + groupUin: groupId, + type: 2, + info: { + busiType: 102, + fileId, + field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, + field5: true, + }, + }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', protobuf_encode>(env)); + } + + // ─────────────── count ─────────────── + + async getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D8, 3, + { count: { groupUin: groupId, appId: 7, busId: 0 } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + return { + fileCount: toInt(resp?.count?.fileCount ?? 0), + maxCount: toInt(resp?.count?.maxCount ?? 10000), + }; + } + + // ─────────────── upload ─────────────── + + async upload( + groupId: number, + source: string, + name = '', + folderId = '/', + uploadFile = true, + ): Promise { + const bridge = asBridge(this.ctx); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); + if (!loaded.bytes.length) throw new Error('group file is empty'); + + const fileName = normalizeUploadFileName(name, loaded.fileName); + const hashes = computeHashes(loaded.bytes); + + const env = makeOidbEnvelope( + 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, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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'); + + // Remember the upload so a later `send_group_msg` carrying just the + // file_id can route via `publish` without forcing the OneBot caller + // to thread fileName/size/md5 separately. For groups the wire + // publish (OIDB 0x6d9_4) only needs the file_id itself, so this is + // mainly for log-line correctness; the c2c counterpart in + // `uploadPrivate` is where the cache is actually load-bearing. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'group', + groupId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + rememberedAt: Date.now(), + }); + + if (!upload.boolFileExist && uploadFile) { + const senderUin = toInt(this.ctx.identity.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); + } + + // Stage 3: file is on the server, now publish it as a chat message. + // + // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes — + // the chat shows nothing. The publish step goes via a dedicated OIDB + // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) + // payload — the QQ-NT server rejects that with `result=79`. Mirrors + // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the + // caller opts out via `uploadFile=false` (treat that as "I only + // wanted the slot allocated, hold the chat post"). Routes through + // `this.publish` so tests can mock at the same Api boundary. + if (uploadFile) { + try { + await this.publish(groupId, fileId); + } catch (err) { + // The bytes are already on the server and the fileId is valid — + // fail loud but don't lose the upload result the action handler + // committed to returning. Callers can still resolve the file by + // id; they'll just have to re-publish it themselves. + log.warn('group file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + + return { fileId }; + } + + async uploadPrivate( + userId: number, + source: string, + name = '', + uploadFile = true, + ): Promise { + const bridge = asBridge(this.ctx); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); + if (!loaded.bytes.length) throw new Error('private file is empty'); + + const targetUid = await this.ctx.resolveUserUid(userId); + let selfUid = this.ctx.identity.selfUid; + if (!selfUid) { + const selfUin = toInt(this.ctx.identity.uin); + if (selfUin > 0) { + selfUid = await this.ctx.resolveUserUid(selfUin); + } + } + if (!selfUid) throw new Error('self uid is unavailable'); + + const senderUin = toInt(this.ctx.identity.uin); + if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); + + const fileName = normalizeUploadFileName(name, loaded.fileName); + const hashes = computeHashes(loaded.bytes); + + const env = makeOidbEnvelope(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, + }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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'); + + // Cache the metadata so a later `send_private_msg` carrying just + // `{type:'file', file_id}` can resurrect the full c2c-file packet + // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without + // this the recipient sees a 0-byte file because the OneBot send path + // has no way to recover those fields from the file_id alone. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'private', + userId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + fileHash: fileHash ?? '', + rememberedAt: Date.now(), + }); + + if (!upload.boolFileExist && uploadFile) { + // Host selection. + // + // Current QQ-NT server rollout has stopped populating the legacy + // `uploadIp` (field 60) entirely. The host now arrives as the first + // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated + // IPv4 message) — same place acidify reads it from since their + // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` + // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); + // acidify uses `inIP`/`inPort` exclusively and so do we, because + // that's the address the highway PUT actually needs to reach. + // + // The 32-bit IPs are little-endian-packed (byte0 = first octet) + // per acidify's `Int.toIpString()`. Cross-checked the byte order + // by inspecting their highway flow — there's no separate htonl + // step, so the integer is already in network-octet-first order. + // + // Older server versions still populate the legacy string fields + // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / + // uploadDns), so we fall through to those after rtpMediaPlatform. + // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's + // what we picked. + const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress) + && upload.rtpMediaPlatformUploadAddress[0]) + ? upload.rtpMediaPlatformUploadAddress[0] : null; + const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 + ? int32ToIpv4Dotted(rtpFirst.inIP) : ''; + const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number' + ? rtpFirst.inPort : 0; + const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) + ? upload.uploadIpList[0] : ''; + const uploadHost = (rtpInIP) + || (typeof upload.uploadIp === 'string' && upload.uploadIp) + || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) + || (ipListFirst) + || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) + || (typeof upload.uploadDns === 'string' && upload.uploadDns) + || ''; + const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst + && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; + const uploadPort = rtpInIP && rtpInPort > 0 + ? rtpInPort + : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 + ? toInt(upload.uploadHttpsPort) + : toInt(upload.uploadPort); + if (!uploadHost || uploadPort <= 0) { + // Surface every host-bearing field we know about so a user + // hitting this can show us exactly which slot the server filled + // (or whether it returned nothing at all — which would point at + // a request mismatch rather than a missing decoder). + const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) + ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e: any) => ({ + outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, + iPType: e.iPType, + }))) + : '[]'; + log.warn( + 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', + rtpDump, + upload.uploadIp ?? '', upload.uploadDomain ?? '', + JSON.stringify(upload.uploadIpList ?? []), + upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', + upload.uploadLanip ?? '', upload.uploadPort ?? 0, + upload.uploadHttpsPort ?? 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); + } + + // Stage 3: publish the file as a c2c chat message. C2C files use + // `RichText.notOnlineFile` (parallel to `elems`), so we go through + // the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate` + // which only knows about elems[]. NapCat does the same atomic + // upload+send dance — without it the file sits on the server and + // the recipient sees nothing. + if (uploadFile) { + try { + await this.ctx.apis.message.sendC2cFile(userId, targetUid, { + fileId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileHash: fileHash ?? '', + }); + } catch (err) { + log.warn('private file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + + return { fileId, fileHash }; + } + + // ─────────────── list ─────────────── + + async list(groupId: number, folderId = '/'): Promise { + const bridge = asBridge(this.ctx); + const targetDirectory = normalizeDirectory(folderId); + const files: GroupFileInfo[] = []; + const folders: GroupFolderInfo[] = []; + + const pageSize = 20; + let startIndex = 0; + for (let page = 0; page < 200; page++) { + const env = makeOidbEnvelope( + 0x6D8, 1, + { + list: { + groupUin: groupId, + appId: 7, + targetDirectory, + fileCount: pageSize, + sortBy: 1, + startIndex, + field17: 2, + field18: 0, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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 = this.ctx.identity.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 = this.ctx.identity.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) ─────────────── + + async getUrl(groupId: number, fileId: string, busId = 102): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D6, 2, + { + download: { + groupUin: groupId, + appId: 7, + busId, + fileId, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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}`; + } + + async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + void userId; + const env = makeOidbEnvelope(0xE37, 1200, { + subCommand: 1200, + field2: 1, + body: { + receiverUid: selfUid, + fileUuid: fileId, + type: 2, + fileHash, + t2: 0, + }, + field101: 3, + field102: 103, + field200: 1, + field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), + }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', protobuf_encode>(env), 5000); + const resp = protobuf_decode>(respBytes).body; + + 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 ─────────────── + + async delete(groupId: number, fileId: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D6, 3, + { + delete: { + groupUin: groupId, + busId: 102, + fileId, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.delete; + if (!result) throw new Error('group file delete response missing'); + ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording); + } + + async move( + groupId: number, + fileId: string, + parentDirectory: string, + targetDirectory: string, + ): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D6, 5, + { + move: { + groupUin: groupId, + appId: 7, + busId: 102, + fileId, + parentDirectory, + targetDirectory, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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 ─────────────── + + async createFolder(groupId: number, name: string, parentId = '/'): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D7, 0, + { + create: { + groupUin: groupId, + rootDirectory: normalizeDirectory(parentId), + folderName: name, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.create; + if (!result) throw new Error('group folder create response missing'); + ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording); + } + + async deleteFolder(groupId: number, folderId: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D7, 1, + { + delete: { + groupUin: groupId, + folderId, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.delete; + if (!result) throw new Error('group folder delete response missing'); + ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording); + } + + async renameFolder(groupId: number, folderId: string, newFolderName: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D7, 2, + { + rename: { + groupUin: groupId, + folderId, + newFolderName, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + 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 ─────────────── + + async getPttUrl(groupId: number, node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + 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 } }, + }, + }); + } + + async getPrivatePttUrl(node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + 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 } }, + }, + }); + } + + async getVideoUrl(groupId: number, node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + 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 } }, + }, + }); + } + + async getPrivateVideoUrl(node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + 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/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 729fdba5..ba546577 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -23,6 +23,7 @@ import type { BridgeContext } from '../bridge-context'; import { ContactsApi } from './contacts'; import { GroupAdminApi } from './group-admin'; +import { GroupFileApi } from './group-file'; import { MessageApi } from './message'; export interface ApiHub { @@ -32,8 +33,9 @@ export interface ApiHub { readonly contacts: ContactsApi; /** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */ readonly groupAdmin: GroupAdminApi; + /** Group file CRUD + private (c2c) file upload + media URL resolvers. */ + readonly groupFile: GroupFileApi; // Pending — added as later commits land: - // readonly groupFile: GroupFileApi; // readonly groupAlbum: GroupAlbumApi; // readonly friend: FriendApi; // readonly interaction: InteractionApi; @@ -57,6 +59,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { message: new MessageApi(ctx), contacts: new ContactsApi(ctx), groupAdmin: new GroupAdminApi(ctx), + groupFile: new GroupFileApi(ctx), }; } @@ -65,4 +68,5 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { // signature use. Concrete instances always come from `bridge.apis.*`. export { ContactsApi } from './contacts'; export { GroupAdminApi } from './group-admin'; +export { GroupFileApi } from './group-file'; export { MessageApi } from './message'; diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index dac9178f..831bc598 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -1,6 +1,5 @@ import type { SendPacketResult } from '../protocol/packet-sender'; import type { ApiHub } from './apis'; -import type { GroupFilesResult } from './actions/group-file'; import type { MediaIndexNode } from './actions/shared'; import type { ClientKeyInfo, @@ -53,32 +52,15 @@ export interface BridgeInterface { deleteFriend(userId: number, block?: boolean): Promise; setFriendRemark(userId: number, remark: string): Promise; - // ─── Files ─── - uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; - uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; - /** - * Publish a previously-uploaded group file as a chat message via - * `OidbSvcTrpcTcp.0x6d9_4`. The atomic upload+publish flow inside - * `uploadGroupFile` already does this, but the OneBot send-message - * path needs it too for {type:'file', file_id} segments. - */ - sendGroupFileMessage(groupId: number, fileId: string): Promise; + // ─── Files (moved to apis.groupFile) ─── + // - upload / uploadPrivate / publish + // - list / getCount + // - getUrl / getPrivateUrl / getPttUrl / getPrivatePttUrl + // - getVideoUrl / getPrivateVideoUrl + // - delete / move / createFolder / deleteFolder / renameFolder /** Cache file metadata so a later send_msg with just `file_id` can rehydrate it. */ rememberUploadedFile(meta: UploadedFileMeta): void; recallUploadedFile(fileId: string): UploadedFileMeta | undefined; - fetchGroupFiles(groupId: number, folderId?: string): Promise; - fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise; - fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise; - fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise; - fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise; - fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise; - fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise; - deleteGroupFile(groupId: number, fileId: string): Promise; - moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise; - createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise; - deleteGroupFileFolder(groupId: number, folderId: string): Promise; - renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise; - fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>; // ─── Group Album ─── getGroupAlbumList(groupId: number): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 9a54e5c3..dd1f79f3 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -38,25 +38,11 @@ import { getGroupAlbumMediaList as getGroupAlbumMediaList_, likeGroupAlbumMedia as likeGroupAlbumMedia_, } from './actions/group-album'; -import type { GroupFilesResult } from './actions/group-file'; -import { - createGroupFileFolder as createGroupFileFolder_, - deleteGroupFile as deleteGroupFile_, - deleteGroupFileFolder as deleteGroupFileFolder_, - fetchGroupFileCount as fetchGroupFileCount_, - fetchGroupFiles as fetchGroupFiles_, - fetchGroupFileUrl as fetchGroupFileUrl_, - fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_, - fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_, - fetchPrivateFileUrl as fetchPrivateFileUrl_, - fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_, - fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_, - moveGroupFile as moveGroupFile_, - renameGroupFileFolder as renameGroupFileFolder_, - sendGroupFileMessage as sendGroupFileMessage_, - uploadGroupFile as uploadGroupFile_, - uploadPrivateFile as uploadPrivateFile_, -} from './actions/group-file'; +// Group file CRUD + private c2c upload + media URL resolvers moved to +// `apis.groupFile` (see `apis/group-file.ts::GroupFileApi`). The shared +// result type still lives here because the OneBot side imports it +// through bridge.ts. +import type { GroupFilesResult } from './apis/group-file'; import { setGroupEssence as setGroupEssence_, } from './actions/group-message'; @@ -84,7 +70,6 @@ import { setProfile as setProfile_, setSelfLongNick as setSelfLongNick_, } from './actions/profile'; -import type { MediaIndexNode } from './actions/shared'; // `bridge-contacts.ts` removed — its 6 functions are now methods on // `apis.contacts` (see `apis/contacts.ts::ContactsApi`). import { BridgeEventBus } from './event-bus'; @@ -346,29 +331,12 @@ export class Bridge implements BridgeInterface { // apis.groupAdmin (apis/group-admin.ts::GroupAdminApi). async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise { return setFriendAddRequest_(this, uidOrFlag, approve); } async deleteFriend(userId: number, block = false): Promise { return deleteFriend_(this, userId, block); } - async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> { - return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile); - } - async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> { - return uploadPrivateFile_(this, userId, file, name, uploadFile); - } - async sendGroupFileMessage(groupId: number, fileId: string): Promise { - return sendGroupFileMessage_(this, groupId, fileId); - } - async fetchGroupFiles(groupId: number, folderId = '/'): Promise { return fetchGroupFiles_(this, groupId, folderId); } - async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise { return fetchGroupFileUrl_(this, groupId, fileId, busId); } - async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); } - async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupPttUrlByNode_(this, groupId, node); } - async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise { return fetchPrivatePttUrlByNode_(this, node); } - async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupVideoUrlByNode_(this, groupId, node); } - async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise { return fetchPrivateVideoUrlByNode_(this, node); } + // GroupFile methods (upload/uploadPrivate/publish/list/getUrl/ + // getPrivateUrl/{Ptt,Video}Url/getPrivate{Ptt,Video}Url/delete/move/ + // createFolder/deleteFolder/renameFolder/getCount) moved to + // apis.groupFile (apis/group-file.ts::GroupFileApi). async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { return uploadForwardNodes_(this, nodes, groupId, userId); } async fetchForwardNodes(resId: string): Promise { return fetchForwardNodes_(this, resId); } - async deleteGroupFile(groupId: number, fileId: string): Promise { return deleteGroupFile_(this, groupId, fileId); } - async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); } - async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise { return createGroupFileFolder_(this, groupId, name, parentId); } - async deleteGroupFileFolder(groupId: number, folderId: string): Promise { return deleteGroupFileFolder_(this, groupId, folderId); } - async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); } async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { return sendPoke_(this, isGroup, peerUin, targetUin); } async sendLike(userId: number, count: number): Promise { return sendLike_(this, userId, count); } async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { return setGroupEssence_(this, groupId, sequence, random, enable); } @@ -423,8 +391,6 @@ export class Bridge implements BridgeInterface { return deleteGroupNotice_(this, groupId, fid); } - async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); } - // extend async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise { return setOnlineStatus_(this, status, extStatus, batteryStatus); diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 0d461c27..65771276 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -1142,7 +1142,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !folderId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); } - await ctx.bridge.deleteGroupFileFolder(groupId, folderId); + await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId); return okResponse(); }); @@ -1215,7 +1215,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } try { const node = await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); - const url = await ctx.bridge.fetchGroupPttUrlByNode(groupId, node); + const url = await ctx.bridge.apis.groupFile.getPttUrl(groupId, node); return okResponse(url); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); diff --git a/packages/core/src/onebot/actions/group-file.ts b/packages/core/src/onebot/actions/group-file.ts index 29581a0e..d5027138 100644 --- a/packages/core/src/onebot/actions/group-file.ts +++ b/packages/core/src/onebot/actions/group-file.ts @@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !fileId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); } - await ctx.bridge.deleteGroupFile(groupId, fileId); + await ctx.bridge.apis.groupFile.delete(groupId, fileId); return okResponse(); }); @@ -70,7 +70,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !fileId || !parentDirectory || !targetDirectory) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required'); } - await ctx.bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory); + await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory); return okResponse(); }); @@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !folderId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); } - await ctx.bridge.deleteGroupFileFolder(groupId, folderId); + await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId); return okResponse(); }); @@ -102,7 +102,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !folderId || !newName) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required'); } - await ctx.bridge.renameGroupFileFolder(groupId, folderId, newName); + await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName); return okResponse(); }); diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index a78d407f..4d4c1ce2 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -120,17 +120,17 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { // Group file — fileId field extraction + defaults. uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => { - const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true); + const result = await bridge.apis.groupFile.upload(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true); return result.fileId; }, uploadPrivateFile: async (userId, file, name, uploadFile) => { - const result = await bridge.uploadPrivateFile(userId, file, name ?? '', uploadFile ?? true); + const result = await bridge.apis.groupFile.uploadPrivate(userId, file, name ?? '', uploadFile ?? true); return result.fileId; }, - getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102), + getGroupFileUrl: (groupId, fileId, busId) => bridge.apis.groupFile.getUrl(groupId, fileId, busId ?? 102), getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId), - createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'), - getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash), + createGroupFileFolder: (groupId, name, parentId) => bridge.apis.groupFile.createFolder(groupId, name, parentId ?? '/'), + getPrivateFileUrl: (userId, fileId, fileHash) => bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash), // Requests — name translation. handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve), @@ -166,7 +166,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark), setGroupRemark: (groupId, remark) => bridge.apis.groupAdmin.setRemark(groupId, remark), setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source), - getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId), + getGroupFileCount: (groupId) => bridge.apis.groupFile.getCount(groupId), // Cross-store: looks up the meta then routes through Bridge. setMsgEmojiLike: async (messageId, emojiId, set) => { diff --git a/packages/core/src/onebot/media-url-resolver.ts b/packages/core/src/onebot/media-url-resolver.ts index d2b68ede..bf716bf0 100644 --- a/packages/core/src/onebot/media-url-resolver.ts +++ b/packages/core/src/onebot/media-url-resolver.ts @@ -26,9 +26,9 @@ export class MediaUrlResolver { private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise { if (element.type === 'file' && element.fileId) { if (isGroup) { - element.url = await this.bridge.fetchGroupFileUrl(sessionId, element.fileId); + element.url = await this.bridge.apis.groupFile.getUrl(sessionId, element.fileId); } else if (element.fileHash) { - element.url = await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash); + element.url = await this.bridge.apis.groupFile.getPrivateUrl(sessionId, element.fileId, element.fileHash); } else { element.url = ''; } @@ -38,12 +38,12 @@ export class MediaUrlResolver { if ((element.type === 'record' || element.type === 'video') && element.mediaNode) { if (isGroup) { element.url = element.type === 'record' - ? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode) - : await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode); + ? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode) + : await this.bridge.apis.groupFile.getVideoUrl(sessionId, element.mediaNode); } else { element.url = element.type === 'record' - ? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode) - : await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode); + ? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode) + : await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode); } } } diff --git a/packages/core/src/onebot/modules/contact-actions.ts b/packages/core/src/onebot/modules/contact-actions.ts index a7756c5d..af3f4459 100644 --- a/packages/core/src/onebot/modules/contact-actions.ts +++ b/packages/core/src/onebot/modules/contact-actions.ts @@ -114,7 +114,7 @@ export async function getGroupFiles( groupId: number, folderId?: string, ): Promise { - const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/'); + const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/'); return { files: result.files.map((file) => ({ group_id: groupId as any, diff --git a/packages/core/src/onebot/modules/media-actions.ts b/packages/core/src/onebot/modules/media-actions.ts index f3be88f9..2094c174 100644 --- a/packages/core/src/onebot/modules/media-actions.ts +++ b/packages/core/src/onebot/modules/media-actions.ts @@ -34,8 +34,8 @@ export async function getRecordInfo( if (!url && cached.mediaNode) { try { url = cached.isGroup - ? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode) - : await bridge.fetchPrivatePttUrlByNode(cached.mediaNode); + ? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode) + : await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode); if (url) { mediaStore.updateRecordUrl(file, url); } diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index 9c1abf45..dc000cc7 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -269,7 +269,7 @@ export async function sendGroupMessage( // wire. If this is the LAST element we still need a receipt so // the OneBot caller can cache the id; synthesise one from the // file_id hash + a fresh timestamp. - await ref.bridge.sendGroupFileMessage(groupId, fileEl.fileId!); + await ref.bridge.apis.groupFile.publish(groupId, fileEl.fileId!); logSentMessage(true, groupId, [fileEl]); if (!lastReceipt) { // Use a hash of the fileId as a stable pseudo-id; this gets diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts index d4b9b3f2..6467dc83 100644 --- a/packages/core/tests/actions/_helpers.ts +++ b/packages/core/tests/actions/_helpers.ts @@ -61,9 +61,50 @@ export function mockContactsApi(): MockContactsApi { }; } +export interface MockGroupFileApi { + upload: ReturnType; + uploadPrivate: ReturnType; + publish: ReturnType; + getCount: ReturnType; + list: ReturnType; + getUrl: ReturnType; + getPrivateUrl: ReturnType; + getPttUrl: ReturnType; + getPrivatePttUrl: ReturnType; + getVideoUrl: ReturnType; + getPrivateVideoUrl: ReturnType; + delete: ReturnType; + move: ReturnType; + createFolder: ReturnType; + deleteFolder: ReturnType; + renameFolder: ReturnType; +} + +export function mockGroupFileApi(): MockGroupFileApi { + return { + upload: vi.fn(async () => ({ fileId: 'stub-fid' })), + uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })), + publish: vi.fn(async () => undefined), + getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })), + list: vi.fn(async () => ({ files: [], folders: [] })), + getUrl: vi.fn(async () => 'stub://url'), + getPrivateUrl: vi.fn(async () => 'stub://private-url'), + getPttUrl: vi.fn(async () => 'stub://ptt-url'), + getPrivatePttUrl: vi.fn(async () => 'stub://private-ptt-url'), + getVideoUrl: vi.fn(async () => 'stub://video-url'), + getPrivateVideoUrl: vi.fn(async () => 'stub://private-video-url'), + delete: vi.fn(async () => undefined), + move: vi.fn(async () => undefined), + createFolder: vi.fn(async () => undefined), + deleteFolder: vi.fn(async () => undefined), + renameFolder: vi.fn(async () => undefined), + }; +} + export interface MockApiHub { message: MockMessageApi; contacts: MockContactsApi; + groupFile: MockGroupFileApi; // additional Apis added commit-by-commit as #6 progresses } @@ -71,6 +112,7 @@ export function mockApiHub(overrides: Partial = {}): MockApiHub { return { message: overrides.message ?? mockMessageApi(), contacts: overrides.contacts ?? mockContactsApi(), + groupFile: overrides.groupFile ?? mockGroupFileApi(), }; } @@ -89,9 +131,8 @@ export interface MockBridge { fetchGroupMemberList: ReturnType; fetchUserProfile: ReturnType; resolveUserUid: ReturnType; - sendGroupFileMessage: ReturnType; - // Uploaded-file metadata cache helpers — actions like uploadGroupFile - // / uploadPrivateFile call these to remember the upload, so tests + // Uploaded-file metadata cache helpers — GroupFileApi.upload / + // uploadPrivate call these to remember the upload, so tests // covering those code paths get a default-no-op shim. rememberUploadedFile: ReturnType; recallUploadedFile: ReturnType; @@ -121,7 +162,6 @@ export function mockBridge(overrides: Partial = {}): MockBridge { fetchGroupMemberList: vi.fn(async () => []), fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })), resolveUserUid: vi.fn(async () => 'resolved-uid'), - sendGroupFileMessage: vi.fn(async () => undefined), rememberUploadedFile: vi.fn(), recallUploadedFile: vi.fn(() => undefined), ...overrides, diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 61b7498a..549d3943 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -45,7 +45,7 @@ vi.mock('../../src/bridge/highway/utils', () => ({ 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 { GroupFileApi } from '../../src/bridge/apis/group-file'; import { mockBridge } from './_helpers'; describe('actions/group-file', () => { @@ -57,27 +57,27 @@ describe('actions/group-file', () => { vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); - it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => { + it('getCount returns { fileCount, maxCount } from the OIDB response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { count: { fileCount: 42, maxCount: 1000 } }, }), ); - const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); + const out = await new GroupFileApi(bridge as any).getCount(12345); expect(out).toEqual({ fileCount: 42, maxCount: 1000 }); }); - it('fetchGroupFileCount falls back to defaults on partial response', async () => { + it('getCount falls back to defaults on partial response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { count: {} } }), ); - const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); + const out = await new GroupFileApi(bridge as any).getCount(12345); expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); }); - it('uploadGroupFile skips highway when boolFileExist is true', async () => { + it('upload skips highway when boolFileExist is true', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -90,13 +90,16 @@ describe('actions/group-file', () => { } as any, }), ); - const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + const api = new GroupFileApi(bridge as any); + // Suppress the auto-publish — that path is covered separately. + vi.spyOn(api, 'publish').mockResolvedValue(); + const out = await api.upload(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 () => { + it('upload runs highway PUT when boolFileExist is false', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -113,90 +116,99 @@ describe('actions/group-file', () => { } as any, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + const api = new GroupFileApi(bridge as any); + vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/file.bin'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); - it('uploadGroupFile throws on missing upload response', async () => { + it('upload throws on missing upload response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) + await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin')) .rejects.toThrow(/response missing/); }); - it('uploadGroupFile bubbles up OIDB retCode errors', async () => { + it('upload bubbles up OIDB retCode errors', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any }, }), ); - await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) + await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin')) .rejects.toThrow(/code=999/); }); - it('uploadGroupFile publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => { + it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => { // Reproduces the bug report: OIDB upload + highway PUT alone only // stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB // call the file never appears in the chat. Earlier attempts used // PbSendMsg with a transElem(24) but the QQ-NT server rejects that // with result=79 (transElem(24) is a receive-side decoding shape, - // not a send-side one). Asserts that `bridge.sendGroupFileMessage` - // is invoked with the uploaded fileId. + // not a send-side one). Asserts that `this.publish` is invoked + // with the uploaded fileId. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any }, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt'); - expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce(); - const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!; + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/some-file.bin', 'mynote.txt'); + expect(publishSpy).toHaveBeenCalledOnce(); + const [groupId, fileId] = publishSpy.mock.calls[0]!; expect(groupId).toBe(12345); expect(fileId).toBe('fid-pub'); - // sendGroupMessage must NOT be touched — the previous wire shape + // sendGroup must NOT be touched — the previous wire shape // (PbSendMsg w/ transElem(24)) is the bug we're guarding against. expect(bridge.apis.message.sendGroup).not.toHaveBeenCalled(); }); - it('uploadGroupFile skips the chat post when uploadFile=false', async () => { + it('upload skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any }, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false); - expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled(); + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/file.bin', '', '/', false); + expect(publishSpy).not.toHaveBeenCalled(); }); - it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => { + it('upload returns success even when the chat post fails (file is still uploaded)', async () => { const bridge = mockBridge(); - vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected')); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any }, }), ); - const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(new Error('message rejected')); + const out = await api.upload(12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-tolerant' }); - expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(publishSpy).toHaveBeenCalledOnce(); }); - it('uploadGroupFile caches the upload metadata for later resend by file_id', async () => { + it('upload caches the upload metadata for later resend by file_id', async () => { // After upload, a later `send_group_msg` carrying just the file_id // needs to recover the name/size/md5 from somewhere. Production - // populates `bridge.rememberUploadedFile` with the full tuple. + // populates `ctx.rememberUploadedFile` with the full tuple. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any }, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/x.bin', 'x.bin'); + const api = new GroupFileApi(bridge as any); + vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/x.bin', 'x.bin'); expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; expect(meta).toMatchObject({ @@ -207,13 +219,13 @@ describe('actions/group-file', () => { }); }); - it('sendGroupFileMessage hits OIDB 0x6d9_4 with the right body', async () => { + it('publish hits OIDB 0x6d9_4 with the right body', async () => { // Direct cover of the new bridge method. The previous send-shape // (PbSendMsg + transElem(24)) failed with result=79; this is the // Lagrange-V2-mirrored fix. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array()); - await groupFile.sendGroupFileMessage(bridge as any, 12345, 'fid-publish'); + await new GroupFileApi(bridge as any).publish(12345, 'fid-publish'); expect(oidb.runOidb).toHaveBeenCalledOnce(); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4'); @@ -234,7 +246,7 @@ describe('actions/group-file', () => { ); }); - it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => { + it('uploadPrivate resolves both target + self UID before OIDB call', async () => { const bridge = mockBridge({ identity: { uin: '10001', @@ -253,17 +265,17 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any }, }), ); - const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file'); + const out = await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file'); expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' }); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); }); - it('uploadPrivateFile publishes the file via sendC2cFileMessage after upload', async () => { + it('uploadPrivate publishes the file via apis.message.sendC2cFile after upload', async () => { // C2C files use `RichText.notOnlineFile` (not in the elems array), - // so `uploadPrivateFile` calls the dedicated `sendC2cFileMessage` - // path on the bridge rather than `sendPrivateMessage`. Same bug - // class as the group case — without this the recipient sees no - // message even though the bytes are on the server. + // so `uploadPrivate` calls the dedicated `sendC2cFile` path on + // the bridge rather than `sendPrivate`. Same bug class as the + // group case — without this the recipient sees no message even + // though the bytes are on the server. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -271,7 +283,7 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/private-file.bin', 'doc.pdf'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/private-file.bin', 'doc.pdf'); expect(bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce(); const [userUin, userUid, info] = bridge.apis.message.sendC2cFile.mock.calls[0]!; expect(userUin).toBe(67890); @@ -280,12 +292,12 @@ describe('actions/group-file', () => { expect(bridge.apis.message.sendPrivate).not.toHaveBeenCalled(); }); - it('uploadPrivateFile caches the upload metadata for later resend by file_id', async () => { + it('uploadPrivate caches the upload metadata for later resend by file_id', async () => { // C2C file resend (send_private_msg with just file_id) was the // "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/ // fileName/fileHash, but the OneBot caller only knows the file_id. // Caching the upload tuple lets the OneBot send-message path - // recover the rest via `bridge.recallUploadedFile(fileId)`. + // recover the rest via `ctx.recallUploadedFile(fileId)`. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -293,7 +305,7 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/cache-me.txt', 'cache-me.txt'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/cache-me.txt', 'cache-me.txt'); expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; expect(meta).toMatchObject({ @@ -305,7 +317,7 @@ describe('actions/group-file', () => { }); }); - it('uploadPrivateFile skips the chat post when uploadFile=false', async () => { + it('uploadPrivate skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -313,11 +325,11 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file', '', false); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', '', false); expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled(); }); - it('uploadPrivateFile reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { + it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { // The 2026 QQ-NT server rollout moved the upload host out of the // legacy `uploadIp` (field 60) string into the new // `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message). @@ -342,11 +354,11 @@ describe('actions/group-file', () => { }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); - it('uploadPrivateFile falls back to uploadDomain when uploadIp is empty', async () => { + it('uploadPrivate falls back to uploadDomain when uploadIp is empty', async () => { // Regression: the server has been observed in the wild returning the // highway host in `uploadDomain` (field 70) instead of `uploadIp` // (field 60), causing "private file upload host is invalid". The @@ -371,11 +383,11 @@ describe('actions/group-file', () => { }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); - it('uploadPrivateFile throws "host is invalid" only when every host field is empty', async () => { + it('uploadPrivate throws "host is invalid" only when every host field is empty', async () => { // The diagnostic warn-log lists every host slot to help users // report which one the server actually populated; this test just // asserts that the throw still fires when none of them carry a @@ -387,11 +399,11 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any }, }), ); - await expect(groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin')) + await expect(new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin')) .rejects.toThrow(/upload host is invalid/); }); - it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { + it('list paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -406,14 +418,14 @@ describe('actions/group-file', () => { }, }), ); - const out = await groupFile.fetchGroupFiles(bridge as any, 12345); + const out = await new GroupFileApi(bridge as any).list(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 () => { + it('getUrl builds the https URL from downloadDns + hex-encoded path', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -425,44 +437,46 @@ describe('actions/group-file', () => { }, }), ); - const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'); + const url = await new GroupFileApi(bridge as any).getUrl(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 () => { + it('getUrl throws when response is missing dns or url', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { download: {} as any }, }), ); - await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz')) + await expect(new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz')) .rejects.toThrow(/invalid/); }); - it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => { + it('delete / move dispatch the right sub-commands', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) .mockResolvedValueOnce(protobuf_encode>({ body: { move: {} as any } })); - await groupFile.deleteGroupFile(bridge as any, 12345, 'fid'); - await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b'); + const api = new GroupFileApi(bridge as any); + await api.delete(12345, 'fid'); + await api.move(12345, 'fid', '/a', '/b'); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]); }); - it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => { + it('createFolder / deleteFolder / renameFolder dispatch 0x6d7 family', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) .mockResolvedValueOnce(protobuf_encode>({ body: { create: {} as any } })) .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) .mockResolvedValueOnce(protobuf_encode>({ body: { rename: {} as any } })); - 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'); + const api = new GroupFileApi(bridge as any); + await api.createFolder(1, 'folder'); + await api.deleteFolder(1, 'fid'); + await api.renameFolder(1, 'fid', 'newname'); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]); }); - it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => { + it('get*Url builds https://domain/path?rkey from the NTV2 response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValue( protobuf_encode>({ @@ -475,7 +489,7 @@ describe('actions/group-file', () => { } as any, }), ); - const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' }); + const url = await new GroupFileApi(bridge as any).getVideoUrl(12345, { fileUuid: 'uuid' }); expect(url).toBe('https://media.example.com/path/x?rkey=abc'); }); }); diff --git a/packages/core/tests/media-url-resolver.test.ts b/packages/core/tests/media-url-resolver.test.ts index 1e167f82..45926d51 100644 --- a/packages/core/tests/media-url-resolver.test.ts +++ b/packages/core/tests/media-url-resolver.test.ts @@ -4,16 +4,25 @@ import type { MessageElement } from '../src/bridge/events'; // Minimal stand-ins for the two collaborators. Each test wires whatever // subset of Bridge methods the element type exercises. - +// +// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl, +// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl, +// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here +// builds an `apis.groupFile` stub directly so tests can keep asserting +// "which file/url helper got called" without going through the +// `mockBridge` shared fixture. function makeBridge(overrides: Record> = {}) { return { - fetchGroupFileUrl: vi.fn(async () => 'http://group/file'), - fetchPrivateFileUrl: vi.fn(async () => 'http://private/file'), - fetchGroupPttUrlByNode: vi.fn(async () => 'http://group/ptt'), - fetchPrivatePttUrlByNode: vi.fn(async () => 'http://private/ptt'), - fetchGroupVideoUrlByNode: vi.fn(async () => 'http://group/video'), - fetchPrivateVideoUrlByNode: vi.fn(async () => 'http://private/video'), - ...overrides, + apis: { + groupFile: { + getUrl: overrides.getUrl ?? vi.fn(async () => 'http://group/file'), + getPrivateUrl: overrides.getPrivateUrl ?? vi.fn(async () => 'http://private/file'), + getPttUrl: overrides.getPttUrl ?? vi.fn(async () => 'http://group/ptt'), + getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => 'http://private/ptt'), + getVideoUrl: overrides.getVideoUrl ?? vi.fn(async () => 'http://group/video'), + getPrivateVideoUrl: overrides.getPrivateVideoUrl ?? vi.fn(async () => 'http://private/video'), + }, + }, }; } @@ -34,7 +43,7 @@ describe('MediaUrlResolver — file element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid-x' }; const out = await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupFileUrl).toHaveBeenCalledWith(12345, 'fid-x'); + expect(bridge.apis.groupFile.getUrl).toHaveBeenCalledWith(12345, 'fid-x'); expect(element.url).toBe('http://group/file'); expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce(); expect(out).toBe('http://group/file'); @@ -44,7 +53,7 @@ describe('MediaUrlResolver — file element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivateFileUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y'); + expect(bridge.apis.groupFile.getPrivateUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y'); expect(element.url).toBe('http://private/file'); }); @@ -52,7 +61,7 @@ describe('MediaUrlResolver — file element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid-x' }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivateFileUrl).not.toHaveBeenCalled(); + expect(bridge.apis.groupFile.getPrivateUrl).not.toHaveBeenCalled(); expect(element.url).toBe(''); }); }); @@ -66,7 +75,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupPttUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE); + expect(bridge.apis.groupFile.getPttUrl).toHaveBeenCalledWith(12345, MEDIA_NODE); expect(element.url).toBe('http://group/ptt'); }); @@ -74,7 +83,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivatePttUrlByNode).toHaveBeenCalledWith(MEDIA_NODE); + expect(bridge.apis.groupFile.getPrivatePttUrl).toHaveBeenCalledWith(MEDIA_NODE); expect(element.url).toBe('http://private/ptt'); }); @@ -82,7 +91,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupVideoUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE); + expect(bridge.apis.groupFile.getVideoUrl).toHaveBeenCalledWith(12345, MEDIA_NODE); expect(element.url).toBe('http://group/video'); }); @@ -90,7 +99,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivateVideoUrlByNode).toHaveBeenCalledWith(MEDIA_NODE); + expect(bridge.apis.groupFile.getPrivateVideoUrl).toHaveBeenCalledWith(MEDIA_NODE); expect(element.url).toBe('http://private/video'); }); @@ -98,7 +107,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'record' }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupPttUrlByNode).not.toHaveBeenCalled(); + expect(bridge.apis.groupFile.getPttUrl).not.toHaveBeenCalled(); expect(element.url).toBeUndefined(); }); }); @@ -110,13 +119,13 @@ describe('MediaUrlResolver — short-circuits and resilience', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupFileUrl).not.toHaveBeenCalled(); + expect(bridge.apis.groupFile.getUrl).not.toHaveBeenCalled(); expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce(); }); it('bridge throws: swallowed, rkey still applied', async () => { const bridge = makeBridge({ - fetchGroupFileUrl: vi.fn(async () => { throw new Error('network down'); }), + getUrl: vi.fn(async () => { throw new Error('network down'); }), }); const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') }); const resolver = new MediaUrlResolver(bridge as any, rkey as any); diff --git a/packages/core/tests/onebot/extended-actions.test.ts b/packages/core/tests/onebot/extended-actions.test.ts index 3922194d..ab351319 100644 --- a/packages/core/tests/onebot/extended-actions.test.ts +++ b/packages/core/tests/onebot/extended-actions.test.ts @@ -28,23 +28,32 @@ function fakeMeta(overrides: Partial = {}): MessageMeta { * pre-stubbed for the test. Same pattern as contact-actions.test.ts — * keeps tests honest about which surface they actually need. */ -// Maps flat method names → ApiHub area they moved to under the #6 -// refactor. Auto-promotion lets tests written against the pre-refactor -// flat surface (`fetchGroupRequests: vi.fn()`) keep working without -// per-test restructure. -const APIS_ROUTING: Record = { - fetchFriendList: 'contacts', fetchGroupList: 'contacts', - fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts', - fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts', +// Maps flat method names → [area, newMethodName] on the ApiHub under +// the #6 refactor. Auto-promotion lets tests written against the +// pre-refactor flat surface (`fetchGroupRequests: vi.fn()`) keep +// working without per-test restructure, even when the new method name +// drops the redundant `Group`/`File` prefix. +const APIS_ROUTING: Record = { + fetchFriendList: ['contacts', 'fetchFriendList'], + fetchGroupList: ['contacts', 'fetchGroupList'], + fetchGroupMemberList: ['contacts', 'fetchGroupMemberList'], + fetchUserProfile: ['contacts', 'fetchUserProfile'], + fetchGroupRequests: ['contacts', 'fetchGroupRequests'], + fetchDownloadRKeys: ['contacts', 'fetchDownloadRKeys'], + // GroupFileApi: methods drop `Group`/`File`/`Folder` suffix where + // the area name already says it. + deleteGroupFileFolder: ['groupFile', 'deleteFolder'], + fetchGroupPttUrlByNode: ['groupFile', 'getPttUrl'], }; function fakeBridge(overrides: Record = {}): BridgeInterface { const apisSynth: Record> = {}; for (const [k, v] of Object.entries(overrides)) { - const area = APIS_ROUTING[k]; - if (area) { + const route = APIS_ROUTING[k]; + if (route) { + const [area, newName] = route; if (!apisSynth[area]) apisSynth[area] = {}; - apisSynth[area][k] = v; + apisSynth[area][newName] = v; } } const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } }; diff --git a/packages/core/tests/onebot/send-group-file.test.ts b/packages/core/tests/onebot/send-group-file.test.ts index a4089c7e..e4c5aec6 100644 --- a/packages/core/tests/onebot/send-group-file.test.ts +++ b/packages/core/tests/onebot/send-group-file.test.ts @@ -11,7 +11,7 @@ // // Fix: split file segments off at the OneBot layer (same pattern as // the c2c-file split for private messages) and dispatch through -// `bridge.sendGroupFileMessage`, which calls dedicated OIDB +// `bridge.apis.groupFile.publish`, which calls dedicated OIDB // `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's // `GroupSendFileService.cs`. @@ -45,7 +45,7 @@ const goodReceipt = { }; describe('send_group_msg with {type:"file"} segment', () => { - it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', async () => { + it('file-only message routes through apis.groupFile.publish (not apis.message.sendGroup)', async () => { // Pure-file case — the elems[] path used to ship a transElem(24) // and got result=79. The dedicated OIDB-0x6d9_4 route must take // over for group file publishing. @@ -53,10 +53,12 @@ describe('send_group_msg with {type:"file"} segment', () => { // Declare params on the fn so `mock.calls[0]` infers a tuple of // [groupId, fileId] instead of `[]` (which makes the destructuring // a tsc error under noUncheckedIndexedAccess). - const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined); + const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); const bridge = fakeBridge({ - apis: { message: { sendGroup: sendGroupMessage_bridge } } as any, - sendGroupFileMessage, + apis: { + message: { sendGroup: sendGroupMessage_bridge }, + groupFile: { publish }, + } as any, resolveUserUid: vi.fn(), } as any); const ctx = makeCtx(bridge); @@ -65,20 +67,22 @@ describe('send_group_msg with {type:"file"} segment', () => { type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 }, }] as any, false); - expect(sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(publish).toHaveBeenCalledOnce(); expect(sendGroupMessage_bridge).not.toHaveBeenCalled(); - const [groupId, fileId] = sendGroupFileMessage.mock.calls[0]!; + const [groupId, fileId] = publish.mock.calls[0]!; expect(groupId).toBe(12345); expect(fileId).toBe('gfid-abc'); }); it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => { const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); - const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined); + const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); const bridge = fakeBridge({ - apis: { message: { sendGroup: sendGroupMessage_bridge } } as any, - sendGroupFileMessage, + apis: { + message: { sendGroup: sendGroupMessage_bridge }, + groupFile: { publish }, + } as any, resolveUserUid: vi.fn(async () => 'u_peer'), } as any); const ctx = makeCtx(bridge); @@ -89,13 +93,13 @@ describe('send_group_msg with {type:"file"} segment', () => { ] as any, false); expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); - expect(sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(publish).toHaveBeenCalledOnce(); const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!; expect(textGid).toBe(12345); expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]); - const [fileGid, fileFileId] = sendGroupFileMessage.mock.calls[0]!; + const [fileGid, fileFileId] = publish.mock.calls[0]!; expect(fileGid).toBe(12345); expect(fileFileId).toBe('gfid-xyz'); }); @@ -104,10 +108,12 @@ describe('send_group_msg with {type:"file"} segment', () => { // Same upload-by-reference contract as the c2c file path — // missing file_id means there's nothing to publish. const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); - const sendGroupFileMessage = vi.fn(); + const publish = vi.fn(); const bridge = fakeBridge({ - apis: { message: { sendGroup: sendGroupMessage_bridge } } as any, - sendGroupFileMessage, + apis: { + message: { sendGroup: sendGroupMessage_bridge }, + groupFile: { publish }, + } as any, resolveUserUid: vi.fn(), } as any); const ctx = makeCtx(bridge); @@ -118,6 +124,6 @@ describe('send_group_msg with {type:"file"} segment', () => { ] as any, false); expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); - expect(sendGroupFileMessage).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); }); });