lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
@@ -10,63 +10,76 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const log = createLogger('Highway.Audio');
|
||||
|
||||
export interface FFmpegVideoInfo {
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
format: string;
|
||||
videoCodec: string;
|
||||
image: Buffer;
|
||||
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,
|
||||
outputPath: string,
|
||||
format: string,
|
||||
): Promise<{ result: boolean; channels: number; sampleRate: number; format: string }>;
|
||||
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,
|
||||
outputPath: string,
|
||||
format: string,
|
||||
): Promise<{ result: boolean; channels: number; sampleRate: number; format: string }>;
|
||||
}
|
||||
|
||||
let cachedAddon: FFmpegNativeAddon | null = null;
|
||||
let cachedLoadError: string | null = null;
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function addonFileName(): string {
|
||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||
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'),
|
||||
];
|
||||
// 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;
|
||||
const fileName = addonFileName();
|
||||
|
||||
for (const dir of addonSearchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
|
||||
if (fs.existsSync(full)) {
|
||||
return full;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,24 +88,30 @@ function resolveAddonPath(): string | null {
|
||||
* so callers don't silently fall back.
|
||||
*/
|
||||
export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
if (cachedAddon) return cachedAddon;
|
||||
if (cachedLoadError) throw new Error(cachedLoadError);
|
||||
if (cachedAddon) {
|
||||
return cachedAddon;
|
||||
}
|
||||
|
||||
const addonPath = resolveAddonPath();
|
||||
if (!addonPath) {
|
||||
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
if (cachedLoadError) {
|
||||
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}): ${errorMessage(error)}`;
|
||||
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}): ${errorMessage(error)}`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,28 +121,29 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
* 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);
|
||||
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;
|
||||
}
|
||||
} 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;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,36 +152,40 @@ export interface EncodeSilkResult {
|
||||
* when `converted === true`.
|
||||
*/
|
||||
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
|
||||
const addon = getFFmpegAddon();
|
||||
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));
|
||||
// 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 };
|
||||
}
|
||||
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 };
|
||||
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(), 'audio-upload');
|
||||
return path.join(os.tmpdir(), 'audio-upload');
|
||||
}
|
||||
|
||||
// ── audio transcode (get_record out_format, #165) ──
|
||||
@@ -172,8 +196,9 @@ export function defaultPttTempDir(): string {
|
||||
/** Output formats accepted by `out_format` (mirrors NapCat's allowlist). */
|
||||
export const AUDIO_OUT_FORMATS = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'] as const;
|
||||
export type AudioOutFormat = (typeof AUDIO_OUT_FORMATS)[number];
|
||||
|
||||
export function isAudioOutFormat(s: string): s is AudioOutFormat {
|
||||
return (AUDIO_OUT_FORMATS as readonly string[]).includes(s);
|
||||
return (AUDIO_OUT_FORMATS as readonly string[]).includes(s);
|
||||
}
|
||||
|
||||
/** Minimal addon surface the transcode needs — lets tests inject a fake. */
|
||||
@@ -192,15 +217,20 @@ const SILK_V3_SIGNATURE = Buffer.from('#!SILK_V3', 'ascii');
|
||||
* transcode boundary. Copy before rewriting to preserve caller-owned bytes.
|
||||
*/
|
||||
function normalizeQqAiSilkContainer(bytes: Uint8Array): Uint8Array {
|
||||
if (bytes.length < SILK_V3_SIGNATURE.length + 1 || bytes[0] !== 0x03) return bytes;
|
||||
for (let index = 0; index < SILK_V3_SIGNATURE.length; index += 1) {
|
||||
if (bytes[index + 1] !== SILK_V3_SIGNATURE[index]) return bytes;
|
||||
}
|
||||
if (bytes.length < SILK_V3_SIGNATURE.length + 1 || bytes[0] !== 0x03) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const normalized = Uint8Array.from(bytes);
|
||||
normalized[0] = 0x02;
|
||||
log.debug('normalized QQ AI SILK container for audio transcoding');
|
||||
return normalized;
|
||||
for (let index = 0; index < SILK_V3_SIGNATURE.length; index += 1) {
|
||||
if (bytes[index + 1] !== SILK_V3_SIGNATURE[index]) {
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
const normalized = Uint8Array.from(bytes);
|
||||
normalized[0] = 0x02;
|
||||
log.debug('normalized QQ AI SILK container for audio transcoding');
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -211,54 +241,79 @@ function normalizeQqAiSilkContainer(bytes: Uint8Array): Uint8Array {
|
||||
* conversion (e.g. the binary lacks SILK decode).
|
||||
*/
|
||||
export async function convertAudioBytes(
|
||||
bytes: Uint8Array,
|
||||
format: string,
|
||||
deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {},
|
||||
bytes: Uint8Array,
|
||||
format: string,
|
||||
deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {},
|
||||
): Promise<{ base64: string; size: number }> {
|
||||
if (!isAudioOutFormat(format)) {
|
||||
throw new Error(`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`);
|
||||
}
|
||||
const addon = deps.addon ?? getFFmpegAddon();
|
||||
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
|
||||
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'audio-transcode');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const inPath = path.join(dir, `${id}.in`);
|
||||
const outPath = path.join(dir, `${id}.${format}`);
|
||||
let outcome: PromiseSettledResult<{ base64: string; size: number }>;
|
||||
try {
|
||||
await fs.promises.writeFile(inPath, normalizeQqAiSilkContainer(bytes));
|
||||
await addon.decodeAudioToFmt(inPath, outPath, format);
|
||||
if (!fs.existsSync(outPath)) throw new Error('audio conversion failed: no output file');
|
||||
// Bound the output before reading it into memory (decompressing direction).
|
||||
const stat = await fs.promises.stat(outPath);
|
||||
if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
|
||||
const out = await fs.promises.readFile(outPath);
|
||||
outcome = { status: 'fulfilled', value: { base64: out.toString('base64'), size: out.length } };
|
||||
} catch (reason) {
|
||||
outcome = { status: 'rejected', reason };
|
||||
}
|
||||
|
||||
// `force` makes missing files harmless. Any remaining rejection is a real
|
||||
// permission/I/O failure and must stay observable instead of leaking voice
|
||||
// data silently. Preserve the conversion error too when both phases fail.
|
||||
const cleanupResults = await Promise.allSettled([
|
||||
fs.promises.rm(inPath, { force: true }),
|
||||
fs.promises.rm(outPath, { force: true }),
|
||||
]);
|
||||
const cleanupErrors = cleanupResults
|
||||
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
||||
.map((result) => result.reason);
|
||||
if (cleanupErrors.length > 0) {
|
||||
const cleanupMessage = cleanupErrors.map(errorMessage).join('; ');
|
||||
if (outcome.status === 'rejected') {
|
||||
throw new AggregateError(
|
||||
[outcome.reason, ...cleanupErrors],
|
||||
`audio conversion failed: ${errorMessage(outcome.reason)}; temporary audio file cleanup failed: ${cleanupMessage}`,
|
||||
);
|
||||
if (!isAudioOutFormat(format)) {
|
||||
throw new Error(
|
||||
`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`,
|
||||
);
|
||||
}
|
||||
throw new AggregateError(cleanupErrors, `temporary audio file cleanup failed: ${cleanupMessage}`);
|
||||
}
|
||||
if (outcome.status === 'rejected') throw outcome.reason;
|
||||
return outcome.value;
|
||||
|
||||
const addon = deps.addon ?? getFFmpegAddon();
|
||||
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
|
||||
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'audio-transcode');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const inPath = path.join(dir, `${id}.in`);
|
||||
const outPath = path.join(dir, `${id}.${format}`);
|
||||
let outcome: PromiseSettledResult<{ base64: string; size: number }>;
|
||||
|
||||
try {
|
||||
await fs.promises.writeFile(inPath, normalizeQqAiSilkContainer(bytes));
|
||||
await addon.decodeAudioToFmt(inPath, outPath, format);
|
||||
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('audio conversion failed: no output file');
|
||||
}
|
||||
|
||||
// Bound the output before reading it into memory (decompressing direction).
|
||||
const stat = await fs.promises.stat(outPath);
|
||||
|
||||
if (stat.size > maxOut) {
|
||||
throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
|
||||
}
|
||||
|
||||
const out = await fs.promises.readFile(outPath);
|
||||
outcome = {
|
||||
status: 'fulfilled',
|
||||
value: { base64: out.toString('base64'), size: out.length },
|
||||
};
|
||||
} catch (reason) {
|
||||
outcome = { status: 'rejected', reason };
|
||||
}
|
||||
|
||||
// `force` makes missing files harmless. Any remaining rejection is a real
|
||||
// permission/I/O failure and must stay observable instead of leaking voice
|
||||
// data silently. Preserve the conversion error too when both phases fail.
|
||||
const cleanupResults = await Promise.allSettled([
|
||||
fs.promises.rm(inPath, { force: true }),
|
||||
fs.promises.rm(outPath, { force: true }),
|
||||
]);
|
||||
const cleanupErrors = cleanupResults
|
||||
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
||||
.map((result) => result.reason);
|
||||
|
||||
if (cleanupErrors.length > 0) {
|
||||
const cleanupMessage = cleanupErrors.map(errorMessage).join('; ');
|
||||
|
||||
if (outcome.status === 'rejected') {
|
||||
throw new AggregateError(
|
||||
[outcome.reason, ...cleanupErrors],
|
||||
`audio conversion failed: ${errorMessage(outcome.reason)}; temporary audio file cleanup failed: ${cleanupMessage}`,
|
||||
);
|
||||
}
|
||||
|
||||
throw new AggregateError(
|
||||
cleanupErrors,
|
||||
`temporary audio file cleanup failed: ${cleanupMessage}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (outcome.status === 'rejected') {
|
||||
throw outcome.reason;
|
||||
}
|
||||
|
||||
return outcome.value;
|
||||
}
|
||||
@@ -19,18 +19,18 @@ import { Sha1Stream } from './sha1-stream';
|
||||
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
export interface StreamedFileHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
/** Per-1 MiB intermediate SHA1 states (little-endian, un-finalized) plus a
|
||||
* final entry that is the finalized whole-file SHA1 — the exact shape
|
||||
* `computeVideoSha1Blocks` returns. Only meaningful for video; file uploads
|
||||
* ignore it. */
|
||||
sha1Blocks: Uint8Array[];
|
||||
/** md5 of the first `headLimit` bytes — the offline-file `md510MCheckSum`.
|
||||
* Present only when `headLimit` was passed. */
|
||||
headMd5?: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
/** Per-1 MiB intermediate SHA1 states (little-endian, un-finalized) plus a
|
||||
* final entry that is the finalized whole-file SHA1 — the exact shape
|
||||
* `computeVideoSha1Blocks` returns. Only meaningful for video; file uploads
|
||||
* ignore it. */
|
||||
sha1Blocks: Uint8Array[];
|
||||
/** md5 of the first `headLimit` bytes — the offline-file `md510MCheckSum`.
|
||||
* Present only when `headLimit` was passed. */
|
||||
headMd5?: Uint8Array;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,73 +39,78 @@ export interface StreamedFileHashes {
|
||||
* when `headLimit` is given) over the file's bytes, without buffering the file.
|
||||
*/
|
||||
export async function hashFileStreaming(
|
||||
filePath: string,
|
||||
opts?: { headLimit?: number },
|
||||
filePath: string,
|
||||
opts?: { headLimit?: number },
|
||||
): Promise<StreamedFileHashes> {
|
||||
const { size } = await fsp.stat(filePath);
|
||||
const src = await FileChunkSource.open(filePath, size);
|
||||
try {
|
||||
const md5 = createHash('md5');
|
||||
const sha1 = createHash('sha1');
|
||||
const headLimit = opts?.headLimit;
|
||||
const headMd5 = headLimit !== undefined ? createHash('md5') : null;
|
||||
let headRemaining = headLimit ?? 0;
|
||||
const { size } = await fsp.stat(filePath);
|
||||
const src = await FileChunkSource.open(filePath, size);
|
||||
|
||||
// Running SHA1 state fed only full 1 MiB chunks, snapshotted at each 1 MiB
|
||||
// boundary — mirrors computeVideoSha1Blocks (which feeds 64-byte blocks and
|
||||
// snapshots at 1 MiB; identical result since 1 MiB is a multiple of 64 and
|
||||
// Sha1Stream buffers internally). The sub-1 MiB tail is never snapshotted,
|
||||
// so it need not be fed to the block-sha1 at all.
|
||||
const blockSha1 = new Sha1Stream();
|
||||
const sha1Blocks: Uint8Array[] = [];
|
||||
try {
|
||||
const md5 = createHash('md5');
|
||||
const sha1 = createHash('sha1');
|
||||
const headLimit = opts?.headLimit;
|
||||
const headMd5 = headLimit !== undefined ? createHash('md5') : null;
|
||||
let headRemaining = headLimit ?? 0;
|
||||
|
||||
let offset = 0;
|
||||
while (offset < size) {
|
||||
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
|
||||
const chunk = await src.read(offset, len);
|
||||
md5.update(chunk);
|
||||
sha1.update(chunk);
|
||||
if (headMd5 && headRemaining > 0) {
|
||||
const take = Math.min(headRemaining, chunk.length);
|
||||
headMd5.update(chunk.subarray(0, take));
|
||||
headRemaining -= take;
|
||||
}
|
||||
if (len === SHA1_STREAM_BLOCK_SIZE) {
|
||||
blockSha1.update(chunk);
|
||||
sha1Blocks.push(blockSha1.hash(true)); // little-endian intermediate state
|
||||
}
|
||||
offset += len;
|
||||
// Running SHA1 state fed only full 1 MiB chunks, snapshotted at each 1 MiB
|
||||
// boundary — mirrors computeVideoSha1Blocks (which feeds 64-byte blocks and
|
||||
// snapshots at 1 MiB; identical result since 1 MiB is a multiple of 64 and
|
||||
// Sha1Stream buffers internally). The sub-1 MiB tail is never snapshotted,
|
||||
// so it need not be fed to the block-sha1 at all.
|
||||
const blockSha1 = new Sha1Stream();
|
||||
const sha1Blocks: Uint8Array[] = [];
|
||||
|
||||
let offset = 0;
|
||||
|
||||
while (offset < size) {
|
||||
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
|
||||
const chunk = await src.read(offset, len);
|
||||
md5.update(chunk);
|
||||
sha1.update(chunk);
|
||||
|
||||
if (headMd5 && headRemaining > 0) {
|
||||
const take = Math.min(headRemaining, chunk.length);
|
||||
headMd5.update(chunk.subarray(0, take));
|
||||
headRemaining -= take;
|
||||
}
|
||||
|
||||
if (len === SHA1_STREAM_BLOCK_SIZE) {
|
||||
blockSha1.update(chunk);
|
||||
sha1Blocks.push(blockSha1.hash(true)); // little-endian intermediate state
|
||||
}
|
||||
|
||||
offset += len;
|
||||
}
|
||||
|
||||
const sha1Digest = sha1.digest();
|
||||
// Final entry: the finalized whole-file SHA1 — the last element
|
||||
// computeVideoSha1Blocks pushes.
|
||||
sha1Blocks.push(new Uint8Array(sha1Digest));
|
||||
const md5Digest = md5.digest();
|
||||
|
||||
return {
|
||||
md5: new Uint8Array(md5Digest),
|
||||
sha1: new Uint8Array(sha1Digest),
|
||||
md5Hex: md5Digest.toString('hex'),
|
||||
sha1Hex: sha1Digest.toString('hex'),
|
||||
sha1Blocks,
|
||||
headMd5: headMd5 ? new Uint8Array(headMd5.digest()) : undefined,
|
||||
};
|
||||
} finally {
|
||||
await src.close();
|
||||
}
|
||||
|
||||
const sha1Digest = sha1.digest();
|
||||
// Final entry: the finalized whole-file SHA1 — the last element
|
||||
// computeVideoSha1Blocks pushes.
|
||||
sha1Blocks.push(new Uint8Array(sha1Digest));
|
||||
const md5Digest = md5.digest();
|
||||
|
||||
return {
|
||||
md5: new Uint8Array(md5Digest),
|
||||
sha1: new Uint8Array(sha1Digest),
|
||||
md5Hex: md5Digest.toString('hex'),
|
||||
sha1Hex: sha1Digest.toString('hex'),
|
||||
sha1Blocks,
|
||||
headMd5: headMd5 ? new Uint8Array(headMd5.digest()) : undefined,
|
||||
};
|
||||
} finally {
|
||||
await src.close();
|
||||
}
|
||||
}
|
||||
|
||||
export interface StreamedFlashHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
/** Flash sliceupload Sha1StateV — un-finalized little-endian state after
|
||||
* every full 1 MiB slice except the last; the last entry is the finalized
|
||||
* whole-file SHA1. Same shape as `computeSha1StateV`, not `sha1Blocks`. */
|
||||
sha1StateV: Uint8Array[];
|
||||
sliceCount: number;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
/** Flash sliceupload Sha1StateV — un-finalized little-endian state after
|
||||
* every full 1 MiB slice except the last; the last entry is the finalized
|
||||
* whole-file SHA1. Same shape as `computeSha1StateV`, not `sha1Blocks`. */
|
||||
sha1StateV: Uint8Array[];
|
||||
sliceCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,45 +123,51 @@ export interface StreamedFlashHashes {
|
||||
* state that flash's Sha1StateV must not carry.
|
||||
*/
|
||||
export async function hashFlashFileStreaming(filePath: string): Promise<StreamedFlashHashes> {
|
||||
const { size } = await fsp.stat(filePath);
|
||||
const sliceCount = Math.ceil(size / SHA1_STREAM_BLOCK_SIZE);
|
||||
const src = await FileChunkSource.open(filePath, size);
|
||||
try {
|
||||
const md5 = createHash('md5');
|
||||
const sha1 = createHash('sha1');
|
||||
const blockSha1 = new Sha1Stream();
|
||||
const sha1StateV: Uint8Array[] = [];
|
||||
const { size } = await fsp.stat(filePath);
|
||||
const sliceCount = Math.ceil(size / SHA1_STREAM_BLOCK_SIZE);
|
||||
const src = await FileChunkSource.open(filePath, size);
|
||||
|
||||
let offset = 0;
|
||||
let sliceIndex = 0;
|
||||
while (offset < size) {
|
||||
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
|
||||
const chunk = await src.read(offset, len);
|
||||
md5.update(chunk);
|
||||
sha1.update(chunk);
|
||||
blockSha1.update(chunk);
|
||||
if (sliceIndex !== sliceCount - 1) {
|
||||
sha1StateV.push(blockSha1.hash(true));
|
||||
}
|
||||
offset += len;
|
||||
sliceIndex += 1;
|
||||
try {
|
||||
const md5 = createHash('md5');
|
||||
const sha1 = createHash('sha1');
|
||||
const blockSha1 = new Sha1Stream();
|
||||
const sha1StateV: Uint8Array[] = [];
|
||||
|
||||
let offset = 0;
|
||||
let sliceIndex = 0;
|
||||
|
||||
while (offset < size) {
|
||||
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
|
||||
const chunk = await src.read(offset, len);
|
||||
md5.update(chunk);
|
||||
sha1.update(chunk);
|
||||
blockSha1.update(chunk);
|
||||
|
||||
if (sliceIndex !== sliceCount - 1) {
|
||||
sha1StateV.push(blockSha1.hash(true));
|
||||
}
|
||||
|
||||
offset += len;
|
||||
sliceIndex += 1;
|
||||
}
|
||||
|
||||
const sha1Digest = sha1.digest();
|
||||
|
||||
if (sliceCount > 0) {
|
||||
sha1StateV.push(new Uint8Array(sha1Digest));
|
||||
}
|
||||
|
||||
const md5Digest = md5.digest();
|
||||
|
||||
return {
|
||||
md5: new Uint8Array(md5Digest),
|
||||
sha1: new Uint8Array(sha1Digest),
|
||||
md5Hex: md5Digest.toString('hex'),
|
||||
sha1Hex: sha1Digest.toString('hex'),
|
||||
sha1StateV,
|
||||
sliceCount,
|
||||
};
|
||||
} finally {
|
||||
await src.close();
|
||||
}
|
||||
|
||||
const sha1Digest = sha1.digest();
|
||||
if (sliceCount > 0) {
|
||||
sha1StateV.push(new Uint8Array(sha1Digest));
|
||||
}
|
||||
const md5Digest = md5.digest();
|
||||
|
||||
return {
|
||||
md5: new Uint8Array(md5Digest),
|
||||
sha1: new Uint8Array(sha1Digest),
|
||||
md5Hex: md5Digest.toString('hex'),
|
||||
sha1Hex: sha1Digest.toString('hex'),
|
||||
sha1StateV,
|
||||
sliceCount,
|
||||
};
|
||||
} finally {
|
||||
await src.close();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,106 +5,122 @@ 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,
|
||||
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;
|
||||
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;
|
||||
/** 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,
|
||||
};
|
||||
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'));
|
||||
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 Promise.resolve(imageDataFromFingerprint(element));
|
||||
}
|
||||
return loadImageFromSource(
|
||||
element.url || element.imageUrl || element.fileId || '',
|
||||
element.fileName ?? '',
|
||||
element.subType ?? 0,
|
||||
element.summary ?? '',
|
||||
);
|
||||
|
||||
return loadImageFromSource(
|
||||
element.url || element.imageUrl || 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);
|
||||
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';
|
||||
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;
|
||||
let finalName = fileName || loaded.fileName;
|
||||
|
||||
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,
|
||||
};
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,82 +128,97 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu
|
||||
* commonElem.
|
||||
*/
|
||||
export async function uploadImageMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
tempGroupId?: number,
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
tempGroupId?: number,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
const pic: PicExtBizInfo = {
|
||||
bizType: image.subType,
|
||||
textSummary: image.summary,
|
||||
...(isGroup
|
||||
? { extData: { subType: image.subType, textSummary: image.summary } }
|
||||
: { bytesPbReserveC2c: protobuf_encode<NotOnlineImagePbReserve>({
|
||||
subType: image.subType, summary: image.summary,
|
||||
}) }),
|
||||
};
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s%s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : tempGroupId !== undefined ? 'group-temp' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
tempGroupId !== undefined ? ` sourceGroup=${tempGroupId}` : '');
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
const pic: PicExtBizInfo = {
|
||||
bizType: image.subType,
|
||||
textSummary: image.summary,
|
||||
...(isGroup
|
||||
? { extData: { subType: image.subType, textSummary: image.summary } }
|
||||
: {
|
||||
bytesPbReserveC2c: protobuf_encode<NotOnlineImagePbReserve>({
|
||||
subType: image.subType,
|
||||
summary: image.summary,
|
||||
}),
|
||||
}),
|
||||
};
|
||||
log.debug(
|
||||
'uploading %d bytes md5=%s... → %s %s%s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : tempGroupId !== undefined ? 'group-temp' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
tempGroupId !== undefined ? ` sourceGroup=${tempGroupId}` : '',
|
||||
);
|
||||
|
||||
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 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,
|
||||
tempGroupId,
|
||||
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
tempGroupId,
|
||||
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,
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'image',
|
||||
});
|
||||
|
||||
const encoded = finalizeMediaMsgInfo(upload, pic);
|
||||
// Retain successful upload metadata for the caller's self-sent history.
|
||||
Object.assign(element, {
|
||||
md5Hex: image.md5Hex,
|
||||
sha1Hex: image.sha1Hex,
|
||||
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,
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'image',
|
||||
});
|
||||
|
||||
const encoded = finalizeMediaMsgInfo(upload, pic);
|
||||
// Retain successful upload metadata for the caller's self-sent history.
|
||||
Object.assign(element, {
|
||||
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, fileSize: image.fileSize,
|
||||
fileName: image.fileName, width: image.width, height: image.height,
|
||||
picFormat: image.picFormat, subType: image.subType, summary: image.summary,
|
||||
});
|
||||
return encoded;
|
||||
picFormat: image.picFormat,
|
||||
subType: image.subType,
|
||||
summary: image.summary,
|
||||
});
|
||||
return encoded;
|
||||
}
|
||||
@@ -1,14 +1,10 @@
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import type {
|
||||
EncodableMediaMsgInfo,
|
||||
HighwayMsgInfoBody,
|
||||
NTV2ExtBizInfo,
|
||||
NTV2UploadInfo,
|
||||
NTV2UploadRespBody,
|
||||
EncodableMediaMsgInfo,
|
||||
HighwayMsgInfoBody,
|
||||
NTV2ExtBizInfo,
|
||||
NTV2UploadInfo,
|
||||
NTV2UploadRespBody,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { PicExtBizInfo } from '@snowluma/proto-defs/element';
|
||||
@@ -16,7 +12,13 @@ import crypto from 'crypto';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { OidbError } from '../oidb-service';
|
||||
import { Ntv2UploadRequest } from '../oidb-services/highway/ntv2-upload-request';
|
||||
import { BufferChunkSource, FileChunkSource, buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
import {
|
||||
BufferChunkSource,
|
||||
FileChunkSource,
|
||||
buildHighwayExtend,
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
} from './highway-client';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
@@ -28,65 +30,65 @@ const moduleLog = createLogger('Highway');
|
||||
* 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. Also empty
|
||||
* when `fileSource` is set (the bytes are streamed from disk instead). */
|
||||
bytes: Uint8Array;
|
||||
/** When set, this sub-file streams from a disk file instead of `bytes`
|
||||
* (which should be empty). runPuts opens a `FileChunkSource`; all size /
|
||||
* data-presence decisions use `fileSource.fileSize`, not `bytes.length`. */
|
||||
fileSource?: { filePath: string; fileSize: number };
|
||||
/** 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;
|
||||
/**
|
||||
* 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. Also empty
|
||||
* when `fileSource` is set (the bytes are streamed from disk instead). */
|
||||
bytes: Uint8Array;
|
||||
/** When set, this sub-file streams from a disk file instead of `bytes`
|
||||
* (which should be empty). runPuts opens a `FileChunkSource`; all size /
|
||||
* data-presence decisions use `fileSource.fileSize`, not `bytes.length`. */
|
||||
fileSource?: { filePath: string; fileSize: number };
|
||||
/** 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;
|
||||
/** Existing passive group temp session; never creates or refreshes a session. */
|
||||
tempGroupId?: 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: NTV2UploadInfo[];
|
||||
/** `upload.compatQmsgSceneType`. */
|
||||
compatQmsgSceneType: number;
|
||||
/** `upload.extBizInfo` — type-specific bytes/flags. */
|
||||
extBizInfo: NTV2ExtBizInfo;
|
||||
/** Sub-file Highway PUTs to perform after the OIDB response. */
|
||||
uploads: MediaSubFileUpload[];
|
||||
/** Used in error messages. Defaults to 'media'. */
|
||||
label?: string;
|
||||
bridge: BridgeContext;
|
||||
isGroup: boolean;
|
||||
/** Group uin when isGroup, otherwise the recipient's uid string. */
|
||||
targetIdOrUid: string | number;
|
||||
/** Existing passive group temp session; never creates or refreshes a session. */
|
||||
tempGroupId?: 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: NTV2UploadInfo[];
|
||||
/** `upload.compatQmsgSceneType`. */
|
||||
compatQmsgSceneType: number;
|
||||
/** `upload.extBizInfo` — type-specific bytes/flags. */
|
||||
extBizInfo: NTV2ExtBizInfo;
|
||||
/** Sub-file Highway PUTs to perform after the OIDB response. */
|
||||
uploads: MediaSubFileUpload[];
|
||||
/** Used in error messages. Defaults to 'media'. */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
// ─────────────── helpers ───────────────
|
||||
@@ -97,39 +99,45 @@ export interface NtV2UploadParams {
|
||||
* Mirrors NapCat.
|
||||
*/
|
||||
export function makeClientRandomId(): bigint {
|
||||
const buf = crypto.randomBytes(8);
|
||||
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
function sha1TraceValue(value: Uint8Array | Uint8Array[]): string {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return `[${values.map((item) => renderTraceBytes(item)).join(',')}]`;
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return `[${values.map((item) => renderTraceBytes(item)).join(',')}]`;
|
||||
}
|
||||
|
||||
function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
|
||||
return `[${uploads.map((sub) => [
|
||||
`source:${JSON.stringify(String(sub.source))}`,
|
||||
`cmdId:${sub.cmdId}`,
|
||||
`size:${sub.fileSource ? sub.fileSource.fileSize : sub.bytes.byteLength}`,
|
||||
`storage:${JSON.stringify(sub.fileSource ? 'disk' : 'buffer')}`,
|
||||
`md5:${renderTraceBytes(sub.md5)}`,
|
||||
`sha1:${sha1TraceValue(sub.sha1)}`,
|
||||
`subFileIndex:${sub.subFileIndex ?? 0}`,
|
||||
].join(',')).join(';')}]`;
|
||||
return `[${uploads
|
||||
.map((sub) =>
|
||||
[
|
||||
`source:${JSON.stringify(String(sub.source))}`,
|
||||
`cmdId:${sub.cmdId}`,
|
||||
`size:${sub.fileSource ? sub.fileSource.fileSize : sub.bytes.byteLength}`,
|
||||
`storage:${JSON.stringify(sub.fileSource ? 'disk' : 'buffer')}`,
|
||||
`md5:${renderTraceBytes(sub.md5)}`,
|
||||
`sha1:${sha1TraceValue(sub.sha1)}`,
|
||||
`subFileIndex:${sub.subFileIndex ?? 0}`,
|
||||
].join(','),
|
||||
)
|
||||
.join(';')}]`;
|
||||
}
|
||||
|
||||
function mediaErrorText(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
// ─────────────── main entrypoint ───────────────
|
||||
@@ -143,203 +151,233 @@ function mediaErrorText(error: unknown): string {
|
||||
* only fetches the Highway session once.
|
||||
*/
|
||||
export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
|
||||
const startedAt = Date.now();
|
||||
const label = params.label ?? 'media';
|
||||
let failureReason = 'unexpected_failure';
|
||||
let didPut = false;
|
||||
return runWithTraceRequest(async () => {
|
||||
moduleLog.trace(() => [
|
||||
'highway_media_start label=%j scope=%s target=%j sourceGroup=%s oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
|
||||
label,
|
||||
params.isGroup ? 'group' : params.tempGroupId !== undefined ? 'group-temp' : 'private',
|
||||
String(params.targetIdOrUid),
|
||||
params.tempGroupId === undefined ? '-' : String(params.tempGroupId),
|
||||
params.oidbCmd,
|
||||
params.serviceCmd,
|
||||
params.requestId,
|
||||
params.businessType,
|
||||
uploadDescriptors(params.uploads),
|
||||
]);
|
||||
try {
|
||||
const result = await runNtv2UploadOperation(params, (reason, put) => {
|
||||
failureReason = reason;
|
||||
if (put !== undefined) didPut = put;
|
||||
});
|
||||
moduleLog.trace(
|
||||
'highway_media_terminal label=%j outcome=completed reason=%s uploads=%d elapsedMs=%d',
|
||||
label,
|
||||
didPut ? 'put_complete' : 'fast_upload',
|
||||
params.uploads.length,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
moduleLog.trace(() => [
|
||||
'highway_media_terminal label=%j outcome=failed reason=%s uploads=%d error=%j elapsedMs=%d',
|
||||
label,
|
||||
failureReason,
|
||||
params.uploads.length,
|
||||
mediaErrorText(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
const label = params.label ?? 'media';
|
||||
let failureReason = 'unexpected_failure';
|
||||
let didPut = false;
|
||||
return runWithTraceRequest(async () => {
|
||||
moduleLog.trace(() => [
|
||||
'highway_media_start label=%j scope=%s target=%j sourceGroup=%s oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
|
||||
label,
|
||||
params.isGroup ? 'group' : params.tempGroupId !== undefined ? 'group-temp' : 'private',
|
||||
String(params.targetIdOrUid),
|
||||
params.tempGroupId === undefined ? '-' : String(params.tempGroupId),
|
||||
params.oidbCmd,
|
||||
params.serviceCmd,
|
||||
params.requestId,
|
||||
params.businessType,
|
||||
uploadDescriptors(params.uploads),
|
||||
]);
|
||||
|
||||
try {
|
||||
const result = await runNtv2UploadOperation(params, (reason, put) => {
|
||||
failureReason = reason;
|
||||
|
||||
if (put !== undefined) {
|
||||
didPut = put;
|
||||
}
|
||||
});
|
||||
moduleLog.trace(
|
||||
'highway_media_terminal label=%j outcome=completed reason=%s uploads=%d elapsedMs=%d',
|
||||
label,
|
||||
didPut ? 'put_complete' : 'fast_upload',
|
||||
params.uploads.length,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
moduleLog.trace(() => [
|
||||
'highway_media_terminal label=%j outcome=failed reason=%s uploads=%d error=%j elapsedMs=%d',
|
||||
label,
|
||||
failureReason,
|
||||
params.uploads.length,
|
||||
mediaErrorText(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function runNtv2UploadOperation(
|
||||
params: NtV2UploadParams,
|
||||
setState: (failureReason: string, didPut?: boolean) => void,
|
||||
params: NtV2UploadParams,
|
||||
setState: (failureReason: string, didPut?: boolean) => void,
|
||||
): Promise<NTV2UploadRespBody> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, 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;
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, 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;
|
||||
|
||||
// Send one OIDB request and return its decoded `upload` body. `tryFast`
|
||||
// toggles `tryFastUploadCompleted`: true asks the server to reuse a
|
||||
// cached resource (skip the bytes); false forces it to allocate a fresh
|
||||
// upload session and hand back a uKey. NOTE: proton only emits a plain
|
||||
// `pb<bool>` when it's `true`, so `tryFast === false` omits field 2 —
|
||||
// the server reads that as "don't fast-upload" (the opt-in default).
|
||||
const requestUpload = async (tryFast: boolean): Promise<NTV2UploadRespBody> => {
|
||||
setState('request_failed');
|
||||
try {
|
||||
return await Ntv2UploadRequest.invoke(bridge, {
|
||||
oidbCmd,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
tempGroupId: params.tempGroupId,
|
||||
requestId: params.requestId,
|
||||
businessType: params.businessType,
|
||||
uploadInfo: params.uploadInfo,
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
tryFast,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
label,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError) setState('oidb_rejected');
|
||||
else if (error instanceof Error && error.message.includes('missing msgInfo')) setState('response_invalid');
|
||||
else if (error instanceof Error && error.message.includes('upload failed')) setState('business_rejected');
|
||||
log.trace(() => [
|
||||
'highway_media_branch branch=oidb_response error=%j',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
// Send one OIDB request and return its decoded `upload` body. `tryFast`
|
||||
// toggles `tryFastUploadCompleted`: true asks the server to reuse a
|
||||
// cached resource (skip the bytes); false forces it to allocate a fresh
|
||||
// upload session and hand back a uKey. NOTE: proton only emits a plain
|
||||
// `pb<bool>` when it's `true`, so `tryFast === false` omits field 2 —
|
||||
// the server reads that as "don't fast-upload" (the opt-in default).
|
||||
const requestUpload = async (tryFast: boolean): Promise<NTV2UploadRespBody> => {
|
||||
setState('request_failed');
|
||||
|
||||
// Highway PUTs. Session is lazily fetched and cached — video does two
|
||||
// PUTs (main + thumb) and shouldn't pay for two sessions, and a forced
|
||||
// retry shouldn't re-fetch it either.
|
||||
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
|
||||
const getSession = async () => {
|
||||
setState('session_failed');
|
||||
session ??= await fetchHighwaySession(bridge);
|
||||
return session;
|
||||
};
|
||||
try {
|
||||
return await Ntv2UploadRequest.invoke(bridge, {
|
||||
oidbCmd,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
tempGroupId: params.tempGroupId,
|
||||
requestId: params.requestId,
|
||||
businessType: params.businessType,
|
||||
uploadInfo: params.uploadInfo,
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
tryFast,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
label,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError) {
|
||||
setState('oidb_rejected');
|
||||
} else if (error instanceof Error && error.message.includes('missing msgInfo')) {
|
||||
setState('response_invalid');
|
||||
} else if (error instanceof Error && error.message.includes('upload failed')) {
|
||||
setState('business_rejected');
|
||||
}
|
||||
|
||||
// Run whatever PUTs the given `upload` response asks for.
|
||||
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
|
||||
const msgInfo = upload.msgInfo;
|
||||
if (!msgInfo) throw new Error('upload response missing msgInfo');
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
// Data size / presence comes from fileSource (streamed) when set, else
|
||||
// from the in-memory bytes — a streamed sub-file has empty `bytes`, so
|
||||
// keying the checks below on `bytes.length` would wrongly treat it as a
|
||||
// fast-only / empty sub-file.
|
||||
const subSize = sub.fileSource ? sub.fileSource.fileSize : sub.bytes.length;
|
||||
// No uKey: the server fast-pathed this sub-file — it already holds
|
||||
// (or claims to hold) the resource, so there are no bytes to push.
|
||||
if (!uKey) {
|
||||
if (subSize > 0) {
|
||||
log.trace(
|
||||
'highway_media_branch branch=fast_upload source=%j cmdId=%d size=%d',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
subSize,
|
||||
);
|
||||
log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source));
|
||||
log.trace(() => [
|
||||
'highway_media_branch branch=oidb_response error=%j',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if (subSize === 0) {
|
||||
log.trace(
|
||||
'highway_media_branch branch=empty_source source=%j cmdId=%d hasFastOnlyError=%s',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
Boolean(sub.fastOnlyError),
|
||||
);
|
||||
if (sub.fastOnlyError) {
|
||||
setState('source_unavailable');
|
||||
throw new Error(sub.fastOnlyError);
|
||||
// Highway PUTs. Session is lazily fetched and cached — video does two
|
||||
// PUTs (main + thumb) and shouldn't pay for two sessions, and a forced
|
||||
// retry shouldn't re-fetch it either.
|
||||
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
|
||||
|
||||
const getSession = async () => {
|
||||
setState('session_failed');
|
||||
session ??= await fetchHighwaySession(bridge);
|
||||
return session;
|
||||
};
|
||||
|
||||
// Run whatever PUTs the given `upload` response asks for.
|
||||
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
|
||||
const msgInfo = upload.msgInfo;
|
||||
|
||||
if (!msgInfo) {
|
||||
throw new Error('upload response missing msgInfo');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!target) continue;
|
||||
let didPut = false;
|
||||
|
||||
log.trace(
|
||||
'highway_media_branch branch=put_required source=%j cmdId=%d size=%d uKey=%j storage=%s',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
subSize,
|
||||
uKey,
|
||||
sub.fileSource ? 'disk' : 'buffer',
|
||||
);
|
||||
setState('extend_build_failed');
|
||||
const extend = buildHighwayExtend(
|
||||
uKey,
|
||||
msgInfo,
|
||||
target.ipv4s ?? [],
|
||||
sub.sha1,
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
// Resolve the (lazy, cached) session BEFORE opening the ChunkSource, so
|
||||
// there is no fallible await between opening the FileChunkSource handle
|
||||
// and the uploadHighwayHttp call that owns closing it — otherwise a
|
||||
// session-fetch failure on the first PUT would leak the open handle.
|
||||
const putSession = await getSession();
|
||||
// uploadHighwayHttp owns the ChunkSource and closes it exactly once.
|
||||
setState('source_open_failed');
|
||||
const chunkSource = sub.fileSource
|
||||
? await FileChunkSource.open(sub.fileSource.filePath, sub.fileSource.fileSize)
|
||||
: new BufferChunkSource(sub.bytes);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, subSize, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
setState('put_failed');
|
||||
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
setState('unexpected_failure', true);
|
||||
}
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
// Data size / presence comes from fileSource (streamed) when set, else
|
||||
// from the in-memory bytes — a streamed sub-file has empty `bytes`, so
|
||||
// keying the checks below on `bytes.length` would wrongly treat it as a
|
||||
// fast-only / empty sub-file.
|
||||
const subSize = sub.fileSource ? sub.fileSource.fileSize : sub.bytes.length;
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
};
|
||||
// No uKey: the server fast-pathed this sub-file — it already holds
|
||||
// (or claims to hold) the resource, so there are no bytes to push.
|
||||
if (!uKey) {
|
||||
if (subSize > 0) {
|
||||
log.trace(
|
||||
'highway_media_branch branch=fast_upload source=%j cmdId=%d size=%d',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
subSize,
|
||||
);
|
||||
log.debug(
|
||||
'%s fast-upload hit for sub=%s (server reusing cached resource)',
|
||||
label,
|
||||
String(sub.source),
|
||||
);
|
||||
}
|
||||
|
||||
// NOTE: a previous attempt re-issued the request with
|
||||
// `tryFastUploadCompleted: false` when the server fast-pathed the main video,
|
||||
// on the theory it would force a fresh upload of a possibly-expired resource.
|
||||
// Real-machine testing + kernel RE proved that ineffective — the server's
|
||||
// fast-path is driven by md5-metadata existence and ignores the flag, and the
|
||||
// QQ NT kernel itself does no validity check either (HandleRspUploadV3 trusts
|
||||
// `fileExist` and reports success). An expired-but-still-indexed video
|
||||
// resource is a platform-level limitation, not something the upload flow can
|
||||
// refresh. See #145.
|
||||
const upload = await requestUpload(true);
|
||||
await runPuts(upload);
|
||||
return upload;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (subSize === 0) {
|
||||
log.trace(
|
||||
'highway_media_branch branch=empty_source source=%j cmdId=%d hasFastOnlyError=%s',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
Boolean(sub.fastOnlyError),
|
||||
);
|
||||
|
||||
if (sub.fastOnlyError) {
|
||||
setState('source_unavailable');
|
||||
throw new Error(sub.fastOnlyError);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
continue;
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'highway_media_branch branch=put_required source=%j cmdId=%d size=%d uKey=%j storage=%s',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
subSize,
|
||||
uKey,
|
||||
sub.fileSource ? 'disk' : 'buffer',
|
||||
);
|
||||
setState('extend_build_failed');
|
||||
const extend = buildHighwayExtend(
|
||||
uKey,
|
||||
msgInfo,
|
||||
target.ipv4s ?? [],
|
||||
sub.sha1,
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
// Resolve the (lazy, cached) session BEFORE opening the ChunkSource, so
|
||||
// there is no fallible await between opening the FileChunkSource handle
|
||||
// and the uploadHighwayHttp call that owns closing it — otherwise a
|
||||
// session-fetch failure on the first PUT would leak the open handle.
|
||||
const putSession = await getSession();
|
||||
// uploadHighwayHttp owns the ChunkSource and closes it exactly once.
|
||||
setState('source_open_failed');
|
||||
const chunkSource = sub.fileSource
|
||||
? await FileChunkSource.open(sub.fileSource.filePath, sub.fileSource.fileSize)
|
||||
: new BufferChunkSource(sub.bytes);
|
||||
log.debug(
|
||||
'%s OIDB requires bytes, PUT %d bytes (sub=%s)',
|
||||
label,
|
||||
subSize,
|
||||
String(sub.source),
|
||||
);
|
||||
const t0 = Date.now();
|
||||
setState('put_failed');
|
||||
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
setState('unexpected_failure', true);
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
};
|
||||
|
||||
// NOTE: a previous attempt re-issued the request with
|
||||
// `tryFastUploadCompleted: false` when the server fast-pathed the main video,
|
||||
// on the theory it would force a fresh upload of a possibly-expired resource.
|
||||
// Real-machine testing + kernel RE proved that ineffective — the server's
|
||||
// fast-path is driven by md5-metadata existence and ignores the flag, and the
|
||||
// QQ NT kernel itself does no validity check either (HandleRspUploadV3 trusts
|
||||
// `fileExist` and reports success). An expired-but-still-indexed video
|
||||
// resource is a platform-level limitation, not something the upload flow can
|
||||
// refresh. See #145.
|
||||
const upload = await requestUpload(true);
|
||||
await runPuts(upload);
|
||||
return upload;
|
||||
}
|
||||
|
||||
// ─────────────── shared finalize ───────────────
|
||||
@@ -351,26 +389,39 @@ async function runNtv2UploadOperation(
|
||||
* scene-specific compatibility reserve. PTT and video omit it.
|
||||
*/
|
||||
export function finalizeMediaMsgInfo(
|
||||
upload: NTV2UploadRespBody,
|
||||
requestedPic?: PicExtBizInfo,
|
||||
upload: NTV2UploadRespBody,
|
||||
requestedPic?: PicExtBizInfo,
|
||||
): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
if (!upload?.msgInfo) {
|
||||
throw new Error('upload response missing msgInfo');
|
||||
}
|
||||
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: HighwayMsgInfoBody) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
}));
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: HighwayMsgInfoBody) => ({
|
||||
index: b.index,
|
||||
picture: b.picture,
|
||||
fileExist: b.fileExist,
|
||||
hashSum: b.hashSum,
|
||||
}));
|
||||
|
||||
const extBizInfo: NonNullable<EncodableMediaMsgInfo['extBizInfo']> = {};
|
||||
if (upload.msgInfo.extBizInfo?.pic || requestedPic) {
|
||||
// Upload responses can reuse cached image metadata. Presentation belongs
|
||||
// to this send, so retain resource metadata but apply the requested style.
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo?.pic, ...requestedPic };
|
||||
}
|
||||
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;
|
||||
}
|
||||
const extBizInfo: NonNullable<EncodableMediaMsgInfo['extBizInfo']> = {};
|
||||
|
||||
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
|
||||
if (upload.msgInfo.extBizInfo?.pic || requestedPic) {
|
||||
// Upload responses can reuse cached image metadata. Presentation belongs
|
||||
// to this send, so retain resource metadata but apply the requested style.
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo?.pic, ...requestedPic };
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
@@ -7,155 +7,204 @@ import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { defaultPttTempDir, encodeSilk, getFFmpegAddon } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import {
|
||||
amplitudesFromPcmS16le,
|
||||
encodePttWaveform,
|
||||
mergePttWaveform,
|
||||
pcmS16leFromWav,
|
||||
amplitudesFromPcmS16le,
|
||||
encodePttWaveform,
|
||||
mergePttWaveform,
|
||||
pcmS16leFromWav,
|
||||
} from './ptt-waveform';
|
||||
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;
|
||||
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>;
|
||||
/** Encoded `PttWaveform` for private-chat progress / peaks. Omitted on fingerprint. */
|
||||
waveform?: Uint8Array;
|
||||
/** 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>;
|
||||
/** Encoded `PttWaveform` for private-chat progress / peaks. Omitted on fingerprint. */
|
||||
waveform?: Uint8Array;
|
||||
}
|
||||
|
||||
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: [],
|
||||
};
|
||||
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);
|
||||
}
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('record fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
|
||||
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 */ } });
|
||||
return pttPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
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 source = element.url || element.fileId || '';
|
||||
|
||||
if (!source) {
|
||||
throw new Error('record source is empty');
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
const hashes = computeHashes(silkBytes);
|
||||
const waveform = await tryPttWaveform(silk.path, tempDir, cleanups);
|
||||
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],
|
||||
waveform,
|
||||
// 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 */
|
||||
}
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
throw err;
|
||||
}
|
||||
|
||||
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);
|
||||
const waveform = await tryPttWaveform(silk.path, tempDir, cleanups);
|
||||
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],
|
||||
waveform,
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function tryPttWaveform(
|
||||
silkPath: string,
|
||||
tempDir: string,
|
||||
cleanups: Array<() => void>,
|
||||
silkPath: string,
|
||||
tempDir: string,
|
||||
cleanups: Array<() => void>,
|
||||
): Promise<Uint8Array | undefined> {
|
||||
const wavPath = path.join(tempDir, `snowluma-ptt-wave-${crypto.randomUUID()}.wav`);
|
||||
cleanups.push(() => { try { fs.unlinkSync(wavPath); } catch { /* ignore */ } });
|
||||
try {
|
||||
const decoded = await getFFmpegAddon().decodeAudioToFmt(silkPath, wavPath, 'wav');
|
||||
if (!decoded.result || !fs.existsSync(wavPath)) return undefined;
|
||||
const wav = new Uint8Array(fs.readFileSync(wavPath));
|
||||
const { pcm, channels } = pcmS16leFromWav(wav);
|
||||
return encodePttWaveform(amplitudesFromPcmS16le(pcm, { channels }));
|
||||
} catch (err) {
|
||||
moduleLog.debug('ptt waveform skipped: %s', err instanceof Error ? err.message : String(err));
|
||||
return undefined;
|
||||
}
|
||||
const wavPath = path.join(tempDir, `snowluma-ptt-wave-${crypto.randomUUID()}.wav`);
|
||||
cleanups.push(() => {
|
||||
try {
|
||||
fs.unlinkSync(wavPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const decoded = await getFFmpegAddon().decodeAudioToFmt(silkPath, wavPath, 'wav');
|
||||
|
||||
if (!decoded.result || !fs.existsSync(wavPath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const wav = new Uint8Array(fs.readFileSync(wavPath));
|
||||
const { pcm, channels } = pcmS16leFromWav(wav);
|
||||
return encodePttWaveform(amplitudesFromPcmS16le(pcm, { channels }));
|
||||
} catch (err) {
|
||||
moduleLog.debug(
|
||||
'ptt waveform skipped: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,94 +212,115 @@ async function tryPttWaveform(
|
||||
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
||||
*/
|
||||
export async function uploadPttMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
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 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,
|
||||
);
|
||||
|
||||
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` is the group blob lifted verbatim from NapCat
|
||||
// (UploadGroupPtt.ts). Private chat must send **none**: with the
|
||||
// NapCat c2c blob (UploadPrivatePtt.ts) present the receiving client
|
||||
// draws the voice bubble without its progress bar, and the waveform
|
||||
// we ship is silently dropped. Confirmed by A/B-ing this single field
|
||||
// against an otherwise identical send (present → flat, absent → drawn).
|
||||
...(isGroup
|
||||
? {
|
||||
bytesGeneralFlags: new Uint8Array([
|
||||
0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00,
|
||||
]),
|
||||
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` is the group blob lifted verbatim from NapCat
|
||||
// (UploadGroupPtt.ts). Private chat must send **none**: with the
|
||||
// NapCat c2c blob (UploadPrivatePtt.ts) present the receiving client
|
||||
// draws the voice bubble without its progress bar, and the waveform
|
||||
// we ship is silently dropped. Confirmed by A/B-ing this single field
|
||||
// against an otherwise identical send (present → flat, absent → drawn).
|
||||
...(isGroup
|
||||
? {
|
||||
bytesGeneralFlags: new Uint8Array([
|
||||
0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00,
|
||||
]),
|
||||
}
|
||||
: {}),
|
||||
...(ptt.waveform ? { waveform: ptt.waveform } : {}),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'ptt',
|
||||
});
|
||||
|
||||
mergePttWaveform(upload, ptt.waveform);
|
||||
const encoded = finalizeMediaMsgInfo(upload);
|
||||
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
|
||||
Object.assign(element, {
|
||||
md5Hex: ptt.md5Hex,
|
||||
sha1Hex: ptt.sha1Hex,
|
||||
fileSize: ptt.fileSize,
|
||||
fileName: ptt.fileName,
|
||||
duration: ptt.duration,
|
||||
voiceFormat: ptt.voiceFormat,
|
||||
fileId: mediaNode?.fileUuid,
|
||||
mediaNode,
|
||||
});
|
||||
return encoded;
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
/* best-effort cleanup */
|
||||
}
|
||||
: {}),
|
||||
...(ptt.waveform ? { waveform: ptt.waveform } : {}),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'ptt',
|
||||
});
|
||||
|
||||
mergePttWaveform(upload, ptt.waveform);
|
||||
const encoded = finalizeMediaMsgInfo(upload);
|
||||
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
|
||||
Object.assign(element, {
|
||||
md5Hex: ptt.md5Hex, sha1Hex: ptt.sha1Hex, fileSize: ptt.fileSize,
|
||||
fileName: ptt.fileName, duration: ptt.duration, voiceFormat: ptt.voiceFormat,
|
||||
fileId: mediaNode?.fileUuid, mediaNode,
|
||||
});
|
||||
return encoded;
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,28 +8,30 @@ export const PTT_WAVEFORM_BINS = 30;
|
||||
export const PTT_WAVEFORM_SILENCE = 25;
|
||||
|
||||
function u16le(bytes: Uint8Array, offset: number): number {
|
||||
return bytes[offset]! | (bytes[offset + 1]! << 8);
|
||||
return bytes[offset]! | (bytes[offset + 1]! << 8);
|
||||
}
|
||||
|
||||
function u32le(bytes: Uint8Array, offset: number): number {
|
||||
return bytes[offset]!
|
||||
| (bytes[offset + 1]! << 8)
|
||||
| (bytes[offset + 2]! << 16)
|
||||
| (bytes[offset + 3]! << 24);
|
||||
return (
|
||||
bytes[offset]! |
|
||||
(bytes[offset + 1]! << 8) |
|
||||
(bytes[offset + 2]! << 16) |
|
||||
(bytes[offset + 3]! << 24)
|
||||
);
|
||||
}
|
||||
|
||||
function fourcc(bytes: Uint8Array, offset: number): string {
|
||||
return String.fromCharCode(
|
||||
bytes[offset]!,
|
||||
bytes[offset + 1]!,
|
||||
bytes[offset + 2]!,
|
||||
bytes[offset + 3]!,
|
||||
);
|
||||
return String.fromCharCode(
|
||||
bytes[offset]!,
|
||||
bytes[offset + 1]!,
|
||||
bytes[offset + 2]!,
|
||||
bytes[offset + 3]!,
|
||||
);
|
||||
}
|
||||
|
||||
function s16le(bytes: Uint8Array, offset: number): number {
|
||||
const raw = u16le(bytes, offset);
|
||||
return raw >= 0x8000 ? raw - 0x10000 : raw;
|
||||
const raw = u16le(bytes, offset);
|
||||
return raw >= 0x8000 ? raw - 0x10000 : raw;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,48 +39,71 @@ function s16le(bytes: Uint8Array, offset: number): number {
|
||||
* Rejects non-PCM / non-16-bit so a botched transcode cannot invent bars.
|
||||
*/
|
||||
export function pcmS16leFromWav(wav: Uint8Array): {
|
||||
pcm: Uint8Array;
|
||||
channels: number;
|
||||
sampleRate: number;
|
||||
pcm: Uint8Array;
|
||||
channels: number;
|
||||
sampleRate: number;
|
||||
} {
|
||||
if (wav.length < 12) throw new Error('wav is truncated');
|
||||
if (fourcc(wav, 0) !== 'RIFF' || fourcc(wav, 8) !== 'WAVE') {
|
||||
throw new Error('wav is not a RIFF/WAVE file');
|
||||
}
|
||||
|
||||
let offset = 12;
|
||||
let channels = 0;
|
||||
let sampleRate = 0;
|
||||
let bitsPerSample = 0;
|
||||
let audioFormat = 0;
|
||||
let data: Uint8Array | undefined;
|
||||
|
||||
while (offset + 8 <= wav.length) {
|
||||
const id = fourcc(wav, offset);
|
||||
const size = u32le(wav, offset + 4);
|
||||
const start = offset + 8;
|
||||
if (start + size > wav.length) throw new Error('wav chunk is truncated');
|
||||
if (id === 'fmt ') {
|
||||
if (size < 16) throw new Error('wav fmt chunk is short');
|
||||
audioFormat = u16le(wav, start);
|
||||
channels = u16le(wav, start + 2);
|
||||
sampleRate = u32le(wav, start + 4);
|
||||
bitsPerSample = u16le(wav, start + 14);
|
||||
} else if (id === 'data') {
|
||||
data = wav.subarray(start, start + size);
|
||||
if (wav.length < 12) {
|
||||
throw new Error('wav is truncated');
|
||||
}
|
||||
offset = start + size + (size & 1);
|
||||
}
|
||||
|
||||
if (!data) throw new Error('wav has no data chunk');
|
||||
if (audioFormat !== 1) throw new Error(`wav format ${audioFormat} is not PCM`);
|
||||
if (channels < 1) throw new Error('wav channel count is invalid');
|
||||
if (bitsPerSample !== 16) throw new Error(`wav bits ${bitsPerSample} is not s16`);
|
||||
return { pcm: data, channels, sampleRate };
|
||||
if (fourcc(wav, 0) !== 'RIFF' || fourcc(wav, 8) !== 'WAVE') {
|
||||
throw new Error('wav is not a RIFF/WAVE file');
|
||||
}
|
||||
|
||||
let offset = 12;
|
||||
let channels = 0;
|
||||
let sampleRate = 0;
|
||||
let bitsPerSample = 0;
|
||||
let audioFormat = 0;
|
||||
let data: Uint8Array | undefined;
|
||||
|
||||
while (offset + 8 <= wav.length) {
|
||||
const id = fourcc(wav, offset);
|
||||
const size = u32le(wav, offset + 4);
|
||||
const start = offset + 8;
|
||||
|
||||
if (start + size > wav.length) {
|
||||
throw new Error('wav chunk is truncated');
|
||||
}
|
||||
|
||||
if (id === 'fmt ') {
|
||||
if (size < 16) {
|
||||
throw new Error('wav fmt chunk is short');
|
||||
}
|
||||
|
||||
audioFormat = u16le(wav, start);
|
||||
channels = u16le(wav, start + 2);
|
||||
sampleRate = u32le(wav, start + 4);
|
||||
bitsPerSample = u16le(wav, start + 14);
|
||||
} else if (id === 'data') {
|
||||
data = wav.subarray(start, start + size);
|
||||
}
|
||||
|
||||
offset = start + size + (size & 1);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
throw new Error('wav has no data chunk');
|
||||
}
|
||||
|
||||
if (audioFormat !== 1) {
|
||||
throw new Error(`wav format ${audioFormat} is not PCM`);
|
||||
}
|
||||
|
||||
if (channels < 1) {
|
||||
throw new Error('wav channel count is invalid');
|
||||
}
|
||||
|
||||
if (bitsPerSample !== 16) {
|
||||
throw new Error(`wav bits ${bitsPerSample} is not s16`);
|
||||
}
|
||||
|
||||
return { pcm: data, channels, sampleRate };
|
||||
}
|
||||
|
||||
function silentWaveform(bins: number): Uint8Array {
|
||||
return new Uint8Array(bins).fill(PTT_WAVEFORM_SILENCE);
|
||||
return new Uint8Array(bins).fill(PTT_WAVEFORM_SILENCE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,66 +112,96 @@ function silentWaveform(bins: number): Uint8Array {
|
||||
* so private-chat clients still draw a progress track.
|
||||
*/
|
||||
export function amplitudesFromPcmS16le(
|
||||
pcm: Uint8Array,
|
||||
options: { channels?: number; bins?: number } = {},
|
||||
pcm: Uint8Array,
|
||||
options: { channels?: number; bins?: number } = {},
|
||||
): Uint8Array {
|
||||
const channels = options.channels ?? 1;
|
||||
const bins = options.bins ?? PTT_WAVEFORM_BINS;
|
||||
if (channels < 1 || bins < 1) throw new Error('waveform channels/bins must be >= 1');
|
||||
const channels = options.channels ?? 1;
|
||||
const bins = options.bins ?? PTT_WAVEFORM_BINS;
|
||||
|
||||
const frameSize = channels * 2;
|
||||
const frames = Math.floor(pcm.length / frameSize);
|
||||
if (frames === 0) return silentWaveform(bins);
|
||||
|
||||
const out = new Uint8Array(bins);
|
||||
let any = false;
|
||||
for (let bin = 0; bin < bins; bin += 1) {
|
||||
const start = Math.floor((bin * frames) / bins);
|
||||
let end = Math.floor(((bin + 1) * frames) / bins);
|
||||
if (end <= start) end = start + 1;
|
||||
let peak = 0;
|
||||
for (let frame = start; frame < end && frame < frames; frame += 1) {
|
||||
const base = frame * frameSize;
|
||||
for (let channel = 0; channel < channels; channel += 1) {
|
||||
const sample = Math.abs(s16le(pcm, base + channel * 2));
|
||||
if (sample > peak) peak = sample;
|
||||
}
|
||||
if (channels < 1 || bins < 1) {
|
||||
throw new Error('waveform channels/bins must be >= 1');
|
||||
}
|
||||
const amplitude = Math.min(255, Math.round((peak * 255) / 32767));
|
||||
if (amplitude > 0) any = true;
|
||||
out[bin] = amplitude;
|
||||
}
|
||||
return any ? out : silentWaveform(bins);
|
||||
|
||||
const frameSize = channels * 2;
|
||||
const frames = Math.floor(pcm.length / frameSize);
|
||||
|
||||
if (frames === 0) {
|
||||
return silentWaveform(bins);
|
||||
}
|
||||
|
||||
const out = new Uint8Array(bins);
|
||||
let any = false;
|
||||
|
||||
for (let bin = 0; bin < bins; bin += 1) {
|
||||
const start = Math.floor((bin * frames) / bins);
|
||||
let end = Math.floor(((bin + 1) * frames) / bins);
|
||||
|
||||
if (end <= start) {
|
||||
end = start + 1;
|
||||
}
|
||||
|
||||
let peak = 0;
|
||||
|
||||
for (let frame = start; frame < end && frame < frames; frame += 1) {
|
||||
const base = frame * frameSize;
|
||||
|
||||
for (let channel = 0; channel < channels; channel += 1) {
|
||||
const sample = Math.abs(s16le(pcm, base + channel * 2));
|
||||
|
||||
if (sample > peak) {
|
||||
peak = sample;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const amplitude = Math.min(255, Math.round((peak * 255) / 32767));
|
||||
|
||||
if (amplitude > 0) {
|
||||
any = true;
|
||||
}
|
||||
|
||||
out[bin] = amplitude;
|
||||
}
|
||||
|
||||
return any ? out : silentWaveform(bins);
|
||||
}
|
||||
|
||||
/** Encode amplitudes as the blob `ParsePttWave` accepts (count == bytes). */
|
||||
export function encodePttWaveform(amplitudes: Uint8Array): Uint8Array {
|
||||
if (amplitudes.length === 0) throw new Error('ptt waveform amplitudes are empty');
|
||||
return protobuf_encode<PttWaveform>({
|
||||
size: amplitudes.length,
|
||||
amplitudes,
|
||||
});
|
||||
if (amplitudes.length === 0) {
|
||||
throw new Error('ptt waveform amplitudes are empty');
|
||||
}
|
||||
|
||||
return protobuf_encode<PttWaveform>({
|
||||
size: amplitudes.length,
|
||||
amplitudes,
|
||||
});
|
||||
}
|
||||
|
||||
export function decodePttWaveform(bytes: Uint8Array): { size: number; amplitudes: Uint8Array } {
|
||||
const decoded = protobuf_decode<PttWaveform>(bytes);
|
||||
const amplitudes = decoded.amplitudes ?? new Uint8Array(0);
|
||||
const size = decoded.size ?? 0;
|
||||
if (size !== amplitudes.length) {
|
||||
throw new Error(`ptt waveform count ${size} != amplitudes ${amplitudes.length}`);
|
||||
}
|
||||
return { size, amplitudes };
|
||||
const decoded = protobuf_decode<PttWaveform>(bytes);
|
||||
const amplitudes = decoded.amplitudes ?? new Uint8Array(0);
|
||||
const size = decoded.size ?? 0;
|
||||
|
||||
if (size !== amplitudes.length) {
|
||||
throw new Error(`ptt waveform count ${size} != amplitudes ${amplitudes.length}`);
|
||||
}
|
||||
|
||||
return { size, amplitudes };
|
||||
}
|
||||
|
||||
/** Stamp computed waveform onto the upload response so finalize cannot drop it. */
|
||||
export function mergePttWaveform(
|
||||
upload: NTV2UploadRespBody,
|
||||
waveform: Uint8Array | undefined,
|
||||
upload: NTV2UploadRespBody,
|
||||
waveform: Uint8Array | undefined,
|
||||
): void {
|
||||
if (!waveform || waveform.length === 0 || !upload.msgInfo) return;
|
||||
const ext = upload.msgInfo.extBizInfo ?? {};
|
||||
upload.msgInfo.extBizInfo = {
|
||||
...ext,
|
||||
ptt: { ...ext.ptt, waveform },
|
||||
};
|
||||
if (!waveform || waveform.length === 0 || !upload.msgInfo) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = upload.msgInfo.extBizInfo ?? {};
|
||||
upload.msgInfo.extBizInfo = {
|
||||
...ext,
|
||||
ptt: { ...ext.ptt, waveform },
|
||||
};
|
||||
}
|
||||
@@ -8,82 +8,119 @@ const SHA1_BLOCK_SIZE = 64;
|
||||
const SHA1_DIGEST_SIZE = 20;
|
||||
|
||||
function rotl(x: number, n: number): number {
|
||||
return ((x << n) | (x >>> (32 - n))) >>> 0;
|
||||
return ((x << n) | (x >>> (32 - n))) >>> 0;
|
||||
}
|
||||
|
||||
export class Sha1Stream {
|
||||
private readonly state = new Uint32Array(5);
|
||||
private readonly count = new Uint32Array(2); // [low, high] bit count
|
||||
private readonly buffer = new Uint8Array(SHA1_BLOCK_SIZE);
|
||||
private readonly state = new Uint32Array(5);
|
||||
private readonly count = new Uint32Array(2); // [low, high] bit count
|
||||
private readonly buffer = new Uint8Array(SHA1_BLOCK_SIZE);
|
||||
|
||||
constructor() { this.reset(); }
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private transform(data: Uint8Array, offset: number): void {
|
||||
const w = new Uint32Array(80);
|
||||
const dv = new DataView(data.buffer, data.byteOffset + offset, 64);
|
||||
for (let i = 0; i < 16; i++) w[i] = dv.getUint32(i * 4, false); // big-endian
|
||||
for (let i = 16; i < 80; i++) {
|
||||
w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
||||
constructor() {
|
||||
this.reset();
|
||||
}
|
||||
let a = this.state[0], b = this.state[1], c = this.state[2], d = this.state[3], 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 = (temp + rotl(a, 5) + e + w[i]) >>> 0;
|
||||
e = d; d = c; c = rotl(b, 30); b = a; a = temp;
|
||||
}
|
||||
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 {
|
||||
const len = data.length;
|
||||
let index = (this.count[0] >>> 3) & 0x3F;
|
||||
this.count[0] = (this.count[0] + (len << 3)) >>> 0;
|
||||
if (this.count[0] < (len << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
|
||||
this.count[1] = (this.count[1] + (len >>> 29)) >>> 0;
|
||||
|
||||
let partLen = SHA1_BLOCK_SIZE - index;
|
||||
let i = 0;
|
||||
if (len >= partLen) {
|
||||
this.buffer.set(data.subarray(0, partLen), index);
|
||||
this.transform(this.buffer, 0);
|
||||
i = partLen;
|
||||
while (i + SHA1_BLOCK_SIZE <= len) {
|
||||
this.transform(data, i);
|
||||
i += SHA1_BLOCK_SIZE;
|
||||
}
|
||||
index = 0;
|
||||
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.set(data.subarray(i), index);
|
||||
}
|
||||
|
||||
/** 输出当前 state(20B)。littleEndian=true 小端,false 大端。不 finalize。 */
|
||||
hash(littleEndian: boolean): Uint8Array {
|
||||
const digest = new Uint8Array(SHA1_DIGEST_SIZE);
|
||||
const dv = new DataView(digest.buffer);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (littleEndian) dv.setUint32(i * 4, this.state[i], true);
|
||||
else dv.setUint32(i * 4, this.state[i], false);
|
||||
private transform(data: Uint8Array, offset: number): void {
|
||||
const w = new Uint32Array(80);
|
||||
const dv = new DataView(data.buffer, data.byteOffset + offset, 64);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
w[i] = dv.getUint32(i * 4, false);
|
||||
} // big-endian
|
||||
|
||||
for (let i = 16; i < 80; i++) {
|
||||
w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
||||
}
|
||||
|
||||
let a = this.state[0],
|
||||
b = this.state[1],
|
||||
c = this.state[2],
|
||||
d = this.state[3],
|
||||
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 = (temp + rotl(a, 5) + e + w[i]) >>> 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = rotl(b, 30);
|
||||
b = a;
|
||||
a = temp;
|
||||
}
|
||||
|
||||
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 {
|
||||
const len = data.length;
|
||||
let index = (this.count[0] >>> 3) & 0x3f;
|
||||
this.count[0] = (this.count[0] + (len << 3)) >>> 0;
|
||||
|
||||
if (this.count[0] < len << 3) {
|
||||
this.count[1] = (this.count[1] + 1) >>> 0;
|
||||
}
|
||||
|
||||
this.count[1] = (this.count[1] + (len >>> 29)) >>> 0;
|
||||
|
||||
let partLen = SHA1_BLOCK_SIZE - index;
|
||||
let i = 0;
|
||||
|
||||
if (len >= partLen) {
|
||||
this.buffer.set(data.subarray(0, partLen), index);
|
||||
this.transform(this.buffer, 0);
|
||||
i = partLen;
|
||||
|
||||
while (i + SHA1_BLOCK_SIZE <= len) {
|
||||
this.transform(data, i);
|
||||
i += SHA1_BLOCK_SIZE;
|
||||
}
|
||||
|
||||
index = 0;
|
||||
}
|
||||
|
||||
this.buffer.set(data.subarray(i), index);
|
||||
}
|
||||
|
||||
/** 输出当前 state(20B)。littleEndian=true 小端,false 大端。不 finalize。 */
|
||||
hash(littleEndian: boolean): Uint8Array {
|
||||
const digest = new Uint8Array(SHA1_DIGEST_SIZE);
|
||||
const dv = new DataView(digest.buffer);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (littleEndian) {
|
||||
dv.setUint32(i * 4, this.state[i], true);
|
||||
} else {
|
||||
dv.setUint32(i * 4, this.state[i], false);
|
||||
}
|
||||
}
|
||||
|
||||
return digest;
|
||||
}
|
||||
return digest;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,19 +131,26 @@ export class Sha1Stream {
|
||||
* 用单个 Sha1Stream 增量 update:每片只喂新增的 sliceSize 字节再快照,O(n)。
|
||||
* (sliceSize=1MB 是 SHA1 块大小 64B 的整数倍,增量 update 不会残留半块。)
|
||||
*/
|
||||
export function computeSha1StateV(bytes: Uint8Array, sliceCount: number, sliceSize: number): Uint8Array[] {
|
||||
const states: Uint8Array[] = [];
|
||||
const sha1 = new Sha1Stream();
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * sliceSize;
|
||||
const end = Math.min(start + sliceSize, bytes.length);
|
||||
sha1.update(bytes.subarray(start, end));
|
||||
if (i !== sliceCount - 1) {
|
||||
states.push(sha1.hash(true)); // 小端中间 state,不 finalize
|
||||
} else {
|
||||
// 最后一片:标准整文件 SHA1(有 finalize)
|
||||
states.push(new Uint8Array(createHash('sha1').update(Buffer.from(bytes)).digest()));
|
||||
export function computeSha1StateV(
|
||||
bytes: Uint8Array,
|
||||
sliceCount: number,
|
||||
sliceSize: number,
|
||||
): Uint8Array[] {
|
||||
const states: Uint8Array[] = [];
|
||||
const sha1 = new Sha1Stream();
|
||||
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * sliceSize;
|
||||
const end = Math.min(start + sliceSize, bytes.length);
|
||||
sha1.update(bytes.subarray(start, end));
|
||||
|
||||
if (i !== sliceCount - 1) {
|
||||
states.push(sha1.hash(true)); // 小端中间 state,不 finalize
|
||||
} else {
|
||||
// 最后一片:标准整文件 SHA1(有 finalize)
|
||||
states.push(new Uint8Array(createHash('sha1').update(Buffer.from(bytes)).digest()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return states;
|
||||
|
||||
return states;
|
||||
}
|
||||
@@ -24,10 +24,10 @@ import path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
downloadHttp,
|
||||
inlineBase64Payload,
|
||||
resolveLocalFilePath,
|
||||
type DownloadSink,
|
||||
downloadHttp,
|
||||
inlineBase64Payload,
|
||||
resolveLocalFilePath,
|
||||
type DownloadSink,
|
||||
} from './utils';
|
||||
|
||||
const log = createLogger('Highway.Stage');
|
||||
@@ -44,109 +44,155 @@ const REAPER_INTERVAL_MS = 5 * 60 * 1000;
|
||||
const active = new Set<string>();
|
||||
|
||||
export interface StagedSource {
|
||||
/** Local disk path the uploader reads from. */
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
/** Caller-facing name (URL basename / original local basename); '' for base64. */
|
||||
fileName: string;
|
||||
/** Remove the staged temp (our hardlink/copy/downloaded file). Idempotent,
|
||||
* best-effort; never throws. Never touches the caller's original file. */
|
||||
cleanup(): Promise<void>;
|
||||
/** Local disk path the uploader reads from. */
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
/** Caller-facing name (URL basename / original local basename); '' for base64. */
|
||||
fileName: string;
|
||||
/** Remove the staged temp (our hardlink/copy/downloaded file). Idempotent,
|
||||
* best-effort; never throws. Never touches the caller's original file. */
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
|
||||
let reaperTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
function ensureReaper(): void {
|
||||
if (reaperTimer) return;
|
||||
reaperTimer = setInterval(() => { void sweepStagedUploads(); }, REAPER_INTERVAL_MS);
|
||||
reaperTimer.unref(); // never pin the event loop
|
||||
void sweepStagedUploads(); // startup sweep of crash orphans
|
||||
if (reaperTimer) {
|
||||
return;
|
||||
}
|
||||
|
||||
reaperTimer = setInterval(() => {
|
||||
void sweepStagedUploads();
|
||||
}, REAPER_INTERVAL_MS);
|
||||
reaperTimer.unref(); // never pin the event loop
|
||||
void sweepStagedUploads(); // startup sweep of crash orphans
|
||||
}
|
||||
|
||||
/** Reap staged temps older than the TTL, skipping any path currently in use.
|
||||
* Best-effort; never throws. Exposed for an explicit startup/interval hook. */
|
||||
export async function sweepStagedUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fsp.readdir(STAGE_DIR);
|
||||
} catch {
|
||||
return 0; // dir not created yet
|
||||
}
|
||||
await Promise.all(names.map(async (n) => {
|
||||
const p = path.join(STAGE_DIR, n);
|
||||
if (active.has(p)) return; // in-flight — never reap
|
||||
let removed = 0;
|
||||
let names: string[];
|
||||
|
||||
try {
|
||||
const s = await fsp.stat(p);
|
||||
if (now - s.mtimeMs > STAGE_TTL_MS) {
|
||||
await fsp.rm(p, { force: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* vanished / racing cleanup */ }
|
||||
}));
|
||||
if (removed > 0) log.debug('reaped %d stale staged upload temp(s)', removed);
|
||||
return removed;
|
||||
names = await fsp.readdir(STAGE_DIR);
|
||||
} catch {
|
||||
return 0; // dir not created yet
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(STAGE_DIR, n);
|
||||
|
||||
if (active.has(p)) {
|
||||
return;
|
||||
} // in-flight — never reap
|
||||
|
||||
try {
|
||||
const s = await fsp.stat(p);
|
||||
|
||||
if (now - s.mtimeMs > STAGE_TTL_MS) {
|
||||
await fsp.rm(p, { force: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch {
|
||||
/* vanished / racing cleanup */
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (removed > 0) {
|
||||
log.debug('reaped %d stale staged upload temp(s)', removed);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
function tempPaths(ext: string): { partPath: string; finalPath: string } {
|
||||
const id = randomUUID();
|
||||
const base = path.join(STAGE_DIR, `stage-${id}${ext}`);
|
||||
return { partPath: `${base}.part`, finalPath: base };
|
||||
const id = randomUUID();
|
||||
const base = path.join(STAGE_DIR, `stage-${id}${ext}`);
|
||||
return { partPath: `${base}.part`, finalPath: base };
|
||||
}
|
||||
|
||||
/** fsync the file's directory entry so the rename survives a crash (POSIX). */
|
||||
async function fsyncDir(): Promise<void> {
|
||||
try {
|
||||
const dh = await fsp.open(STAGE_DIR, 'r');
|
||||
try { await dh.sync(); } finally { await dh.close(); }
|
||||
} catch { /* some platforms reject directory fsync — best effort */ }
|
||||
try {
|
||||
const dh = await fsp.open(STAGE_DIR, 'r');
|
||||
|
||||
try {
|
||||
await dh.sync();
|
||||
} finally {
|
||||
await dh.close();
|
||||
}
|
||||
} catch {
|
||||
/* some platforms reject directory fsync — best effort */
|
||||
}
|
||||
}
|
||||
|
||||
async function finalizeRename(partPath: string, finalPath: string): Promise<void> {
|
||||
await fsp.rename(partPath, finalPath);
|
||||
await fsyncDir();
|
||||
await fsp.rename(partPath, finalPath);
|
||||
await fsyncDir();
|
||||
}
|
||||
|
||||
function registerStaged(filePath: string, fileSize: number, fileName: string): StagedSource {
|
||||
active.add(filePath);
|
||||
let done = false;
|
||||
return {
|
||||
filePath,
|
||||
fileSize,
|
||||
fileName,
|
||||
async cleanup() {
|
||||
if (done) return;
|
||||
done = true;
|
||||
active.delete(filePath);
|
||||
await fsp.unlink(filePath).catch(() => { /* best-effort */ });
|
||||
},
|
||||
};
|
||||
active.add(filePath);
|
||||
let done = false;
|
||||
return {
|
||||
filePath,
|
||||
fileSize,
|
||||
fileName,
|
||||
async cleanup() {
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
|
||||
done = true;
|
||||
active.delete(filePath);
|
||||
await fsp.unlink(filePath).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Disk sink for `downloadHttp`: streams chunks to a FileHandle, fsyncs on
|
||||
* success, and closes-before-unlink on failure. Backpressure comes from
|
||||
* awaiting each `fh.write`. */
|
||||
function fileSink(partPath: string): DownloadSink<void> {
|
||||
let opened: Promise<import('fs').promises.FileHandle> | null = null;
|
||||
const open = () => (opened ??= fsp.open(partPath, 'w'));
|
||||
return {
|
||||
async write(chunk) { const fh = await open(); await fh.write(chunk); },
|
||||
async done() {
|
||||
const fh = await open(); // create even for an empty body
|
||||
await fh.sync();
|
||||
await fh.close();
|
||||
},
|
||||
async discard() {
|
||||
if (opened) { try { const fh = await opened; await fh.close(); } catch { /* already closed */ } }
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
},
|
||||
};
|
||||
let opened: Promise<import('fs').promises.FileHandle> | null = null;
|
||||
const open = () => (opened ??= fsp.open(partPath, 'w'));
|
||||
return {
|
||||
async write(chunk) {
|
||||
const fh = await open();
|
||||
await fh.write(chunk);
|
||||
},
|
||||
async done() {
|
||||
const fh = await open(); // create even for an empty body
|
||||
await fh.sync();
|
||||
await fh.close();
|
||||
},
|
||||
async discard() {
|
||||
if (opened) {
|
||||
try {
|
||||
const fh = await opened;
|
||||
await fh.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
await fsp.unlink(partPath).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** base64 decoded byte length without allocating the buffer. */
|
||||
function base64DecodedLength(b64: string): number {
|
||||
const clean = b64.replace(/[^A-Za-z0-9+/=]/g, '');
|
||||
const pad = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
|
||||
return Math.floor((clean.length * 3) / 4) - pad;
|
||||
const clean = b64.replace(/[^A-Za-z0-9+/=]/g, '');
|
||||
const pad = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
|
||||
return Math.floor((clean.length * 3) / 4) - pad;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,99 +202,146 @@ function base64DecodedLength(b64: string): number {
|
||||
* upload is done (or fails) to remove the staged temp.
|
||||
*/
|
||||
export async function stageSourceToDisk(source: string, maxBytes: number): Promise<StagedSource> {
|
||||
if (!source) throw new Error('stage source is empty');
|
||||
ensureReaper();
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
if (!source) {
|
||||
throw new Error('stage source is empty');
|
||||
}
|
||||
|
||||
// ── inline Base64 (`base64://` or RFC 2397 `data:`) ────────────────────
|
||||
const b64 = inlineBase64Payload(source);
|
||||
if (b64 !== null) {
|
||||
const decodedLen = base64DecodedLength(b64);
|
||||
if (decodedLen > maxBytes) {
|
||||
throw new Error(`stage source too large: ${decodedLen} > ${maxBytes}`);
|
||||
ensureReaper();
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
|
||||
// ── inline Base64 (`base64://` or RFC 2397 `data:`) ────────────────────
|
||||
const b64 = inlineBase64Payload(source);
|
||||
|
||||
if (b64 !== null) {
|
||||
const decodedLen = base64DecodedLength(b64);
|
||||
|
||||
if (decodedLen > maxBytes) {
|
||||
throw new Error(`stage source too large: ${decodedLen} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(b64, 'base64');
|
||||
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`stage source too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const { partPath, finalPath } = tempPaths('.bin');
|
||||
active.add(partPath);
|
||||
|
||||
try {
|
||||
const fh = await fsp.open(partPath, 'w');
|
||||
|
||||
try {
|
||||
await fh.write(bytes);
|
||||
await fh.sync();
|
||||
} finally {
|
||||
await fh.close();
|
||||
}
|
||||
|
||||
await finalizeRename(partPath, finalPath);
|
||||
} catch (e) {
|
||||
await fsp.unlink(partPath).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
throw e;
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
|
||||
log.debug('staged inline base64 source (%d bytes)', bytes.length);
|
||||
return registerStaged(finalPath, bytes.length, '');
|
||||
}
|
||||
const bytes = Buffer.from(b64, 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`stage source too large: ${bytes.length} > ${maxBytes}`);
|
||||
|
||||
// ── http(s):// ─────────────────────────────────────────────────────────
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const { partPath, finalPath } = tempPaths('.bin');
|
||||
active.add(partPath);
|
||||
let fileName = '';
|
||||
|
||||
try {
|
||||
const r = await downloadHttp<void>(source, 'stage', maxBytes, () => fileSink(partPath));
|
||||
fileName = r.fileName;
|
||||
await finalizeRename(partPath, finalPath);
|
||||
} catch (e) {
|
||||
await fsp.unlink(partPath).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
throw e;
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
|
||||
const { size } = await fsp.stat(finalPath);
|
||||
log.debug('staged http source %s (%d bytes)', fileName || '(unnamed)', size);
|
||||
return registerStaged(finalPath, size, fileName);
|
||||
}
|
||||
const { partPath, finalPath } = tempPaths('.bin');
|
||||
active.add(partPath);
|
||||
|
||||
// ── local path / file:// ───────────────────────────────────────────────
|
||||
const local = resolveLocalFilePath(source);
|
||||
|
||||
if (!local) {
|
||||
throw new Error('stage source is not a local file');
|
||||
}
|
||||
|
||||
const real = await fsp.realpath(local); // resolve symlinks — hardlink the target, not the link
|
||||
const st = await fsp.stat(real);
|
||||
|
||||
if (!st.isFile()) {
|
||||
throw new Error(`stage source is not a regular file: ${local}`);
|
||||
}
|
||||
|
||||
if (st.size > maxBytes) {
|
||||
throw new Error(`stage source too large: ${st.size} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const fileName = path.basename(local); // caller-facing name (before symlink resolution)
|
||||
const { partPath, finalPath } = tempPaths(path.extname(local) || '.bin');
|
||||
|
||||
// Reserve finalPath in `active` BEFORE it exists on disk. A hardlink inherits
|
||||
// the source's (often old) mtime, so — unlike the fresh-mtime http/base64/copy
|
||||
// temps whose TTL saves them during the pre-register gap — only the active-set
|
||||
// can keep the age reaper from deleting this live staged file in the window
|
||||
// between link and registerStaged.
|
||||
active.add(finalPath);
|
||||
let staged: 'link' | 'copy';
|
||||
|
||||
try {
|
||||
const fh = await fsp.open(partPath, 'w');
|
||||
try { await fh.write(bytes); await fh.sync(); } finally { await fh.close(); }
|
||||
await finalizeRename(partPath, finalPath);
|
||||
try {
|
||||
await fsp.link(real, finalPath); // O(1) hardlink; pins the inode against caller-side unlink
|
||||
staged = 'link';
|
||||
} catch {
|
||||
// Any link() failure (cross-fs EXDEV, hardlink protection, permissions,
|
||||
// link-count/platform limits) — fall back to a streamed copy of the
|
||||
// readable source (disk-to-disk, never buffered in RAM).
|
||||
active.add(partPath);
|
||||
|
||||
try {
|
||||
await fsp.copyFile(real, partPath);
|
||||
const fh = await fsp.open(partPath, 'r+'); // fsync copied data before rename
|
||||
|
||||
try {
|
||||
await fh.sync();
|
||||
} finally {
|
||||
await fh.close();
|
||||
}
|
||||
|
||||
await finalizeRename(partPath, finalPath);
|
||||
staged = 'copy';
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
throw e;
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
active.delete(finalPath);
|
||||
await fsp.unlink(finalPath).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
await fsp.unlink(partPath).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
log.debug('staged inline base64 source (%d bytes)', bytes.length);
|
||||
return registerStaged(finalPath, bytes.length, '');
|
||||
}
|
||||
|
||||
// ── http(s):// ─────────────────────────────────────────────────────────
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const { partPath, finalPath } = tempPaths('.bin');
|
||||
active.add(partPath);
|
||||
let fileName = '';
|
||||
try {
|
||||
const r = await downloadHttp<void>(source, 'stage', maxBytes, () => fileSink(partPath));
|
||||
fileName = r.fileName;
|
||||
await finalizeRename(partPath, finalPath);
|
||||
} catch (e) {
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
throw e;
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
const { size } = await fsp.stat(finalPath);
|
||||
log.debug('staged http source %s (%d bytes)', fileName || '(unnamed)', size);
|
||||
return registerStaged(finalPath, size, fileName);
|
||||
}
|
||||
|
||||
// ── local path / file:// ───────────────────────────────────────────────
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (!local) throw new Error('stage source is not a local file');
|
||||
const real = await fsp.realpath(local); // resolve symlinks — hardlink the target, not the link
|
||||
const st = await fsp.stat(real);
|
||||
if (!st.isFile()) throw new Error(`stage source is not a regular file: ${local}`);
|
||||
if (st.size > maxBytes) throw new Error(`stage source too large: ${st.size} > ${maxBytes}`);
|
||||
const fileName = path.basename(local); // caller-facing name (before symlink resolution)
|
||||
const { partPath, finalPath } = tempPaths(path.extname(local) || '.bin');
|
||||
|
||||
// Reserve finalPath in `active` BEFORE it exists on disk. A hardlink inherits
|
||||
// the source's (often old) mtime, so — unlike the fresh-mtime http/base64/copy
|
||||
// temps whose TTL saves them during the pre-register gap — only the active-set
|
||||
// can keep the age reaper from deleting this live staged file in the window
|
||||
// between link and registerStaged.
|
||||
active.add(finalPath);
|
||||
let staged: 'link' | 'copy';
|
||||
try {
|
||||
try {
|
||||
await fsp.link(real, finalPath); // O(1) hardlink; pins the inode against caller-side unlink
|
||||
staged = 'link';
|
||||
} catch {
|
||||
// Any link() failure (cross-fs EXDEV, hardlink protection, permissions,
|
||||
// link-count/platform limits) — fall back to a streamed copy of the
|
||||
// readable source (disk-to-disk, never buffered in RAM).
|
||||
active.add(partPath);
|
||||
try {
|
||||
await fsp.copyFile(real, partPath);
|
||||
const fh = await fsp.open(partPath, 'r+'); // fsync copied data before rename
|
||||
try { await fh.sync(); } finally { await fh.close(); }
|
||||
await finalizeRename(partPath, finalPath);
|
||||
staged = 'copy';
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
active.delete(finalPath);
|
||||
await fsp.unlink(finalPath).catch(() => { /* best-effort */ });
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
throw e;
|
||||
}
|
||||
log.debug('staged local source %s via %s (%d bytes)', fileName, staged, st.size);
|
||||
return registerStaged(finalPath, st.size, fileName);
|
||||
log.debug('staged local source %s via %s (%d bytes)', fileName, staged, st.size);
|
||||
return registerStaged(finalPath, st.size, fileName);
|
||||
}
|
||||
@@ -4,8 +4,8 @@ import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,19 +40,19 @@ const FETCH_TIMEOUT_MS = 60_000;
|
||||
* `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`.
|
||||
*/
|
||||
const DOWNLOAD_USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
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;
|
||||
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// --- Binary source loading ---
|
||||
@@ -66,45 +66,68 @@ export interface ImageFormat {
|
||||
* the local-file path.
|
||||
*/
|
||||
export function inlineBase64Payload(source: string): string | null {
|
||||
if (/^base64:\/\//i.test(source)) return source.slice(9);
|
||||
if (!/^data:/i.test(source)) return null;
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
return source.slice(9);
|
||||
}
|
||||
|
||||
const comma = source.indexOf(',');
|
||||
if (comma < 0) throw new Error('data URL source is missing its payload separator');
|
||||
if (!/^data:/i.test(source)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = source.slice(5, comma);
|
||||
if (!/;base64$/i.test(metadata)) {
|
||||
throw new Error('data URL source must use base64 encoding');
|
||||
}
|
||||
return source.slice(comma + 1);
|
||||
const comma = source.indexOf(',');
|
||||
|
||||
if (comma < 0) {
|
||||
throw new Error('data URL source is missing its payload separator');
|
||||
}
|
||||
|
||||
const metadata = source.slice(5, comma);
|
||||
|
||||
if (!/;base64$/i.test(metadata)) {
|
||||
throw new Error('data URL source must use base64 encoding');
|
||||
}
|
||||
|
||||
return source.slice(comma + 1);
|
||||
}
|
||||
|
||||
export function resolveLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (/^(?:base64:\/\/|data:)/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 (!source) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (process.platform !== 'win32' && filePath.startsWith('//')) {
|
||||
filePath = filePath.replace(/^\/+/, '/');
|
||||
if (/^(?:base64:\/\/|data:)/i.test(source)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Windows-style paths can arrive from file:///C:/... as /C:/...
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
return filePath;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,7 +135,7 @@ export function resolveLocalFilePath(source: string): string | null {
|
||||
* a too-large response just re-downloads the same oversized body.
|
||||
*/
|
||||
export function tooLarge(message: string): Error {
|
||||
return Object.assign(new Error(message), { noRetry: true });
|
||||
return Object.assign(new Error(message), { noRetry: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,9 +144,9 @@ export function tooLarge(message: string): Error {
|
||||
* attempt and `discard()`ed on failure so a Referer retry starts clean.
|
||||
*/
|
||||
export interface DownloadSink<T> {
|
||||
write(chunk: Uint8Array): Promise<void> | void;
|
||||
done(): Promise<T> | T;
|
||||
discard(): Promise<void> | void;
|
||||
write(chunk: Uint8Array): Promise<void> | void;
|
||||
done(): Promise<T> | T;
|
||||
discard(): Promise<void> | void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -136,285 +159,394 @@ export interface DownloadSink<T> {
|
||||
* or disk.
|
||||
*/
|
||||
export async function downloadHttp<T>(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number,
|
||||
makeSink: () => DownloadSink<T>,
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number,
|
||||
makeSink: () => DownloadSink<T>,
|
||||
): Promise<{ result: T; fileName: string }> {
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
|
||||
const attempt = async (headers: Record<string, string>): Promise<T> => {
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
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 tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const attempt = async (headers: Record<string, string>): Promise<T> => {
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
const sink = makeSink();
|
||||
try {
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const buf = new Uint8Array(await resp.arrayBuffer());
|
||||
if (buf.length > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${buf.length} > ${maxBytes}`);
|
||||
if (!resp.ok) {
|
||||
throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
}
|
||||
await sink.write(buf);
|
||||
} else {
|
||||
let total = 0;
|
||||
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const sink = makeSink();
|
||||
|
||||
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 tooLarge(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
await sink.write(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
return await sink.done();
|
||||
} catch (e) {
|
||||
await sink.discard();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const reader = resp.body?.getReader();
|
||||
|
||||
if (!reader) {
|
||||
const buf = new Uint8Array(await resp.arrayBuffer());
|
||||
|
||||
if (buf.length > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${buf.length} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
await sink.write(buf);
|
||||
} else {
|
||||
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 tooLarge(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
|
||||
await sink.write(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
return await sink.done();
|
||||
} catch (e) {
|
||||
await sink.discard();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
// First try with a browser UA only. On any non-size failure — a
|
||||
// network-level `fetch failed` (connection reset by an anti-bot front-end)
|
||||
// or a 403/4xx from anti-hotlink — retry once with a Referer pointing at the
|
||||
// resource itself, the common bypass for same-origin hotlink checks.
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'User-Agent': DOWNLOAD_USER_AGENT,
|
||||
Accept: '*/*',
|
||||
};
|
||||
|
||||
// First try with a browser UA only. On any non-size failure — a
|
||||
// network-level `fetch failed` (connection reset by an anti-bot front-end)
|
||||
// or a 403/4xx from anti-hotlink — retry once with a Referer pointing at the
|
||||
// resource itself, the common bypass for same-origin hotlink checks.
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'User-Agent': DOWNLOAD_USER_AGENT,
|
||||
Accept: '*/*',
|
||||
};
|
||||
try {
|
||||
return { result: await attempt(baseHeaders), fileName };
|
||||
} catch (err) {
|
||||
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
|
||||
try {
|
||||
return { result: await attempt({ ...baseHeaders, Referer: source }), fileName };
|
||||
} catch {
|
||||
throw err;
|
||||
return { result: await attempt(baseHeaders), fileName };
|
||||
} catch (err) {
|
||||
if ((err as { noRetry?: boolean } | null)?.noRetry) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
try {
|
||||
return { result: await attempt({ ...baseHeaders, Referer: source }), fileName };
|
||||
} catch {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
const inlinePayload = inlineBase64Payload(source);
|
||||
if (inlinePayload !== null) {
|
||||
const bytes = Buffer.from(inlinePayload, 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
if (!source) {
|
||||
throw new Error(`${resourceName} source is empty`);
|
||||
}
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
// Buffered sink: accumulate the streamed chunks and assemble them into one
|
||||
// contiguous buffer. The shared `downloadHttp` owns the transport, the
|
||||
// incremental length check, and the Referer retry.
|
||||
const memorySink = (): DownloadSink<Uint8Array> => {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
return {
|
||||
write(chunk) { chunks.push(chunk); total += chunk.byteLength; },
|
||||
done() {
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
||||
return bytes;
|
||||
},
|
||||
discard() { chunks.length = 0; },
|
||||
};
|
||||
};
|
||||
const { result, fileName } = await downloadHttp(source, resourceName, maxBytes, memorySink);
|
||||
return { bytes: result, fileName };
|
||||
}
|
||||
const inlinePayload = inlineBase64Payload(source);
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
if (inlinePayload !== null) {
|
||||
const bytes = Buffer.from(inlinePayload, 'base64');
|
||||
|
||||
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 };
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
// Buffered sink: accumulate the streamed chunks and assemble them into one
|
||||
// contiguous buffer. The shared `downloadHttp` owns the transport, the
|
||||
// incremental length check, and the Referer retry.
|
||||
const memorySink = (): DownloadSink<Uint8Array> => {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
return {
|
||||
write(chunk) {
|
||||
chunks.push(chunk);
|
||||
total += chunk.byteLength;
|
||||
},
|
||||
done() {
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
|
||||
return bytes;
|
||||
},
|
||||
discard() {
|
||||
chunks.length = 0;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const { result, fileName } = await downloadHttp(source, resourceName, maxBytes, memorySink);
|
||||
return { bytes: result, 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 };
|
||||
}
|
||||
|
||||
export function guessFileNameFromUrl(url: string): string {
|
||||
const queryPos = url.search(/[?#]/);
|
||||
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
const raw = lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||
if (!raw) return '';
|
||||
try {
|
||||
return decodeURIComponent(raw);
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
const queryPos = url.search(/[?#]/);
|
||||
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
const raw = lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||
|
||||
if (!raw) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
return decodeURIComponent(raw);
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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'),
|
||||
};
|
||||
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());
|
||||
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];
|
||||
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;
|
||||
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);
|
||||
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;
|
||||
return (
|
||||
(data[offset] |
|
||||
(data[offset + 1] << 8) |
|
||||
(data[offset + 2] << 16) |
|
||||
(data[offset + 3] << 24)) >>>
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
function readLE24(data: Uint8Array, offset: number): number {
|
||||
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16);
|
||||
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16);
|
||||
}
|
||||
|
||||
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
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 };
|
||||
// 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 };
|
||||
}
|
||||
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) {
|
||||
// VP8X canvas width/height are 24-bit LITTLE-endian (Minus-One). Reading
|
||||
// them big-endian inflated dims to absurd values (e.g. 1920×1080 →
|
||||
// 8324865×3605505), cropping the QQ thumbnail. (issue #112)
|
||||
width = readLE24(bytes, 24) + 1;
|
||||
height = readLE24(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;
|
||||
// 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) {
|
||||
// VP8X canvas width/height are 24-bit LITTLE-endian (Minus-One). Reading
|
||||
// them big-endian inflated dims to absurd values (e.g. 1920×1080 →
|
||||
// 8324865×3605505), cropping the QQ thumbnail. (issue #112)
|
||||
width = readLE24(bytes, 24) + 1;
|
||||
height = readLE24(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 };
|
||||
}
|
||||
|
||||
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;
|
||||
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),
|
||||
};
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -6,17 +6,12 @@ import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { getFFmpegAddon } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import {
|
||||
computeHashes,
|
||||
detectImageFormat,
|
||||
loadBinarySource,
|
||||
resolveLocalFilePath,
|
||||
} from './utils';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource, resolveLocalFilePath } from './utils';
|
||||
import { stageSourceToDisk } from './stage';
|
||||
import { hashFileStreaming } from './hash-file';
|
||||
import { Sha1Stream } from './sha1-stream';
|
||||
@@ -24,9 +19,9 @@ import { Sha1Stream } from './sha1-stream';
|
||||
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;
|
||||
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;
|
||||
@@ -47,19 +42,28 @@ const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
|
||||
const SHA1_BLOCK_SIZE = 64;
|
||||
|
||||
export function getVideoSourceSize(element: MessageElement): number | null {
|
||||
if (element.fileSize && element.fileSize > 0) return element.fileSize;
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) return null;
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
return fs.statSync(local).size;
|
||||
}
|
||||
return null;
|
||||
if (element.fileSize && element.fileSize > 0) {
|
||||
return element.fileSize;
|
||||
}
|
||||
|
||||
const source = element.url || element.fileId || '';
|
||||
|
||||
if (!source) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
|
||||
if (local && fs.existsSync(local)) {
|
||||
return fs.statSync(local).size;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const FALLBACK_THUMB = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAtAAAAUACAIAAADhrPJqAAAACXBIWXMAAAABAAAAAQBPJcTWAAAQAElEQVR4nO3WQQkAMAzAwOqYf6FVEQblTkGemQcAEJvfAQDAfYYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEALine truncated
|
||||
'base64',
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAtAAAAUACAIAAADhrPJqAAAACXBIWXMAAAABAAAAAQBPJcTWAAAQAElEQVR4nO3WQQkAMAzAwOqYf6FVEQblTkGemQcAEJvfAQDAfYYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOEAAHKGAwDIGQ4AIGc4AICc4QAAcoYDAMgZDgAgZzgAgJzhAAByhgMAyBkOACBnOACAnOLine truncated
|
||||
'base64',
|
||||
);
|
||||
|
||||
// [#145] The fast-upload (fingerprint / forward) path has no video bytes to
|
||||
@@ -75,84 +79,86 @@ const FAST_UPLOAD_FALLBACK_WIDTH = FALLBACK_THUMB_FORMAT.width || 720;
|
||||
const FAST_UPLOAD_FALLBACK_HEIGHT = FALLBACK_THUMB_FORMAT.height || 1280;
|
||||
|
||||
interface VideoPayload {
|
||||
/** Main-file bytes. Empty on the normal path (streamed from `fileSource`)
|
||||
* and when forwarding from cached fingerprints (fastOnly). */
|
||||
bytes: Uint8Array;
|
||||
/** Normal path: the staged video streams from this disk file instead of
|
||||
* buffering `bytes`. Absent for the fingerprint fast path. */
|
||||
fileSource?: { filePath: string; fileSize: number };
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
sha1Blocks: Uint8Array[];
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: 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;
|
||||
/** Baseline stat of the staged file captured before hashing; re-checked
|
||||
* before the upload to fail cleanly if the source was mutated mid-send.
|
||||
* Absent for the fingerprint fast path. */
|
||||
guard?: { size: number; mtimeMs: number };
|
||||
/** Release the staged temp (hardlink / download). Best-effort, idempotent. */
|
||||
cleanup: () => Promise<void>;
|
||||
/** Main-file bytes. Empty on the normal path (streamed from `fileSource`)
|
||||
* and when forwarding from cached fingerprints (fastOnly). */
|
||||
bytes: Uint8Array;
|
||||
/** Normal path: the staged video streams from this disk file instead of
|
||||
* buffering `bytes`. Absent for the fingerprint fast path. */
|
||||
fileSource?: { filePath: string; fileSize: number };
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
sha1Blocks: Uint8Array[];
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: 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;
|
||||
/** Baseline stat of the staged file captured before hashing; re-checked
|
||||
* before the upload to fail cleanly if the source was mutated mid-send.
|
||||
* Absent for the fingerprint fast path. */
|
||||
guard?: { size: number; mtimeMs: number };
|
||||
/** Release the staged temp (hardlink / download). Best-effort, idempotent. */
|
||||
cleanup: () => Promise<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,
|
||||
// Declared cover dims == FALLBACK_THUMB's real pixels (same source as the
|
||||
// video fallback), so content and declared size always agree.
|
||||
width: FAST_UPLOAD_FALLBACK_WIDTH,
|
||||
height: FAST_UPLOAD_FALLBACK_HEIGHT,
|
||||
};
|
||||
const bytes = new Uint8Array(FALLBACK_THUMB);
|
||||
const hashes = computeHashes(bytes);
|
||||
return {
|
||||
bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
// Declared cover dims == FALLBACK_THUMB's real pixels (same source as the
|
||||
// video fallback), so content and declared size always agree.
|
||||
width: FAST_UPLOAD_FALLBACK_WIDTH,
|
||||
height: FAST_UPLOAD_FALLBACK_HEIGHT,
|
||||
};
|
||||
}
|
||||
|
||||
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`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
// Zero-trust on the fast-upload path (no bytes to probe): `|| fallback` not
|
||||
// `??`, so a cached-but-zero value is replaced too. width/height=0 → the
|
||||
// receiver shows 文件已过期; duration=0 → every client renders 00:00 (#145).
|
||||
width: element.width || FAST_UPLOAD_FALLBACK_WIDTH,
|
||||
height: element.height || FAST_UPLOAD_FALLBACK_HEIGHT,
|
||||
duration: element.duration || 1,
|
||||
videoFormat: element.videoFormat ?? 0,
|
||||
thumb: makeFallbackThumb(),
|
||||
fastOnly: true,
|
||||
cleanup: async () => { /* nothing staged */ },
|
||||
};
|
||||
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`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
// Zero-trust on the fast-upload path (no bytes to probe): `|| fallback` not
|
||||
// `??`, so a cached-but-zero value is replaced too. width/height=0 → the
|
||||
// receiver shows 文件已过期; duration=0 → every client renders 00:00 (#145).
|
||||
width: element.width || FAST_UPLOAD_FALLBACK_WIDTH,
|
||||
height: element.height || FAST_UPLOAD_FALLBACK_HEIGHT,
|
||||
duration: element.duration || 1,
|
||||
videoFormat: element.videoFormat ?? 0,
|
||||
thumb: makeFallbackThumb(),
|
||||
fastOnly: true,
|
||||
cleanup: async () => {
|
||||
/* nothing staged */
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface ThumbPayload {
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
width: number;
|
||||
height: number;
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
|
||||
@@ -163,140 +169,160 @@ interface ThumbPayload {
|
||||
// split as computeSha1StateV), replacing a ~110-line hand-rolled, untested
|
||||
// SHA1 duplicate.
|
||||
export function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
|
||||
const sha1 = new Sha1Stream();
|
||||
const blocks: Uint8Array[] = [];
|
||||
let bytesRead = 0;
|
||||
let offset = 0;
|
||||
while (offset + SHA1_BLOCK_SIZE <= bytes.length) {
|
||||
sha1.update(bytes.subarray(offset, offset + SHA1_BLOCK_SIZE));
|
||||
offset += SHA1_BLOCK_SIZE;
|
||||
bytesRead += SHA1_BLOCK_SIZE;
|
||||
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
|
||||
blocks.push(sha1.hash(true)); // little-endian intermediate state
|
||||
const sha1 = new Sha1Stream();
|
||||
const blocks: Uint8Array[] = [];
|
||||
let bytesRead = 0;
|
||||
let offset = 0;
|
||||
|
||||
while (offset + SHA1_BLOCK_SIZE <= bytes.length) {
|
||||
sha1.update(bytes.subarray(offset, offset + SHA1_BLOCK_SIZE));
|
||||
offset += SHA1_BLOCK_SIZE;
|
||||
bytesRead += SHA1_BLOCK_SIZE;
|
||||
|
||||
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
|
||||
blocks.push(sha1.hash(true)); // little-endian intermediate state
|
||||
}
|
||||
}
|
||||
}
|
||||
// Overall SHA1 (finalized) via Node crypto — the reference impl.
|
||||
blocks.push(new Uint8Array(crypto.createHash('sha1').update(Buffer.from(bytes)).digest()));
|
||||
return blocks;
|
||||
|
||||
// Overall SHA1 (finalized) via Node crypto — the reference impl.
|
||||
blocks.push(new Uint8Array(crypto.createHash('sha1').update(Buffer.from(bytes)).digest()));
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// ─────────────── thumb extraction ───────────────
|
||||
|
||||
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumb: ThumbPayload;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
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;
|
||||
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 (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) {
|
||||
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);
|
||||
}
|
||||
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 fmt = detectImageFormat(thumbBytes);
|
||||
width = width || fmt.width || 1;
|
||||
height = height || fmt.height || 1;
|
||||
duration = duration || 1;
|
||||
|
||||
// The cover sub-file must declare its OWN pixel size, which can be smaller
|
||||
// than the video: the ffmpeg addon downscales large frames (4K/8K → ≤1080p)
|
||||
// so the JPEG cover stays under QQ's 1 MiB cover limit. Fall back to the video
|
||||
// dims when the format can't be read. For 1080p and custom-thumb sends the
|
||||
// cover already equals the video size, so this is a no-op there.
|
||||
const thumbWidth = fmt.width || width;
|
||||
const thumbHeight = fmt.height || height;
|
||||
// The cover sub-file must declare its OWN pixel size, which can be smaller
|
||||
// than the video: the ffmpeg addon downscales large frames (4K/8K → ≤1080p)
|
||||
// so the JPEG cover stays under QQ's 1 MiB cover limit. Fall back to the video
|
||||
// dims when the format can't be read. For 1080p and custom-thumb sends the
|
||||
// cover already equals the video size, so this is a no-op there.
|
||||
const thumbWidth = fmt.width || width;
|
||||
const thumbHeight = fmt.height || height;
|
||||
|
||||
const hashes = computeHashes(thumbBytes);
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb: {
|
||||
bytes: thumbBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width: thumbWidth,
|
||||
height: thumbHeight,
|
||||
},
|
||||
};
|
||||
const hashes = computeHashes(thumbBytes);
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb: {
|
||||
bytes: thumbBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width: thumbWidth,
|
||||
height: thumbHeight,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('video fast-upload requires md5Hex + sha1Hex');
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('video fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
|
||||
return videoPayloadFromFingerprint(element);
|
||||
}
|
||||
return videoPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('video source is empty');
|
||||
const source = element.url || element.fileId || '';
|
||||
|
||||
// Stage onto a local disk path (hardlink / streamed download) and hash it in
|
||||
// one streaming pass — the video is never fully buffered in RAM. maxBytes =
|
||||
// MAX_VIDEO_SIZE; oversize sources throw here and the OneBot layer re-routes
|
||||
// them to the file pipeline (matches the message-actions size fallback).
|
||||
const staged = await stageSourceToDisk(source, MAX_VIDEO_SIZE);
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('video file is empty');
|
||||
if (!source) {
|
||||
throw new Error('video source is empty');
|
||||
}
|
||||
|
||||
// Baseline stat captured BEFORE hashing; re-checked before the upload so a
|
||||
// source mutated mid-send fails cleanly (see uploadVideoMsgInfo).
|
||||
const g = await fsp.stat(staged.filePath);
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
|
||||
// Stage onto a local disk path (hardlink / streamed download) and hash it in
|
||||
// one streaming pass — the video is never fully buffered in RAM. maxBytes =
|
||||
// MAX_VIDEO_SIZE; oversize sources throw here and the OneBot layer re-routes
|
||||
// them to the file pipeline (matches the message-actions size fallback).
|
||||
const staged = await stageSourceToDisk(source, MAX_VIDEO_SIZE);
|
||||
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
fileSource: { filePath: staged.filePath, fileSize: staged.fileSize },
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
sha1Blocks: hashes.sha1Blocks,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: (element.fileName || staged.fileName) || `${hashes.md5Hex}.mp4`,
|
||||
fileSize: staged.fileSize,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
videoFormat: 0,
|
||||
thumb,
|
||||
fastOnly: false,
|
||||
guard: { size: g.size, mtimeMs: g.mtimeMs },
|
||||
cleanup: staged.cleanup,
|
||||
};
|
||||
} catch (err) {
|
||||
await staged.cleanup();
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
if (staged.fileSize === 0) {
|
||||
throw new Error('video file is empty');
|
||||
}
|
||||
|
||||
// Baseline stat captured BEFORE hashing; re-checked before the upload so a
|
||||
// source mutated mid-send fails cleanly (see uploadVideoMsgInfo).
|
||||
const g = await fsp.stat(staged.filePath);
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
|
||||
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
fileSource: { filePath: staged.filePath, fileSize: staged.fileSize },
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
sha1Blocks: hashes.sha1Blocks,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: element.fileName || staged.fileName || `${hashes.md5Hex}.mp4`,
|
||||
fileSize: staged.fileSize,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
videoFormat: 0,
|
||||
thumb,
|
||||
fastOnly: false,
|
||||
guard: { size: g.size, mtimeMs: g.mtimeMs },
|
||||
cleanup: staged.cleanup,
|
||||
};
|
||||
} catch (err) {
|
||||
await staged.cleanup();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── exported entry ───────────────
|
||||
@@ -309,143 +335,160 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
* (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,
|
||||
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,
|
||||
fileSource: video.fileSource, // streamed from disk (undefined on the fingerprint fast path)
|
||||
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 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),
|
||||
);
|
||||
|
||||
// Mutation guard: the streaming path reads the staged file twice (hash pass
|
||||
// in loadVideo, then the highway PUT). For a hardlinked local source a
|
||||
// concurrent in-place write would make the uploaded bytes disagree with the
|
||||
// hashes we already sent. Re-stat before the PUT and fail cleanly if the
|
||||
// file changed since the baseline (the server's per-chunk md5 check is the
|
||||
// backstop during the PUT itself).
|
||||
if (video.guard && video.fileSource) {
|
||||
const now = await fsp.stat(video.fileSource.filePath);
|
||||
if (now.size !== video.guard.size || now.mtimeMs !== video.guard.mtimeMs) {
|
||||
throw new Error('video source changed during send (mutated between hashing and upload)');
|
||||
}
|
||||
}
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
|
||||
bytes: video.bytes,
|
||||
fileSource: video.fileSource, // streamed from disk (undefined on the fingerprint fast path)
|
||||
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: {
|
||||
// Mutation guard: the streaming path reads the staged file twice (hash pass
|
||||
// in loadVideo, then the highway PUT). For a hardlinked local source a
|
||||
// concurrent in-place write would make the uploaded bytes disagree with the
|
||||
// hashes we already sent. Re-stat before the PUT and fail cleanly if the
|
||||
// file changed since the baseline (the server's per-chunk md5 check is the
|
||||
// backstop during the PUT itself).
|
||||
if (video.guard && video.fileSource) {
|
||||
const now = await fsp.stat(video.fileSource.filePath);
|
||||
|
||||
if (now.size !== video.guard.size || now.mtimeMs !== video.guard.mtimeMs) {
|
||||
throw new Error(
|
||||
'video source changed during send (mutated between hashing and upload)',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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 },
|
||||
// [#145] Group video MUST carry real width/height. A real QQ
|
||||
// group video's MsgInfo has them (e.g. 296x640); sending 0x0
|
||||
// makes QQ-NT receivers (Android especially) fail to lay out
|
||||
// the video tile and render 文件已过期 even though the resource
|
||||
// is fresh and downloadable (iOS is lenient — shows expired but
|
||||
// still opens). c2c is left at 0 because the QQ-NT server has
|
||||
// been observed to reject non-zero dimensions there with a
|
||||
// schema-mismatch error (no c2c regression coverage yet).
|
||||
height: isGroup ? video.height : 0,
|
||||
width: isGroup ? video.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',
|
||||
);
|
||||
const encoded = finalizeMediaMsgInfo(upload);
|
||||
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
|
||||
Object.assign(element, {
|
||||
md5Hex: video.md5Hex,
|
||||
sha1Hex: video.sha1Hex,
|
||||
fileSize: video.fileSize,
|
||||
fileHash: video.md5Hex,
|
||||
fileSha1: video.sha1Hex,
|
||||
fileName: 'nya.mp4',
|
||||
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
// [#145] Group video MUST carry real width/height. A real QQ
|
||||
// group video's MsgInfo has them (e.g. 296x640); sending 0x0
|
||||
// makes QQ-NT receivers (Android especially) fail to lay out
|
||||
// the video tile and render 文件已过期 even though the resource
|
||||
// is fresh and downloadable (iOS is lenient — shows expired but
|
||||
// still opens). c2c is left at 0 because the QQ-NT server has
|
||||
// been observed to reject non-zero dimensions there with a
|
||||
// schema-mismatch error (no c2c regression coverage yet).
|
||||
height: isGroup ? video.height : 0,
|
||||
width: isGroup ? video.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');
|
||||
const encoded = finalizeMediaMsgInfo(upload);
|
||||
const mediaNode = upload.msgInfo?.msgInfoBody?.[0]?.index;
|
||||
Object.assign(element, {
|
||||
md5Hex: video.md5Hex, sha1Hex: video.sha1Hex, fileSize: video.fileSize,
|
||||
fileName: 'nya.mp4', duration: video.duration, width: video.width, height: video.height, videoFormat: 0,
|
||||
fileId: mediaNode?.fileUuid, mediaNode,
|
||||
});
|
||||
return encoded;
|
||||
} finally {
|
||||
await video.cleanup();
|
||||
}
|
||||
duration: video.duration,
|
||||
width: video.width,
|
||||
height: video.height,
|
||||
videoFormat: 0,
|
||||
fileId: mediaNode?.fileUuid,
|
||||
mediaNode,
|
||||
});
|
||||
return encoded;
|
||||
} finally {
|
||||
await video.cleanup();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user