fix onebot video file sending
This commit is contained in:
8 files changed
+145
-48
No files matched your search
@@ -470,7 +470,7 @@ export class Bridge {
|
|||||||
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||||
if (elements.length === 0) throw new Error('message is empty');
|
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 = '';
|
let userUid = '';
|
||||||
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
||||||
if (hasMedia) {
|
if (hasMedia) {
|
||||||
@@ -485,6 +485,7 @@ export class Bridge {
|
|||||||
routingHead: {
|
routingHead: {
|
||||||
c2c: {
|
c2c: {
|
||||||
uin: userUin,
|
uin: userUin,
|
||||||
|
...(userUid ? { uid: userUid } : {}),
|
||||||
},
|
},
|
||||||
} as any,
|
} as any,
|
||||||
contentHead: {
|
contentHead: {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
NTV2UploadRichMediaRespSchema,
|
NTV2UploadRichMediaRespSchema,
|
||||||
EncodableMediaMsgInfoSchema,
|
EncodableMediaMsgInfoSchema,
|
||||||
} from '../proto/highway';
|
} from '../proto/highway';
|
||||||
import { loadBinarySource, computeHashes } from './utils';
|
import { loadBinarySource, computeHashes, resolveLocalFilePath } from './utils';
|
||||||
import {
|
import {
|
||||||
fetchHighwaySession,
|
fetchHighwaySession,
|
||||||
uploadHighwayHttp,
|
uploadHighwayHttp,
|
||||||
@@ -49,23 +49,6 @@ interface PttPayload {
|
|||||||
cleanups: Array<() => void>;
|
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<PttPayload> {
|
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
||||||
const source = element.url || element.fileId || '';
|
const source = element.url || element.fileId || '';
|
||||||
if (!source) throw new Error('record source is empty');
|
if (!source) throw new Error('record source is empty');
|
||||||
@@ -87,7 +70,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
|||||||
// Resolve the on-disk path the addon should read. Anything that isn't
|
// Resolve the on-disk path the addon should read. Anything that isn't
|
||||||
// already a local file (base64, HTTP) gets staged into the temp dir.
|
// already a local file (base64, HTTP) gets staged into the temp dir.
|
||||||
let inputPath: string;
|
let inputPath: string;
|
||||||
const local = asLocalFilePath(source);
|
const local = resolveLocalFilePath(source);
|
||||||
if (local && fs.existsSync(local)) {
|
if (local && fs.existsSync(local)) {
|
||||||
inputPath = local;
|
inputPath = local;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
import { createHash } from 'crypto';
|
import { createHash } from 'crypto';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
export interface LoadedBinary {
|
export interface LoadedBinary {
|
||||||
bytes: Uint8Array;
|
bytes: Uint8Array;
|
||||||
@@ -25,14 +26,42 @@ export interface ImageFormat {
|
|||||||
|
|
||||||
// --- Binary source loading ---
|
// --- Binary source loading ---
|
||||||
|
|
||||||
|
export function resolveLocalFilePath(source: string): string | null {
|
||||||
|
if (!source) return null;
|
||||||
|
if (/^base64:\/\//i.test(source)) return null;
|
||||||
|
if (/^https?:\/\//i.test(source)) return null;
|
||||||
|
|
||||||
|
let filePath = source;
|
||||||
|
if (/^file:\/\//i.test(source)) {
|
||||||
|
try {
|
||||||
|
filePath = fileURLToPath(source);
|
||||||
|
} catch {
|
||||||
|
filePath = source.replace(/^file:\/+/i, '/');
|
||||||
|
try {
|
||||||
|
filePath = decodeURIComponent(filePath);
|
||||||
|
} catch {
|
||||||
|
// Keep the original fallback path when percent decoding fails.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.platform !== 'win32' && filePath.startsWith('//')) {
|
||||||
|
filePath = filePath.replace(/^\/+/, '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Windows-style paths can arrive from file:///C:/... as /C:/...
|
||||||
|
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
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: '' };
|
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);
|
const resp = await fetch(source);
|
||||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||||
@@ -40,11 +69,8 @@ export async function loadBinarySource(source: string, resourceName: string): Pr
|
|||||||
return { bytes, fileName };
|
return { bytes, fileName };
|
||||||
}
|
}
|
||||||
|
|
||||||
// File path (strip file:// prefix)
|
const filePath = resolveLocalFilePath(source);
|
||||||
let filePath = source;
|
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||||
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 bytes = fs.readFileSync(filePath);
|
const bytes = fs.readFileSync(filePath);
|
||||||
const fileName = path.basename(filePath);
|
const fileName = path.basename(filePath);
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import {
|
|||||||
loadBinarySource,
|
loadBinarySource,
|
||||||
computeHashes,
|
computeHashes,
|
||||||
detectImageFormat,
|
detectImageFormat,
|
||||||
|
resolveLocalFilePath,
|
||||||
} from './utils';
|
} from './utils';
|
||||||
import {
|
import {
|
||||||
fetchHighwaySession,
|
fetchHighwaySession,
|
||||||
@@ -212,18 +213,6 @@ function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
|
|||||||
return blocks;
|
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 {
|
function defaultVideoTempDir(): string {
|
||||||
return path.join(os.tmpdir(), 'snowluma-video');
|
return path.join(os.tmpdir(), 'snowluma-video');
|
||||||
}
|
}
|
||||||
@@ -232,7 +221,7 @@ function sourceExtension(fileName: string, source: string): string {
|
|||||||
const fromName = path.extname(fileName);
|
const fromName = path.extname(fileName);
|
||||||
if (fromName) return fromName;
|
if (fromName) return fromName;
|
||||||
|
|
||||||
const local = asLocalFilePath(source);
|
const local = resolveLocalFilePath(source);
|
||||||
const fromSource = local ? path.extname(local) : '';
|
const fromSource = local ? path.extname(local) : '';
|
||||||
return fromSource || '.mp4';
|
return fromSource || '.mp4';
|
||||||
}
|
}
|
||||||
@@ -250,7 +239,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
|
|||||||
const source = element.url || element.fileId || '';
|
const source = element.url || element.fileId || '';
|
||||||
if (!source) throw new Error('video source is empty');
|
if (!source) throw new Error('video source is empty');
|
||||||
|
|
||||||
const local = asLocalFilePath(source);
|
const local = resolveLocalFilePath(source);
|
||||||
if (local && fs.existsSync(local)) {
|
if (local && fs.existsSync(local)) {
|
||||||
return {
|
return {
|
||||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export interface ParseMessageOptions {
|
|||||||
|
|
||||||
// --- CQ Code parsing ---
|
// --- CQ Code parsing ---
|
||||||
|
|
||||||
const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g;
|
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
|
||||||
|
|
||||||
function parseCQParams(raw: string): Record<string, string> {
|
function parseCQParams(raw: string): Record<string, string> {
|
||||||
const params: Record<string, string> = {};
|
const params: Record<string, string> = {};
|
||||||
@@ -71,6 +71,7 @@ async function parseFromCQString(message: string, options?: ParseMessageOptions)
|
|||||||
interface MessageSegment {
|
interface MessageSegment {
|
||||||
type: string;
|
type: string;
|
||||||
data?: Record<string, unknown>;
|
data?: Record<string, unknown>;
|
||||||
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isSegmentArray(val: unknown): val is MessageSegment[] {
|
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<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||||
switch (type) {
|
const normalizedType = type.toLowerCase();
|
||||||
|
switch (normalizedType) {
|
||||||
case 'text': {
|
case 'text': {
|
||||||
const text = String(data.text ?? '');
|
const text = String(data.text ?? '');
|
||||||
return text ? { type: 'text', text } : null;
|
return text ? { type: 'text', text } : null;
|
||||||
@@ -143,14 +145,14 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
|||||||
case 'image': {
|
case 'image': {
|
||||||
return {
|
return {
|
||||||
type: 'image',
|
type: 'image',
|
||||||
url: String(data.file ?? data.url ?? ''),
|
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
|
||||||
flash: data.type === 'flash',
|
flash: data.type === 'flash',
|
||||||
subType: parseInt(String(data.subType ?? '0'), 10),
|
subType: parseInt(String(data.subType ?? '0'), 10),
|
||||||
summary: data.summary ? String(data.summary) : undefined,
|
summary: data.summary ? String(data.summary) : undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case 'record': {
|
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;
|
if (!source) return null;
|
||||||
return {
|
return {
|
||||||
type: 'record',
|
type: 'record',
|
||||||
@@ -158,7 +160,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
case 'video': {
|
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;
|
if (!source) return null;
|
||||||
return {
|
return {
|
||||||
type: 'video',
|
type: 'video',
|
||||||
@@ -320,6 +322,16 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||||
|
const topLevel = { ...seg } as Record<string, unknown>;
|
||||||
|
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 ---
|
// --- Public API ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -341,7 +353,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
|
|||||||
if (isSegmentArray(message)) {
|
if (isSegmentArray(message)) {
|
||||||
const elements: MessageElement[] = [];
|
const elements: MessageElement[] = [];
|
||||||
for (const seg of message) {
|
for (const seg of message) {
|
||||||
const data = (seg.data ?? {}) as Record<string, unknown>;
|
const data = segmentPayload(seg);
|
||||||
const elem = await segmentToElement(seg.type, data, options);
|
const elem = await segmentToElement(seg.type, data, options);
|
||||||
if (elem) elements.push(elem);
|
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)) {
|
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
|
||||||
const seg = message as unknown as MessageSegment;
|
const seg = message as unknown as MessageSegment;
|
||||||
if (seg.type) {
|
if (seg.type) {
|
||||||
const data = (seg.data ?? {}) as Record<string, unknown>;
|
const data = segmentPayload(seg);
|
||||||
const elem = await segmentToElement(seg.type, data, options);
|
const elem = await segmentToElement(seg.type, data, options);
|
||||||
return elem ? [elem] : [];
|
return elem ? [elem] : [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<string> {
|
||||||
|
expect(uin).toBe(12345);
|
||||||
|
return 'u_peer_12345';
|
||||||
|
}
|
||||||
|
|
||||||
|
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||||
|
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',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 */ }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -108,6 +108,14 @@ describe('parseMessage', () => {
|
|||||||
expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]);
|
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 () => {
|
it('drops video segment with empty source', async () => {
|
||||||
const result = await parseMessage(
|
const result = await parseMessage(
|
||||||
[{ type: 'video', data: {} }] as any,
|
[{ type: 'video', data: {} }] as any,
|
||||||
|
|||||||
Reference in new issue
Block a user