diff --git a/.github/workflows/macos-native.yml b/.github/workflows/macos-native.yml index 903b0e607..05e8e25b2 100644 --- a/.github/workflows/macos-native.yml +++ b/.github/workflows/macos-native.yml @@ -45,7 +45,7 @@ jobs: - uses: actions/checkout@v4 with: repository: NapNeko/ffmpegAddon - ref: 3a6e99cea9a856ca71f7d70e11d6d769498121d9 + ref: 7a68e99b52921a47f7f6d99864ed6217a0a90e7d path: ffmpeg-native-tests - name: Verify packaged FFmpeg working-directory: ffmpeg-native-tests @@ -53,4 +53,4 @@ jobs: FFMPEG_ADDON_PATH: ${{ github.workspace }}/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.${{ matrix.arch }}.node run: | npm ci --ignore-scripts - node --test test/video-info.test.js + npm test diff --git a/.github/workflows/release-downstream.yml b/.github/workflows/release-downstream.yml index 6bbfc5606..47910a574 100644 --- a/.github/workflows/release-downstream.yml +++ b/.github/workflows/release-downstream.yml @@ -9,8 +9,8 @@ on: type: string env: - QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.AppImage' - QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.AppImage' + QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.36/beta/9ee04bef/linuxqq_3.2.34-53644_x86_64.AppImage' + QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.36/beta/9ee04bef/linuxqq_3.2.34-53644_arm64.AppImage' jobs: get-version: @@ -86,17 +86,19 @@ jobs: git push shell-docker: + needs: get-version runs-on: ubuntu-latest steps: - name: Trigger NapCat-Docker docker-publish workflow env: GH_TOKEN: ${{ secrets.NAPCAT_BUILD }} + NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }} run: | curl -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer $GH_TOKEN" \ https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \ - -d '{"ref":"main"}' + -d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\"}}" framework-docker: runs-on: ubuntu-latest diff --git a/packages/napcat-core/helper/audio.ts b/packages/napcat-core/helper/audio.ts index 960421611..4a29d64fd 100644 --- a/packages/napcat-core/helper/audio.ts +++ b/packages/napcat-core/helper/audio.ts @@ -1,45 +1,16 @@ -import fsPromise from 'fs/promises'; import path from 'node:path'; import { randomUUID } from 'crypto'; import { LogWrapper } from '@/napcat-core/helper/log'; import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg'; -async function guessDuration (pttPath: string, logger: LogWrapper) { - const pttFileInfo = await fsPromise.stat(pttPath); - const duration = Math.max(1, Math.floor(pttFileInfo.size / 1024 / 3)); // 3kb/s - logger.log('通过文件大小估算语音的时长:', duration); - return duration; -} - -export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: LogWrapper) { - try { - const pttPath = path.join(TEMP_DIR, randomUUID()); - if (!(await FFmpegService.isSilk(filePath))) { - logger.log(`语音文件${filePath}需要转换成silk`); - await FFmpegService.convertToNTSilkTct(filePath, pttPath); - const duration = await FFmpegService.getDuration(filePath); - logger.log(`语音文件${filePath}转换成功!`, pttPath, '时长:', duration); - return { - converted: true, - path: pttPath, - duration, - }; - } else { - let duration = 0; - try { - duration = await FFmpegService.getDuration(filePath); - } catch (e: unknown) { - logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, (e as Error).stack); - duration = await guessDuration(filePath, logger); - } - return { - converted: false, - path: filePath, - duration, - }; - } - } catch (error: unknown) { - logger.logError('convert silk failed', error); - return {}; +export async function encodeSilk (filePath: string, temporaryDirectory: string, logger: LogWrapper) { + const converted = !(await FFmpegService.isSilk(filePath)); + const pttPath = converted ? path.join(temporaryDirectory, randomUUID()) : filePath; + if (converted) { + logger.log(`语音文件${filePath}需要转换成silk`); + await FFmpegService.convertToNTSilkTct(filePath, pttPath); } + const duration = await FFmpegService.getDuration(pttPath); + logger.log('语音文件已就绪:', pttPath, '时长:', duration); + return { converted, path: pttPath, duration }; } diff --git a/packages/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory.ts b/packages/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory.ts index 46786510f..a80a9f4f4 100644 --- a/packages/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory.ts +++ b/packages/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory.ts @@ -4,7 +4,8 @@ */ import { LogWrapper } from '@/napcat-core/helper/log'; -import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter'; +import { FFmpegAddonAdapter, getAddonPath } from './ffmpeg-addon-adapter'; +import { existsSync } from 'node:fs'; import { FFmpegExecAdapter } from './ffmpeg-exec-adapter'; import type { IFFmpegAdapter } from './ffmpeg-adapter-interface'; @@ -58,8 +59,8 @@ export class FFmpegAdapterFactory { ffprobePath: string, binaryPath?: string ): Promise { - // 1. 优先尝试使用 Native Addon - if (binaryPath) { + const useCommandLine = Boolean(process.env['FFMPEG_PATH'] || process.env['FFPROBE_PATH']); + if (binaryPath && !useCommandLine && existsSync(getAddonPath(binaryPath))) { const addonAdapter = new FFmpegAddonAdapter(binaryPath); logger.log('[FFmpeg] 检查 Native Addon 可用性...'); @@ -68,13 +69,10 @@ export class FFmpegAdapterFactory { return addonAdapter; } - logger.log('[FFmpeg] Native Addon 不可用,尝试使用命令行工具'); - } else { - logger.log('[FFmpeg] 未提供 binaryPath,跳过 Native Addon 检测'); + throw new Error('FFmpeg Native Addon 加载失败: ' + getAddonPath(binaryPath)); } - // 2. 降级到 execFile 实现 - const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath, binaryPath, logger); + const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath); logger.log(`[FFmpeg] 检查命令行工具可用性: ${ffmpegPath}`); if (await execAdapter.isAvailable()) { @@ -82,9 +80,7 @@ export class FFmpegAdapterFactory { return execAdapter; } - // 3. 都不可用,返回 execAdapter 但会在使用时报错 - logger.logError('[FFmpeg] 警告: FFmpeg 不可用,将使用命令行适配器但可能失败'); - return execAdapter; + throw new Error('FFmpeg 命令行工具不可用,请检查 ffmpeg 和 ffprobe 路径: ' + ffmpegPath + ', ' + ffprobePath); } /** @@ -105,20 +101,14 @@ export class FFmpegAdapterFactory { logger: LogWrapper, ffmpegPath: string, ffprobePath: string - ): Promise { - // 如果当前使用的是 Exec 适配器,更新路径 - if (this.instance && this.instance instanceof FFmpegExecAdapter) { - logger.log(`[FFmpeg] 更新 FFmpeg 路径: ${ffmpegPath}`); - this.instance.setFFmpegPath(ffmpegPath); - this.instance.setFFprobePath(ffprobePath); - - // 验证新路径是否可用 - if (await this.instance.isAvailable()) { - logger.log('[FFmpeg] 新路径验证成功 ✓'); - } else { - logger.logError('[FFmpeg] 警告: 新 FFmpeg 路径不可用'); - } + ): Promise { + const adapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath); + if (!await adapter.isAvailable()) { + throw new Error('FFmpeg 路径不可用: ' + ffmpegPath + ', ' + ffprobePath); } + this.instance = adapter; + logger.log('[FFmpeg] 已更新命令行工具路径:', ffmpegPath, ffprobePath); + return adapter; } /** diff --git a/packages/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter.ts b/packages/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter.ts index c15a5aad8..c3859acd4 100644 --- a/packages/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter.ts +++ b/packages/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter.ts @@ -3,9 +3,8 @@ * 使用原生 Node.js Addon 实现的 FFmpeg 适配器 */ -import { platform, arch } from 'node:os'; import path from 'node:path'; -import { existsSync, openSync, readSync, closeSync } from 'node:fs'; +import { openSync, readSync, closeSync } from 'node:fs'; import { writeFile } from 'node:fs/promises'; import type { FFmpeg } from './ffmpeg-addon'; import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface'; @@ -15,15 +14,9 @@ import { dlopen } from 'node:process'; * 获取 Native Addon 路径 * @param binaryPath 二进制文件路径(来自 pathWrapper.binaryPath) */ -function getAddonPath (binaryPath: string): string { - const platformName = platform(); - const archName = arch(); - +export function getAddonPath (binaryPath: string): string { const addonFileName: string = process.platform + '.' + process.arch; const addonPath = path.join(binaryPath, './native/ffmpeg/', `ffmpegAddon.${addonFileName}.node`); - if (!existsSync(addonPath)) { - throw new Error(`Unsupported platform: ${platformName} ${archName} - Addon not found at ${addonPath}`); - } return addonPath; } @@ -130,9 +123,9 @@ export class FFmpegAddonAdapter implements IFFmpegAdapter { /** * 提取缩略图 */ - async extractThumbnail (videoPath: string, thumbnailPath: string): Promise { + async extractThumbnail (videoPath: string, thumbnailPath: string, format: 'jpg' | 'png' = 'jpg'): Promise { const addon = this.ensureAddon(); - const info = await addon.getVideoInfo(videoPath); + const info = await addon.getVideoInfo(videoPath, format); // 将缩略图写入文件 await writeFile(thumbnailPath, info.image); diff --git a/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts b/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts index 3ecb0cd71..1ba0409c3 100644 --- a/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts +++ b/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts @@ -53,7 +53,7 @@ export interface FFmpeg { /** * Get video information including resolution, duration, format, codec and first frame thumbnail */ - getVideoInfo (filePath: string, format?: 'bmp' | 'bmp24'): Promise; + getVideoInfo (filePath: string, format?: 'jpg' | 'png'): Promise; /** * Get duration of audio or video file in seconds diff --git a/packages/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter.ts b/packages/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter.ts index 063e29961..1134720d6 100644 --- a/packages/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter.ts +++ b/packages/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter.ts @@ -3,14 +3,10 @@ * 使用 execFile 调用 FFmpeg 命令行工具的适配器实现 */ -import { readFileSync, existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs'; -import { dirname, join } from 'path'; +import { existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs'; +import { dirname } from 'path'; import { execFile } from 'child_process'; import { promisify } from 'util'; -import { fileTypeFromFile } from 'file-type'; -import { imageSizeFallBack } from 'napcat-image-size/src/index'; -import { downloadFFmpegIfNotExists } from './download-ffmpeg'; -import { LogWrapper } from '@/napcat-core/helper/log'; import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface'; const execFileAsync = promisify(execFile); @@ -30,52 +26,24 @@ function ensureDirExists (filePath: string): void { */ export class FFmpegExecAdapter implements IFFmpegAdapter { public readonly name = 'FFmpegExec'; - private downloadAttempted = false; constructor ( private ffmpegPath: string = 'ffmpeg', - private ffprobePath: string = 'ffprobe', - private binaryPath?: string, - private logger?: LogWrapper + private ffprobePath: string = 'ffprobe' ) { } /** - * 检查 FFmpeg 是否可用,如果不可用则尝试下载 + * 检查 FFmpeg 和 FFprobe 是否可用 */ async isAvailable (): Promise { // 首先检查当前路径 try { - await execFileAsync(this.ffmpegPath, ['-version']); + await Promise.all([ + execFileAsync(this.ffmpegPath, ['-version'], { timeout: 10000, windowsHide: true }), + execFileAsync(this.ffprobePath, ['-version'], { timeout: 10000, windowsHide: true }), + ]); return true; } catch { - // 如果失败且未尝试下载,尝试下载 - if (!this.downloadAttempted && this.binaryPath && this.logger) { - this.downloadAttempted = true; - - if (process.env['NAPCAT_DISABLE_FFMPEG_DOWNLOAD']) { - return false; - } - - this.logger.log('[FFmpeg] 未找到可用的 FFmpeg,尝试自动下载...'); - const result = await downloadFFmpegIfNotExists(this.logger); - - if (result.path && result.reset) { - // 更新路径 - if (process.platform === 'win32') { - this.ffmpegPath = join(result.path, 'ffmpeg.exe'); - this.ffprobePath = join(result.path, 'ffprobe.exe'); - this.logger.log('[FFmpeg] 已更新路径:', this.ffmpegPath); - - // 再次检查 - try { - await execFileAsync(this.ffmpegPath, ['-version']); - return true; - } catch { - return false; - } - } - } - } return false; } } @@ -98,40 +66,29 @@ export class FFmpegExecAdapter implements IFFmpegAdapter { * 获取视频信息 */ async getVideoInfo (videoPath: string): Promise { - // 获取文件大小和类型 - const [fileType, duration] = await Promise.all([ - fileTypeFromFile(videoPath).catch(() => null), - this.getDuration(videoPath).catch(() => 60), + const [probe, frame] = await Promise.all([ + execFileAsync(this.ffprobePath, [ + '-v', 'error', '-select_streams', 'v:0', + '-show_entries', 'stream=width,height:format=duration,format_name', + '-of', 'json', videoPath, + ], { timeout: 30000, windowsHide: true }), + execFileAsync(this.ffmpegPath, [ + '-v', 'error', '-i', videoPath, '-frames:v', '1', + '-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1', + ], { encoding: 'buffer', maxBuffer: 16 * 1024 * 1024, timeout: 30000, windowsHide: true }), ]); - - // 创建临时缩略图路径 - const thumbnailPath = `${videoPath}.thumbnail.bmp`; - let width = 100; - let height = 100; - let thumbnail: Buffer | undefined; - - try { - await this.extractThumbnail(videoPath, thumbnailPath); - - // 获取图片尺寸 - const dimensions = await imageSizeFallBack(thumbnailPath); - width = dimensions.width ?? 100; - height = dimensions.height ?? 100; - - // 读取缩略图 - if (existsSync(thumbnailPath)) { - thumbnail = readFileSync(thumbnailPath); - } - } catch (_error) { - // 使用默认值 + const metadata = JSON.parse(probe.stdout); + const stream = metadata.streams[0]; + const duration = Number(metadata.format.duration); + if (!stream || !Number.isFinite(duration) || duration < 0 || frame.stdout.length === 0) { + throw new Error('FFmpeg 无法读取视频信息或首帧: ' + videoPath); } - return { - width, - height, + width: stream.width, + height: stream.height, duration, - format: fileType?.ext ?? 'mp4', - thumbnail, + format: metadata.format.format_name, + thumbnail: frame.stdout, }; } @@ -147,10 +104,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter { '-of', 'default=noprint_wrappers=1:nokey=1', filePath, - ]); + ], { timeout: 30000, windowsHide: true }); const duration = parseFloat(stdout.trim()); - if (isNaN(duration)) { + if (!Number.isFinite(duration) || duration < 0) { throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`); } return duration; @@ -186,7 +143,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter { '-ac', '1', '-f', 's16le', pcmPath, - ]); + ], { timeout: 120000, windowsHide: true }); if (!existsSync(pcmPath)) { throw new Error('转换PCM失败,输出文件不存在'); @@ -207,25 +164,22 @@ export class FFmpegExecAdapter implements IFFmpegAdapter { const params = format === 'amr' ? [ - '-f', 's16le', - '-ar', '24000', - '-ac', '1', '-i', inputFile, + '-vn', '-ac', '1', '-ar', '8000', '-b:a', '12.2k', '-y', outputFile, ] : [ - '-f', 's16le', - '-ar', '24000', - '-ac', '1', '-i', inputFile, + '-vn', '-ac', '1', + ...(format === 'spx' ? ['-ar', '32000'] : []), '-y', outputFile, ]; - await execFileAsync(this.ffmpegPath, params); + await execFileAsync(this.ffmpegPath, params, { timeout: 120000, windowsHide: true }); if (!existsSync(outputFile)) { throw new Error('转换失败,输出文件不存在'); @@ -245,11 +199,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter { const { stderr } = await execFileAsync(this.ffmpegPath, [ '-i', videoPath, - '-ss', '00:00:01.000', '-vframes', '1', '-y', // 覆盖输出文件 thumbnailPath, - ]); + ], { timeout: 30000, windowsHide: true }); if (!existsSync(thumbnailPath)) { throw new Error(`提取缩略图失败,输出文件不存在: ${stderr}`); @@ -260,7 +213,11 @@ export class FFmpegExecAdapter implements IFFmpegAdapter { } } - async convertToNTSilkTct (_inputFile: string, _outputFile: string): Promise { - throw new Error('convertToNTSilkTct is not implemented in FFmpegExecAdapter'); + async convertToNTSilkTct (inputFile: string, outputFile: string): Promise { + ensureDirExists(outputFile); + await execFileAsync(this.ffmpegPath, [ + '-v', 'error', '-y', '-i', inputFile, '-vn', '-ac', '1', '-ar', '24000', + '-c:a', 'ntsilk_s16le', '-f', 'ntsilk_s16le', outputFile, + ], { timeout: 120000, windowsHide: true }); } } diff --git a/packages/napcat-core/helper/ffmpeg/ffmpeg.ts b/packages/napcat-core/helper/ffmpeg/ffmpeg.ts index 52d6aae55..24fa09803 100644 --- a/packages/napcat-core/helper/ffmpeg/ffmpeg.ts +++ b/packages/napcat-core/helper/ffmpeg/ffmpeg.ts @@ -1,21 +1,29 @@ import { statSync, existsSync, writeFileSync } from 'fs'; import path from 'path'; import type { VideoInfo } from './video'; -import { fileTypeFromFile } from 'file-type'; -import { platform } from 'node:os'; import { LogWrapper } from '@/napcat-core/helper/log'; import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory'; import type { IFFmpegAdapter } from './ffmpeg-adapter-interface'; import { FFmpegExecAdapter } from './ffmpeg-exec-adapter'; +import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter'; -const getFFmpegPath = (tool: string, binaryPath?: string): string => { - if (process.platform === 'win32' && binaryPath) { - const exeName = `${tool}.exe`; - const localPath = path.join(binaryPath, 'ffmpeg', exeName); - const isLocalExeExists = existsSync(localPath); - return isLocalExeExists ? localPath : exeName; +export const getFFmpegPath = (tool: 'ffmpeg' | 'ffprobe', binaryPath?: string): string => { + const configuredPath = process.env[tool === 'ffmpeg' ? 'FFMPEG_PATH' : 'FFPROBE_PATH']; + if (configuredPath) return configuredPath; + const executable = tool + (process.platform === 'win32' ? '.exe' : ''); + if (binaryPath) { + const localPath = path.join(binaryPath, 'ffmpeg', executable); + if (existsSync(localPath)) return localPath; } - return tool; + if (process.platform === 'darwin') { + const directories = (process.env['PATH'] ?? '').split(':').filter(Boolean); + directories.push(process.arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin'); + for (const directory of directories) { + const candidate = path.join(directory, executable); + if (existsSync(candidate)) return candidate; + } + } + return executable; }; export let FFMPEG_CMD = 'ffmpeg'; @@ -23,6 +31,7 @@ export let FFPROBE_CMD = 'ffprobe'; export class FFmpegService { private static adapter: IFFmpegAdapter | null = null; private static initialized = false; + private static initializationError: unknown; /** * 初始化 FFmpeg 服务 @@ -38,20 +47,24 @@ export class FFmpegService { FFMPEG_CMD = getFFmpegPath('ffmpeg', binaryPath); FFPROBE_CMD = getFFmpegPath('ffprobe', binaryPath); - // 立即初始化适配器(会触发自动下载等逻辑) - this.adapter = await FFmpegAdapterFactory.getAdapter( - logger, - FFMPEG_CMD, - FFPROBE_CMD, - binaryPath - ); + try { + this.adapter = await FFmpegAdapterFactory.getAdapter( + logger, + FFMPEG_CMD, + FFPROBE_CMD, + binaryPath + ); + } catch (error) { + this.initializationError = error; + logger.logError('[FFmpeg] 媒体功能初始化失败:', error); + } this.initialized = true; } public static getAdapterName (): string { if (!this.adapter) { - throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.'); + throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.'); } return this.adapter.name; } @@ -61,7 +74,7 @@ export class FFmpegService { */ private static async getAdapter (): Promise { if (!this.adapter) { - throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.'); + throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.'); } return this.adapter; } @@ -76,15 +89,14 @@ export class FFmpegService { * @deprecated 建议使用 init() 方法初始化 */ public static async setFfmpegPath (ffmpegPath: string, logger: LogWrapper): Promise { - if (platform() === 'win32') { - FFMPEG_CMD = path.join(ffmpegPath, 'ffmpeg.exe'); - FFPROBE_CMD = path.join(ffmpegPath, 'ffprobe.exe'); - logger.log('[Check] ffmpeg:', FFMPEG_CMD); - logger.log('[Check] ffprobe:', FFPROBE_CMD); - - // 更新适配器路径 - await FFmpegAdapterFactory.updateFFmpegPath(logger, FFMPEG_CMD, FFPROBE_CMD); - } + const suffix = process.platform === 'win32' ? '.exe' : ''; + const ffmpegCommand = path.join(ffmpegPath, 'ffmpeg' + suffix); + const ffprobeCommand = path.join(ffmpegPath, 'ffprobe' + suffix); + this.adapter = await FFmpegAdapterFactory.updateFFmpegPath(logger, ffmpegCommand, ffprobeCommand); + FFMPEG_CMD = ffmpegCommand; + FFPROBE_CMD = ffprobeCommand; + this.initializationError = undefined; + this.initialized = true; } /** @@ -100,6 +112,11 @@ export class FFmpegService { * Packet/forward 路径继续使用当前适配器生成的 JPEG。 */ public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise { + const currentAdapter = await this.getAdapter(); + if (currentAdapter instanceof FFmpegAddonAdapter) { + await currentAdapter.extractThumbnail(videoPath, thumbnailPath, 'png'); + return; + } const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD); await adapter.extractThumbnail(videoPath, thumbnailPath); } @@ -142,41 +159,18 @@ export class FFmpegService { public static async getVideoInfo (videoPath: string, thumbnailPath: string): Promise { const adapter = await this.getAdapter(); - try { - // 获取文件大小 - const fileSize = statSync(videoPath).size; - - // 使用适配器获取视频信息 - const videoInfo = await adapter.getVideoInfo(videoPath); - - // 如果提供了缩略图路径且适配器返回了缩略图,保存到指定路径 - if (thumbnailPath && videoInfo.thumbnail) { - writeFileSync(thumbnailPath, videoInfo.thumbnail); - } - - const result: VideoInfo = { - width: videoInfo.width, - height: videoInfo.height, - time: videoInfo.duration, - format: videoInfo.format, - size: fileSize, - filePath: videoPath, - }; - - return result; - } catch (_error) { - // 降级处理:返回默认值 - const fileType = await fileTypeFromFile(videoPath).catch(() => null); - const fileSize = statSync(videoPath).size; - - return { - width: 100, - height: 100, - time: 60, - format: fileType?.ext ?? 'mp4', - size: fileSize, - filePath: videoPath, - }; + const fileSize = statSync(videoPath).size; + const videoInfo = await adapter.getVideoInfo(videoPath); + if (thumbnailPath && videoInfo.thumbnail) { + writeFileSync(thumbnailPath, videoInfo.thumbnail); } + return { + width: videoInfo.width, + height: videoInfo.height, + time: videoInfo.duration, + format: videoInfo.format, + size: fileSize, + filePath: videoPath, + }; } } diff --git a/packages/napcat-core/packet/client/nativeClient.ts b/packages/napcat-core/packet/client/nativeClient.ts index dabc4103d..4022d240a 100644 --- a/packages/napcat-core/packet/client/nativeClient.ts +++ b/packages/napcat-core/packet/client/nativeClient.ts @@ -38,7 +38,8 @@ export class NativePacketClient { } async init (_pid: number, recv: string, send: string): Promise { - const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824'); + this.available = false; + const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40768'); if (!isNewQQ) { this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化'); return; @@ -77,8 +78,9 @@ export class NativePacketClient { data: (ret as { rspbuffer: Buffer; }).rspbuffer, })); + let timeoutHandle: ReturnType; const timeoutPromise = new Promise((_resolve, reject) => { - setTimeout( + timeoutHandle = setTimeout( () => reject( new Error( @@ -89,7 +91,11 @@ export class NativePacketClient { ); }); - return Promise.race([sendPromise, timeoutPromise]); + try { + return await Promise.race([sendPromise, timeoutPromise]); + } finally { + clearTimeout(timeoutHandle!); + } } async sendOidbPacket (pkt: OidbPacket, rsp = false, timeout = 5000): Promise { diff --git a/packages/napcat-core/packet/handler/client.ts b/packages/napcat-core/packet/handler/client.ts index 3f3cc2761..4603ebaf1 100644 --- a/packages/napcat-core/packet/handler/client.ts +++ b/packages/napcat-core/packet/handler/client.ts @@ -14,7 +14,7 @@ interface OffsetType { const typedOffset: OffsetType = offset; // 0 send 1 recv export interface NativePacketExportType { - initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => boolean; + initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => string; } export type PacketType = 0 | 1; // 0: send, 1: recv @@ -38,10 +38,15 @@ export class NativePacketHandler { this.logger = logger; try { const platform = process.platform + '.' + process.arch; + if (!this.supportedPlatforms.includes(platform)) { + this.logger.logWarn(`NativePacketClient: 不支持的平台: ${platform}`); + return; + } const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/packet/MoeHoo.' + platform + '.node'); if (!fs.existsSync(moehoo_path)) { this.logger.logWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`); this.loaded = false; + return; } process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY); this.loaded = true; @@ -213,9 +218,13 @@ export class NativePacketHandler { return false; } - this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => { + const result = this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => { this.emitPacket(type, uin, cmd, seq, hex_data); }, o3HookMode); + if (result !== 'success') { + this.logger.logError(`[PacketHandler] 初始化失败: ${result}`); + return false; + } this.logger.log('[PacketHandler] 初始化成功'); return true; } catch (error) { diff --git a/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.arm64.node b/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.arm64.node index 03263c808..11b16ed77 100644 Binary files a/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.arm64.node and b/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.arm64.node differ diff --git a/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.x64.node b/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.x64.node index f533b04b9..13a1c6140 100644 Binary files a/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.x64.node and b/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.x64.node differ diff --git a/packages/napcat-native/ffmpeg/ffmpegAddon.linux.arm64.node b/packages/napcat-native/ffmpeg/ffmpegAddon.linux.arm64.node index 2a7d07a39..87642d82f 100644 Binary files a/packages/napcat-native/ffmpeg/ffmpegAddon.linux.arm64.node and b/packages/napcat-native/ffmpeg/ffmpegAddon.linux.arm64.node differ diff --git a/packages/napcat-native/ffmpeg/ffmpegAddon.linux.x64.node b/packages/napcat-native/ffmpeg/ffmpegAddon.linux.x64.node index f08ec0c41..588025118 100644 Binary files a/packages/napcat-native/ffmpeg/ffmpegAddon.linux.x64.node and b/packages/napcat-native/ffmpeg/ffmpegAddon.linux.x64.node differ diff --git a/packages/napcat-native/ffmpeg/ffmpegAddon.win32.x64.node b/packages/napcat-native/ffmpeg/ffmpegAddon.win32.x64.node index b9b5c92f9..6e70cdb27 100644 Binary files a/packages/napcat-native/ffmpeg/ffmpegAddon.win32.x64.node and b/packages/napcat-native/ffmpeg/ffmpegAddon.win32.x64.node differ diff --git a/packages/napcat-test/audioEncoding.test.ts b/packages/napcat-test/audioEncoding.test.ts new file mode 100644 index 000000000..283cd0097 --- /dev/null +++ b/packages/napcat-test/audioEncoding.test.ts @@ -0,0 +1,38 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { encodeSilk } from '@/napcat-core/helper/audio'; +import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg'; +import type { LogWrapper } from '@/napcat-core/helper/log'; + +vi.mock('@/napcat-core/helper/ffmpeg/ffmpeg', () => ({ + FFmpegService: { isSilk: vi.fn(), convertToNTSilkTct: vi.fn(), getDuration: vi.fn() }, +})); + +const logger = { log: vi.fn() } as unknown as LogWrapper; + +beforeEach(() => vi.resetAllMocks()); + +describe('SILK encoding', () => { + it('reads duration from the encoded output including the final packet', async () => { + vi.mocked(FFmpegService.isSilk).mockResolvedValue(false); + vi.mocked(FFmpegService.getDuration).mockResolvedValue(0.02); + const result = await encodeSilk('/short.wav', '/temp', logger); + expect(result.converted).toBe(true); + expect(FFmpegService.convertToNTSilkTct).toHaveBeenCalledWith('/short.wav', result.path); + expect(FFmpegService.getDuration).toHaveBeenCalledWith(result.path); + expect(result.duration).toBe(0.02); + }); + + it('propagates a corrupt SILK error without estimating its duration', async () => { + vi.mocked(FFmpegService.isSilk).mockResolvedValue(true); + vi.mocked(FFmpegService.getDuration).mockRejectedValue(new Error('corrupt SILK packet')); + await expect(encodeSilk('/corrupt.silk', '/temp', logger)).rejects.toThrow('corrupt SILK packet'); + expect(FFmpegService.convertToNTSilkTct).not.toHaveBeenCalled(); + }); + + it('propagates conversion errors to the caller', async () => { + vi.mocked(FFmpegService.isSilk).mockResolvedValue(false); + vi.mocked(FFmpegService.convertToNTSilkTct).mockRejectedValue(new Error('encoder unavailable')); + await expect(encodeSilk('/audio.wav', '/temp', logger)).rejects.toThrow('encoder unavailable'); + expect(FFmpegService.getDuration).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/napcat-test/ffmpegAdapters.test.ts b/packages/napcat-test/ffmpegAdapters.test.ts new file mode 100644 index 000000000..0b46d6ed9 --- /dev/null +++ b/packages/napcat-test/ffmpegAdapters.test.ts @@ -0,0 +1,180 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import path from 'node:path'; +import { FFmpegAdapterFactory } from '@/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory'; +import { FFmpegAddonAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter'; +import { FFmpegExecAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter'; +import { FFmpegService, getFFmpegPath } from '@/napcat-core/helper/ffmpeg/ffmpeg'; +import type { LogWrapper } from '@/napcat-core/helper/log'; + +const mocks = vi.hoisted(() => ({ + execute: vi.fn(), + dlopen: vi.fn(), + exists: vi.fn(), +})); + +vi.mock('fs', async (importOriginal) => { + const original = await importOriginal(); + return { ...original, existsSync: mocks.exists }; +}); + +vi.mock('child_process', async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + execFile: Object.assign(vi.fn(), { + [Symbol.for('nodejs.util.promisify.custom')]: mocks.execute, + }), + }; +}); + +vi.mock('node:process', async (importOriginal) => { + const original = await importOriginal(); + return { ...original, dlopen: mocks.dlopen }; +}); + +const logger = { log: vi.fn(), logError: vi.fn() } as unknown as LogWrapper; +const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!; +const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!; + +beforeEach(() => { + FFmpegAdapterFactory.reset(); + vi.stubEnv('FFMPEG_PATH', ''); + vi.stubEnv('FFPROBE_PATH', ''); + mocks.execute.mockReset().mockResolvedValue({ stdout: '', stderr: '' }); + mocks.dlopen.mockReset(); + mocks.exists.mockReset().mockReturnValue(false); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + Object.defineProperty(process, 'platform', platformDescriptor); + Object.defineProperty(process, 'arch', archDescriptor); +}); + +describe('FFmpeg platform paths', () => { + it.each(['arm64', 'x64'])('finds Homebrew for macOS %s outside GUI PATH', (arch) => { + Object.defineProperty(process, 'platform', { value: 'darwin' }); + Object.defineProperty(process, 'arch', { value: arch }); + vi.stubEnv('PATH', '/usr/bin:/bin'); + const prefix = arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin'; + mocks.exists.mockImplementation(candidate => String(candidate).startsWith(path.join(prefix))); + expect(getFFmpegPath('ffmpeg')).toBe(path.join(prefix, 'ffmpeg')); + expect(getFFmpegPath('ffprobe')).toBe(path.join(prefix, 'ffprobe')); + }); + + it('preserves explicit paths containing spaces without searching alternatives', () => { + vi.stubEnv('FFMPEG_PATH', '/private/My Tools/ffmpeg'); + vi.stubEnv('FFPROBE_PATH', '/private/My Tools/ffprobe'); + const exists = mocks.exists.mockReturnValue(true); + expect(getFFmpegPath('ffmpeg', '/app')).toBe('/private/My Tools/ffmpeg'); + expect(getFFmpegPath('ffprobe', '/app')).toBe('/private/My Tools/ffprobe'); + expect(exists).not.toHaveBeenCalled(); + }); + + it('uses packaged Windows executables before PATH', () => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + mocks.exists.mockReturnValue(true); + expect(getFFmpegPath('ffmpeg', '/app')).toBe(path.join('/app', 'ffmpeg', 'ffmpeg.exe')); + }); +}); + +describe('FFmpeg adapter selection', () => { + it.each(['arm64', 'x64'])('loads the packaged macOS %s addon', async (arch) => { + Object.defineProperty(process, 'platform', { value: 'darwin' }); + Object.defineProperty(process, 'arch', { value: arch }); + mocks.exists.mockReturnValue(true); + mocks.dlopen.mockImplementation(module => { module.exports = {}; }); + const adapter = await FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app'); + expect(adapter.name).toBe('FFmpegAddon'); + expect(mocks.dlopen).toHaveBeenCalledWith(expect.anything(), path.join('/app', 'native/ffmpeg', 'ffmpegAddon.darwin.' + arch + '.node')); + expect(mocks.execute).not.toHaveBeenCalled(); + }); + + it('does not hide a broken packaged addon behind another adapter', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}); + mocks.exists.mockReturnValue(true); + mocks.dlopen.mockImplementation(() => { throw new Error('wrong architecture'); }); + await expect(FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app')).rejects.toThrow('Native Addon'); + expect(mocks.execute).not.toHaveBeenCalled(); + expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull(); + }); + + it('honors an explicit command line configuration', async () => { + vi.stubEnv('FFMPEG_PATH', '/tools/ffmpeg'); + mocks.exists.mockReturnValue(true); + const adapter = await FFmpegAdapterFactory.getAdapter(logger, '/tools/ffmpeg', '/tools/ffprobe', '/app'); + expect(adapter.name).toBe('FFmpegExec'); + expect(mocks.dlopen).not.toHaveBeenCalled(); + expect(mocks.execute).toHaveBeenCalledWith('/tools/ffmpeg', ['-version'], expect.objectContaining({ timeout: 10000 })); + expect(mocks.execute).toHaveBeenCalledWith('/tools/ffprobe', ['-version'], expect.objectContaining({ timeout: 10000 })); + }); + + it('rejects a missing ffprobe and allows a corrected configuration', async () => { + mocks.exists.mockReturnValue(false); + mocks.execute.mockImplementation(async command => { + if (command === 'ffprobe') throw new Error('ENOENT'); + return { stdout: '', stderr: '' }; + }); + await expect(FFmpegAdapterFactory.getAdapter(logger)).rejects.toThrow('ffprobe'); + expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull(); + mocks.execute.mockResolvedValue({ stdout: '', stderr: '' }); + expect((await FFmpegAdapterFactory.getAdapter(logger)).name).toBe('FFmpegExec'); + }); + + it('validates replacement paths before changing the active adapter', async () => { + const adapter = await FFmpegAdapterFactory.getAdapter(logger); + mocks.execute.mockRejectedValue(new Error('EACCES')); + await expect(FFmpegAdapterFactory.updateFFmpegPath(logger, '/bad/ffmpeg', '/bad/ffprobe')).rejects.toThrow('/bad/ffprobe'); + expect(FFmpegAdapterFactory.getCurrentAdapter()).toBe(adapter); + }); +}); + +describe('FFmpeg media operations', () => { + it('transcodes encoded audio without treating its bytes as raw PCM', async () => { + mocks.exists.mockReturnValue(true); + await new FFmpegExecAdapter().convertFile('/record.wav', '/record.mp3', 'mp3'); + expect(mocks.execute).toHaveBeenCalledWith('ffmpeg', [ + '-i', '/record.wav', '-vn', '-ac', '1', '-y', '/record.mp3', + ], expect.objectContaining({ timeout: 120000, windowsHide: true })); + }); + + it('reports a corrupt video instead of inventing dimensions and duration', async () => { + mocks.execute.mockRejectedValue(new Error('invalid video')); + await expect(new FFmpegExecAdapter().getVideoInfo('/video.mp4')).rejects.toThrow('invalid video'); + }); + + it('reads actual video metadata and JPEG bytes without a shared temporary file', async () => { + const thumbnail = Buffer.from([255, 216, 255, 217]); + mocks.execute.mockImplementation(async command => command === 'ffprobe' + ? { stdout: JSON.stringify({ streams: [{ width: 360, height: 480 }], format: { duration: '0.5', format_name: 'mov,mp4' } }) } + : { stdout: thumbnail }); + await expect(new FFmpegExecAdapter().getVideoInfo('/clip with spaces.mp4')).resolves.toEqual({ + width: 360, height: 480, duration: 0.5, format: 'mov,mp4', thumbnail, + }); + }); + + it('uses the native PNG encoder for legacy videos on macOS', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin' }); + const adapter = new FFmpegAddonAdapter('/app'); + const extract = vi.spyOn(adapter, 'extractThumbnail').mockResolvedValue(); + vi.spyOn(FFmpegAdapterFactory, 'getAdapter').mockResolvedValue(adapter); + await FFmpegService.init('/app', logger); + await FFmpegService.extractLegacyVideoThumbnail('/video.mp4', '/thumbnail.png'); + expect(extract).toHaveBeenCalledWith('/video.mp4', '/thumbnail.png', 'png'); + expect(mocks.execute).not.toHaveBeenCalled(); + }); + + it('keeps startup available and reports unavailable media until paths are corrected', async () => { + vi.resetModules(); + const { FFmpegService: service } = await import('@/napcat-core/helper/ffmpeg/ffmpeg'); + mocks.exists.mockReturnValue(false); + mocks.execute.mockRejectedValue(new Error('ENOENT')); + await expect(service.init('/app', logger)).resolves.toBeUndefined(); + await expect(service.getDuration('/audio.wav')).rejects.toThrow('ffprobe'); + expect(logger.logError).toHaveBeenCalled(); + mocks.execute.mockResolvedValue({ stdout: '1.5', stderr: '' }); + await service.setFfmpegPath('/installed tools', logger); + await expect(service.getDuration('/audio.wav')).resolves.toBe(1.5); + }); +}); diff --git a/packages/napcat-test/nativePacketClients.test.ts b/packages/napcat-test/nativePacketClients.test.ts new file mode 100644 index 000000000..77369a6de --- /dev/null +++ b/packages/napcat-test/nativePacketClients.test.ts @@ -0,0 +1,104 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import { NativePacketHandler } from '@/napcat-core/packet/handler/client'; +import { Napi2NativeLoader } from '@/napcat-core/packet/handler/napi2nativeLoader'; +import { NativePacketClient } from '@/napcat-core/packet/client/nativeClient'; +import type { LogWrapper } from '@/napcat-core/helper/log'; +import type { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext'; +import type { PacketLogger } from '@/napcat-core/packet/context/loggerContext'; +import type { LogStack } from '@/napcat-core/packet/context/clientContext'; +import type { PacketBuf } from '@/napcat-core/packet/transformer/base'; + +const logger = { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn() } as unknown as LogWrapper; +const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!; +const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!; + +beforeEach(() => { + Object.defineProperty(process, 'platform', { value: 'darwin' }); + vi.spyOn(fs, 'existsSync').mockReturnValue(true); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + Object.defineProperty(process, 'platform', platformDescriptor); + Object.defineProperty(process, 'arch', archDescriptor); +}); + +describe('macOS native loaders', () => { + it.each(['arm64', 'x64'])('loads both packet modules for %s', async (arch) => { + Object.defineProperty(process, 'arch', { value: arch }); + const dlopen = vi.spyOn(process, 'dlopen').mockImplementation((module) => { + Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue('success') } }); + }); + const handler = new NativePacketHandler({ logger }); + expect(await handler.init('7.0.2-53644')).toBe(true); + expect(dlopen.mock.calls[0]![1]).toContain('MoeHoo.darwin.' + arch + '.node'); + const loader = new Napi2NativeLoader({ logger }); + expect(loader.loaded).toBe(true); + expect(dlopen.mock.calls[1]![1]).toContain('napi2native.darwin.' + arch + '.node'); + }); + + it.each(['error hook', 'error search', undefined])('does not report native failure %s as success', async (result) => { + Object.defineProperty(process, 'arch', { value: 'arm64' }); + vi.spyOn(process, 'dlopen').mockImplementation(module => { + Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue(result) } }); + }); + expect(await new NativePacketHandler({ logger }).init('7.0.2-53644')).toBe(false); + }); + + it('does not attempt dlopen when a native binary is absent', async () => { + vi.mocked(fs.existsSync).mockReturnValue(false); + const dlopen = vi.spyOn(process, 'dlopen').mockImplementation(() => {}); + const handler = new NativePacketHandler({ logger }); + expect(await handler.init('7.0.2-53644')).toBe(false); + expect(new Napi2NativeLoader({ logger }).loaded).toBe(false); + expect(dlopen).not.toHaveBeenCalled(); + }); +}); + +describe('NativePacketClient', () => { + function fixture () { + const send = vi.fn(); + const minimum = vi.fn().mockImplementation(version => Number(version) <= 40768); + const native = { initHook: vi.fn().mockReturnValue(true) }; + const core = { basicInfo: { requireMinNTQQBuild: minimum }, sendSsoCmdReqByContend: send }; + const logs = { pushLogWarn: vi.fn(), pushLogInfo: vi.fn(), pushLogError: vi.fn() }; + const client = new NativePacketClient( + core as unknown as NapCoreContext, + { error: vi.fn() } as unknown as PacketLogger, + logs as unknown as LogStack, + native as unknown as Napi2NativeLoader + ); + return { client, send, minimum, native }; + } + + it('initializes the oldest supported build and clears availability after failure', async () => { + const { client, minimum, native } = fixture(); + await client.init(0, '10', '20'); + expect(minimum).toHaveBeenCalledWith('40768'); + expect(client.available).toBe(true); + native.initHook.mockReturnValue(false); + await client.init(0, '10', '20'); + expect(client.available).toBe(false); + }); + + it.each(['success', 'failure', 'timeout'])('clears request timers after %s', async (outcome) => { + vi.useFakeTimers(); + const { client, send } = fixture(); + const payload = Buffer.from([0, 255, 128]) as PacketBuf; + if (outcome === 'success') send.mockResolvedValue({ rspbuffer: payload }); + if (outcome === 'failure') send.mockRejectedValue(new Error('network unavailable')); + if (outcome === 'timeout') send.mockReturnValue(new Promise(() => {})); + const pending = client.sendPacket('Test.Command', payload, true, 50); + if (outcome === 'success') { + await expect(pending).resolves.toEqual({ seq: 0, cmd: 'Test.Command', data: payload }); + } else { + const assertion = expect(pending).rejects.toThrow(outcome === 'timeout' ? '超时' : 'network unavailable'); + if (outcome === 'timeout') await vi.advanceTimersByTimeAsync(50); + await assertion; + } + expect(vi.getTimerCount()).toBe(0); + expect(send).toHaveBeenCalledWith('Test.Command', payload); + }); +});