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
+122
-79
No files matched your search
@@ -288,8 +288,9 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
|||||||
}
|
}
|
||||||
case 'file': {
|
case 'file': {
|
||||||
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
|
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
|
||||||
if (!fileId) {
|
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
|
||||||
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
|
if (!fileId && !source) {
|
||||||
|
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
|
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 md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
||||||
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
||||||
const fileHash = String(data.file_hash ?? data.fileHash ?? '').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 (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;
|
||||||
|
|||||||
@@ -241,54 +241,40 @@ export async function sendPrivateMessage(
|
|||||||
// never mixed with the regular elements. We only need it for file
|
// never mixed with the regular elements. We only need it for file
|
||||||
// here — video/ARK/ptt already go through commonElem so the
|
// here — video/ARK/ptt already go through commonElem so the
|
||||||
// element-builder handles them inline.
|
// 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');
|
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;
|
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
|
||||||
if (nonFileElements.length > 0) {
|
if (nonFileElements.length > 0) {
|
||||||
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
|
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
|
||||||
logSentMessage(false, userId, nonFileElements);
|
logSentMessage(false, userId, nonFileElements);
|
||||||
}
|
}
|
||||||
if (fileElements.length > 0) {
|
if (allFileElements.length > 0) {
|
||||||
// C2C file send needs the recipient's UID — resolve once and reuse.
|
|
||||||
const userUid = await ref.bridge.resolveUserUid(userId);
|
const userUid = await ref.bridge.resolveUserUid(userId);
|
||||||
if (!userUid) {
|
if (!userUid) 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 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) };
|
||||||
}
|
}
|
||||||
for (const fileEl of fileElements) {
|
} else if (fileEl.fileId) {
|
||||||
// C2C file send requires fileSize/fileMd5/fileName to ride on the
|
const cached = ref.bridge.recallUploadedFile(fileEl.fileId);
|
||||||
// wire (NotOnlineFile inside msgContent). The OneBot caller
|
const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') : (cached?.fileMd5 ?? new Uint8Array(0));
|
||||||
// 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;
|
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 fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
|
||||||
const fileHash = fileEl.fileHash ?? cached?.fileHash;
|
const fileHash = fileEl.fileHash ?? cached?.fileHash;
|
||||||
if (fileSize === 0 && !cached) {
|
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash });
|
||||||
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.apis.message.sendC2cFile(userId, userUid, {
|
|
||||||
fileId: fileEl.fileId!,
|
|
||||||
fileName,
|
|
||||||
fileSize,
|
|
||||||
fileMd5,
|
|
||||||
fileHash,
|
|
||||||
});
|
|
||||||
logSentMessage(false, userId, [fileEl]);
|
logSentMessage(false, userId, [fileEl]);
|
||||||
|
} else {
|
||||||
|
log.warn('[OneBot] private file segment without file_id or url — skipped');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!lastReceipt) throw new Error('message is empty');
|
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');
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
|
||||||
// Group `{type:'file', file_id}` segments don't ride on the elems[]
|
// Two sub-paths for group file segments:
|
||||||
// pipeline either. The QQ-NT server rejects PbSendMsg with a
|
// a) has url/path but no file_id → upload() which internally calls publish()
|
||||||
// transElem(24) file payload (result=79); the correct send path is a
|
// b) has file_id from a prior upload_group_file → publish() only
|
||||||
// dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a
|
const allFileElements = elements.filter(e => e.type === 'file');
|
||||||
// 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');
|
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;
|
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
|
||||||
if (nonFileElements.length > 0) {
|
if (nonFileElements.length > 0) {
|
||||||
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
|
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
|
||||||
logSentMessage(true, groupId, nonFileElements);
|
logSentMessage(true, groupId, nonFileElements);
|
||||||
}
|
}
|
||||||
for (const fileEl of fileElements) {
|
for (const fileEl of allFileElements) {
|
||||||
// Group-file publish has no per-message sequence/random tuple to
|
let fileId: string;
|
||||||
// hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the
|
if (fileEl.url && !fileEl.fileId) {
|
||||||
// wire. If this is the LAST element we still need a receipt so
|
// upload() already calls publish() internally — do NOT call publish() again.
|
||||||
// the OneBot caller can cache the id; synthesise one from the
|
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
|
||||||
// file_id hash + a fresh timestamp.
|
const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true);
|
||||||
await ref.bridge.apis.groupFile.publish(groupId, fileEl.fileId!);
|
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]);
|
logSentMessage(true, groupId, [fileEl]);
|
||||||
if (!lastReceipt) {
|
if (!lastReceipt) {
|
||||||
// Use a hash of the fileId as a stable pseudo-id; this gets
|
|
||||||
// mixed with groupId in `hashMessageIdInt32` below.
|
|
||||||
let h = 0;
|
let h = 0;
|
||||||
const s = fileEl.fileId ?? '';
|
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 0;
|
||||||
for (let i = 0; i < s.length; i++) {
|
lastReceipt = { messageId: 0, sequence: h & 0x7FFFFFFF, clientSequence: 0, random: h & 0x7FFFFFFF, timestamp: Math.floor(Date.now() / 1000) };
|
||||||
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');
|
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 () => {
|
it('parses {type:"file", file:"/path"} (no file_id) into a file element with url', async () => {
|
||||||
// Path-only segments aren't supported here — callers must
|
// Inline file path: the parser now accepts file/url/path and stores
|
||||||
// upload via `upload_group_file` / `upload_private_file` first
|
// it in `url`. The send layer (sendGroupMessage / sendPrivateMessage)
|
||||||
// to obtain a file_id. Dropping with a warning is preferable
|
// handles the actual upload so the parser stays side-effect-free.
|
||||||
// to silently kicking off an upload from inside the message
|
|
||||||
// parser, which can't fail loudly without changing call sites.
|
|
||||||
const result = await parseMessage(
|
const result = await parseMessage(
|
||||||
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
|
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
|
||||||
false,
|
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([]);
|
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 () => {
|
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 sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
|
||||||
const publish = vi.fn();
|
const publish = vi.fn();
|
||||||
|
const upload = vi.fn();
|
||||||
const bridge = fakeBridge({
|
const bridge = fakeBridge({
|
||||||
apis: {
|
apis: {
|
||||||
message: { sendGroup: sendGroupMessage_bridge },
|
message: { sendGroup: sendGroupMessage_bridge },
|
||||||
groupFile: { publish },
|
groupFile: { publish, upload },
|
||||||
} as any,
|
} as any,
|
||||||
resolveUserUid: vi.fn(),
|
resolveUserUid: vi.fn(),
|
||||||
} as any);
|
} as any);
|
||||||
@@ -120,10 +119,42 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
|||||||
|
|
||||||
await sendGroupMessage(ctx, 12345, [
|
await sendGroupMessage(ctx, 12345, [
|
||||||
{ type: 'text', data: { text: 'with bad file segment' } },
|
{ 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);
|
] as any, false);
|
||||||
|
|
||||||
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
||||||
expect(publish).not.toHaveBeenCalled();
|
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();
|
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