refactor(packages): rename @snowluma/bridge → @snowluma/protocol
The package previously named "bridge" houses the protocol-byte layer (OIDB cmds, msg-push decoders, highway uploaders, element-builder, event bus). The name "bridge" suggested transport/lifecycle, which it isn't — that role lives in core/hook and core/bridge/manager. Rename to match what's actually inside. This is a pure rename: zero logic changes, all 73 import sites updated mechanically and TS-verified. core/onebot dependencies key updated. ESLint override path adjusted for the moved oidb-services directory. Rename detection threshold: git log --find-renames=20% recommended when following history across this commit — content-replacement (@snowluma/bridge → @snowluma/protocol) dropped per-file similarity below git's default 50% on import-heavy files.
This commit is contained in:
238 files changed
+247
-284
No files matched your search
@@ -0,0 +1,154 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface FFmpegVideoInfo {
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
format: string;
|
||||
videoCodec: string;
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
interface FFmpegNativeAddon {
|
||||
convertFile(inputFile: string, outputFile: string, format: string): Promise<{ success: boolean }>;
|
||||
getVideoInfo(filePath: string, format?: 'bmp' | 'bmp24'): Promise<FFmpegVideoInfo>;
|
||||
getDuration(filePath: string): Promise<number>;
|
||||
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
|
||||
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
|
||||
decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>;
|
||||
}
|
||||
|
||||
let cachedAddon: FFmpegNativeAddon | null = null;
|
||||
let cachedLoadError: string | null = null;
|
||||
|
||||
function addonFileName(): string {
|
||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||
}
|
||||
|
||||
function addonSearchDirs(): string[] {
|
||||
// Mirrors the hook injector's resolution strategy so the addon is found
|
||||
// regardless of whether we're running from:
|
||||
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
|
||||
// the dist root.
|
||||
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
|
||||
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
|
||||
// __dirname is `packages/core/src/bridge/highway` — four levels deep
|
||||
// under `packages/`. Note: the hook injector lives at
|
||||
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
|
||||
return [
|
||||
path.resolve(__dirname, 'native', 'ffmpeg'),
|
||||
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveAddonPath(): string | null {
|
||||
const fileName = addonFileName();
|
||||
for (const dir of addonSearchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
if (fs.existsSync(full)) return full;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the ffmpegAddon once and return a cached instance.
|
||||
* Throws on first-use failure; subsequent calls replay the same error message
|
||||
* so callers don't silently fall back.
|
||||
*/
|
||||
export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
if (cachedAddon) return cachedAddon;
|
||||
if (cachedLoadError) throw new Error(cachedLoadError);
|
||||
|
||||
const addonPath = resolveAddonPath();
|
||||
if (!addonPath) {
|
||||
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
|
||||
return cachedAddon;
|
||||
} catch (error) {
|
||||
cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether `filePath` is already an NT SILK container. The addon can
|
||||
* read any input directly so the only reason we peek at the header is to
|
||||
* skip the conversion (and the temp file) when the caller already fed us
|
||||
* a ready-to-upload silk file.
|
||||
*/
|
||||
export function isSilkFile(filePath: string): boolean {
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(10);
|
||||
fs.readSync(fd, buf, 0, 10, 0);
|
||||
const header = buf.toString();
|
||||
return header.includes('#!SILK') || header.includes('\x02#!SILK');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface EncodeSilkResult {
|
||||
/** Absolute path to the silk file ready for highway upload. */
|
||||
path: string;
|
||||
/** Voice duration in whole seconds (>= 1). */
|
||||
duration: number;
|
||||
/** `true` if we wrote a new silk file and the caller should unlink it. */
|
||||
converted: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert `inputFile` to NT SILK when necessary and return the output path
|
||||
* + duration. The caller is responsible for unlinking the returned path
|
||||
* when `converted === true`.
|
||||
*/
|
||||
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
|
||||
const addon = getFFmpegAddon();
|
||||
|
||||
// Already silk — trust the file, just measure duration via the addon.
|
||||
if (isSilkFile(inputFile)) {
|
||||
let duration = 1;
|
||||
try {
|
||||
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
} catch {
|
||||
// getDuration on a silk file occasionally fails on certain encodings;
|
||||
// the upload path only needs a rough, non-zero value, so fall back
|
||||
// to the size-based heuristic used by NapCat's audio.ts.
|
||||
const stat = fs.statSync(inputFile);
|
||||
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
|
||||
}
|
||||
return { path: inputFile, duration, converted: false };
|
||||
}
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
const outPath = path.join(tempDir, crypto.randomUUID());
|
||||
await addon.convertToNTSilkTct(inputFile, outPath);
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('convertToNTSilkTct produced no output file');
|
||||
}
|
||||
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
return { path: outPath, duration, converted: true };
|
||||
}
|
||||
|
||||
/** Default location for temporary silk files. */
|
||||
export function defaultPttTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-ptt');
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import net from 'net';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type {
|
||||
HttpConn0x6FF501Request,
|
||||
HttpConn0x6FF501Response,
|
||||
NTV2RichMediaHighwayExt,
|
||||
ReqDataHighwayHead,
|
||||
RespDataHighwayHead,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
|
||||
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
export const PRIVATE_IMAGE_CMD_ID = 1003;
|
||||
export const GROUP_IMAGE_CMD_ID = 1004;
|
||||
|
||||
export interface HighwaySession {
|
||||
sigSession: Uint8Array;
|
||||
sessionKey: Uint8Array;
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
function ipv4ToString(value: number): string {
|
||||
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
|
||||
}
|
||||
|
||||
export async function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
|
||||
const request = protobuf_encode<HttpConn0x6FF501Request>({
|
||||
httpConn: {
|
||||
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||
serviceTypes: [1, 5, 10, 21],
|
||||
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||
},
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
|
||||
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||
throw new Error('HttpConn response missing sig_session');
|
||||
}
|
||||
|
||||
const session: HighwaySession = {
|
||||
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||
host: 'htdata3.qq.com',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||
for (const addr of si.serverAddrs) {
|
||||
const ip = addr.ip ?? 0;
|
||||
const port = addr.port ?? 0;
|
||||
if (ip && port) {
|
||||
session.host = ipv4ToString(ip);
|
||||
session.port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
|
||||
return session;
|
||||
}
|
||||
|
||||
function makeHighwayHead(
|
||||
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<ReqDataHighwayHead>({
|
||||
msgBaseHead: {
|
||||
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
|
||||
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
|
||||
},
|
||||
msgSegHead: {
|
||||
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
|
||||
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
|
||||
},
|
||||
bytesReqExtendInfo: extend,
|
||||
timestamp: 0n,
|
||||
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
|
||||
});
|
||||
}
|
||||
|
||||
export function buildHighwayExtend(
|
||||
uKey: string,
|
||||
msgInfo: any,
|
||||
ipv4s: any[],
|
||||
sha1: Uint8Array | Uint8Array[],
|
||||
fileIndex = 0,
|
||||
): Uint8Array {
|
||||
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
|
||||
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
|
||||
|
||||
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
|
||||
const networkIpv4s: any[] = [];
|
||||
for (const ipv4 of ipv4s ?? []) {
|
||||
const ip = ipv4.outIp ?? 0;
|
||||
const port = ipv4.outPort ?? 0;
|
||||
if (ip && port) {
|
||||
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
|
||||
}
|
||||
}
|
||||
|
||||
return protobuf_encode<NTV2RichMediaHighwayExt>({
|
||||
fileUuid: selected?.index?.fileUuid ?? '',
|
||||
uKey,
|
||||
network: { ipv4s: networkIpv4s },
|
||||
msgInfoBody: msgInfoBody.map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
})),
|
||||
blockSize: HIGHWAY_BLOCK_SIZE,
|
||||
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
|
||||
});
|
||||
}
|
||||
|
||||
// --- TCP-based HTTP highway upload ---
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const onTimeout = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
reject(new Error('TCP connect timeout'));
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(err);
|
||||
};
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
// Drop the connect-only listeners so subsequent IO errors / idle
|
||||
// timeouts don't try to reject this already-resolved promise.
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
resolve(socket);
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.once('timeout', onTimeout);
|
||||
socket.once('error', onError);
|
||||
});
|
||||
}
|
||||
|
||||
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.write(data, (err) => err ? reject(err) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
|
||||
const detach = () => {
|
||||
socket.off('data', onData);
|
||||
socket.off('error', onError);
|
||||
socket.off('close', onClose);
|
||||
};
|
||||
const finish = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
detach();
|
||||
fn();
|
||||
};
|
||||
const onData = (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
if (idx >= 0) {
|
||||
headerEnd = idx + 4;
|
||||
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
|
||||
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
|
||||
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
|
||||
totalNeeded = headerEnd + contentLength;
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
|
||||
}
|
||||
};
|
||||
const onError = (err: Error) => finish(() => reject(err));
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
socket.on('error', onError);
|
||||
socket.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
async function httpPostFrame(
|
||||
socket: net.Socket, host: string, path: string, body: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
if (body.length > 0) await socketWrite(socket, body);
|
||||
return readHttpResponseBody(socket);
|
||||
}
|
||||
|
||||
export async function uploadHighwayHttp(
|
||||
bridge: BridgeContext, session: HighwaySession, commandId: number,
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
// Surface every diagnostic the highway response carries so
|
||||
// user reports of `error_code=921` and friends include the
|
||||
// server-side context (segHead.retCode, chunk size, file md5)
|
||||
// — without these we can't tell apart a malformed-payload
|
||||
// reject, a session-ticket mismatch, or a per-account rate-
|
||||
// limit.
|
||||
const segRetCode = resp.msgSegHead?.retCode ?? 0;
|
||||
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
|
||||
throw new Error(
|
||||
`highway upload error_code=${resp.errorCode}` +
|
||||
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
|
||||
` offset=${offset} segRetCode=${segRetCode}` +
|
||||
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
|
||||
);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
function loggerFor(bridge: BridgeContext) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
interface ImageData {
|
||||
/** Empty when the caller is forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
summary: string;
|
||||
subType: number;
|
||||
width: number;
|
||||
height: number;
|
||||
picFormat: number;
|
||||
/** True when `bytes` is empty; runNtv2Upload throws fastOnlyError if
|
||||
* the server demands the bytes anyway. */
|
||||
fastOnly: boolean;
|
||||
}
|
||||
|
||||
function imageDataFromFingerprint(element: MessageElement): ImageData {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
// QQ ecosystem convention — mobile QQ + Lagrange.Core + NapCat all
|
||||
// surface these exact Chinese strings as the chat-list bubble
|
||||
// preview text. English fallbacks would render `[image]` /
|
||||
// `[sticker]` in QQ users' chat lists instead of the expected
|
||||
// `[图片]` / `[动画表情]`. Cross-checked against:
|
||||
// dev/NapCatQQ/.../packet/message/element.ts:367-371
|
||||
// dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192
|
||||
summary: element.summary || (element.subType === 1 ? '[动画表情]' : '[图片]'),
|
||||
subType: element.subType ?? 0,
|
||||
width: element.width ?? 0,
|
||||
height: element.height ?? 0,
|
||||
picFormat: element.picFormat ?? 1000,
|
||||
fastOnly: true,
|
||||
};
|
||||
}
|
||||
|
||||
function loadImage(element: MessageElement): Promise<ImageData> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
return Promise.reject(new Error('image fast-upload requires md5Hex + sha1Hex'));
|
||||
}
|
||||
return Promise.resolve(imageDataFromFingerprint(element));
|
||||
}
|
||||
return loadImageFromSource(
|
||||
element.url || element.fileId || '',
|
||||
element.fileName ?? '',
|
||||
element.subType ?? 0,
|
||||
element.summary ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
|
||||
const loaded = await loadBinarySource(source, 'image');
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fmt = detectImageFormat(loaded.bytes);
|
||||
|
||||
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
|
||||
const ext = extMap[fmt.format] ?? '.jpg';
|
||||
|
||||
let finalName = fileName || loaded.fileName;
|
||||
if (!finalName) finalName = hashes.md5Hex + ext;
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: finalName,
|
||||
fileSize: loaded.bytes.length,
|
||||
summary: summary || (subType === 1 ? '[动画表情]' : '[图片]'),
|
||||
subType,
|
||||
width: fmt.width,
|
||||
height: fmt.height,
|
||||
picFormat: fmt.format,
|
||||
fastOnly: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image and return the encoded MsgInfo bytes for the outgoing
|
||||
* commonElem.
|
||||
*/
|
||||
export async function uploadImageMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID,
|
||||
bytes: image.bytes,
|
||||
md5: image.md5,
|
||||
sha1: image.sha1,
|
||||
fastOnlyError: 'image fast-upload not available (server requires bytes)',
|
||||
}];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: image.fileSize,
|
||||
fileHash: image.md5Hex,
|
||||
fileSha1: image.sha1Hex,
|
||||
fileName: image.fileName,
|
||||
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
time: 0,
|
||||
original: 1,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
pic: {
|
||||
bizType: image.subType,
|
||||
textSummary: image.summary,
|
||||
...(isGroup
|
||||
? { reserveTroop: { subType: image.subType } }
|
||||
: { reserveC2c: { subType: image.subType } }),
|
||||
},
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'image',
|
||||
});
|
||||
|
||||
return finalizeMediaMsgInfo(upload, { bizType: image.subType, textSummary: image.summary });
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import crypto from 'crypto';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { makeOidbEnvelope } from '../bridge-oidb';
|
||||
import type {
|
||||
EncodableMediaMsgInfo,
|
||||
NTV2UploadRichMediaReq,
|
||||
NTV2UploadRichMediaResp,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
// ─────────────── public types ───────────────
|
||||
|
||||
/**
|
||||
* Highway upload spec for one sub-file of an NTV2 upload response.
|
||||
* The server returns 0..N sub-files; for each we either fast-path (skip)
|
||||
* or do an HTTP PUT.
|
||||
*/
|
||||
export interface MediaSubFileUpload {
|
||||
/**
|
||||
* Where to read uKey + ipv4s from on the OIDB response:
|
||||
* 'top' -> `upload.uKey` + `upload.ipv4s` (main file)
|
||||
* N (int) -> `upload.subFileInfos[N].uKey` + `.ipv4s` (sub-file)
|
||||
*
|
||||
* Image and PTT use 'top' only. Video uses 'top' (main) and 0 (thumb).
|
||||
*/
|
||||
source: 'top' | number;
|
||||
/** Highway command id for this sub-file. */
|
||||
cmdId: number;
|
||||
/** Bytes to upload. Empty when the caller is forwarding from cached
|
||||
* fingerprints; in that case set fastOnlyError so we throw with a
|
||||
* typed message when the server actually demands the bytes. */
|
||||
bytes: Uint8Array;
|
||||
/** md5 used for the highway request. */
|
||||
md5: Uint8Array;
|
||||
/** sha1 — single buffer or per-1MB block array. Passed verbatim to
|
||||
* buildHighwayExtend. */
|
||||
sha1: Uint8Array | Uint8Array[];
|
||||
/** subFileIndex argument for buildHighwayExtend. Defaults to 0;
|
||||
* video thumb passes 1. */
|
||||
subFileIndex?: number;
|
||||
/** Error message to throw when uKey is present but `bytes.length === 0`.
|
||||
* Omit if the caller guarantees bytes always exist (e.g. video thumb
|
||||
* always has FALLBACK_THUMB bytes). */
|
||||
fastOnlyError?: string;
|
||||
}
|
||||
|
||||
export interface NtV2UploadParams {
|
||||
bridge: BridgeContext;
|
||||
isGroup: boolean;
|
||||
/** Group uin when isGroup, otherwise the recipient's uid string. */
|
||||
targetIdOrUid: string | number;
|
||||
/** OIDB command id (e.g. 0x11C4 / 0x11C5 / 0x126E / 0x126D / 0x11EA / 0x11E9). */
|
||||
oidbCmd: number;
|
||||
/** Service cmd (e.g. 'OidbSvcTrpcTcp.0x11c4_100'). */
|
||||
serviceCmd: string;
|
||||
/** `reqHead.common.requestId`. NTV2 sub-protocols use different values
|
||||
* here (image=1, video=3, ptt = group:1 / c2c:4). */
|
||||
requestId: number;
|
||||
/** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */
|
||||
businessType: number;
|
||||
/** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */
|
||||
uploadInfo: unknown[];
|
||||
/** `upload.compatQmsgSceneType`. */
|
||||
compatQmsgSceneType: number;
|
||||
/** `upload.extBizInfo` — type-specific bytes/flags. */
|
||||
extBizInfo: unknown;
|
||||
/** Sub-file Highway PUTs to perform after the OIDB response. */
|
||||
uploads: MediaSubFileUpload[];
|
||||
/** Used in error messages. Defaults to 'media'. */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
// ─────────────── helpers ───────────────
|
||||
|
||||
/**
|
||||
* 8 random bytes masked into the positive int64 range so the resulting
|
||||
* BigInt survives signed-int64 protobuf encoding without surprises.
|
||||
* Mirrors NapCat.
|
||||
*/
|
||||
export function makeClientRandomId(): bigint {
|
||||
const buf = crypto.randomBytes(8);
|
||||
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
|
||||
}
|
||||
|
||||
/** Hex string -> Uint8Array. Used by every format's fingerprint path. */
|
||||
export function hexToBytes(hex: string): Uint8Array {
|
||||
const clean = hex.length % 2 === 0 ? hex : '0' + hex;
|
||||
const out = new Uint8Array(clean.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─────────────── main entrypoint ───────────────
|
||||
|
||||
/**
|
||||
* Send a NTV2UploadRichMediaReq and run any Highway PUTs the server asks
|
||||
* for. Returns the decoded `upload` object so the caller can pass it to
|
||||
* `finalizeMediaMsgInfo`.
|
||||
*
|
||||
* Sessions are cached across sub-file uploads — video does two PUTs but
|
||||
* only fetches the Highway session once.
|
||||
*/
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
// Build the full body once. Pulling this in here means each format file
|
||||
// only specifies the seven fields that actually vary.
|
||||
const body: any = {
|
||||
reqHead: {
|
||||
common: { requestId: params.requestId, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: params.businessType,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: params.uploadInfo,
|
||||
tryFastUploadCompleted: true,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
|
||||
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
|
||||
|
||||
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || `${label} upload request failed`);
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
|
||||
if (!resp) throw new Error(`failed to decode ${label} upload response`);
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody: any = resp.body;
|
||||
if (!uploadBody) throw new Error(`${label} upload response body missing`);
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
|
||||
}
|
||||
const upload = uploadBody.upload;
|
||||
if (!upload) throw new Error(`${label} upload response body missing`);
|
||||
|
||||
// Highway PUTs. Session is lazily fetched and cached — video does two
|
||||
// PUTs (main + thumb) and shouldn't pay for two sessions.
|
||||
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
|
||||
const getSession = async () => {
|
||||
session ??= await fetchHighwaySession(bridge);
|
||||
return session;
|
||||
};
|
||||
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
// Either the server fast-pathed this sub-file (no uKey) or msgInfo is
|
||||
// missing entirely; either way nothing to push.
|
||||
if (!uKey || !upload.msgInfo) continue;
|
||||
|
||||
if (sub.bytes.length === 0) {
|
||||
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
|
||||
continue;
|
||||
}
|
||||
|
||||
const extend = buildHighwayExtend(
|
||||
uKey,
|
||||
upload.msgInfo,
|
||||
target.ipv4s ?? [],
|
||||
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
|
||||
return upload;
|
||||
}
|
||||
|
||||
// ─────────────── shared finalize ───────────────
|
||||
|
||||
/**
|
||||
* Build the encoded MsgInfo bytes that go inside the outgoing commonElem.
|
||||
*
|
||||
* `defaultPic` is the image-only fall-back: image uploads inject
|
||||
* `bizType` + `textSummary` defaults when the server response omits the
|
||||
* `pic` ext-biz-info. PTT and video pass `undefined` here — they leave
|
||||
* pic alone unless the server populates it.
|
||||
*/
|
||||
export function finalizeMediaMsgInfo(
|
||||
upload: any,
|
||||
defaultPic?: { bizType: number; textSummary: string },
|
||||
): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
}));
|
||||
|
||||
const extBizInfo: any = {};
|
||||
if (upload.msgInfo.extBizInfo?.pic) {
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
|
||||
if (defaultPic) {
|
||||
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? defaultPic.bizType;
|
||||
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? defaultPic.textSummary;
|
||||
}
|
||||
} else if (defaultPic) {
|
||||
extBizInfo.pic = { bizType: defaultPic.bizType, textSummary: defaultPic.textSummary };
|
||||
}
|
||||
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
|
||||
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
|
||||
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
|
||||
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
|
||||
}
|
||||
|
||||
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
|
||||
function loggerFor(bridge: BridgeContext) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
|
||||
interface PttPayload {
|
||||
/** Silk bytes uploaded to Highway. Empty when forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
/** Whole seconds, >= 1. */
|
||||
duration: number;
|
||||
voiceFormat: number;
|
||||
/** True when bytes is empty; pipeline throws fastOnlyError if the
|
||||
* server demands the bytes anyway. */
|
||||
fastOnly: boolean;
|
||||
/** Cleanup hooks for any temp silk files staged during loadPtt. */
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'record'}.amr`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
duration: element.duration ?? 1,
|
||||
// Voice format: 1 = silk (NTV2 standard). Honour any fingerprint that
|
||||
// declares a different format; legacy NTQQ paths all use 1.
|
||||
voiceFormat: element.voiceFormat || 1,
|
||||
fastOnly: true,
|
||||
cleanups: [],
|
||||
};
|
||||
}
|
||||
|
||||
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('record fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
return pttPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('record source is empty');
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
// Run all queued cleanups; called both on the success path (via the
|
||||
// returned `cleanups` array) and on the failure path (try/catch below).
|
||||
const runCleanups = () => {
|
||||
while (cleanups.length > 0) {
|
||||
const fn = cleanups.pop();
|
||||
if (!fn) continue;
|
||||
try { fn(); } catch { /* best-effort */ }
|
||||
}
|
||||
};
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
// 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.
|
||||
let inputPath: string;
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
inputPath = local;
|
||||
} else {
|
||||
const loaded = await loadBinarySource(source, 'record');
|
||||
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
|
||||
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
|
||||
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
|
||||
}
|
||||
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
||||
|
||||
const hashes = computeHashes(silkBytes);
|
||||
return {
|
||||
bytes: silkBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: `${hashes.md5Hex}.amr`,
|
||||
fileSize: silkBytes.length,
|
||||
duration: silk.duration,
|
||||
voiceFormat: 1,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
|
||||
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
||||
*/
|
||||
export async function uploadPttMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
|
||||
ptt.fileSize,
|
||||
ptt.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
ptt.duration);
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID,
|
||||
bytes: ptt.bytes,
|
||||
md5: ptt.md5,
|
||||
sha1: ptt.sha1,
|
||||
fastOnlyError: 'record fast-upload not available (server requires bytes)',
|
||||
}];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x126E : 0x126D,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100',
|
||||
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
|
||||
requestId: isGroup ? 1 : 4,
|
||||
businessType: 3,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: ptt.fileSize,
|
||||
fileHash: ptt.md5Hex,
|
||||
fileSha1: ptt.sha1Hex,
|
||||
fileName: ptt.fileName,
|
||||
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: ptt.voiceFormat },
|
||||
width: 0,
|
||||
height: 0,
|
||||
time: ptt.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
// NapCat fills in a placeholder textSummary so the legacy compat
|
||||
// QMsg path still has something to render. Mirror it.
|
||||
pic: { textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
|
||||
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
|
||||
bytesGeneralFlags: isGroup
|
||||
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
|
||||
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'ptt',
|
||||
});
|
||||
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default cap on a single binary load issued through this helper. Callers
|
||||
* that route here (image / voice via base64+HTTP, group/private file
|
||||
* uploads, avatar) get bounded reads. Not all callers route through here
|
||||
* — in particular `video-upload.stageVideoSource` reads local-video files
|
||||
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
|
||||
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
|
||||
* file protocol legitimately supports up to 4 GiB.
|
||||
*/
|
||||
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
}
|
||||
|
||||
export interface ImageFormat {
|
||||
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// --- 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,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
const bytes = Buffer.from(source.slice(9), 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
// Stream the body incrementally so a server that omits or
|
||||
// understates Content-Length can't make us buffer a chunked response
|
||||
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
|
||||
// the entire payload before we get a chance to length-check it.
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.size > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
function guessFileNameFromUrl(url: string): string {
|
||||
const queryPos = url.search(/[?#]/);
|
||||
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||
}
|
||||
|
||||
// --- Hashing ---
|
||||
|
||||
export function computeHashes(data: Uint8Array): ImageHashes {
|
||||
const md5 = createHash('md5').update(data).digest();
|
||||
const sha1 = createHash('sha1').update(data).digest();
|
||||
return {
|
||||
md5: new Uint8Array(md5),
|
||||
sha1: new Uint8Array(sha1),
|
||||
md5Hex: md5.toString('hex'),
|
||||
sha1Hex: sha1.toString('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
export function computeMd5(data: Uint8Array): Uint8Array {
|
||||
return new Uint8Array(createHash('md5').update(data).digest());
|
||||
}
|
||||
|
||||
// --- Image format detection (port of C++ detect_image_format) ---
|
||||
|
||||
function readBE16(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 8) | data[offset + 1];
|
||||
}
|
||||
|
||||
function readBE32(data: Uint8Array, offset: number): number {
|
||||
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
|
||||
}
|
||||
|
||||
function readLE16(data: Uint8Array, offset: number): number {
|
||||
return data[offset] | (data[offset + 1] << 8);
|
||||
}
|
||||
|
||||
function readLE32(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
|
||||
}
|
||||
|
||||
function readBE24(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
|
||||
}
|
||||
|
||||
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
|
||||
// PNG
|
||||
if (bytes.length >= 24 &&
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
width = readBE32(bytes, 16);
|
||||
height = readBE32(bytes, 20);
|
||||
return { format: 1001, width, height };
|
||||
}
|
||||
|
||||
// GIF
|
||||
if (bytes.length >= 10 &&
|
||||
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
|
||||
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
|
||||
width = readLE16(bytes, 6);
|
||||
height = readLE16(bytes, 8);
|
||||
return { format: 2000, width, height };
|
||||
}
|
||||
|
||||
// BMP
|
||||
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
|
||||
width = readLE32(bytes, 18);
|
||||
height = readLE32(bytes, 22);
|
||||
return { format: 1005, width, height };
|
||||
}
|
||||
|
||||
// WebP
|
||||
if (bytes.length >= 30 &&
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
|
||||
width = readLE16(bytes, 26);
|
||||
height = readLE16(bytes, 28);
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
|
||||
const bits = readLE32(bytes, 21);
|
||||
width = (bits & 0x3FFF) + 1;
|
||||
height = ((bits >> 14) & 0x3FFF) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
|
||||
width = readBE24(bytes, 24) + 1;
|
||||
height = readBE24(bytes, 27) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
}
|
||||
|
||||
// JPEG
|
||||
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
|
||||
let offset = 2;
|
||||
while (offset + 9 <= bytes.length) {
|
||||
if (bytes[offset] !== 0xFF) { offset++; continue; }
|
||||
const marker = bytes[offset + 1];
|
||||
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
|
||||
if (offset + 4 > bytes.length) break;
|
||||
const segLen = readBE16(bytes, offset + 2);
|
||||
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||
// Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC
|
||||
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
|
||||
// and friends, then misread Huffman table bytes as image dimensions.
|
||||
const isSof = marker >= 0xC0 && marker <= 0xCF
|
||||
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
|
||||
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
}
|
||||
offset += 2 + segLen;
|
||||
}
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
// --- Highway frame packing/unpacking ---
|
||||
|
||||
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
|
||||
const frame = new Uint8Array(9 + head.length + body.length + 1);
|
||||
frame[0] = 0x28;
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
dv.setUint32(1, head.length, false);
|
||||
dv.setUint32(5, body.length, false);
|
||||
frame.set(head, 9);
|
||||
frame.set(body, 9 + head.length);
|
||||
frame[frame.length - 1] = 0x29;
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
|
||||
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
|
||||
throw new Error('invalid highway response frame');
|
||||
}
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
const headLen = dv.getUint32(1, false);
|
||||
const bodyLen = dv.getUint32(5, false);
|
||||
return {
|
||||
head: frame.subarray(9, 9 + headLen),
|
||||
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { getFFmpegAddon } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import {
|
||||
computeHashes,
|
||||
detectImageFormat,
|
||||
loadBinarySource,
|
||||
resolveLocalFilePath,
|
||||
} from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Video');
|
||||
|
||||
function loggerFor(bridge: BridgeContext) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_VIDEO_CMD_ID = 1001;
|
||||
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;
|
||||
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
const FALLBACK_THUMB = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
|
||||
interface VideoPayload {
|
||||
/** Video bytes. Empty when forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
sha1Blocks: Uint8Array[];
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
videoFormat: number;
|
||||
thumb: ThumbPayload;
|
||||
/** When true, video bytes are empty; pipeline throws fastOnlyError
|
||||
* for the main file if the server demands the bytes. The thumb is
|
||||
* always present (FALLBACK_THUMB at worst) so its sub-file uploads
|
||||
* normally regardless. */
|
||||
fastOnly: boolean;
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
function makeFallbackThumb(): ThumbPayload {
|
||||
const bytes = new Uint8Array(FALLBACK_THUMB);
|
||||
const hashes = computeHashes(bytes);
|
||||
return {
|
||||
bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function videoPayloadFromFingerprint(element: MessageElement): VideoPayload {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
sha1Blocks: [],
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'video'}.mp4`,
|
||||
filePath: '',
|
||||
fileSize: element.fileSize ?? 0,
|
||||
width: element.width ?? 0,
|
||||
height: element.height ?? 0,
|
||||
duration: element.duration ?? 1,
|
||||
videoFormat: element.videoFormat ?? 0,
|
||||
thumb: makeFallbackThumb(),
|
||||
fastOnly: true,
|
||||
cleanups: [],
|
||||
};
|
||||
}
|
||||
|
||||
interface ThumbPayload {
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
|
||||
|
||||
// Highway expects sha1 computed over each 1 MB block of the file, plus
|
||||
// the final overall sha1. This is a streaming implementation that doesn't
|
||||
// reuse Node's crypto because Node only exposes the final digest.
|
||||
|
||||
class Sha1StreamState {
|
||||
readonly blockSize = 64;
|
||||
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
|
||||
private readonly state = new Uint32Array(5);
|
||||
private readonly count = new Uint32Array(2);
|
||||
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
|
||||
private readonly w = new Uint32Array(80);
|
||||
|
||||
constructor() {
|
||||
this.reset();
|
||||
}
|
||||
|
||||
private reset(): void {
|
||||
this.state[0] = 0x67452301;
|
||||
this.state[1] = 0xEFCDAB89;
|
||||
this.state[2] = 0x98BADCFE;
|
||||
this.state[3] = 0x10325476;
|
||||
this.state[4] = 0xC3D2E1F0;
|
||||
this.count[0] = 0;
|
||||
this.count[1] = 0;
|
||||
this.buffer.fill(0);
|
||||
}
|
||||
|
||||
private rotateLeft(value: number, offset: number): number {
|
||||
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
|
||||
}
|
||||
|
||||
private transform(chunk: Uint8Array, offset: number): void {
|
||||
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
this.w[i] = view.getUint32(i * 4, false);
|
||||
}
|
||||
for (let i = 16; i < 80; i++) {
|
||||
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
|
||||
}
|
||||
|
||||
let a = this.state[0];
|
||||
let b = this.state[1];
|
||||
let c = this.state[2];
|
||||
let d = this.state[3];
|
||||
let e = this.state[4];
|
||||
|
||||
for (let i = 0; i < 80; i++) {
|
||||
let temp: number;
|
||||
if (i < 20) {
|
||||
temp = ((b & c) | (~b & d)) + 0x5A827999;
|
||||
} else if (i < 40) {
|
||||
temp = (b ^ c ^ d) + 0x6ED9EBA1;
|
||||
} else if (i < 60) {
|
||||
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
|
||||
} else {
|
||||
temp = (b ^ c ^ d) + 0xCA62C1D6;
|
||||
}
|
||||
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = this.rotateLeft(b, 30);
|
||||
b = a;
|
||||
a = temp >>> 0;
|
||||
}
|
||||
|
||||
this.state[0] = (this.state[0] + a) >>> 0;
|
||||
this.state[1] = (this.state[1] + b) >>> 0;
|
||||
this.state[2] = (this.state[2] + c) >>> 0;
|
||||
this.state[3] = (this.state[3] + d) >>> 0;
|
||||
this.state[4] = (this.state[4] + e) >>> 0;
|
||||
}
|
||||
|
||||
update(data: Uint8Array): void {
|
||||
let index = (this.count[0] >>> 3) & 0x3F;
|
||||
const dataLen = data.length;
|
||||
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
|
||||
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
|
||||
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
|
||||
|
||||
const partLen = this.blockSize - index;
|
||||
let i = 0;
|
||||
|
||||
if (dataLen >= partLen) {
|
||||
this.buffer.set(data.subarray(0, partLen), index);
|
||||
this.transform(this.buffer, 0);
|
||||
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
|
||||
this.transform(data, i);
|
||||
}
|
||||
index = 0;
|
||||
}
|
||||
|
||||
if (i < dataLen) {
|
||||
this.buffer.set(data.subarray(i, dataLen), index);
|
||||
}
|
||||
}
|
||||
|
||||
hash(bigEndian = true): Uint8Array {
|
||||
const digest = Buffer.allocUnsafe(20);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
|
||||
else digest.writeUInt32LE(this.state[i], i * 4);
|
||||
}
|
||||
return new Uint8Array(digest);
|
||||
}
|
||||
|
||||
final(): Uint8Array {
|
||||
const bits = Buffer.allocUnsafe(8);
|
||||
bits.writeUInt32BE(this.count[1], 0);
|
||||
bits.writeUInt32BE(this.count[0], 4);
|
||||
|
||||
const index = (this.count[0] >>> 3) & 0x3F;
|
||||
const padLen = index < 56 ? 56 - index : 120 - index;
|
||||
this.update(this.padding.subarray(0, padLen));
|
||||
this.update(bits);
|
||||
return this.hash(true);
|
||||
}
|
||||
}
|
||||
|
||||
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
|
||||
const sha1 = new Sha1StreamState();
|
||||
const blocks: Uint8Array[] = [];
|
||||
let bytesRead = 0;
|
||||
let offset = 0;
|
||||
|
||||
while (offset + sha1.blockSize <= bytes.length) {
|
||||
const block = bytes.subarray(offset, offset + sha1.blockSize);
|
||||
sha1.update(block);
|
||||
offset += sha1.blockSize;
|
||||
bytesRead += sha1.blockSize;
|
||||
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
|
||||
blocks.push(sha1.hash(false));
|
||||
}
|
||||
}
|
||||
|
||||
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
|
||||
blocks.push(sha1.final());
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// ─────────────── source staging + thumb extraction ───────────────
|
||||
|
||||
function defaultVideoTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-video');
|
||||
}
|
||||
|
||||
function sourceExtension(fileName: string, source: string): string {
|
||||
const fromName = path.extname(fileName);
|
||||
if (fromName) return fromName;
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
const fromSource = local ? path.extname(local) : '';
|
||||
return fromSource || '.mp4';
|
||||
}
|
||||
|
||||
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
|
||||
bytes: Uint8Array;
|
||||
filePath: string;
|
||||
fileName: string;
|
||||
}> {
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('video source is empty');
|
||||
|
||||
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) {
|
||||
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.`);
|
||||
}
|
||||
return {
|
||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||
filePath: local,
|
||||
fileName: element.fileName || path.basename(local),
|
||||
};
|
||||
}
|
||||
|
||||
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
|
||||
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));
|
||||
cleanups.push(() => { try { fs.unlinkSync(stagedPath); } catch { /* ignore */ } });
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
filePath: stagedPath,
|
||||
fileName,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumb: ThumbPayload;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
}> {
|
||||
let width = element.width ?? 0;
|
||||
let height = element.height ?? 0;
|
||||
let duration = element.duration ?? 0;
|
||||
let thumbBytes: Uint8Array | null = null;
|
||||
|
||||
if (element.thumbUrl) {
|
||||
try {
|
||||
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
|
||||
} catch (err) {
|
||||
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbBytes) {
|
||||
try {
|
||||
const info = await getFFmpegAddon().getVideoInfo(videoPath);
|
||||
width = width || info.width || 0;
|
||||
height = height || info.height || 0;
|
||||
duration = duration || Math.max(1, Math.round(info.duration || 0));
|
||||
if (info.image && info.image.length > 0) {
|
||||
thumbBytes = new Uint8Array(info.image);
|
||||
}
|
||||
} catch (err) {
|
||||
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbBytes) {
|
||||
thumbBytes = new Uint8Array(FALLBACK_THUMB);
|
||||
}
|
||||
|
||||
const fmt = detectImageFormat(thumbBytes);
|
||||
width = width || fmt.width || 1;
|
||||
height = height || fmt.height || 1;
|
||||
duration = duration || 1;
|
||||
|
||||
const hashes = computeHashes(thumbBytes);
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb: {
|
||||
bytes: thumbBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('video fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
return videoPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const tempDir = defaultVideoTempDir();
|
||||
const cleanups: Array<() => void> = [];
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
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) {
|
||||
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.`);
|
||||
}
|
||||
|
||||
const hashes = computeHashes(staged.bytes);
|
||||
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
|
||||
|
||||
return {
|
||||
bytes: staged.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
sha1Blocks: computeVideoSha1Blocks(staged.bytes),
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
|
||||
filePath: staged.filePath,
|
||||
fileSize: staged.bytes.length,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
videoFormat: 0,
|
||||
thumb,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
for (const fn of cleanups.reverse()) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── exported entry ───────────────
|
||||
|
||||
/**
|
||||
* Upload a video and return the encoded MsgInfo bytes that go inside a
|
||||
* `commonElem { serviceType: 48, businessType: 21 }`.
|
||||
*
|
||||
* Two highway PUTs run when the server doesn't fast-path: the main video
|
||||
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
|
||||
*/
|
||||
export async function uploadVideoMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const video = await loadVideo(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
video.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
|
||||
bytes: video.bytes,
|
||||
md5: video.md5,
|
||||
sha1: video.sha1Blocks,
|
||||
subFileIndex: 0,
|
||||
fastOnlyError: 'video fast-upload not available (server requires bytes)',
|
||||
},
|
||||
{
|
||||
source: 0, // upload.subFileInfos[0]
|
||||
cmdId: isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID,
|
||||
bytes: video.thumb.bytes,
|
||||
md5: video.thumb.md5,
|
||||
sha1: video.thumb.sha1,
|
||||
subFileIndex: 1,
|
||||
// No fastOnlyError: thumb always has bytes (FALLBACK_THUMB at worst).
|
||||
},
|
||||
];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x11EA : 0x11E9,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100',
|
||||
requestId: 3,
|
||||
businessType: 2,
|
||||
uploadInfo: [
|
||||
{
|
||||
fileInfo: {
|
||||
fileSize: video.fileSize,
|
||||
fileHash: video.md5Hex,
|
||||
fileSha1: video.sha1Hex,
|
||||
fileName: 'nya.mp4',
|
||||
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
// Width/height kept at 0 — NapCat does the same and the QQ-NT
|
||||
// server has been observed to reject non-zero dimensions
|
||||
// here on c2c sends with a schema-mismatch error. acidify
|
||||
// *does* fill them (`payload.videoWidth/Height`) but we
|
||||
// leave that alone until c2c regression coverage exists.
|
||||
height: 0,
|
||||
width: 0,
|
||||
// `time` MUST be the real duration in seconds, otherwise
|
||||
// every receiving client renders "00:00" on the video.
|
||||
// NapCat ships `time: 0` because it sits on top of QQ-NT's
|
||||
// IPC layer, which the desktop client patches up before
|
||||
// the wire message goes out. We're a protocol-direct
|
||||
// client (same position as acidify), so we own this field.
|
||||
// acidify writes `payload.videoDuration` here for the same
|
||||
// reason — verified against `RichMediaUpload.kt::
|
||||
// buildVideoUploadInfoList` (2026-04 refactor).
|
||||
time: video.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
},
|
||||
{
|
||||
fileInfo: {
|
||||
fileSize: video.thumb.bytes.length,
|
||||
fileHash: video.thumb.md5Hex,
|
||||
fileSha1: video.thumb.sha1Hex,
|
||||
fileName: 'nya.jpg',
|
||||
type: { type: 1, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
height: video.thumb.height,
|
||||
width: video.thumb.width,
|
||||
time: 0,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 100,
|
||||
},
|
||||
],
|
||||
// Hardcoded 2 even on c2c (matches NapCat). Image/PTT use
|
||||
// `isGroup ? 2 : 1` because their legacy compat elements differ
|
||||
// per scene (notOnlineImage vs customFace; ptt c2c vs group),
|
||||
// but the legacy `videoFile` element has no scene split — its
|
||||
// fromChatType/toChatType live inside the element itself — so
|
||||
// the server generates a single group-shaped compat payload
|
||||
// regardless. Setting 1 here makes the server emit a c2c-scene
|
||||
// shaped compat blob that old QQ clients fail to resolve,
|
||||
// showing the message as "视频已过期" on those receivers while
|
||||
// new clients (which only read the commonElem) display fine.
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: {
|
||||
pic: { bizType: 0, textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
|
||||
ptt: {
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'video',
|
||||
});
|
||||
|
||||
log.debug('video upload completed: md5=%s scene=%s', video.md5Hex, isGroup ? 'group' : 'c2c');
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of video.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user