diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 2408904a..f56b408f 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -28,8 +28,11 @@ import type { } from '../proto/proton/oidb-action'; import type { FileUploadExt } from '../proto/proton/highway'; import { toHexUpper } from '../../utils/hex'; +import { createLogger } from '../../utils/logger'; import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; +const log = createLogger('GroupFile'); + // ─────────────── public result types ─────────────── export interface GroupFileInfo { @@ -349,6 +352,33 @@ export async function uploadGroupFile( await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext); } + // 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 — + // the chat shows nothing. NapCat does the same (upload + sendMsg + // atomically inside `upload_group_file`, see + // `dev/napcatQQ/.../UploadGroupFile.ts:54-58`). Only suppressed when + // the caller opts out via `uploadFile=false` (treat that as "I only + // wanted the slot allocated, hold the chat post"). + if (uploadFile) { + try { + await bridge.sendGroupMessage(groupId, [{ + type: 'file', + fileId, + fileName, + fileSize: loaded.bytes.length, + md5Hex: bytesToHexUpper(hashes.md5), + sha1Hex: bytesToHexUpper(hashes.sha1), + }]); + } catch (err) { + // The bytes are already on the server and the fileId is valid — + // fail loud but don't lose the upload result the action handler + // committed to returning. Callers can still resolve the file by + // id; they'll just have to re-publish it themselves. + log.warn('group file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + return { fileId }; } @@ -435,6 +465,27 @@ export async function uploadPrivateFile( await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext); } + // Stage 3: publish the file as a c2c chat message. C2C files use + // `RichText.notOnlineFile` (parallel to `elems`), so we go through + // the dedicated `sendC2cFileMessage` instead of `sendPrivateMessage` + // which only knows about elems[]. NapCat does the same atomic + // upload+send dance — without it the file sits on the server and + // the recipient sees nothing. + if (uploadFile) { + try { + await bridge.sendC2cFileMessage(userId, targetUid, { + fileId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileHash: fileHash ?? '', + }); + } catch (err) { + log.warn('private file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + return { fileId, fileHash }; } diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index ca50979c..225a8d0e 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -43,6 +43,18 @@ export interface BridgeInterface { // ─── Send (messages) ─── sendGroupMessage(groupId: number, elements: MessageElement[]): Promise; sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise; + /** + * Send a c2c file as a chat message. Bypasses the regular elems[] + * pipeline because c2c files live on `RichText.notOnlineFile`, not + * inside the elems array. Group files go through `sendGroupMessage` + * with a `{type:'file', fileId, fileName, fileSize, md5Hex, sha1Hex}` + * element instead. + */ + sendC2cFileMessage( + userUin: number, + userUid: string, + info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, + ): Promise; // ─── Fetch (contacts / profile / system) ─── fetchFriendList(): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 5f032774..aabd813f 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -398,6 +398,76 @@ export class Bridge implements BridgeInterface { }; } + /** + * Send a c2c file as a chat message. + * + * Unlike images / videos / records that ride on `RichText.elems` as + * regular Elem entries, c2c files use `RichText.notOnlineFile` + * (parallel to `elems`, see `proto/proton/message.ts:75`). The + * receive-side decoder strips this back to a `{type:'file'}` segment + * in `rich-body-decoder.ts:425-433`. There's no Elem you can stuff + * into `buildSendElems` for this, so this helper short-circuits the + * normal send pipeline. + */ + async sendC2cFileMessage( + userUin: number, + userUid: string, + info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, + ): Promise { + const random = this.nextMessageRandom(); + const clientSeq = this.nextClientSequence(); + + const request = protobuf_encode({ + routingHead: { + c2c: { uin: userUin, uid: userUid }, + }, + contentHead: { + type: 1, + subType: 0, + c2cCmd: 11, + }, + messageBody: { + richText: { + notOnlineFile: { + fileType: 0, + fileUuid: info.fileId, + fileMd5: info.fileMd5, + fileName: info.fileName, + fileSize: BigInt(info.fileSize), + fileHash: info.fileHash ?? '', + }, + }, + } as any, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { + msgFlag: Math.floor(Date.now() / 1000), + }, + multiSendSeq: 0, + }); + + const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + if (response.result !== undefined && response.result !== 0) { + throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + + const seq = response.privateSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + // --- Delegated: OIDB helpers --- async resolveUserUid(uin: number, groupId?: number): Promise { diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index a2840292..cace04b2 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -13,9 +13,11 @@ import type { MentionExtraSend, MarkdownData, } from './proto/proton/action'; +import type { GroupFileExtra } from './proto/proton/element'; import { uploadImageMsgInfo } from './highway/image-upload'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; +import { hexToBytes } from './highway/pipeline'; type ProtoElem = Partial>; @@ -244,6 +246,55 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

({ + inner: { + info: { + busId: 102, + fileId: element.fileId, + fileSize: BigInt(fileSize), + fileName, + fileSha: sha1, + extInfoString: '', + fileMd5: md5, + }, + }, + }); + if (extraBytes.length > 0xFFFF) { + // The 16-bit length prefix caps the payload at 64 KiB; even the + // densest GroupFileExtra (fileId/name/two hashes) is well under. + // This is here so a future schema change can't silently truncate. + throw new Error(`group file extra too large (${extraBytes.length} > 65535)`); + } + const elemValue = new Uint8Array(3 + extraBytes.length); + elemValue[0] = 0x01; + elemValue[1] = (extraBytes.length >> 8) & 0xff; + elemValue[2] = extraBytes.length & 0xff; + elemValue.set(extraBytes, 3); + + return { + transElem: { + elemType: 24, + elemValue, + } as any, + }; +} + async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise { const isGroup = ctx.groupId !== undefined; const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? ''); @@ -331,6 +382,18 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte } break; + case 'file': + // The group `TransElem(24)` shape works for group chats only. + // C2C files live on `RichText.notOnlineFile` instead of in the + // elems array, so `sendPrivateMessage` short-circuits before it + // ever lands here — see `bridge.sendPrivateMessage`. + if (ctx?.groupId !== undefined) { + result.push(makeGroupFileElem(elem)); + } else { + console.warn('[ElemBuilder] file send via elems[] is group-only; use bridge.sendC2cFileMessage for c2c'); + } + break; + default: console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`); break; diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts index 638079e1..097cdcae 100644 --- a/packages/core/tests/actions/_helpers.ts +++ b/packages/core/tests/actions/_helpers.ts @@ -24,6 +24,13 @@ export interface MockBridge { fetchGroupMemberList: ReturnType; fetchUserProfile: ReturnType; resolveUserUid: ReturnType; + // High-level message senders. Default to no-op resolves so actions + // that fire off a follow-up chat message after their main work + // (e.g. `upload_group_file` → `sendGroupMessage` to publish the + // file in chat) don't crash test setups that don't care about it. + sendGroupMessage: ReturnType; + sendPrivateMessage: ReturnType; + sendC2cFileMessage: ReturnType; } export function mockBridge(overrides: Partial = {}): MockBridge { @@ -49,6 +56,9 @@ export function mockBridge(overrides: Partial = {}): MockBridge { fetchGroupMemberList: vi.fn(async () => []), fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })), resolveUserUid: vi.fn(async () => 'resolved-uid'), + sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), + sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), + sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), ...overrides, }; } diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 2a10edd9..54eb890a 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -136,6 +136,54 @@ describe('actions/group-file', () => { .rejects.toThrow(/code=999/); }); + it('uploadGroupFile publishes the file as a chat message 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 + // `sendGroupMessage` the file never appears in the chat. Asserts + // that `bridge.sendGroupMessage` is invoked with a single + // `{type:'file'}` element pointing at the uploaded fileId. + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt'); + expect(bridge.sendGroupMessage).toHaveBeenCalledOnce(); + const [groupId, elements] = bridge.sendGroupMessage.mock.calls[0]!; + expect(groupId).toBe(12345); + expect(elements).toHaveLength(1); + expect(elements[0]).toMatchObject({ + type: 'file', + fileId: 'fid-pub', + fileName: 'mynote.txt', + }); + }); + + it('uploadGroupFile skips the chat post when uploadFile=false', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false); + expect(bridge.sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => { + const bridge = mockBridge(); + vi.mocked(bridge.sendGroupMessage).mockRejectedValueOnce(new Error('message rejected')); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any }, + }), + ); + const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + expect(out).toEqual({ fileId: 'fid-tolerant' }); + expect(bridge.sendGroupMessage).toHaveBeenCalledOnce(); + }); + it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => { const bridge = mockBridge({ identity: { @@ -160,6 +208,40 @@ describe('actions/group-file', () => { expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); }); + it('uploadPrivateFile publishes the file via sendC2cFileMessage after upload', async () => { + // C2C files use `RichText.notOnlineFile` (not in the elems array), + // so `uploadPrivateFile` calls the dedicated `sendC2cFileMessage` + // path on the bridge rather than `sendPrivateMessage`. Same bug + // class as the group case — without this the recipient sees no + // message even though the bytes are on the server. + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/private-file.bin', 'doc.pdf'); + expect(bridge.sendC2cFileMessage).toHaveBeenCalledOnce(); + const [userUin, userUid, info] = bridge.sendC2cFileMessage.mock.calls[0]!; + expect(userUin).toBe(67890); + expect(userUid).toBe('target-uid'); + expect(info).toMatchObject({ fileId: 'pfid', fileName: 'doc.pdf', fileHash: 'phash' }); + expect(bridge.sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('uploadPrivateFile skips the chat post when uploadFile=false', async () => { + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file', '', false); + expect(bridge.sendC2cFileMessage).not.toHaveBeenCalled(); + }); + it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce(