diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index dcfda82c..c0ad678b 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -406,6 +406,7 @@ export class ForwardApi { name: string, groupId?: number, userId?: number, + allowTemporary = true, ): Promise> { if (groupId !== undefined) { const uploaded = await this.ctx.apis.groupFile.upload( @@ -415,6 +416,7 @@ export class ForwardApi { '/', true, false, + { allowTemporary }, ); if (!uploaded.fileId) { @@ -482,6 +484,7 @@ export class ForwardApi { element: MessageElement, groupId?: number, userId?: number, + allowTemporary = true, ): Promise { if (element.type !== 'file') { return element; @@ -495,6 +498,7 @@ export class ForwardApi { fileNameForUpload(element), groupId, userId, + allowTemporary, ); return { ...stripFileSource(element), @@ -506,6 +510,14 @@ export class ForwardApi { const cached = this.ctx.recallUploadedFile(element.fileId); if (isCachedFileUsableInTarget(cached, groupId, userId)) { + if (groupId !== undefined && cached?.busId === 104 && !allowTemporary) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'temporary group files require only file or image segments in the same forward node', + 'file', + ); + } + return element; } @@ -515,6 +527,7 @@ export class ForwardApi { fileNameForUpload(element, cached), groupId, userId, + allowTemporary, ); return { ...stripFileSource(element), @@ -532,9 +545,12 @@ export class ForwardApi { ): Promise { return Promise.all( nodes.map(async (node) => { + const allowTemporary = node.elements.every( + (element) => element.type === 'file' || element.type === 'image', + ); const elements = await Promise.all( node.elements.map((element) => - this.prepareForwardFileElement(element, groupId, userId), + this.prepareForwardFileElement(element, groupId, userId, allowTemporary), ), ); return cloneNodeWithElements(node, elements); diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index cec86c9d..24f9f4b6 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -76,6 +76,16 @@ export interface UploadFileResult { fileHash?: string | null; } +export interface GroupFileUploadResult { + fileId: string; + busId: number; +} + +export interface GroupFileUploadOptions { + /** False when the enclosing message contains content a temporary file cannot carry. */ + allowTemporary?: boolean; +} + // Re-export so callers don't have to dig into apis/shared. export type { MediaIndexNode } from './shared'; @@ -136,6 +146,7 @@ async function assertUnchanged( function buildGroupFileUploadExt( senderUin: number, groupId: number, + busId: number, fileName: string, fileSize: number, md5: Uint8Array, @@ -150,7 +161,7 @@ function buildGroupFileUploadExt( unknown2: 1, entry: { busiBuff: { - busId: 102, + busId, senderUin: BigInt(senderUin), receiverUin: BigInt(groupId), groupCode: BigInt(groupId), @@ -255,12 +266,23 @@ export class GroupFileApi { // ─────────────── publish (group file → chat) ─────────────── - publish(groupId: number, fileId: string): Promise { + publish(groupId: number, fileId: string, busId?: number): Promise { if (!fileId) { throw new Error('publish requires fileId'); } - return PublishGroupFile.invoke(this.ctx, { groupId, fileId }); + return PublishGroupFile.invoke(this.ctx, { + groupId, + fileId, + busId: busId ?? this.cachedBusId(groupId, fileId), + }); + } + + private cachedBusId(groupId: number, fileId: string): number { + const cached = this.ctx.recallUploadedFile(fileId); + return cached?.scope === 'group' && cached.groupId === groupId + ? (cached.busId ?? 102) + : 102; } trans(groupId: number, fileId: string): Promise { @@ -290,7 +312,8 @@ export class GroupFileApi { folderId = '/', uploadFile = true, publishFile = uploadFile, - ): Promise { + options: GroupFileUploadOptions = {}, + ): Promise { const bridge = this.ctx; // Group/private files may legitimately be up to 4 GiB on QQ's wire, so // override the default 1 GiB cap with the protocol ceiling. Stage onto a @@ -307,14 +330,36 @@ export class GroupFileApi { const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline const hashes = await hashFileStreaming(staged.filePath); - const upload = await UploadGroupFileRequest.invoke(this.ctx, { + const params: UploadGroupFileRequest.Params = { groupId, fileName, folderId: normalizeDirectory(folderId), fileSize: staged.fileSize, fileSha1: hashes.sha1, fileMd5: hashes.md5, - }); + busId: 102, + }; + let upload = await UploadGroupFileRequest.invoke(this.ctx, params); + + // These are the storage-limit responses for which QQ switches to + // temporary storage. Never retry transport, permission or arbitrary + // service errors, and never retry the temporary request itself. + if (upload.retCode === -403 || upload.retCode === -9801 || upload.retCode === -98090) { + if (options.allowTemporary === false) { + throw new Error( + `temporary group files require only file or image segments; remove text and other content before retrying (group file upload code=${upload.retCode})`, + ); + } + + log.warn( + 'Group %d permanent file storage rejected upload (code=%d); retrying as a temporary file', + groupId, + upload.retCode, + ); + params.busId = 104; + upload = await UploadGroupFileRequest.invoke(this.ctx, params); + } + ensureRetCodeZero( 'group file upload', upload.retCode, @@ -322,6 +367,18 @@ export class GroupFileApi { upload.clientWording, ); + const busId = upload.busId || params.busId; + + if (busId !== 102 && busId !== 104) { + throw new Error(`group file upload returned unsupported storage type: ${busId}`); + } + + if (busId === 104 && options.allowTemporary === false) { + throw new Error( + 'temporary group files require only file or image segments; remove text and other content before retrying', + ); + } + const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; @@ -329,23 +386,6 @@ export class GroupFileApi { 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 `publish` 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 - // `uploadPrivate` is where the cache is actually load-bearing. - this.ctx.rememberUploadedFile({ - fileId, - scope: 'group', - groupId, - fileName, - fileSize: staged.fileSize, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - rememberedAt: Date.now(), - }); - if (!upload.boolFileExist && uploadFile) { const senderUin = toInt(this.ctx.identity.uin); @@ -366,6 +406,7 @@ export class GroupFileApi { const ext = buildGroupFileUploadExt( senderUin, groupId, + busId, fileName, staged.fileSize, hashes.md5, @@ -386,6 +427,20 @@ export class GroupFileApi { await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext); } + // Retain the storage type for later file_id publication and download. + // A failed byte transfer must not leave a usable-looking cache entry. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'group', + groupId, + busId, + fileName, + fileSize: staged.fileSize, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + rememberedAt: Date.now(), + }); + // 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 — @@ -398,7 +453,7 @@ export class GroupFileApi { // tests can mock at the same Api boundary. if (publishFile) { try { - await this.publish(groupId, fileId); + await this.publish(groupId, fileId, busId); } catch (err) { // Keep the completed upload identifiable, but a requested chat // publication must not be reported as a successful send. @@ -409,7 +464,7 @@ export class GroupFileApi { } } - return { fileId }; + return { fileId, busId }; } finally { await staged.cleanup(); } @@ -711,8 +766,12 @@ export class GroupFileApi { // ─────────────── url fetch (group / private files) ─────────────── - async getUrl(groupId: number, fileId: string, busId = 102): Promise { - return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId }); + async getUrl(groupId: number, fileId: string, busId?: number): Promise { + return GetGroupFileUrl.invoke(this.ctx, { + groupId, + fileId, + busId: busId ?? this.cachedBusId(groupId, fileId), + }); } async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 1cb65d69..e5000527 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -17,6 +17,8 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events'; import { buildApiHub, type ApiHub } from './apis'; import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras'; import type { BridgeInterface, RosterWarmupResult } from './bridge-interface'; +import type { UploadedFileMeta } from './bridge-context'; +export type { UploadedFileMeta } from './bridge-context'; const log = createLogger('Bridge'); const runtimeLog = createLogger('Bridge.Runtime'); @@ -594,23 +596,6 @@ export interface SendMessageReceipt { timestamp: number; } -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 { rkey: string; ttlSeconds: number; diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index fc07d9f8..46dd97ae 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult { } describe('actions/forward — file segment inside forward node', () => { + it('rejects cached temporary files mixed with text before building a forward payload', async () => { + buildSendElemsMock.mockClear(); + const bridge = mockBridge({ + recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })), + }); + await expect( + new ForwardApi(bridge as any).upload( + [ + { + userUin: 10001, + nickname: 'alice', + elements: [ + { type: 'text', text: 'caption' }, + { type: 'file', fileId: 'temp' }, + ], + }, + ], + 12345, + ), + ).rejects.toThrow(/temporary group files.*only file or image/i); + expect(buildSendElemsMock).not.toHaveBeenCalled(); + expect(bridge.sendRawPacket).not.toHaveBeenCalled(); + }); + + it('disallows temporary fallback when a forward node mixes a new file with text', async () => { + buildSendElemsMock.mockClear(); + const bridge = mockBridge(); + bridge.apis.groupFile.upload.mockRejectedValueOnce( + new Error('temporary group files require only file or image segments'), + ); + await expect( + new ForwardApi(bridge as any).upload( + [ + { + userUin: 10001, + nickname: 'alice', + elements: [ + { type: 'text', text: 'caption' }, + { type: 'file', url: 'base64://AQID', fileName: 'note.txt' }, + ], + }, + ], + 12345, + ), + ).rejects.toThrow(/temporary group files/); + expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith( + 12345, + 'base64://AQID', + 'note.txt', + '/', + true, + false, + { allowTemporary: false }, + ); + expect(buildSendElemsMock).not.toHaveBeenCalled(); + expect(bridge.sendRawPacket).not.toHaveBeenCalled(); + }); + it('rejects a recursive window shake before identity resolution or upload', async () => { buildSendElemsMock.mockClear(); const resolveUserUid = vi.fn(); @@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => { 12345, ); - expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false); + expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, { + allowTemporary: true, + }); expect(publish).not.toHaveBeenCalled(); const [elements] = buildSendElemsMock.mock.calls[0]!; expect(elements).toEqual([ @@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => { '/', true, false, + { allowTemporary: true }, ); const [elements] = buildSendElemsMock.mock.calls[0]!; expect(elements).toEqual([ diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 35fd22d3..2eb3111a 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -1,10 +1,12 @@ import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { FileUploadExt } from '@snowluma/proto-defs/highway'; import type { OidbGroupFileCountViewResp, OidbGroupFileReq, OidbGroupFileResp, + OidbGroupFileUploadResp, OidbGroupFileViewResp, OidbGroupFileFolderResp, OidbGroupSendFileReq, @@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) { }; } +function uploadResponse(upload: OidbGroupFileUploadResp) { + return packResponse(protobuf_encode>({ body: { upload } })); +} + let STAGED_FILE: string; describe('apis/group-file', () => { @@ -138,7 +144,7 @@ describe('apis/group-file', () => { const api = new GroupFileApi(bridge as any); vi.spyOn(api, 'publish').mockResolvedValue(); const out = await api.upload(12345, '/path/file.bin'); - expect(out).toEqual({ fileId: 'fid-xyz' }); + expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 }); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); }); @@ -224,8 +230,180 @@ describe('apis/group-file', () => { await expect( new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'), ).rejects.toThrow(/code=999/); + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); }); + it.each([-403, -9801, -98090])( + 'retries capacity error %s as a temporary group file', + async (retCode) => { + const bridge = mockBridge(); + bridge.sendRawPacket + .mockResolvedValueOnce( + uploadResponse({ retCode, retMsg: 'permanent storage full' }), + ) + .mockResolvedValueOnce( + uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }), + ); + const api = new GroupFileApi(bridge as any); + const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder'); + expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 }); + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3); + const requests = bridge.sendRawPacket.mock.calls + .slice(0, 2) + .map(([, bytes]) => protobuf_decode>(bytes).body?.file); + expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' }); + expect(requests[1]).toEqual({ ...requests[0], busId: 104 }); + const publish = protobuf_decode>( + bridge.sendRawPacket.mock.calls[2]![1], + ); + expect(publish.body?.body?.info).toMatchObject({ + fileId: 'temporary-file', + busiType: 104, + }); + expect(bridge.rememberUploadedFile).toHaveBeenCalledWith( + expect.objectContaining({ busId: 104, groupId: 12345 }), + ); + expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); + }, + ); + + it('carries the server-selected storage type through bytes, publication and cached reuse', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce( + uploadResponse({ + fileId: 'temporary-file', + busId: 104, + uploadIp: '127.0.0.1', + uploadPort: 8080, + fileKey: new Uint8Array([7]), + checkKey: new Uint8Array([8]), + }), + ); + bridge.recallUploadedFile.mockImplementation( + () => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0], + ); + const api = new GroupFileApi(bridge as any); + await api.upload(12345, '/path/file.bin'); + const ext = protobuf_decode( + vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5], + ); + expect(ext.entry?.busiBuff?.busId).toBe(104); + await api.publish(12345, 'temporary-file'); + + for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) { + expect( + protobuf_decode>(bytes).body?.body?.info?.busiType, + ).toBe(104); + } + }); + + it('stops after a failed temporary attempt and releases the staged file', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket + .mockResolvedValueOnce(uploadResponse({ retCode: -403 })) + .mockResolvedValueOnce( + uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }), + ); + await expect( + new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'), + ).rejects.toThrow(/code=-9801/); + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); + expect(bridge.rememberUploadedFile).not.toHaveBeenCalled(); + expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); + const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value; + expect(staged.cleanup).toHaveBeenCalledOnce(); + }); + + it('retains temporary mode when the successful retry omits its storage type', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket + .mockResolvedValueOnce(uploadResponse({ retCode: -403 })) + .mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true })); + const api = new GroupFileApi(bridge as any); + const publish = vi.spyOn(api, 'publish').mockResolvedValue(); + await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({ + fileId: 'temp', + busId: 104, + }); + expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104); + }); + + it('rejects an unknown server storage type before bytes or publication', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce( + uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }), + ); + await expect( + new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'), + ).rejects.toThrow(/unsupported storage type: 777/); + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + expect(bridge.rememberUploadedFile).not.toHaveBeenCalled(); + expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); + }); + + it.each([ + { scope: 'group', groupId: 12345, expected: 104 }, + { scope: 'group', groupId: 54321, expected: 102 }, + { scope: 'private', groupId: undefined, expected: 102 }, + ] as const)( + 'scopes cached storage to the target group for download and reuse (%j)', + async ({ scope, groupId, expected }) => { + const bridge = mockBridge(); + bridge.recallUploadedFile.mockReturnValue({ + fileId: 'temp', + scope, + groupId, + busId: 104, + }); + bridge.sendRawPacket.mockResolvedValueOnce( + packResponse( + protobuf_encode>({ + body: { + download: { + downloadDns: 'download.example.com', + downloadUrl: new Uint8Array([1]), + }, + }, + }), + ), + ); + const api = new GroupFileApi(bridge as any); + await api.getUrl(12345, 'temp'); + await api.publish(12345, 'temp'); + const requests = bridge.sendRawPacket.mock.calls; + expect( + protobuf_decode>(requests[0]![1]).body?.download?.busId, + ).toBe(expected); + expect( + protobuf_decode>(requests[1]![1]).body?.body?.info + ?.busiType, + ).toBe(expected); + }, + ); + + it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])( + 'rejects a disallowed temporary upload before transferring bytes or publishing (%j)', + async (response) => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response)); + await expect( + new GroupFileApi(bridge as any).upload( + 12345, + '/path/file.bin', + '', + '/', + true, + false, + { allowTemporary: false }, + ), + ).rejects.toThrow(/temporary group files.*only file or image/i); + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + expect(bridge.rememberUploadedFile).not.toHaveBeenCalled(); + expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); + }, + ); + it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => { // Reproduces the bug report: OIDB upload + highway PUT alone only // stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB @@ -341,11 +519,12 @@ describe('apis/group-file', () => { const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt'); if (confirmed) { - await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' }); - expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm'); + await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 }); + expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102); } else { await expect(upload).rejects.toBe(failure); expect(publishSpy).not.toHaveBeenCalled(); + expect(bridge.rememberUploadedFile).not.toHaveBeenCalled(); } expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 0597cc6c..5abcd080 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -30,7 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({ })); import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { MsgInfo } from '@snowluma/proto-defs/element'; +import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element'; import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder'; import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload'; import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; @@ -374,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => { }); describe('element-builder / file element is no longer carried in elems[]', () => { + it.each([12345, 54321])( + 'preserves temporary storage only in a matching group forward (%s)', + async (cachedGroupId) => { + const bridge = { + recallUploadedFile: vi.fn(() => ({ + scope: 'group', + groupId: cachedGroupId, + busId: 104, + fileName: 'doc.pdf', + fileSize: 3, + })), + } as any; + const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], { + bridge, + groupId: 12345, + forwardFake: true, + }); + const extra = protobuf_decode(elem!.transElem!.elemValue!.subarray(3)); + expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102); + }, + ); // Regression for the `result=79` class: previously the element-builder // emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments // and the QQ-NT server rejected the outgoing PbSendMsg with that wire diff --git a/packages/onebot/GROUP_FILES.md b/packages/onebot/GROUP_FILES.md new file mode 100644 index 00000000..c87a98a3 --- /dev/null +++ b/packages/onebot/GROUP_FILES.md @@ -0,0 +1,26 @@ +# 群文件发送与临时存储 + +`upload_group_file` 和 `send_group_msg` 中的文件段默认使用群永久文件空间。 +当服务器明确返回容量或文件数量限制时,SnowLuma 会尝试一次临时存储,并在日志中记录这次切换。 +临时申请、文件传输或聊天发布失败仍会报错;权限不足、连接失败等其他错误不会触发切换。 +临时文件可能过期,不能作为永久保存的替代。 + +## 消息内容限制 + +进入临时文件路径时,一条消息只能包含文件或图片段。 +含文字、提及、表情等其他内容的混合消息会被拒绝,需要调用方拆成独立消息后再发送。 +合并转发按每个节点的内容检查同一规则。 + +SnowLuma 会在发布聊天消息前检查附件;发现不允许的组合时,不会先发文字、再丢掉附件或文字。 +检查之前已完成的其他附件上传不会自动删除。上传成功后如果聊天发布失败,错误仍会保留文件标识。 +这不是跨多条消息的事务:开始发布后出现的网络或服务端错误仍可能使前面的消息已经送达。 + +普通图片加文字仍通过图片消息通道发送,不会因为群永久文件空间不足而转成群文件。 +永久文件与文字的现有分开发送方式保持兼容。超大视频按原有规则转成文件后,也适用临时文件的内容限制。 + +## 文件复用与下载 + +运行期间上传过的群文件会按账号、群和文件标识保留其存储类型。 +同一群中用 `file_id` 再次发送、获取下载链接或生成合并转发时,会使用该存储类型。 +`get_group_file_url` 显式传入的 `busid` 仍优先;未提供有效值时,使用当前会话记住的类型,否则沿用永久文件默认值。 +上传记录不是持久化目录;重启后获取临时文件链接,应从群文件列表取得对应的 `busid` 并传入。 diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 1d61d5fb..d1700b66 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -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), ), }); }, diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index fc6bb0af..994922c8 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -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>) => { + // 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> | 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]); diff --git a/packages/onebot/tests/actions-group-file.test.ts b/packages/onebot/tests/actions-group-file.test.ts new file mode 100644 index 00000000..0e0f8393 --- /dev/null +++ b/packages/onebot/tests/actions-group-file.test.ts @@ -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); + }, + ); +}); diff --git a/packages/onebot/tests/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts index d8e92ce2..21e70a56 100644 --- a/packages/onebot/tests/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -22,15 +22,22 @@ import { MessageStore } from '../src/message-store'; import { sendGroupMessage } from '../src/modules/message-actions'; function fakeBridge(overrides: Partial = {}): 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 () => { diff --git a/packages/onebot/tests/send-video-fallback.test.ts b/packages/onebot/tests/send-video-fallback.test.ts index 70c678b0..b077b702 100644 --- a/packages/onebot/tests/send-video-fallback.test.ts +++ b/packages/onebot/tests/send-video-fallback.test.ts @@ -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 () => { diff --git a/packages/protocol/src/bridge-context.ts b/packages/protocol/src/bridge-context.ts index b4278112..49b50294 100644 --- a/packages/protocol/src/bridge-context.ts +++ b/packages/protocol/src/bridge-context.ts @@ -31,6 +31,8 @@ export interface UploadedFileMeta { scope: 'group' | 'private'; /** Group id if scope='group', else `undefined`. */ groupId?: number; + /** Server-selected group storage type: 102 permanent, 104 temporary. */ + busId?: number; /** Friend uin if scope='private', else `undefined`. */ userId?: number; fileName: string; diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index d64d4660..e5fdebec 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -607,6 +607,8 @@ function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoEle } const cached = ctx?.bridge.recallUploadedFile(element.fileId); + const busId = + cached?.scope === 'group' && cached.groupId === ctx?.groupId ? (cached.busId ?? 102) : 102; const fileSize = element.fileSize ?? cached?.fileSize ?? 0; const fileName = element.fileName ?? cached?.fileName ?? ''; const md5 = element.md5Hex @@ -618,13 +620,13 @@ function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoEle // Outer field1 is hardcoded to 6 in NapCat's encoder // (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries - // busId=102 + the file_id + name + size + sha1/md5 hashes. + // the storage type + file_id + name + size + sha1/md5 hashes. const extraBytes = protobuf_encode({ field1: 6, fileName, inner: { info: { - busId: 102, + busId, fileId: element.fileId, fileSize: BigInt(fileSize), fileName, diff --git a/packages/protocol/src/oidb-services/group-file/publish-group-file.ts b/packages/protocol/src/oidb-services/group-file/publish-group-file.ts index a49dcd56..d7f831e3 100644 --- a/packages/protocol/src/oidb-services/group-file/publish-group-file.ts +++ b/packages/protocol/src/oidb-services/group-file/publish-group-file.ts @@ -21,6 +21,7 @@ export namespace PublishGroupFile { export interface Params { groupId: number; fileId: string; + busId?: number; } export type Deps = OidbSender; @@ -29,7 +30,7 @@ export namespace PublishGroupFile { groupUin: p.groupId, type: 2, info: { - busiType: 102, + busiType: p.busId ?? 102, fileId: p.fileId, field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, field5: true, diff --git a/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts b/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts index e0036fc2..c4aa8ae1 100644 --- a/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts +++ b/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts @@ -33,6 +33,7 @@ export namespace UploadGroupFileRequest { fileSize: number; fileSha1: Uint8Array; fileMd5: Uint8Array; + busId?: 102 | 104; } export type Deps = OidbSender; @@ -41,7 +42,7 @@ export namespace UploadGroupFileRequest { file: { groupUin: p.groupId, appId: 4, - busId: 102, + busId: p.busId ?? 102, entrance: 6, targetDirectory: p.folderId, fileName: p.fileName,