fix(file): route group publish through OIDB 0x6d9_4 and cache upload meta for c2c resend

The chat-publish step after upload_group_file used to ship a PbSendMsg
with a transElem(elemType=24) — but that wire shape is RECEIVE-side
only, and current QQ-NT rejects it on send with `result=79`. Lagrange.
Core V2 uses a dedicated `OidbSvcTrpcTcp.0x6d9_4` for the publish
(`GroupSendFileService.cs`); mirror that. Send_group_msg with a
`{type:'file', file_id}` segment now routes through the same path
after the OneBot layer splits file segments out (matching the c2c
file split pattern).

Separately, send_private_msg with just `{file_id}` was shipping a 0 B
file because the wire packet for c2c file send needs fileSize/fileMd5/
fileName/fileHash but the OneBot caller only echoes the file_id from
upload_private_file. Add a bounded (1024-entry, FIFO) bridge cache
populated at upload time so the send-message path can rehydrate the
full tuple; inline segment fields still take precedence so callers
that track the metadata themselves can bypass the cache. Parser now
also accepts `file_hash`/`fileHash` on file segments.

Also: file segments no longer get a `[空消息]` log line — the format
string now shows `[文件:<name-or-id>]`.
This commit is contained in:
DrSmoothl committed 2026-05-20 13:30:13 +08:00
1 parent 6de2e071be
commit c83c333e73
12 files changed
+634 -158

No files matched your search

+88 -13
View File
@@ -19,6 +19,7 @@ import type {
OidbGroupFileResp,
OidbGroupFileViewReq,
OidbGroupFileViewResp,
OidbGroupSendFileReq,
OidbPrivateFileDownloadReq,
OidbPrivateFileDownloadResp,
OidbPrivateFileUploadReq,
@@ -273,6 +274,48 @@ async function fetchNtv2DownloadUrl(
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', encodeOidbEnv<OidbGroupSendFileReq>(env));
}
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
@@ -336,6 +379,23 @@ export async function uploadGroupFile(
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');
@@ -366,22 +426,20 @@ export async function uploadGroupFile(
}
// 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. NapCat does the same (upload + sendMsg
// atomically inside `upload_group_file`, see
// `dev/napcatQQ/.../UploadGroupFile.ts:54-58`). Only suppressed when
// the caller opts out via `uploadFile=false` (treat that as "I only
// wanted the slot allocated, hold the chat post").
// 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.sendGroupMessage(groupId, [{
type: 'file',
fileId,
fileName,
fileSize: loaded.bytes.length,
md5Hex: bytesToHexUpper(hashes.md5),
sha1Hex: bytesToHexUpper(hashes.sha1),
}]);
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
@@ -452,6 +510,23 @@ export async function uploadPrivateFile(
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.
//
@@ -22,6 +22,7 @@ import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
UploadedFileMeta,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
@@ -89,6 +90,16 @@ export interface BridgeInterface {
// ─── 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>;
/** 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>;
+76
View File
@@ -48,6 +48,7 @@ import {
import {
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
sendGroupFileMessage as sendGroupFileMessage_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
@@ -147,6 +148,29 @@ export interface SendMessageReceipt {
timestamp: number;
}
/**
* Metadata remembered after `upload_group_file` / `upload_private_file`
* succeeds. Lets the OneBot send-message path reconstruct the full
* payload when the caller only echoes the `file_id` back later. See
* `Bridge.rememberUploadedFile` / `recallUploadedFile`.
*/
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
@@ -186,6 +210,24 @@ export class Bridge implements BridgeInterface {
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch_ = new Map<number, { at: number; data: GroupMemberInfo[] }>();
// ── Uploaded-file metadata cache ────────────────────────────────────
//
// After a file goes through `upload_group_file` / `upload_private_file`
// we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed
// by the returned file_id. The OneBot send-message paths consult this
// when the caller later passes `{type:'file', file_id:'xxx'}` without
// the rest of the metadata — c2c file send needs the size/md5/name
// for the wire packet (server-side rejection / "0 byte file" otherwise),
// and the group send path falls back to the name for the log line.
//
// Bounded at ~1024 entries with simple FIFO eviction. Files older
// than 7 days expire on QQ's side anyway, so this isn't load-bearing
// for correctness — just a UX convenience cache so the OneBot caller
// doesn't have to thread the metadata themselves between upload and
// send_msg.
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
@@ -252,6 +294,37 @@ export class Bridge implements BridgeInterface {
return true;
}
// --- Uploaded-file metadata cache ---
/**
* Remember a freshly-uploaded file so a later `send_*_msg` carrying
* just the file_id can reconstruct the full c2c-file packet (fileName
* / fileSize / fileMd5 are required by the QQ NT server's c2c file
* intake, even if only the uuid is needed for the OIDB lookup
* internally — without them the file shows as 0 B in the recipient's
* chat or is silently rejected). Insertion is FIFO; oldest entry is
* evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`.
*/
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
/**
* Recall metadata for a previously-uploaded file. Returns `undefined`
* if the file_id was never uploaded through this bridge instance, or
* if it's been evicted from the cache.
*/
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
// --- Sequence / random generators ---
private nextClientSequence(): number {
@@ -562,6 +635,9 @@ export class Bridge implements BridgeInterface {
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); }
+25 -73
View File
@@ -13,11 +13,12 @@ import type {
MentionExtraSend,
MarkdownData,
} from './proto/proton/action';
import type { GroupFileExtra } from './proto/proton/element';
// `GroupFileExtra` + `hexToBytes` used to support `makeGroupFileElem`
// (removed — see comment above the former call site). The receive-side
// decoder in `msg-push/rich-body-decoder.ts` still pulls those in.
import { uploadImageMsgInfo } from './highway/image-upload';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
import { hexToBytes } from './highway/pipeline';
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
@@ -246,63 +247,12 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
};
}
function makeGroupFileElem(element: MessageElement): ProtoElem {
// Group file chat element. The OIDB 0x6D6_0 upload + highway PUT only
// stages the bytes on QQ's side; without this trailing message the
// file is uploaded but never appears in the chat — that's the
// "log says uploaded but message is empty" bug the user reported.
//
// Wire shape: `Elem.transElem` (field 5) with `elemType=24` and an
// `elemValue` of `0x01 | BE16(len) | GroupFileExtra(protobuf)`. The
// 0x01 prefix and BE16 length wrapper match what the receive-side
// decoder in `msg-push/rich-body-decoder.ts:171-185` already strips.
if (!element.fileId) throw new Error('file element missing fileId');
const fileSize = element.fileSize ?? 0;
const fileName = element.fileName ?? '';
const md5 = element.md5Hex ? hexToBytes(element.md5Hex) : new Uint8Array(0);
const sha1 = element.sha1Hex ? hexToBytes(element.sha1Hex) : new Uint8Array(0);
// Outer field1 is hardcoded to 6 in NapCat's encoder
// (`packet/message/element.ts:589`). It's a magic tag the server
// expects on send (acidify ships the same shape via their generic
// `field1: Int` default but their consumer writes it too). Without
// these outer fields the current QQ-NT server rejects the message
// with `result=79`. Inner field5 is the uint32 placeholder both
// NapCat and acidify leave at 0 — we follow suit.
const extraBytes = protobuf_encode<GroupFileExtra>({
field1: 6,
fileName,
inner: {
info: {
busId: 102,
fileId: element.fileId,
fileSize: BigInt(fileSize),
fileName,
fileSha: sha1,
extInfoString: '',
fileMd5: md5,
},
},
});
if (extraBytes.length > 0xFFFF) {
// The 16-bit length prefix caps the payload at 64 KiB; even the
// densest GroupFileExtra (fileId/name/two hashes) is well under.
// This is here so a future schema change can't silently truncate.
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
}
const elemValue = new Uint8Array(3 + extraBytes.length);
elemValue[0] = 0x01;
elemValue[1] = (extraBytes.length >> 8) & 0xff;
elemValue[2] = extraBytes.length & 0xff;
elemValue.set(extraBytes, 3);
return {
transElem: {
elemType: 24,
elemValue,
} as any,
};
}
// (formerly `makeGroupFileElem` — removed. The `transElem(24)` shape it
// produced was a RECEIVE-side encoding only. The QQ-NT server rejects
// outgoing PbSendMsg with that element with `result=79`; group files
// publish through `OidbSvcTrpcTcp.0x6d9_4` instead, called from the
// OneBot layer at `modules/message-actions.ts::sendGroupMessage` after
// the file segment is split off.)
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
@@ -392,20 +342,22 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'file':
// The group `TransElem(24)` shape works for group chats only.
// C2C files live on `RichText.notOnlineFile` (parallel to elems,
// see proto/proton/message.ts:notOnlineFile) and are routed
// out at the OneBot layer in `sendPrivateMessage` — split off
// from elems[] and dispatched via `bridge.sendC2cFileMessage`.
// If a c2c file segment still reaches us here, the caller
// forgot to route — log loudly and drop, otherwise the message
// ships as "[空消息]" (only-file case) or quietly loses the
// file (mixed case).
if (ctx?.groupId !== undefined) {
result.push(makeGroupFileElem(elem));
} else {
console.warn('[ElemBuilder] BUG: c2c {type:"file"} reached element-builder — should be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage)');
}
// Files NEVER ride on the elems[] pipeline anymore — both flavors
// route at the OneBot layer:
// * c2c (private): split off and dispatched via
// `bridge.sendC2cFileMessage` (uses routingHead.trans0x211 +
// msgContent FileExtra; see bridge.ts::sendC2cFileMessage).
// * group: split off and dispatched via
// `bridge.sendGroupFileMessage` (uses OIDB 0x6d9_4; see
// actions/group-file.ts::sendGroupFileMessage).
//
// The old transElem(24) shape DOES work for receive-side decode
// (rich-body-decoder unpacks it into a FileEntity), but the
// QQ-NT server rejects it on outgoing with result=79. If a file
// segment still reaches us here the caller forgot to route at
// the OneBot layer — drop with a loud warn so it doesn't silently
// ship as "[空消息]" or a 0-byte stub.
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
break;
default:
@@ -548,6 +548,41 @@ export interface OidbGroupFileResp {
move?: pb<6, OidbGroupFileRetResp>;
}
// --- 0x6D9_4: Group file PUBLISH-AS-CHAT-MESSAGE ---
//
// Posts an already-uploaded group file (via 0x6D6_0 + highway) as a
// chat message in the group. This is a separate OIDB endpoint from
// the file upload — NOT a `MessageSvc.PbSendMsg` with a `TransElem`
// payload (sending the file as a transElem(24) is a RECEIVE-side
// decoding shape, and the QQ-NT server rejects it on send with
// `result=79`).
//
// Wire shape (mirrors Lagrange.Core V2's nesting):
// OidbBase.body (envelope field 4)
// → OidbGroupSendFileReq.body (field 5) ← the nested wrapper
// → OidbGroupSendFileBody { groupUin, type, info }
//
// Ports `dev/Lagrange.Core/.../Internal/Service/Message/GroupSendFileService.cs`
// + `Internal/Packets/Service/Oidb/Request/OidbSvcTrpcTcp0x6D9_4.cs`.
export interface OidbGroupSendFileInfo {
busiType?: pb<1, uint_32>; // hardcoded 102
fileId?: pb<2, string>; // uuid from 0x6D6_0 upload response
field3?: pb<3, uint_32>; // random uint32 (msg id seed)
field4?: pb<4, string>; // null/empty on send
field5?: pb<5, bool>; // hardcoded true
}
export interface OidbGroupSendFileBody {
groupUin?: pb<1, uint_32>;
type?: pb<2, uint_32>; // hardcoded 2 (= chat post)
info?: pb<3, OidbGroupSendFileInfo>;
}
export interface OidbGroupSendFileReq {
body?: pb<5, OidbGroupSendFileBody>;
}
// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops ---
export interface OidbGroupFileCreateFolderReq {