fix(core): handle group file storage limits
Retry eligible storage failures as temporary files and preserve their storage type for later use. Reject incompatible mixed content before chat publication. Refs #644
This commit is contained in:
16 files changed
+750
-104
No files matched your search
@@ -0,0 +1,26 @@
|
||||
# 群文件发送与临时存储
|
||||
|
||||
`upload_group_file` 和 `send_group_msg` 中的文件段默认使用群永久文件空间。
|
||||
当服务器明确返回容量或文件数量限制时,SnowLuma 会尝试一次临时存储,并在日志中记录这次切换。
|
||||
临时申请、文件传输或聊天发布失败仍会报错;权限不足、连接失败等其他错误不会触发切换。
|
||||
临时文件可能过期,不能作为永久保存的替代。
|
||||
|
||||
## 消息内容限制
|
||||
|
||||
进入临时文件路径时,一条消息只能包含文件或图片段。
|
||||
含文字、提及、表情等其他内容的混合消息会被拒绝,需要调用方拆成独立消息后再发送。
|
||||
合并转发按每个节点的内容检查同一规则。
|
||||
|
||||
SnowLuma 会在发布聊天消息前检查附件;发现不允许的组合时,不会先发文字、再丢掉附件或文字。
|
||||
检查之前已完成的其他附件上传不会自动删除。上传成功后如果聊天发布失败,错误仍会保留文件标识。
|
||||
这不是跨多条消息的事务:开始发布后出现的网络或服务端错误仍可能使前面的消息已经送达。
|
||||
|
||||
普通图片加文字仍通过图片消息通道发送,不会因为群永久文件空间不足而转成群文件。
|
||||
永久文件与文字的现有分开发送方式保持兼容。超大视频按原有规则转成文件后,也适用临时文件的内容限制。
|
||||
|
||||
## 文件复用与下载
|
||||
|
||||
运行期间上传过的群文件会按账号、群和文件标识保留其存储类型。
|
||||
同一群中用 `file_id` 再次发送、获取下载链接或生成合并转发时,会使用该存储类型。
|
||||
`get_group_file_url` 显式传入的 `busid` 仍优先;未提供有效值时,使用当前会话记住的类型,否则沿用永久文件默认值。
|
||||
上传记录不是持久化目录;重启后获取临时文件链接,应从群文件列表取得对应的 `busid` 并传入。
|
||||
@@ -4,17 +4,17 @@ import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
// NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely,
|
||||
// so whatever value a client tacks on is silently ignored. Mirror that here:
|
||||
// accept any value, coerce when it's a usable non-negative integer, else fall
|
||||
// back to the canonical 102. Restores the legacy `asNumber(busid) || 102`
|
||||
// back to the uploaded file's known storage type (otherwise 102). Retains the
|
||||
// semantics that a strict `f.int({min:0}).default(102)` regressed (a *present*
|
||||
// non-numeric busid was rejected with `expected an integer`). See issue #147.
|
||||
function busidOr102(raw: unknown): number {
|
||||
function optionalBusId(raw: unknown): number | undefined {
|
||||
const n =
|
||||
typeof raw === 'number' && Number.isFinite(raw)
|
||||
? Math.trunc(raw)
|
||||
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
|
||||
? Math.trunc(Number(raw))
|
||||
: NaN;
|
||||
return Number.isInteger(n) && n >= 0 ? n : 102;
|
||||
return Number.isInteger(n) && n >= 0 ? n : undefined;
|
||||
}
|
||||
|
||||
export const actions = [
|
||||
@@ -159,7 +159,7 @@ export const actions = [
|
||||
properties: { url: { type: 'string', description: '文件下载直链' } },
|
||||
required: ['url'],
|
||||
},
|
||||
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
|
||||
// busid is accepted but tolerant (see optionalBusId): NapCat/LLBot ignore it,
|
||||
// so a present null/empty/non-numeric value must not 400 the request (#147).
|
||||
params: { file_id: f.fileId(), busid: f.raw() },
|
||||
run: async (p, ctx) => {
|
||||
@@ -167,7 +167,7 @@ export const actions = [
|
||||
url: await ctx.bridge.apis.groupFile.getUrl(
|
||||
p.group_id,
|
||||
p.file_id,
|
||||
busidOr102(p.busid),
|
||||
optionalBusId(p.busid),
|
||||
),
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1409,9 +1409,8 @@ export async function sendGroupMessage(
|
||||
throw new Error('message is empty');
|
||||
}
|
||||
|
||||
// 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
|
||||
// Prepare all file uploads before publishing any part of the message.
|
||||
// Whether storage is temporary is only known after the upload preflight.
|
||||
let allFileElements = elements.filter((e) => e.type === 'file');
|
||||
let nonFileElements = elements.filter((e) => e.type !== 'file');
|
||||
|
||||
@@ -1426,6 +1425,73 @@ export async function sendGroupMessage(
|
||||
}
|
||||
}
|
||||
|
||||
let allowTemporary = nonFileElements.every((element) => element.type === 'image');
|
||||
|
||||
const assertStorageAllowed = (busId: number | undefined) => {
|
||||
if (busId === 104 && !allowTemporary) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'temporary group files require only file or image segments; remove text and other content before retrying',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const preparedFiles: Array<{
|
||||
element: MessageElementOf<'file'>;
|
||||
fileId: string;
|
||||
busId?: number;
|
||||
}> = [];
|
||||
|
||||
const prepareFiles = async (files: Array<MessageElementOf<'file'>>) => {
|
||||
// Check known temporary ids first, even if preceded by a new upload.
|
||||
const candidates = files.map((element) => {
|
||||
const cached = element.fileId
|
||||
? ref.bridge.recallUploadedFile(element.fileId)
|
||||
: undefined;
|
||||
const busId =
|
||||
cached?.scope === 'group' && cached.groupId === groupId ? cached.busId : undefined;
|
||||
assertStorageAllowed(busId);
|
||||
return { element, fileId: element.fileId, busId };
|
||||
});
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const { element } = candidate;
|
||||
|
||||
if (!candidate.fileId) {
|
||||
if (!element.url) {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
'group file segment requires file_id or url',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
|
||||
const name = element.fileName || guessFileNameFromUrl(element.url) || 'file';
|
||||
const uploaded = await ref.bridge.apis.groupFile.upload(
|
||||
groupId,
|
||||
element.url,
|
||||
name,
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary },
|
||||
);
|
||||
candidate.fileId = uploaded.fileId;
|
||||
candidate.busId = uploaded.busId;
|
||||
assertStorageAllowed(candidate.busId);
|
||||
}
|
||||
|
||||
if (!candidate.fileId) {
|
||||
throw new Error('group file auto-upload returned no file_id');
|
||||
}
|
||||
|
||||
preparedFiles.push({ element, fileId: candidate.fileId, busId: candidate.busId });
|
||||
}
|
||||
};
|
||||
|
||||
await prepareFiles(allFileElements);
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
|
||||
|
||||
if (nonFileElements.length > 0) {
|
||||
@@ -1447,8 +1513,9 @@ export async function sendGroupMessage(
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
|
||||
allFileElements = [...allFileElements, ...fileEls];
|
||||
nonFileElements = remaining;
|
||||
allowTemporary = remaining.every((element) => element.type === 'image');
|
||||
await prepareFiles(fileEls);
|
||||
|
||||
if (nonFileElements.length > 0) {
|
||||
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
|
||||
@@ -1457,34 +1524,14 @@ export async function sendGroupMessage(
|
||||
}
|
||||
}
|
||||
|
||||
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 || guessFileNameFromUrl(fileEl.url) || 'file';
|
||||
const result = await ref.bridge.apis.groupFile.upload(
|
||||
groupId,
|
||||
fileEl.url,
|
||||
name,
|
||||
'/',
|
||||
true,
|
||||
for (const { element: fileEl, fileId, busId } of preparedFiles) {
|
||||
try {
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileId, busId);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`group file chat post failed (fileId=${fileId}): ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ cause: err },
|
||||
);
|
||||
fileId = result.fileId ?? '';
|
||||
|
||||
if (!fileId) {
|
||||
throw new Error('group file auto-upload returned no file_id');
|
||||
}
|
||||
} else if (fileEl.fileId) {
|
||||
fileId = fileEl.fileId;
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileId);
|
||||
} else {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
'group file segment requires file_id or url',
|
||||
'file',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
logSentMessage(true, groupId, [fileEl]);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { ApiActionContext } from '../src/api-handler';
|
||||
import { actions } from '../src/actions/group-file';
|
||||
|
||||
describe('get_group_file_url storage selection', () => {
|
||||
it.each([
|
||||
{ busid: undefined, expected: undefined },
|
||||
{ busid: null, expected: undefined },
|
||||
{ busid: '', expected: undefined },
|
||||
{ busid: 'invalid', expected: undefined },
|
||||
{ busid: -1, expected: undefined },
|
||||
{ busid: 102, expected: 102 },
|
||||
{ busid: '104', expected: 104 },
|
||||
{ busid: 0, expected: 0 },
|
||||
])(
|
||||
'passes an explicit valid type, otherwise lets the file cache select it (%j)',
|
||||
async ({ busid, expected }) => {
|
||||
const getUrl = vi.fn(async () => 'https://download.example.com/file');
|
||||
const ctx = {
|
||||
bridge: { apis: { groupFile: { getUrl } } },
|
||||
} as unknown as ApiActionContext;
|
||||
const action = actions.find((entry) => entry.names[0] === 'get_group_file_url')!;
|
||||
const result = await action.toHandler(ctx)({ group_id: 12345, file_id: 'temp', busid });
|
||||
expect(result).toMatchObject({ status: 'ok' });
|
||||
expect(getUrl).toHaveBeenCalledExactlyOnceWith(12345, 'temp', expected);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -22,15 +22,22 @@ import { MessageStore } from '../src/message-store';
|
||||
import { sendGroupMessage } from '../src/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
}
|
||||
return new Proxy(
|
||||
{
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
recallUploadedFile: vi.fn(),
|
||||
...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`);
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext {
|
||||
@@ -345,10 +352,214 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('file segment with url (no file_id) auto-uploads via groupFile.upload (not publish)', async () => {
|
||||
it('rejects text + image + temporary file before any chat publication', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const upload = vi.fn(async () => ({ fileId: 'temp', busId: 104 }));
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup }, groupFile: { upload, publish } } as any,
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'image', data: { file: 'base64://AQID' } },
|
||||
{ type: 'file', data: { file: '/tmp/report.pdf' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects cached temporary file + text before publishing an earlier permanent file', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup }, groupFile: { publish } } as any,
|
||||
recallUploadedFile: vi.fn((id) =>
|
||||
id === 'temp'
|
||||
? {
|
||||
fileId: id,
|
||||
scope: 'group',
|
||||
groupId: 12345,
|
||||
busId: 104,
|
||||
}
|
||||
: undefined,
|
||||
),
|
||||
} as any),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'file', data: { file_id: 'permanent' } },
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'file', data: { file_id: 'temp' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'allows temporary files with only file/image content (image=%s)',
|
||||
async (withImage) => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const upload = vi.fn(async () => {
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
return { fileId: 'temp', busId: 104 };
|
||||
});
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup }, groupFile: { upload, publish } } as any,
|
||||
}),
|
||||
);
|
||||
const message = [
|
||||
{ type: 'file', data: { file: '/tmp/report.pdf' } },
|
||||
...(withImage ? [{ type: 'image', data: { file: 'base64://AQID' } }] : []),
|
||||
];
|
||||
await sendGroupMessage(ctx, 12345, message, false);
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'/tmp/report.pdf',
|
||||
'report.pdf',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: true },
|
||||
);
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
|
||||
expect(sendGroup).toHaveBeenCalledTimes(withImage ? 1 : 0);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves ordinary image + text without entering the group-file path', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const upload = vi.fn();
|
||||
const publish = vi.fn();
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
|
||||
);
|
||||
await sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'image', data: { file: 'base64://AQID' } },
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
],
|
||||
false,
|
||||
);
|
||||
expect(sendGroup).toHaveBeenCalledOnce();
|
||||
expect(sendGroup.mock.calls[0]).toMatchObject([
|
||||
12345,
|
||||
[
|
||||
{ type: 'image', url: 'base64://AQID' },
|
||||
{ type: 'text', text: 'caption' },
|
||||
],
|
||||
]);
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps permanent file + text sends, but checks uploads before sending the text', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const upload = vi.fn(async () => {
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
return { fileId: 'permanent', busId: 102 };
|
||||
});
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
|
||||
);
|
||||
await sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'file', data: { file: '/tmp/report.pdf' } },
|
||||
],
|
||||
false,
|
||||
);
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'/tmp/report.pdf',
|
||||
'report.pdf',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: false },
|
||||
);
|
||||
expect(sendGroup).toHaveBeenCalledOnce();
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'permanent', 102);
|
||||
});
|
||||
|
||||
it('does not publish the first file or text if a later upload fails', async () => {
|
||||
const sendGroup = vi.fn();
|
||||
const publish = vi.fn();
|
||||
const upload = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ fileId: 'first', busId: 102 })
|
||||
.mockRejectedValueOnce(
|
||||
new Error('temporary group files require only file or image segments'),
|
||||
);
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'file', data: { file: '/tmp/one.pdf' } },
|
||||
{ type: 'file', data: { file: '/tmp/two.pdf' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files/);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a failed file publication with its identity and never retries the send', async () => {
|
||||
const cause = new Error('chat post rejected');
|
||||
const publish = vi.fn().mockRejectedValueOnce(cause);
|
||||
const upload = vi.fn(async () => ({ fileId: 'temp', busId: 104 }));
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup: vi.fn() }, groupFile: { upload, publish } } as any,
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[{ type: 'file', data: { file: '/tmp/report.pdf' } }],
|
||||
false,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
message: 'group file chat post failed (fileId=temp): chat post rejected',
|
||||
cause,
|
||||
});
|
||||
expect(upload).toHaveBeenCalledOnce();
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('uploads a file source without publishing, then publishes it exactly once', 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.
|
||||
// directly. Delay chat publication until all uploads are checked.
|
||||
const upload = vi.fn(
|
||||
async (
|
||||
_gid: number,
|
||||
@@ -387,8 +598,16 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
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();
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'/tmp/audio.wav',
|
||||
'audio.wav',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: true },
|
||||
);
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'auto-fid', undefined);
|
||||
});
|
||||
|
||||
it('percent-decodes a file:// URL basename when name is omitted (#354)', async () => {
|
||||
|
||||
@@ -95,8 +95,7 @@ describe('send_group_msg large-video fallback', () => {
|
||||
expect(gid).toBe(12345);
|
||||
expect(src).toBe('http://example.com/big.mp4');
|
||||
expect(name).toBe('video.mp4');
|
||||
// upload() publishes internally — no second publish().
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'auto-fid', undefined);
|
||||
});
|
||||
|
||||
it('rethrows (no fallback) when a remote video fails with a non-size error', async () => {
|
||||
|
||||
Reference in new issue
Block a user