fix(onebot): support inline file url/path in send_group/private_msg (#80)
file 段现接受 file/url/path(无需先 upload_group_file/upload_private_file);群走 groupFile.upload()、私聊走 uploadPrivate()(内部已 publish/sendC2c),file_id 老路径不变。含 parser 与群/私聊文件发送测试。
This commit is contained in:
1 parent
69c8960ea9
commit
d3092a1806
5 files changed
+126
-83
No files matched your search
@@ -288,8 +288,9 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
}
|
||||
case 'file': {
|
||||
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
|
||||
if (!fileId) {
|
||||
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
|
||||
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
|
||||
if (!fileId && !source) {
|
||||
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
|
||||
return null;
|
||||
}
|
||||
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
|
||||
@@ -297,7 +298,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
||||
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
||||
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
|
||||
const elem: MessageElement = { type: 'file', fileId };
|
||||
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
|
||||
if (fileName) elem.fileName = fileName;
|
||||
if (fileSize > 0) elem.fileSize = fileSize;
|
||||
if (md5Hex) elem.md5Hex = md5Hex;
|
||||
|
||||
@@ -241,54 +241,40 @@ export async function sendPrivateMessage(
|
||||
// never mixed with the regular elements. We only need it for file
|
||||
// here — video/ARK/ptt already go through commonElem so the
|
||||
// element-builder handles them inline.
|
||||
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
|
||||
// Two sub-paths:
|
||||
// a) has url/path but no file_id → uploadPrivate() which internally calls sendC2cFile()
|
||||
// b) has file_id from a prior upload_private_file → sendC2cFile() only
|
||||
const allFileElements = elements.filter(e => e.type === 'file');
|
||||
const nonFileElements = elements.filter(e => e.type !== 'file');
|
||||
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
|
||||
log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)');
|
||||
}
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
|
||||
if (nonFileElements.length > 0) {
|
||||
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
|
||||
logSentMessage(false, userId, nonFileElements);
|
||||
}
|
||||
if (fileElements.length > 0) {
|
||||
// C2C file send needs the recipient's UID — resolve once and reuse.
|
||||
if (allFileElements.length > 0) {
|
||||
const userUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (!userUid) {
|
||||
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||
}
|
||||
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
|
||||
? Buffer.from(fileEl.md5Hex, 'hex')
|
||||
: (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,
|
||||
);
|
||||
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||
for (const fileEl of allFileElements) {
|
||||
if (fileEl.url && !fileEl.fileId) {
|
||||
// uploadPrivate() already calls sendC2cFile() internally — do NOT call it again.
|
||||
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
|
||||
await ref.bridge.apis.groupFile.uploadPrivate(userId, fileEl.url, name, true);
|
||||
logSentMessage(false, userId, [fileEl]);
|
||||
if (!lastReceipt) {
|
||||
lastReceipt = { messageId: 0, sequence: 0, clientSequence: 0, random: 0, timestamp: Math.floor(Date.now() / 1000) };
|
||||
}
|
||||
} else if (fileEl.fileId) {
|
||||
const cached = ref.bridge.recallUploadedFile(fileEl.fileId);
|
||||
const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') : (cached?.fileMd5 ?? new Uint8Array(0));
|
||||
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
|
||||
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
|
||||
const fileHash = fileEl.fileHash ?? cached?.fileHash;
|
||||
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash });
|
||||
logSentMessage(false, userId, [fileEl]);
|
||||
} else {
|
||||
log.warn('[OneBot] private file segment without file_id or url — skipped');
|
||||
}
|
||||
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, {
|
||||
fileId: fileEl.fileId!,
|
||||
fileName,
|
||||
fileSize,
|
||||
fileMd5,
|
||||
fileHash,
|
||||
});
|
||||
logSentMessage(false, userId, [fileEl]);
|
||||
}
|
||||
}
|
||||
if (!lastReceipt) throw new Error('message is empty');
|
||||
@@ -345,47 +331,37 @@ export async function sendGroupMessage(
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
// Group `{type:'file', file_id}` segments don't ride on the elems[]
|
||||
// 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);
|
||||
// Two sub-paths for group file segments:
|
||||
// a) has url/path but no file_id → upload() which internally calls publish()
|
||||
// b) has file_id from a prior upload_group_file → publish() only
|
||||
const allFileElements = elements.filter(e => e.type === 'file');
|
||||
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)');
|
||||
}
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
|
||||
if (nonFileElements.length > 0) {
|
||||
lastReceipt = await ref.bridge.apis.message.sendGroup(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.apis.groupFile.publish(groupId, fileEl.fileId!);
|
||||
for (const fileEl of allFileElements) {
|
||||
let fileId: string;
|
||||
if (fileEl.url && !fileEl.fileId) {
|
||||
// upload() already calls publish() internally — do NOT call publish() again.
|
||||
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
|
||||
const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true);
|
||||
fileId = result.fileId ?? '';
|
||||
if (!fileId) { log.warn('[OneBot] group file auto-upload returned no file_id — skipped'); continue; }
|
||||
} else if (fileEl.fileId) {
|
||||
fileId = fileEl.fileId;
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileId);
|
||||
} else {
|
||||
log.warn('[OneBot] group file segment without file_id or url — skipped');
|
||||
continue;
|
||||
}
|
||||
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),
|
||||
};
|
||||
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.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');
|
||||
|
||||
@@ -481,16 +481,22 @@ describe('parseMessage', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops a file segment with no file_id (upload-first contract)', async () => {
|
||||
// Path-only segments aren't supported here — callers must
|
||||
// upload via `upload_group_file` / `upload_private_file` first
|
||||
// to obtain a file_id. Dropping with a warning is preferable
|
||||
// to silently kicking off an upload from inside the message
|
||||
// parser, which can't fail loudly without changing call sites.
|
||||
it('parses {type:"file", file:"/path"} (no file_id) into a file element with url', async () => {
|
||||
// Inline file path: the parser now accepts file/url/path and stores
|
||||
// it in `url`. The send layer (sendGroupMessage / sendPrivateMessage)
|
||||
// handles the actual upload so the parser stays side-effect-free.
|
||||
const result = await parseMessage(
|
||||
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'file', url: '/local/path/a.bin' }]);
|
||||
});
|
||||
|
||||
it('drops a file segment with neither file_id nor file/url', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'file', data: {} } as any],
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -105,14 +105,13 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
});
|
||||
|
||||
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 publish = vi.fn();
|
||||
const upload = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: {
|
||||
message: { sendGroup: sendGroupMessage_bridge },
|
||||
groupFile: { publish },
|
||||
groupFile: { publish, upload },
|
||||
} as any,
|
||||
resolveUserUid: vi.fn(),
|
||||
} as any);
|
||||
@@ -120,10 +119,42 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
|
||||
await sendGroupMessage(ctx, 12345, [
|
||||
{ type: 'text', data: { text: 'with bad file segment' } },
|
||||
{ type: 'file', data: {} }, // no file_id
|
||||
{ type: 'file', data: {} }, // no file_id and no url
|
||||
] as any, false);
|
||||
|
||||
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('file segment with url (no file_id) auto-uploads via groupFile.upload (not publish)', async () => {
|
||||
// Happy path for inline file sending: the bot passes a local path
|
||||
// directly. upload() internally calls publish(), so we must NOT
|
||||
// call publish() a second time.
|
||||
const upload = vi.fn(async (_gid: number, _src: string, _name: string, _folder: string, _doUpload: boolean) =>
|
||||
({ fileId: 'auto-fid', fileHash: null }));
|
||||
const publish = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: {
|
||||
message: { sendGroup: vi.fn() },
|
||||
groupFile: { upload, publish },
|
||||
} as any,
|
||||
resolveUserUid: vi.fn(),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendGroupMessage(ctx, 12345, [{
|
||||
type: 'file', data: { file: '/tmp/audio.wav', name: 'audio.wav' },
|
||||
}] as any, false);
|
||||
|
||||
expect(upload).toHaveBeenCalledOnce();
|
||||
const [gid, src, name, folder, doUpload] = upload.mock.calls[0]!;
|
||||
expect(gid).toBe(12345);
|
||||
expect(src).toBe('/tmp/audio.wav');
|
||||
expect(name).toBe('audio.wav');
|
||||
expect(folder).toBe('/');
|
||||
expect(doUpload).toBe(true);
|
||||
// publish must NOT be called — upload() already handles it internally
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -227,4 +227,33 @@ describe('send_private_msg with {type:"file"} segment', () => {
|
||||
|
||||
expect(sendC2cFileMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('file segment with url (no file_id) auto-uploads via groupFile.uploadPrivate (not sendC2cFile)', async () => {
|
||||
// uploadPrivate() internally calls sendC2cFile() — must NOT call it again.
|
||||
const uploadPrivate = vi.fn(async (_uid: number, _src: string, _name: string, _doUpload: boolean) =>
|
||||
({ fileId: 'auto-fid', fileHash: null }));
|
||||
const sendC2cFileMessage = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: {
|
||||
message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage },
|
||||
groupFile: { uploadPrivate },
|
||||
} as any,
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
recallUploadedFile: vi.fn(() => undefined),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [{
|
||||
type: 'file', data: { file: '/tmp/audio.wav', name: 'audio.wav' },
|
||||
}] as any, false);
|
||||
|
||||
expect(uploadPrivate).toHaveBeenCalledOnce();
|
||||
const [uid, src, name, doUpload] = uploadPrivate.mock.calls[0]!;
|
||||
expect(uid).toBe(67890);
|
||||
expect(src).toBe('/tmp/audio.wav');
|
||||
expect(name).toBe('audio.wav');
|
||||
expect(doUpload).toBe(true);
|
||||
// sendC2cFile must NOT be called — uploadPrivate() handles it internally
|
||||
expect(sendC2cFileMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user