From 6f506ff52c1db16f66853e54b71bf3a267ce75c3 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 11 May 2026 23:26:45 +0800 Subject: [PATCH] fix onebot video file sending --- packages/core/src/bridge/bridge.ts | 3 +- .../core/src/bridge/highway/ptt-upload.ts | 21 +------- packages/core/src/bridge/highway/utils.ts | 40 ++++++++++++--- .../core/src/bridge/highway/video-upload.ts | 17 ++----- packages/core/src/onebot/message-parser.ts | 26 +++++++--- .../core/tests/bridge-private-routing.test.ts | 50 +++++++++++++++++++ packages/core/tests/highway-utils.test.ts | 28 +++++++++++ packages/core/tests/message-parser.test.ts | 8 +++ 8 files changed, 145 insertions(+), 48 deletions(-) create mode 100644 packages/core/tests/bridge-private-routing.test.ts create mode 100644 packages/core/tests/highway-utils.test.ts diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index aabd6662..55ab4e64 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -470,7 +470,7 @@ export class Bridge { async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise { if (elements.length === 0) throw new Error('message is empty'); - // Resolve UID for image upload (C++ resolves UID before building elems) + // Resolve UID for media upload and the final c2c routing head. let userUid = ''; const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'); if (hasMedia) { @@ -485,6 +485,7 @@ export class Bridge { routingHead: { c2c: { uin: userUin, + ...(userUid ? { uid: userUid } : {}), }, } as any, contentHead: { diff --git a/packages/core/src/bridge/highway/ptt-upload.ts b/packages/core/src/bridge/highway/ptt-upload.ts index a95dd773..a02b2a07 100644 --- a/packages/core/src/bridge/highway/ptt-upload.ts +++ b/packages/core/src/bridge/highway/ptt-upload.ts @@ -21,7 +21,7 @@ import { NTV2UploadRichMediaRespSchema, EncodableMediaMsgInfoSchema, } from '../proto/highway'; -import { loadBinarySource, computeHashes } from './utils'; +import { loadBinarySource, computeHashes, resolveLocalFilePath } from './utils'; import { fetchHighwaySession, uploadHighwayHttp, @@ -49,23 +49,6 @@ interface PttPayload { cleanups: Array<() => void>; } -/** - * Decide whether `source` looks like a local filesystem path. The shape - * matches the heuristics used inside `loadBinarySource`: we only reuse the - * caller-supplied path verbatim for things the addon can read directly. - */ -function asLocalFilePath(source: string): string | null { - if (!source) return null; - if (source.startsWith('base64://')) return null; - if (source.startsWith('http://') || source.startsWith('https://')) return null; - - let filePath = source; - if (filePath.startsWith('file://')) filePath = filePath.slice(7); - if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1); - - return filePath; -} - async function loadPtt(element: MessageElement, tempDir: string): Promise { const source = element.url || element.fileId || ''; if (!source) throw new Error('record source is empty'); @@ -87,7 +70,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise { if (!source) throw new Error(`${resourceName} source is empty`); - if (source.startsWith('base64://')) { + if (/^base64:\/\//i.test(source)) { return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' }; } - if (source.startsWith('http://') || source.startsWith('https://')) { + if (/^https?:\/\//i.test(source)) { const resp = await fetch(source); if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); const bytes = new Uint8Array(await resp.arrayBuffer()); @@ -40,11 +69,8 @@ export async function loadBinarySource(source: string, resourceName: string): Pr return { bytes, fileName }; } - // File path (strip file:// prefix) - let filePath = source; - if (filePath.startsWith('file://')) filePath = filePath.slice(7); - // Windows: strip leading / before drive letter - if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1); + const filePath = resolveLocalFilePath(source); + if (!filePath) throw new Error(`${resourceName} source is not a local file`); const bytes = fs.readFileSync(filePath); const fileName = path.basename(filePath); diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index af9d4f73..d5351b10 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -26,6 +26,7 @@ import { loadBinarySource, computeHashes, detectImageFormat, + resolveLocalFilePath, } from './utils'; import { fetchHighwaySession, @@ -212,18 +213,6 @@ function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] { return blocks; } -function asLocalFilePath(source: string): string | null { - if (!source) return null; - if (source.startsWith('base64://')) return null; - if (source.startsWith('http://') || source.startsWith('https://')) return null; - - let filePath = source; - if (filePath.startsWith('file://')) filePath = filePath.slice(7); - if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1); - - return filePath; -} - function defaultVideoTempDir(): string { return path.join(os.tmpdir(), 'snowluma-video'); } @@ -232,7 +221,7 @@ function sourceExtension(fileName: string, source: string): string { const fromName = path.extname(fileName); if (fromName) return fromName; - const local = asLocalFilePath(source); + const local = resolveLocalFilePath(source); const fromSource = local ? path.extname(local) : ''; return fromSource || '.mp4'; } @@ -250,7 +239,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu const source = element.url || element.fileId || ''; if (!source) throw new Error('video source is empty'); - const local = asLocalFilePath(source); + const local = resolveLocalFilePath(source); if (local && fs.existsSync(local)) { return { bytes: new Uint8Array(fs.readFileSync(local)), diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index 68ca69f4..89339ef1 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -14,7 +14,7 @@ export interface ParseMessageOptions { // --- CQ Code parsing --- -const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g; +const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; function parseCQParams(raw: string): Record { const params: Record = {}; @@ -71,6 +71,7 @@ async function parseFromCQString(message: string, options?: ParseMessageOptions) interface MessageSegment { type: string; data?: Record; + [key: string]: unknown; } function isSegmentArray(val: unknown): val is MessageSegment[] { @@ -80,7 +81,8 @@ function isSegmentArray(val: unknown): val is MessageSegment[] { } async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { - switch (type) { + const normalizedType = type.toLowerCase(); + switch (normalizedType) { case 'text': { const text = String(data.text ?? ''); return text ? { type: 'text', text } : null; @@ -143,14 +145,14 @@ async function segmentToElement(type: string, data: Record, opt case 'image': { return { type: 'image', - url: String(data.file ?? data.url ?? ''), + url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''), flash: data.type === 'flash', subType: parseInt(String(data.subType ?? '0'), 10), summary: data.summary ? String(data.summary) : undefined, }; } case 'record': { - const source = String(data.file ?? data.url ?? data.path ?? ''); + const source = String(data.file ?? data.url ?? data.path ?? data.media ?? ''); if (!source) return null; return { type: 'record', @@ -158,7 +160,7 @@ async function segmentToElement(type: string, data: Record, opt }; } case 'video': { - const source = String(data.file ?? data.url ?? data.path ?? ''); + const source = String(data.file ?? data.url ?? data.path ?? data.media ?? ''); if (!source) return null; return { type: 'video', @@ -320,6 +322,16 @@ async function segmentToElement(type: string, data: Record, opt } } +function segmentPayload(seg: MessageSegment): Record { + const topLevel = { ...seg } as Record; + delete topLevel.type; + delete topLevel.data; + const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data)) + ? seg.data + : {}; + return { ...topLevel, ...nested }; +} + // --- Public API --- /** @@ -341,7 +353,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti if (isSegmentArray(message)) { const elements: MessageElement[] = []; for (const seg of message) { - const data = (seg.data ?? {}) as Record; + const data = segmentPayload(seg); const elem = await segmentToElement(seg.type, data, options); if (elem) elements.push(elem); } @@ -352,7 +364,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti if (typeof message === 'object' && message !== null && !Array.isArray(message)) { const seg = message as unknown as MessageSegment; if (seg.type) { - const data = (seg.data ?? {}) as Record; + const data = segmentPayload(seg); const elem = await segmentToElement(seg.type, data, options); return elem ? [elem] : []; } diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts new file mode 100644 index 00000000..a729a17b --- /dev/null +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { SendPacketResult } from '../src/protocol/packet-sender'; +import { protoDecode, protoEncode } from '../src/protobuf/decode'; +import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action'; + +vi.mock('../src/bridge/builders/element-builder', () => ({ + buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), +})); + +describe('Bridge private media routing', () => { + it('includes resolved uid in the final c2c send request for media messages', async () => { + const { Bridge } = await import('../src/bridge/bridge'); + const { QQInfo } = await import('../src/bridge/qq-info'); + + class TestBridge extends Bridge { + capturedBody: Uint8Array | null = null; + + override async resolveUserUid(uin: number): Promise { + expect(uin).toBe(12345); + return 'u_peer_12345'; + } + + override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise { + expect(serviceCmd).toBe('MessageSvc.PbSendMsg'); + this.capturedBody = body; + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protoEncode({ + result: 0, + privateSequence: 88, + timestamp1: 1710000000, + }, SendMessageResponseSchema)), + }; + } + } + + const bridge = new TestBridge(new QQInfo('10000')); + await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); + + expect(bridge.capturedBody).toBeInstanceOf(Uint8Array); + const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema); + expect(request?.routingHead?.c2c).toMatchObject({ + uin: 12345, + uid: 'u_peer_12345', + }); + }); +}); diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts new file mode 100644 index 00000000..087f22cd --- /dev/null +++ b/packages/core/tests/highway-utils.test.ts @@ -0,0 +1,28 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { pathToFileURL } from 'url'; +import { describe, expect, it } from 'vitest'; +import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils'; + +describe('highway source paths', () => { + it('normalizes file URLs with an extra leading slash on POSIX', () => { + if (process.platform === 'win32') return; + expect(resolveLocalFilePath('file:////AstrBot/data/plugin/cache/BV-test.mp4')) + .toBe('/AstrBot/data/plugin/cache/BV-test.mp4'); + }); + + it('loads encoded file URLs from the local filesystem', async () => { + const filePath = path.join(os.tmpdir(), `snowluma video ${process.pid}-${Date.now()}.txt`); + fs.writeFileSync(filePath, 'ok'); + + try { + const source = pathToFileURL(filePath).href; + const loaded = await loadBinarySource(source, 'test file'); + expect(Buffer.from(loaded.bytes).toString('utf8')).toBe('ok'); + expect(loaded.fileName).toBe(path.basename(filePath)); + } finally { + try { fs.unlinkSync(filePath); } catch { /* ignore */ } + } + }); +}); diff --git a/packages/core/tests/message-parser.test.ts b/packages/core/tests/message-parser.test.ts index d78205a0..d71c1303 100644 --- a/packages/core/tests/message-parser.test.ts +++ b/packages/core/tests/message-parser.test.ts @@ -108,6 +108,14 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]); }); + it('parses AstrBot-style Video segment with top-level media', async () => { + const result = await parseMessage( + [{ type: 'Video', media: 'file:////AstrBot/data/cache/BV-test.mp4' }] as any, + false, + ); + expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]); + }); + it('drops video segment with empty source', async () => { const result = await parseMessage( [{ type: 'video', data: {} }] as any,