feat(protocol,onebot): raise video size limit with Highway-first fallback (#153)

Round 3: fix hardcoded 4096 MB in error messages
- Use MAX_VIDEO_SIZE_HARD constant instead of hardcoded 4096 MB
- Both throw sites now derive limit from the same constant
This commit is contained in:
stla authored and GitHub committed 2026-06-27 16:10:25 +08:00
1 parent 70fd40e34c
commit 85182795b5
3 files changed
+82 -23

No files matched your search

+41 -4
View File
@@ -1,6 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload';
import type { MessageSendResult } from '../api-handler';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
import { segmentsToRawMessage } from '../helper/cq';
@@ -536,13 +537,49 @@ export async function sendPrivateMessage(
// 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');
let allFileElements = elements.filter(e => e.type === 'file');
let nonFileElements = elements.filter(e => e.type !== '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);
try {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
} catch (err) {
// Highway upload failed — check if a large video element triggered it
// and fall back to file upload for that element (private messages
// cannot carry file elements through the element pipeline).
const isSizeErr = err instanceof Error && /size limit|too large|413|too big|exceed/i.test(err.message);
const videoElements = nonFileElements.filter(e => e.type === 'video');
// Trigger fallback when a video element is known to exceed the size
// limit, OR when the error message itself indicates a size-related
// failure (covers remote videos whose size couldn't be inferred).
const needsFallback = videoElements.some(e => {
const sz = getVideoSourceSize(e);
return sz !== null ? sz > MAX_VIDEO_SIZE : isSizeErr;
});
if (needsFallback) {
log.warn('[OneBot] private video upload failed, falling back to file upload: %s', err instanceof Error ? err.message : String(err));
const remaining: MessageElement[] = [];
for (const e of nonFileElements) {
if (e.type === 'video') {
const sz = getVideoSourceSize(e);
if (sz !== null ? sz > MAX_VIDEO_SIZE : isSizeErr) {
allFileElements = [...allFileElements, { type: 'file', url: e.url, fileId: e.fileId, fileName: e.fileName || 'video.mp4' }];
continue;
}
}
remaining.push(e);
}
nonFileElements = remaining;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
}
} else {
throw err;
}
}
}
if (allFileElements.length > 0) {
const userUid = await ref.bridge.resolveUserUid(userId);
+19 -11
View File
@@ -375,18 +375,26 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
throw new Error('private video target uid is missing');
}
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
try {
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 21 : 11,
},
};
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 21 : 11,
},
};
} catch (err) {
if (isGroup && element.fileId) {
console.warn('[ElemBuilder] video upload failed, falling back to file element: %s', err instanceof Error ? err.message : String(err));
return makeGroupFileElem(element, ctx);
}
throw err;
}
}
/**
+22 -8
View File
@@ -32,9 +32,21 @@ export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
export const GROUP_VIDEO_CMD_ID = 1005;
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
const MAX_VIDEO_SIZE_HARD = 1536 * 1024 * 1024;
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
export function getVideoSourceSize(element: MessageElement): number | null {
if (element.fileSize && element.fileSize > 0) return element.fileSize;
const source = element.url || element.fileId || '';
if (!source) return null;
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
return fs.statSync(local).size;
}
return null;
}
const FALLBACK_THUMB = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
'base64',
@@ -276,13 +288,12 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
// Pre-check on disk size BEFORE reading bytes into memory. The later
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
// run after we'd already allocated the entire file (so a 10 GiB
// local path still OOMs us before the check fires).
const stat = fs.statSync(local);
if (stat.size > MAX_VIDEO_SIZE_HARD) {
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE_HARD / (1024 * 1024)} MB`);
}
if (stat.size > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
moduleLog.warn('video exceeds 100 MB (%d MB), trying Highway upload', stat.size / (1024 * 1024));
}
return {
bytes: new Uint8Array(fs.readFileSync(local)),
@@ -291,7 +302,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
};
}
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE_HARD);
const fileName = element.fileName || loaded.fileName || '';
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
@@ -378,8 +389,11 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
try {
const staged = await stageVideoSource(element, tempDir, cleanups);
if (staged.bytes.length === 0) throw new Error('video file is empty');
if (staged.bytes.length > MAX_VIDEO_SIZE_HARD) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE_HARD / (1024 * 1024)} MB`);
}
if (staged.bytes.length > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
moduleLog.warn('video bytes exceed 100 MB (%d MB), Highway upload may fail', staged.bytes.length / (1024 * 1024));
}
const hashes = computeHashes(staged.bytes);