refactor(api): move 17 group-file methods to GroupFileApi (#6 commit 4/13)

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).
This commit is contained in:
DrSmoothl committed 2026-05-20 23:08:50 +08:00
1 parent 0b91e4db8d
commit dad501ebc0
17 files changed
+1241 -1185

No files matched your search

@@ -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<FileUploadExt>({
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<FileUploadExt>({
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<string, unknown> {
const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
if (!fileUuid) throw new Error('media node fileUuid is required');
const info = node.info ?? {};
const type = info.type ?? {};
return {
info: {
fileSize: toInt(info.fileSize),
fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
fileName: typeof info.fileName === 'string' ? info.fileName : '',
type: {
type: toInt(type.type),
picFormat: toInt(type.picFormat),
videoFormat: toInt(type.videoFormat),
voiceFormat: toInt(type.voiceFormat),
},
width: toInt(info.width),
height: toInt(info.height),
time: toInt(info.time),
original: toInt(info.original),
},
fileUuid,
storeId: toInt(node.storeId),
uploadTime: toInt(node.uploadTime),
ttl: toInt(node.ttl),
subType: toInt(node.subType),
};
}
async function fetchNtv2DownloadUrl(
bridge: Bridge,
serviceCmd: string,
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const env = makeOidbEnvelope<NTV2RichMediaReq>(oidbCmd, 200, payload as any, true);
const respBytes = await runOidb(bridge, serviceCmd, protobuf_encode<OidbBase<NTV2RichMediaReq>>(env));
const resp = protobuf_decode<OidbBase<NTV2RichMediaResp>>(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<void> {
if (!fileId) throw new Error('sendGroupFileMessage requires fileId');
const env = makeOidbEnvelope<OidbGroupSendFileReq>(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<OidbBase<OidbGroupSendFileReq>>(env));
}
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const env = makeOidbEnvelope<OidbGroupFileCountViewReq>(
0x6D8, 3,
{ count: { groupUin: groupId, appId: 7, busId: 0 } },
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', protobuf_encode<OidbBase<OidbGroupFileCountViewReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileCountViewResp>>(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<UploadFileResult> {
// 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<OidbGroupFileReq>(
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<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(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<UploadFileResult> {
// 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<OidbPrivateFileUploadReq>(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<OidbBase<OidbPrivateFileUploadReq>>(env));
const resp = protobuf_decode<OidbBase<OidbPrivateFileUploadResp>>(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<GroupFilesResult> {
const targetDirectory = normalizeDirectory(folderId);
const files: GroupFileInfo[] = [];
const folders: GroupFolderInfo[] = [];
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const env = makeOidbEnvelope<OidbGroupFileViewReq>(
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<OidbBase<OidbGroupFileViewReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileViewResp>>(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<string> {
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 2,
{
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(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<string> {
const selfUid = await resolveSelfUid(bridge);
void userId;
const env = makeOidbEnvelope<OidbPrivateFileDownloadReq>(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<OidbBase<OidbPrivateFileDownloadReq>>(env), 5000);
const resp = protobuf_decode<OidbBase<OidbPrivateFileDownloadResp>>(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<void> {
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 3,
{
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(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<void> {
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 5,
{
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(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<void> {
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 0,
{
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(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<void> {
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 1,
{
delete: {
groupUin: groupId,
folderId,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(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<void> {
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 2,
{
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(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<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, {
reqHead: {
common: { requestId: 4, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -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';
+6 -24
View File
@@ -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<void>;
setFriendRemark(userId: number, remark: string): Promise<void>;
// ─── Files ───
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
/**
* 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<void>;
// ─── 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<GroupFilesResult>;
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string>;
fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string>;
deleteGroupFile(groupId: number, fileId: string): Promise<void>;
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void>;
createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise<void>;
deleteGroupFileFolder(groupId: number, folderId: string): Promise<void>;
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Group Album ───
getGroupAlbumList(groupId: number): Promise<any>;
+9 -43
View File
@@ -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<void> { return setFriendAddRequest_(this, uidOrFlag, approve); }
async deleteFriend(userId: number, block = false): Promise<void> { 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<void> {
return sendGroupFileMessage_(this, groupId, fileId);
}
async fetchGroupFiles(groupId: number, folderId = '/'): Promise<GroupFilesResult> { return fetchGroupFiles_(this, groupId, folderId); }
async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise<string> { return fetchGroupFileUrl_(this, groupId, fileId, busId); }
async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupPttUrlByNode_(this, groupId, node); }
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { 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<string> { return uploadForwardNodes_(this, nodes, groupId, userId); }
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise<void> { return createGroupFileFolder_(this, groupId, name, parentId); }
async deleteGroupFileFolder(groupId: number, folderId: string): Promise<void> { return deleteGroupFileFolder_(this, groupId, folderId); }
async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); }
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { return sendPoke_(this, isGroup, peerUin, targetUin); }
async sendLike(userId: number, count: number): Promise<void> { return sendLike_(this, userId, count); }
async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { 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<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
+2 -2
View File
@@ -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));
@@ -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();
});
+6 -6
View File
@@ -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) => {
@@ -26,9 +26,9 @@ export class MediaUrlResolver {
private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise<void> {
if (element.type === 'file' && element.fileId) {
if (isGroup) {
element.url = await this.bridge.fetchGroupFileUrl(sessionId, element.fileId);
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);
}
}
}
@@ -114,7 +114,7 @@ export async function getGroupFiles(
groupId: number,
folderId?: string,
): Promise<JsonObject> {
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,
@@ -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);
}
@@ -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
+44 -4
View File
@@ -61,9 +61,50 @@ export function mockContactsApi(): MockContactsApi {
};
}
export interface MockGroupFileApi {
upload: ReturnType<typeof vi.fn>;
uploadPrivate: ReturnType<typeof vi.fn>;
publish: ReturnType<typeof vi.fn>;
getCount: ReturnType<typeof vi.fn>;
list: ReturnType<typeof vi.fn>;
getUrl: ReturnType<typeof vi.fn>;
getPrivateUrl: ReturnType<typeof vi.fn>;
getPttUrl: ReturnType<typeof vi.fn>;
getPrivatePttUrl: ReturnType<typeof vi.fn>;
getVideoUrl: ReturnType<typeof vi.fn>;
getPrivateVideoUrl: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
move: ReturnType<typeof vi.fn>;
createFolder: ReturnType<typeof vi.fn>;
deleteFolder: ReturnType<typeof vi.fn>;
renameFolder: ReturnType<typeof vi.fn>;
}
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> = {}): MockApiHub {
return {
message: overrides.message ?? mockMessageApi(),
contacts: overrides.contacts ?? mockContactsApi(),
groupFile: overrides.groupFile ?? mockGroupFileApi(),
};
}
@@ -89,9 +131,8 @@ export interface MockBridge {
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
resolveUserUid: ReturnType<typeof vi.fn>;
sendGroupFileMessage: ReturnType<typeof vi.fn>;
// 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<typeof vi.fn>;
recallUploadedFile: ReturnType<typeof vi.fn>;
@@ -121,7 +162,6 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): 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,
+80 -66
View File
@@ -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<OidbBase<OidbGroupFileCountViewResp>>({
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<OidbBase<OidbGroupFileCountViewResp>>({ 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<OidbBase<OidbGroupFileResp>>({
@@ -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<OidbBase<OidbGroupFileResp>>({
@@ -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<OidbBase<OidbGroupFileResp>>({ 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<OidbBase<OidbGroupFileResp>>({
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<OidbBase<OidbGroupFileResp>>({
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<OidbBase<OidbGroupFileResp>>({
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<OidbBase<OidbGroupFileResp>>({
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<OidbBase<OidbGroupFileResp>>({
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<OidbBase<OidbGroupFileViewResp>>({
@@ -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<OidbBase<OidbGroupFileResp>>({
@@ -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<OidbBase<OidbGroupFileResp>>({
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<OidbBase<OidbGroupFileResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ 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<OidbBase<OidbGroupFileFolderResp>>({ body: { create: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ 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<OidbBase<NTV2RichMediaResp>>({
@@ -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');
});
});
+27 -18
View File
@@ -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<string, ReturnType<typeof vi.fn>> = {}) {
return {
fetchGroupFileUrl: vi.fn(async () => 'http://group/file'),
fetchPrivateFileUrl: vi.fn(async () => 'http://private/file'),
fetchGroupPttUrlByNode: vi.fn(async () => 'http://group/ptt'),
fetchPrivatePttUrlByNode: vi.fn(async () => 'http://private/ptt'),
fetchGroupVideoUrlByNode: vi.fn(async () => 'http://group/video'),
fetchPrivateVideoUrlByNode: vi.fn(async () => 'http://private/video'),
...overrides,
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);
@@ -28,23 +28,32 @@ function fakeMeta(overrides: Partial<MessageMeta> = {}): 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<string, string> = {
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<string, [string, string]> = {
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<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
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 ?? {}) } };
@@ -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();
});
});