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:
12 files changed
+634
-158
No files matched your search
@@ -19,6 +19,7 @@ import type {
|
|||||||
OidbGroupFileResp,
|
OidbGroupFileResp,
|
||||||
OidbGroupFileViewReq,
|
OidbGroupFileViewReq,
|
||||||
OidbGroupFileViewResp,
|
OidbGroupFileViewResp,
|
||||||
|
OidbGroupSendFileReq,
|
||||||
OidbPrivateFileDownloadReq,
|
OidbPrivateFileDownloadReq,
|
||||||
OidbPrivateFileDownloadResp,
|
OidbPrivateFileDownloadResp,
|
||||||
OidbPrivateFileUploadReq,
|
OidbPrivateFileUploadReq,
|
||||||
@@ -273,6 +274,48 @@ async function fetchNtv2DownloadUrl(
|
|||||||
return `https://${domain}${path}${rKeyParam}`;
|
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 ───────────────
|
// ─────────────── file count ───────────────
|
||||||
|
|
||||||
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
|
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;
|
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
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) {
|
if (!upload.boolFileExist && uploadFile) {
|
||||||
const senderUin = toInt(bridge.identity.uin);
|
const senderUin = toInt(bridge.identity.uin);
|
||||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
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.
|
// 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 —
|
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||||
// the chat shows nothing. NapCat does the same (upload + sendMsg
|
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||||
// atomically inside `upload_group_file`, see
|
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||||
// `dev/napcatQQ/.../UploadGroupFile.ts:54-58`). Only suppressed when
|
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||||
// the caller opts out via `uploadFile=false` (treat that as "I only
|
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
|
||||||
// wanted the slot allocated, hold the chat post").
|
// 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) {
|
if (uploadFile) {
|
||||||
try {
|
try {
|
||||||
await bridge.sendGroupMessage(groupId, [{
|
await bridge.sendGroupFileMessage(groupId, fileId);
|
||||||
type: 'file',
|
|
||||||
fileId,
|
|
||||||
fileName,
|
|
||||||
fileSize: loaded.bytes.length,
|
|
||||||
md5Hex: bytesToHexUpper(hashes.md5),
|
|
||||||
sha1Hex: bytesToHexUpper(hashes.sha1),
|
|
||||||
}]);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// The bytes are already on the server and the fileId is valid —
|
// The bytes are already on the server and the fileId is valid —
|
||||||
// fail loud but don't lose the upload result the action handler
|
// 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;
|
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
|
||||||
if (!fileId) throw new Error('private file upload response missing file_id');
|
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) {
|
if (!upload.boolFileExist && uploadFile) {
|
||||||
// Host selection.
|
// Host selection.
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import type {
|
|||||||
SendMessageReceipt,
|
SendMessageReceipt,
|
||||||
DownloadRKeyInfo,
|
DownloadRKeyInfo,
|
||||||
ClientKeyInfo,
|
ClientKeyInfo,
|
||||||
|
UploadedFileMeta,
|
||||||
} from './bridge';
|
} from './bridge';
|
||||||
import type { SendPacketResult } from '../protocol/packet-sender';
|
import type { SendPacketResult } from '../protocol/packet-sender';
|
||||||
|
|
||||||
@@ -89,6 +90,16 @@ export interface BridgeInterface {
|
|||||||
// ─── Files ───
|
// ─── Files ───
|
||||||
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
|
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 }>;
|
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>;
|
fetchGroupFiles(groupId: number, folderId?: string): Promise<GroupFilesResult>;
|
||||||
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
|
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
|
||||||
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
|
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
uploadGroupFile as uploadGroupFile_,
|
uploadGroupFile as uploadGroupFile_,
|
||||||
uploadPrivateFile as uploadPrivateFile_,
|
uploadPrivateFile as uploadPrivateFile_,
|
||||||
|
sendGroupFileMessage as sendGroupFileMessage_,
|
||||||
fetchGroupFiles as fetchGroupFiles_,
|
fetchGroupFiles as fetchGroupFiles_,
|
||||||
fetchGroupFileUrl as fetchGroupFileUrl_,
|
fetchGroupFileUrl as fetchGroupFileUrl_,
|
||||||
fetchPrivateFileUrl as fetchPrivateFileUrl_,
|
fetchPrivateFileUrl as fetchPrivateFileUrl_,
|
||||||
@@ -147,6 +148,29 @@ export interface SendMessageReceipt {
|
|||||||
timestamp: number;
|
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 {
|
export interface DownloadRKeyInfo {
|
||||||
rkey: string;
|
rkey: string;
|
||||||
ttlSeconds: number;
|
ttlSeconds: number;
|
||||||
@@ -186,6 +210,24 @@ export class Bridge implements BridgeInterface {
|
|||||||
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
|
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||||
private memberListLastFetch_ = new Map<number, { at: number; data: 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
|
// Sequence and random generators for outgoing messages
|
||||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||||
@@ -252,6 +294,37 @@ export class Bridge implements BridgeInterface {
|
|||||||
return true;
|
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 ---
|
// --- Sequence / random generators ---
|
||||||
|
|
||||||
private nextClientSequence(): number {
|
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 }> {
|
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
|
||||||
return uploadPrivateFile_(this, userId, file, name, uploadFile);
|
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 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 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 fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
|
||||||
|
|||||||
@@ -13,11 +13,12 @@ import type {
|
|||||||
MentionExtraSend,
|
MentionExtraSend,
|
||||||
MarkdownData,
|
MarkdownData,
|
||||||
} from './proto/proton/action';
|
} 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 { uploadImageMsgInfo } from './highway/image-upload';
|
||||||
import { uploadPttMsgInfo } from './highway/ptt-upload';
|
import { uploadPttMsgInfo } from './highway/ptt-upload';
|
||||||
import { uploadVideoMsgInfo } from './highway/video-upload';
|
import { uploadVideoMsgInfo } from './highway/video-upload';
|
||||||
import { hexToBytes } from './highway/pipeline';
|
|
||||||
|
|
||||||
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
|
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
|
||||||
|
|
||||||
@@ -246,63 +247,12 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeGroupFileElem(element: MessageElement): ProtoElem {
|
// (formerly `makeGroupFileElem` — removed. The `transElem(24)` shape it
|
||||||
// Group file chat element. The OIDB 0x6D6_0 upload + highway PUT only
|
// produced was a RECEIVE-side encoding only. The QQ-NT server rejects
|
||||||
// stages the bytes on QQ's side; without this trailing message the
|
// outgoing PbSendMsg with that element with `result=79`; group files
|
||||||
// file is uploaded but never appears in the chat — that's the
|
// publish through `OidbSvcTrpcTcp.0x6d9_4` instead, called from the
|
||||||
// "log says uploaded but message is empty" bug the user reported.
|
// OneBot layer at `modules/message-actions.ts::sendGroupMessage` after
|
||||||
//
|
// the file segment is split off.)
|
||||||
// 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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||||
const isGroup = ctx.groupId !== undefined;
|
const isGroup = ctx.groupId !== undefined;
|
||||||
@@ -392,20 +342,22 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case 'file':
|
case 'file':
|
||||||
// The group `TransElem(24)` shape works for group chats only.
|
// Files NEVER ride on the elems[] pipeline anymore — both flavors
|
||||||
// C2C files live on `RichText.notOnlineFile` (parallel to elems,
|
// route at the OneBot layer:
|
||||||
// see proto/proton/message.ts:notOnlineFile) and are routed
|
// * c2c (private): split off and dispatched via
|
||||||
// out at the OneBot layer in `sendPrivateMessage` — split off
|
// `bridge.sendC2cFileMessage` (uses routingHead.trans0x211 +
|
||||||
// from elems[] and dispatched via `bridge.sendC2cFileMessage`.
|
// msgContent FileExtra; see bridge.ts::sendC2cFileMessage).
|
||||||
// If a c2c file segment still reaches us here, the caller
|
// * group: split off and dispatched via
|
||||||
// forgot to route — log loudly and drop, otherwise the message
|
// `bridge.sendGroupFileMessage` (uses OIDB 0x6d9_4; see
|
||||||
// ships as "[空消息]" (only-file case) or quietly loses the
|
// actions/group-file.ts::sendGroupFileMessage).
|
||||||
// file (mixed case).
|
//
|
||||||
if (ctx?.groupId !== undefined) {
|
// The old transElem(24) shape DOES work for receive-side decode
|
||||||
result.push(makeGroupFileElem(elem));
|
// (rich-body-decoder unpacks it into a FileEntity), but the
|
||||||
} else {
|
// QQ-NT server rejects it on outgoing with result=79. If a file
|
||||||
console.warn('[ElemBuilder] BUG: c2c {type:"file"} reached element-builder — should be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage)');
|
// 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;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -548,6 +548,41 @@ export interface OidbGroupFileResp {
|
|||||||
move?: pb<6, OidbGroupFileRetResp>;
|
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 ---
|
// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops ---
|
||||||
|
|
||||||
export interface OidbGroupFileCreateFolderReq {
|
export interface OidbGroupFileCreateFolderReq {
|
||||||
|
|||||||
@@ -354,11 +354,17 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
|||||||
const fileSize = intOr(data.size ?? data.fileSize, 0);
|
const fileSize = intOr(data.size ?? data.fileSize, 0);
|
||||||
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
||||||
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
||||||
|
// file_hash is the c2c-file server-issued addon string — needed
|
||||||
|
// on the wire when re-sending a previously-uploaded c2c file.
|
||||||
|
// get_private_file_url callers already pass it through, so honour
|
||||||
|
// the same field naming here.
|
||||||
|
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
|
||||||
const elem: MessageElement = { type: 'file', fileId };
|
const elem: MessageElement = { type: 'file', fileId };
|
||||||
if (fileName) elem.fileName = fileName;
|
if (fileName) elem.fileName = fileName;
|
||||||
if (fileSize > 0) elem.fileSize = fileSize;
|
if (fileSize > 0) elem.fileSize = fileSize;
|
||||||
if (md5Hex) elem.md5Hex = md5Hex;
|
if (md5Hex) elem.md5Hex = md5Hex;
|
||||||
if (sha1Hex) elem.sha1Hex = sha1Hex;
|
if (sha1Hex) elem.sha1Hex = sha1Hex;
|
||||||
|
if (fileHash) elem.fileHash = fileHash;
|
||||||
return elem;
|
return elem;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -167,18 +167,34 @@ export async function sendPrivateMessage(
|
|||||||
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||||
}
|
}
|
||||||
for (const fileEl of fileElements) {
|
for (const fileEl of fileElements) {
|
||||||
|
// C2C file send requires fileSize/fileMd5/fileName to ride on the
|
||||||
|
// wire (NotOnlineFile inside msgContent). The OneBot caller
|
||||||
|
// usually only echoes the file_id from a previous
|
||||||
|
// `upload_private_file`, so look up the rest from the upload
|
||||||
|
// cache. Inline segment fields (md5/size/name) take precedence so
|
||||||
|
// a caller that already knows everything can bypass the cache.
|
||||||
|
const cached = ref.bridge.recallUploadedFile(fileEl.fileId!);
|
||||||
const fileMd5 = fileEl.md5Hex
|
const fileMd5 = fileEl.md5Hex
|
||||||
? Buffer.from(fileEl.md5Hex, 'hex')
|
? Buffer.from(fileEl.md5Hex, 'hex')
|
||||||
: new Uint8Array(0);
|
: (cached?.fileMd5 ?? new Uint8Array(0));
|
||||||
|
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
|
||||||
|
// Fall back to a generic name — the QQ server resolves the
|
||||||
|
// file by fileUuid, not name, so a missing name only affects
|
||||||
|
// the chat bubble display.
|
||||||
|
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
|
||||||
|
const fileHash = fileEl.fileHash ?? cached?.fileHash;
|
||||||
|
if (fileSize === 0 && !cached) {
|
||||||
|
log.warn(
|
||||||
|
'[OneBot] c2c file_id=%s sent without fileSize and no upload cache — recipient may see 0 B',
|
||||||
|
fileEl.fileId,
|
||||||
|
);
|
||||||
|
}
|
||||||
lastReceipt = await ref.bridge.sendC2cFileMessage(userId, userUid, {
|
lastReceipt = await ref.bridge.sendC2cFileMessage(userId, userUid, {
|
||||||
fileId: fileEl.fileId!,
|
fileId: fileEl.fileId!,
|
||||||
// Fall back to a generic name — the QQ server resolves the
|
fileName,
|
||||||
// file by fileUuid, not name, so a missing name only affects
|
fileSize,
|
||||||
// the chat bubble display.
|
|
||||||
fileName: fileEl.fileName ?? 'file',
|
|
||||||
fileSize: fileEl.fileSize ?? 0,
|
|
||||||
fileMd5,
|
fileMd5,
|
||||||
fileHash: fileEl.fileHash,
|
fileHash,
|
||||||
});
|
});
|
||||||
logSentMessage(false, userId, [fileEl]);
|
logSentMessage(false, userId, [fileEl]);
|
||||||
}
|
}
|
||||||
@@ -229,19 +245,60 @@ export async function sendGroupMessage(
|
|||||||
});
|
});
|
||||||
if (elements.length === 0) throw new Error('message is empty');
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
|
||||||
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
|
// Group `{type:'file', file_id}` segments don't ride on the elems[]
|
||||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
// pipeline either. The QQ-NT server rejects PbSendMsg with a
|
||||||
|
// transElem(24) file payload (result=79); the correct send path is a
|
||||||
|
// dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a
|
||||||
|
// previously-uploaded file id as a chat bubble. Mirrors the c2c-file
|
||||||
|
// split below (private path) — both must be peeled off before the
|
||||||
|
// regular sendGroupMessage runs.
|
||||||
|
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
|
||||||
|
const nonFileElements = elements.filter(e => e.type !== 'file');
|
||||||
|
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
|
||||||
|
log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)');
|
||||||
|
}
|
||||||
|
|
||||||
logSentMessage(true, groupId, elements);
|
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.sendGroupMessage>> | undefined;
|
||||||
|
if (nonFileElements.length > 0) {
|
||||||
|
lastReceipt = await ref.bridge.sendGroupMessage(groupId, nonFileElements);
|
||||||
|
logSentMessage(true, groupId, nonFileElements);
|
||||||
|
}
|
||||||
|
for (const fileEl of fileElements) {
|
||||||
|
// Group-file publish has no per-message sequence/random tuple to
|
||||||
|
// hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the
|
||||||
|
// 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!);
|
||||||
|
logSentMessage(true, groupId, [fileEl]);
|
||||||
|
if (!lastReceipt) {
|
||||||
|
// Use a hash of the fileId as a stable pseudo-id; this gets
|
||||||
|
// mixed with groupId in `hashMessageIdInt32` below.
|
||||||
|
let h = 0;
|
||||||
|
const s = fileEl.fileId ?? '';
|
||||||
|
for (let i = 0; i < s.length; i++) {
|
||||||
|
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
|
||||||
|
}
|
||||||
|
lastReceipt = {
|
||||||
|
messageId: 0,
|
||||||
|
sequence: h & 0x7FFFFFFF,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: h & 0x7FFFFFFF,
|
||||||
|
timestamp: Math.floor(Date.now() / 1000),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!lastReceipt) throw new Error('message is empty');
|
||||||
|
|
||||||
|
const messageId = hashMessageIdInt32(lastReceipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||||
ref.cacheMessageMeta(messageId, {
|
ref.cacheMessageMeta(messageId, {
|
||||||
isGroup: true,
|
isGroup: true,
|
||||||
targetId: groupId,
|
targetId: groupId,
|
||||||
sequence: receipt.sequence,
|
sequence: lastReceipt.sequence,
|
||||||
eventName: GROUP_MESSAGE_EVENT,
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
clientSequence: receipt.clientSequence,
|
clientSequence: lastReceipt.clientSequence,
|
||||||
random: receipt.random,
|
random: lastReceipt.random,
|
||||||
timestamp: receipt.timestamp,
|
timestamp: lastReceipt.timestamp,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { messageId };
|
return { messageId };
|
||||||
@@ -575,6 +632,13 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
|
|||||||
case 'poke':
|
case 'poke':
|
||||||
parts.push('[戳一戳]');
|
parts.push('[戳一戳]');
|
||||||
break;
|
break;
|
||||||
|
case 'file':
|
||||||
|
// Avoid the misleading "[空消息]" the user previously saw when
|
||||||
|
// sending a file segment — the message is NOT empty, it's a
|
||||||
|
// file post. Show the name (or id as fallback) so the log
|
||||||
|
// reflects what actually went out.
|
||||||
|
parts.push(`[文件:${elem.fileName || elem.fileId || ''}]`);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,11 +26,17 @@ export interface MockBridge {
|
|||||||
resolveUserUid: ReturnType<typeof vi.fn>;
|
resolveUserUid: ReturnType<typeof vi.fn>;
|
||||||
// High-level message senders. Default to no-op resolves so actions
|
// High-level message senders. Default to no-op resolves so actions
|
||||||
// that fire off a follow-up chat message after their main work
|
// that fire off a follow-up chat message after their main work
|
||||||
// (e.g. `upload_group_file` → `sendGroupMessage` to publish the
|
// (e.g. `upload_group_file` → `sendGroupFileMessage` to publish the
|
||||||
// file in chat) don't crash test setups that don't care about it.
|
// file in chat) don't crash test setups that don't care about it.
|
||||||
sendGroupMessage: ReturnType<typeof vi.fn>;
|
sendGroupMessage: ReturnType<typeof vi.fn>;
|
||||||
sendPrivateMessage: ReturnType<typeof vi.fn>;
|
sendPrivateMessage: ReturnType<typeof vi.fn>;
|
||||||
sendC2cFileMessage: ReturnType<typeof vi.fn>;
|
sendC2cFileMessage: 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
|
||||||
|
// covering those code paths get a default-no-op shim.
|
||||||
|
rememberUploadedFile: ReturnType<typeof vi.fn>;
|
||||||
|
recallUploadedFile: ReturnType<typeof vi.fn>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
||||||
@@ -59,6 +65,9 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
|||||||
sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
|
sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
|
||||||
sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
|
sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
|
||||||
sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
|
sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
|
||||||
|
sendGroupFileMessage: vi.fn(async () => undefined),
|
||||||
|
rememberUploadedFile: vi.fn(),
|
||||||
|
recallUploadedFile: vi.fn(() => undefined),
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -136,12 +136,14 @@ describe('actions/group-file', () => {
|
|||||||
.rejects.toThrow(/code=999/);
|
.rejects.toThrow(/code=999/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uploadGroupFile publishes the file as a chat message after upload (the "empty message" regression)', async () => {
|
it('uploadGroupFile publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
|
||||||
// Reproduces the bug report: OIDB upload + highway PUT alone only
|
// Reproduces the bug report: OIDB upload + highway PUT alone only
|
||||||
// stage the bytes on QQ's side; without the trailing
|
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
|
||||||
// `sendGroupMessage` the file never appears in the chat. Asserts
|
// call the file never appears in the chat. Earlier attempts used
|
||||||
// that `bridge.sendGroupMessage` is invoked with a single
|
// PbSendMsg with a transElem(24) but the QQ-NT server rejects that
|
||||||
// `{type:'file'}` element pointing at the uploaded fileId.
|
// 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.
|
||||||
const bridge = mockBridge();
|
const bridge = mockBridge();
|
||||||
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
|
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
|
||||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||||
@@ -149,15 +151,13 @@ describe('actions/group-file', () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt');
|
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt');
|
||||||
expect(bridge.sendGroupMessage).toHaveBeenCalledOnce();
|
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
|
||||||
const [groupId, elements] = bridge.sendGroupMessage.mock.calls[0]!;
|
const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!;
|
||||||
expect(groupId).toBe(12345);
|
expect(groupId).toBe(12345);
|
||||||
expect(elements).toHaveLength(1);
|
expect(fileId).toBe('fid-pub');
|
||||||
expect(elements[0]).toMatchObject({
|
// sendGroupMessage must NOT be touched — the previous wire shape
|
||||||
type: 'file',
|
// (PbSendMsg w/ transElem(24)) is the bug we're guarding against.
|
||||||
fileId: 'fid-pub',
|
expect(bridge.sendGroupMessage).not.toHaveBeenCalled();
|
||||||
fileName: 'mynote.txt',
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uploadGroupFile skips the chat post when uploadFile=false', async () => {
|
it('uploadGroupFile skips the chat post when uploadFile=false', async () => {
|
||||||
@@ -168,12 +168,12 @@ describe('actions/group-file', () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false);
|
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false);
|
||||||
expect(bridge.sendGroupMessage).not.toHaveBeenCalled();
|
expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => {
|
it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => {
|
||||||
const bridge = mockBridge();
|
const bridge = mockBridge();
|
||||||
vi.mocked(bridge.sendGroupMessage).mockRejectedValueOnce(new Error('message rejected'));
|
vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected'));
|
||||||
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
|
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
|
||||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||||
body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any },
|
body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any },
|
||||||
@@ -181,7 +181,55 @@ describe('actions/group-file', () => {
|
|||||||
);
|
);
|
||||||
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
|
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
|
||||||
expect(out).toEqual({ fileId: 'fid-tolerant' });
|
expect(out).toEqual({ fileId: 'fid-tolerant' });
|
||||||
expect(bridge.sendGroupMessage).toHaveBeenCalledOnce();
|
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uploadGroupFile 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.
|
||||||
|
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');
|
||||||
|
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
|
||||||
|
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
|
||||||
|
expect(meta).toMatchObject({
|
||||||
|
fileId: 'fid-cached',
|
||||||
|
scope: 'group',
|
||||||
|
groupId: 12345,
|
||||||
|
fileName: 'x.bin',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sendGroupFileMessage 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');
|
||||||
|
expect(oidb.runOidb).toHaveBeenCalledOnce();
|
||||||
|
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
|
||||||
|
expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4');
|
||||||
|
// The envelope wraps a `{body: {groupUin, type=2, info: {busiType=102, fileId, ...}}}`.
|
||||||
|
expect(oidb.makeOidbEnvelope).toHaveBeenCalledWith(
|
||||||
|
0x6D9, 4,
|
||||||
|
expect.objectContaining({
|
||||||
|
body: expect.objectContaining({
|
||||||
|
groupUin: 12345,
|
||||||
|
type: 2,
|
||||||
|
info: expect.objectContaining({
|
||||||
|
busiType: 102,
|
||||||
|
fileId: 'fid-publish',
|
||||||
|
field5: true,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
|
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
|
||||||
@@ -230,6 +278,31 @@ describe('actions/group-file', () => {
|
|||||||
expect(bridge.sendPrivateMessage).not.toHaveBeenCalled();
|
expect(bridge.sendPrivateMessage).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('uploadPrivateFile 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)`.
|
||||||
|
const bridge = mockBridge();
|
||||||
|
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
|
||||||
|
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
|
||||||
|
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
|
||||||
|
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');
|
||||||
|
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
|
||||||
|
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
|
||||||
|
expect(meta).toMatchObject({
|
||||||
|
fileId: 'pfid-cache',
|
||||||
|
scope: 'private',
|
||||||
|
userId: 67890,
|
||||||
|
fileName: 'cache-me.txt',
|
||||||
|
fileHash: 'addon-hash',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('uploadPrivateFile skips the chat post when uploadFile=false', async () => {
|
it('uploadPrivateFile skips the chat post when uploadFile=false', async () => {
|
||||||
const bridge = mockBridge();
|
const bridge = mockBridge();
|
||||||
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
|
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
|
||||||
|
|||||||
@@ -93,16 +93,18 @@ describe('element-builder / commonElem.businessType per scene', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('element-builder / group file element wire shape', () => {
|
describe('element-builder / file element is no longer carried in elems[]', () => {
|
||||||
// Regression for the same `result=79` class: the GroupFileExtra outer
|
// Regression for the `result=79` class: previously the element-builder
|
||||||
// wrapper was missing the magic `field1=6` + `fileName` slots and the
|
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
|
||||||
// inner GroupFileInfo had fileSha/extInfoString/fileMd5 shifted one
|
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire
|
||||||
// tag to the left (5/6/7 instead of the correct 6/7/8). Both
|
// shape. The fix moves group-file publishing onto a dedicated OIDB
|
||||||
// mistakes made the current QQ-NT server reject the chat post. This
|
// call (`OidbSvcTrpcTcp.0x6d9_4`), driven from the OneBot layer in
|
||||||
// test decodes the element back through the proton-generated codec
|
// `modules/message-actions.ts::sendGroupMessage` after the file
|
||||||
// and asserts each field lands at the right tag.
|
// segment is split off. The element-builder therefore must NOT emit
|
||||||
it('encodes outer field1=6 + fileName, and inner fields at tags 6/7/8', async () => {
|
// any element for `{type:'file'}` anymore — if it does, the message
|
||||||
const [elem] = await buildSendElems(
|
// ships with a transElem(24) payload and result=79 returns.
|
||||||
|
it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => {
|
||||||
|
const result = await buildSendElems(
|
||||||
[{
|
[{
|
||||||
type: 'file',
|
type: 'file',
|
||||||
fileId: 'fid-abc',
|
fileId: 'fid-abc',
|
||||||
@@ -113,36 +115,6 @@ describe('element-builder / group file element wire shape', () => {
|
|||||||
} as any],
|
} as any],
|
||||||
{ bridge: fakeBridge, groupId: 12345 },
|
{ bridge: fakeBridge, groupId: 12345 },
|
||||||
);
|
);
|
||||||
const transElem = (elem as any).transElem as { elemType: number; elemValue: Uint8Array };
|
expect(result).toEqual([]);
|
||||||
expect(transElem.elemType).toBe(24);
|
|
||||||
// 0x01 prefix + BE16 length + payload
|
|
||||||
expect(transElem.elemValue[0]).toBe(0x01);
|
|
||||||
const len = (transElem.elemValue[1] << 8) | transElem.elemValue[2];
|
|
||||||
const payload = transElem.elemValue.subarray(3, 3 + len);
|
|
||||||
|
|
||||||
// Hand-walk the wire bytes to verify each tag lands where the
|
|
||||||
// server expects. Each varint tag = (field << 3) | wire_type:
|
|
||||||
// outer field1=6 → tag 8 (wire 0 / varint), value 6
|
|
||||||
// outer fileName → tag 18 (wire 2 / length-delimited), 'doc.txt'
|
|
||||||
// outer inner → tag 58 (field 7 wire 2)
|
|
||||||
// inner.info → tag 18 (field 2 wire 2)
|
|
||||||
// info.busId → tag 8 (field 1 wire 0), value 102
|
|
||||||
// info.fileId → tag 18 (field 2 wire 2)
|
|
||||||
// info.fileSize → tag 24 (field 3 wire 0), value 123
|
|
||||||
// info.fileName → tag 34 (field 4 wire 2)
|
|
||||||
// info.fileSha → tag 50 (field 6 wire 2) ← was 42 (field 5)
|
|
||||||
// info.extInfoString → tag 58 (field 7 wire 2) ← was 50 (field 6)
|
|
||||||
// info.fileMd5 → tag 66 (field 8 wire 2) ← was 58 (field 7)
|
|
||||||
const tagAt = (i: number) => payload[i];
|
|
||||||
expect(tagAt(0)).toBe(8); // outer field1 tag — regression: missing entirely before
|
|
||||||
expect(payload[1]).toBe(6); // value of field1 (NapCat hardcodes 6)
|
|
||||||
expect(tagAt(2)).toBe(18); // outer fileName tag — regression: missing
|
|
||||||
// Locate the inner GroupFileExtraInfo by scanning for tag 50 (was 42
|
|
||||||
// in the bug). A naive scan for `0x32` is enough because no string
|
|
||||||
// field happens to contain that byte in this test fixture.
|
|
||||||
expect(payload.includes(50)).toBe(true); // fileSha at tag 50 (field 6)
|
|
||||||
expect(payload.includes(58)).toBe(true); // extInfoString at tag 58 (field 7)
|
|
||||||
expect(payload.includes(66)).toBe(true); // fileMd5 at tag 66 (field 8)
|
|
||||||
expect(payload.includes(42)).toBe(false); // sanity: nothing at the old (wrong) tag for fileSha
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// Regression coverage for the group-file-in-send_group_msg bug.
|
||||||
|
//
|
||||||
|
// Symptom in the wild: bot uploaded a group file via `upload_group_file`,
|
||||||
|
// then sent `{type:'file', file_id}` through `send_group_msg`; the
|
||||||
|
// element-builder wrapped it as `transElem(elemType=24, ...)` inside
|
||||||
|
// `richText.elems` and shipped a regular `MessageSvc.PbSendMsg`. The
|
||||||
|
// QQ-NT server rejected the message with `result=79` because that wire
|
||||||
|
// shape is RECEIVE-side only (rich-body-decoder unpacks it into a
|
||||||
|
// FileEntity for inbound messages, but the server's intake validator
|
||||||
|
// flags it on the send side).
|
||||||
|
//
|
||||||
|
// 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
|
||||||
|
// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's
|
||||||
|
// `GroupSendFileService.cs`.
|
||||||
|
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||||
|
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
|
||||||
|
import { sendGroupMessage } from '../../src/onebot/modules/message-actions';
|
||||||
|
|
||||||
|
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||||
|
return new Proxy(overrides as BridgeInterface, {
|
||||||
|
get(target, prop) {
|
||||||
|
if (prop in target) return (target as any)[prop];
|
||||||
|
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||||
|
return {
|
||||||
|
uin: '10001',
|
||||||
|
bridge,
|
||||||
|
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
|
||||||
|
cacheMessageMeta: vi.fn(),
|
||||||
|
mediaStore: {} as any,
|
||||||
|
musicSignUrl: '',
|
||||||
|
} as unknown as OneBotInstanceContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
const goodReceipt = {
|
||||||
|
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('send_group_msg with {type:"file"} segment', () => {
|
||||||
|
it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', 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.
|
||||||
|
const sendGroupMessage_bridge = vi.fn();
|
||||||
|
const sendGroupFileMessage = vi.fn(async () => undefined);
|
||||||
|
const bridge = fakeBridge({
|
||||||
|
sendGroupMessage: sendGroupMessage_bridge,
|
||||||
|
sendGroupFileMessage,
|
||||||
|
resolveUserUid: vi.fn(),
|
||||||
|
} as any);
|
||||||
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
|
await sendGroupMessage(ctx, 12345, [{
|
||||||
|
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
|
||||||
|
}] as any, false);
|
||||||
|
|
||||||
|
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
|
||||||
|
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const [groupId, fileId] = sendGroupFileMessage.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 () => undefined);
|
||||||
|
const bridge = fakeBridge({
|
||||||
|
sendGroupMessage: sendGroupMessage_bridge,
|
||||||
|
sendGroupFileMessage,
|
||||||
|
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||||
|
} as any);
|
||||||
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
|
await sendGroupMessage(ctx, 12345, [
|
||||||
|
{ type: 'text', data: { text: 'here is the file:' } },
|
||||||
|
{ type: 'file', data: { file_id: 'gfid-xyz', name: 'pkg.zip' } },
|
||||||
|
] as any, false);
|
||||||
|
|
||||||
|
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
||||||
|
expect(sendGroupFileMessage).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]!;
|
||||||
|
expect(fileGid).toBe(12345);
|
||||||
|
expect(fileFileId).toBe('gfid-xyz');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('file segment without file_id is skipped (with a warn-level log)', async () => {
|
||||||
|
// 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 bridge = fakeBridge({
|
||||||
|
sendGroupMessage: sendGroupMessage_bridge,
|
||||||
|
sendGroupFileMessage,
|
||||||
|
resolveUserUid: vi.fn(),
|
||||||
|
} as any);
|
||||||
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
|
await sendGroupMessage(ctx, 12345, [
|
||||||
|
{ type: 'text', data: { text: 'with bad file segment' } },
|
||||||
|
{ type: 'file', data: {} }, // no file_id
|
||||||
|
] as any, false);
|
||||||
|
|
||||||
|
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
||||||
|
expect(sendGroupFileMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -50,10 +50,12 @@ describe('send_private_msg with {type:"file"} segment', () => {
|
|||||||
const sendPrivateMessage_bridge = vi.fn();
|
const sendPrivateMessage_bridge = vi.fn();
|
||||||
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||||
const resolveUserUid = vi.fn(async () => 'u_peer');
|
const resolveUserUid = vi.fn(async () => 'u_peer');
|
||||||
|
const recallUploadedFile = vi.fn(() => undefined);
|
||||||
const bridge = fakeBridge({
|
const bridge = fakeBridge({
|
||||||
sendPrivateMessage: sendPrivateMessage_bridge,
|
sendPrivateMessage: sendPrivateMessage_bridge,
|
||||||
sendC2cFileMessage,
|
sendC2cFileMessage,
|
||||||
resolveUserUid,
|
resolveUserUid,
|
||||||
|
recallUploadedFile,
|
||||||
} as any);
|
} as any);
|
||||||
const ctx = makeCtx(bridge);
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
@@ -77,6 +79,84 @@ describe('send_private_msg with {type:"file"} segment', () => {
|
|||||||
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
|
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => {
|
||||||
|
// Reproduces the "0 B file" bug: a caller passes only `file_id` from
|
||||||
|
// a previous upload_private_file, with no size/md5/name. Without
|
||||||
|
// the cache lookup the wire packet ships fileSize=0/md5=empty and
|
||||||
|
// the recipient sees a 0-byte file. With the cache we recover the
|
||||||
|
// real tuple.
|
||||||
|
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||||
|
const recallUploadedFile = vi.fn((id: string) => id === 'uuid-cached' ? {
|
||||||
|
fileId: 'uuid-cached',
|
||||||
|
scope: 'private' as const,
|
||||||
|
userId: 67890,
|
||||||
|
fileName: 'real-doc.pdf',
|
||||||
|
fileSize: 4096,
|
||||||
|
fileMd5: Buffer.from('aabbccddeeff', 'hex'),
|
||||||
|
fileSha1: new Uint8Array(20),
|
||||||
|
fileHash: 'srv-hash',
|
||||||
|
rememberedAt: 0,
|
||||||
|
} : undefined);
|
||||||
|
const bridge = fakeBridge({
|
||||||
|
sendPrivateMessage: vi.fn(),
|
||||||
|
sendC2cFileMessage,
|
||||||
|
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||||
|
recallUploadedFile,
|
||||||
|
} as any);
|
||||||
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
|
await sendPrivateMessage(ctx, 67890, [{
|
||||||
|
type: 'file', data: { file_id: 'uuid-cached' },
|
||||||
|
}] as any, false);
|
||||||
|
|
||||||
|
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
|
||||||
|
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
|
||||||
|
expect(info).toMatchObject({
|
||||||
|
fileId: 'uuid-cached',
|
||||||
|
fileName: 'real-doc.pdf',
|
||||||
|
fileSize: 4096,
|
||||||
|
fileHash: 'srv-hash',
|
||||||
|
});
|
||||||
|
expect(info.fileMd5).toEqual(Buffer.from('aabbccddeeff', 'hex'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('inline segment fields take precedence over the upload cache', async () => {
|
||||||
|
// If the caller threads the metadata inline (e.g. they tracked the
|
||||||
|
// upload response themselves), honour that over the cache so a
|
||||||
|
// refresh of an evicted file still works.
|
||||||
|
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||||
|
const recallUploadedFile = vi.fn(() => ({
|
||||||
|
fileId: 'uuid-x',
|
||||||
|
scope: 'private' as const,
|
||||||
|
userId: 67890,
|
||||||
|
fileName: 'stale-cache-name.txt',
|
||||||
|
fileSize: 99,
|
||||||
|
fileMd5: new Uint8Array(16),
|
||||||
|
fileSha1: new Uint8Array(20),
|
||||||
|
fileHash: 'stale-hash',
|
||||||
|
rememberedAt: 0,
|
||||||
|
}));
|
||||||
|
const bridge = fakeBridge({
|
||||||
|
sendPrivateMessage: vi.fn(),
|
||||||
|
sendC2cFileMessage,
|
||||||
|
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||||
|
recallUploadedFile,
|
||||||
|
} as any);
|
||||||
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
|
await sendPrivateMessage(ctx, 67890, [{
|
||||||
|
type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' },
|
||||||
|
}] as any, false);
|
||||||
|
|
||||||
|
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
|
||||||
|
expect(info).toMatchObject({
|
||||||
|
fileName: 'inline.txt',
|
||||||
|
fileSize: 200,
|
||||||
|
fileHash: 'inline-hash',
|
||||||
|
});
|
||||||
|
expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex'));
|
||||||
|
});
|
||||||
|
|
||||||
it('mixed file + text splits across two sends (text first, file second)', async () => {
|
it('mixed file + text splits across two sends (text first, file second)', async () => {
|
||||||
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
|
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
|
||||||
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||||
@@ -85,6 +165,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
|
|||||||
sendPrivateMessage: sendPrivateMessage_bridge,
|
sendPrivateMessage: sendPrivateMessage_bridge,
|
||||||
sendC2cFileMessage,
|
sendC2cFileMessage,
|
||||||
resolveUserUid,
|
resolveUserUid,
|
||||||
|
recallUploadedFile: vi.fn(() => undefined),
|
||||||
} as any);
|
} as any);
|
||||||
const ctx = makeCtx(bridge);
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
@@ -118,6 +199,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
|
|||||||
sendPrivateMessage: sendPrivateMessage_bridge,
|
sendPrivateMessage: sendPrivateMessage_bridge,
|
||||||
sendC2cFileMessage,
|
sendC2cFileMessage,
|
||||||
resolveUserUid: vi.fn(),
|
resolveUserUid: vi.fn(),
|
||||||
|
recallUploadedFile: vi.fn(() => undefined),
|
||||||
} as any);
|
} as any);
|
||||||
const ctx = makeCtx(bridge);
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
@@ -141,6 +223,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
|
|||||||
sendPrivateMessage: vi.fn(),
|
sendPrivateMessage: vi.fn(),
|
||||||
sendC2cFileMessage,
|
sendC2cFileMessage,
|
||||||
resolveUserUid: vi.fn(async () => ''), // intentional empty
|
resolveUserUid: vi.fn(async () => ''), // intentional empty
|
||||||
|
recallUploadedFile: vi.fn(() => undefined),
|
||||||
} as any);
|
} as any);
|
||||||
const ctx = makeCtx(bridge);
|
const ctx = makeCtx(bridge);
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user