fix: restore PNG thumbnails for direct video sends (#2000)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s

This commit is contained in:
Chace authored and GitHub committed 2026-08-06 22:08:51 +08:00
1 parent 31c45bf18e
commit efd8679e70
5 files changed
+177 -9

No files matched your search

@@ -6,6 +6,7 @@ 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';
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
if (process.platform === 'win32' && binaryPath) {
@@ -94,6 +95,15 @@ export class FFmpegService {
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 直接发送到 QQ kernel 的旧视频元素使用 PNG 缩略图。
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
*/
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 转换音频文件
*/
+6 -1
View File
@@ -245,7 +245,12 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
});
}
} else {
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(
OB11Data,
msgPeer,
[],
{ usePacketVideoMetadata: true }
);
sendElements = sendElementsCreateReturn.sendElements;
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
}
+20 -6
View File
@@ -129,9 +129,16 @@ export class OneBotFileApi {
}
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.jpg`);
const usePacketVideoMetadata = context.usePacketVideoMetadata === true;
const thumbExtension = usePacketVideoMetadata ? 'jpg' : 'png';
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.${thumbExtension}`);
try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (usePacketVideoMetadata) {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
} else {
videoInfo = await FFmpegService.getVideoInfo(filePath, '');
await FFmpegService.extractLegacyVideoThumbnail(filePath, thumbPath);
}
if (!fs.existsSync(thumbPath)) {
this.core.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
@@ -152,6 +159,16 @@ export class OneBotFileApi {
const thumbMd5 = await calculateFileMD5(thumbPath);
const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? (fileName || _fileName) : `${fileName || _fileName}.${fileExt}`;
const videoMetadata = usePacketVideoMetadata
? {
fileTime: Math.max(0, Math.round(videoInfo.time)),
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
fileWidth: videoInfo.width,
fileHeight: videoInfo.height,
}
: {
fileTime: videoInfo.time,
};
return {
elementType: ElementType.VIDEO,
elementId: '',
@@ -160,10 +177,7 @@ export class OneBotFileApi {
filePath: path,
videoMd5: md5,
thumbMd5,
fileTime: Math.max(0, Math.round(videoInfo.time)),
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
fileWidth: videoInfo.width,
fileHeight: videoInfo.height,
...videoMetadata,
thumbPath: new Map([[0, thumbPath]]),
thumbSize,
thumbWidth: videoInfo.width,
+10 -2
View File
@@ -74,6 +74,7 @@ type Ob11ToRawConverters = {
export type SendMessageContext = {
deleteAfterSentFiles: string[],
peer: Peer;
usePacketVideoMetadata?: boolean;
};
export type RecvMessageContext = {
@@ -1219,7 +1220,10 @@ export class OneBotMsgApi {
async createSendElements (
messageData: OB11MessageData[],
peer: Peer,
ignoreTypes: OB11MessageDataType[] = []
ignoreTypes: OB11MessageDataType[] = [],
options: {
usePacketVideoMetadata?: boolean;
} = {}
) {
const deleteAfterSentFiles: string[] = [];
const callResultList: Array<Promise<SendMessageElement | undefined>> = [];
@@ -1236,7 +1240,11 @@ export class OneBotMsgApi {
}
const callResult = converter(
sendMsg,
{ peer, deleteAfterSentFiles }
{
peer,
deleteAfterSentFiles,
usePacketVideoMetadata: options.usePacketVideoMetadata,
}
)?.catch(undefined);
callResultList.push(callResult);
}
+131
View File
@@ -0,0 +1,131 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { OneBotFileApi } from '@/napcat-onebot/api/file';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { NTVideoType } from '@/napcat-core/types/msg';
const MP4_HEADER = Buffer.from([
0x00, 0x00, 0x00, 0x18,
0x66, 0x74, 0x79, 0x70,
0x69, 0x73, 0x6f, 0x6d,
0x00, 0x00, 0x00, 0x00,
0x69, 0x73, 0x6f, 0x6d,
]);
const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const JPEG_HEADER = Buffer.from([0xff, 0xd8, 0xff, 0xe0]);
describe('OneBot video send modes', () => {
let tempDir: string;
let sourceVideoPath: string;
let uploadedVideoPath: string;
let fileApi: OneBotFileApi;
beforeEach(async () => {
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-video-send-mode-'));
sourceVideoPath = path.join(tempDir, 'clip.mp4');
uploadedVideoPath = path.join(tempDir, 'cache', 'Ori', 'clip.mp4');
await mkdir(path.dirname(uploadedVideoPath), { recursive: true });
await Promise.all([
writeFile(sourceVideoPath, MP4_HEADER),
writeFile(uploadedVideoPath, MP4_HEADER),
]);
const core = {
NapCatTempPath: tempDir,
context: {
logger: {
logError: vi.fn(),
},
},
apis: {
FileApi: {
uploadFile: vi.fn().mockResolvedValue({
fileName: 'clip.mp4',
path: uploadedVideoPath,
fileSize: MP4_HEADER.length,
md5: '00112233445566778899aabbccddeeff',
}),
copyFile: vi.fn(),
},
},
} as unknown as ConstructorParameters<typeof OneBotFileApi>[1];
fileApi = new OneBotFileApi(
{} as ConstructorParameters<typeof OneBotFileApi>[0],
core
);
});
afterEach(async () => {
vi.restoreAllMocks();
await rm(tempDir, { recursive: true, force: true });
});
it('uses a PNG thumbnail and legacy minimal metadata for direct kernel sends', async () => {
const getVideoInfo = vi.spyOn(FFmpegService, 'getVideoInfo').mockResolvedValue({
width: 480,
height: 852,
time: 3.6,
format: 'jpg',
size: MP4_HEADER.length,
filePath: sourceVideoPath,
});
const extractLegacyThumbnail = vi
.spyOn(FFmpegService, 'extractLegacyVideoThumbnail')
.mockImplementation(async (_videoPath, thumbnailPath) => {
await writeFile(thumbnailPath, PNG_HEADER);
});
const context = {
deleteAfterSentFiles: [],
peer: {},
} as unknown as Parameters<OneBotFileApi['createValidSendVideoElement']>[0];
const element = await fileApi.createValidSendVideoElement(context, sourceVideoPath);
const thumbnailPath = element.videoElement.thumbPath?.get(0) as string;
expect(getVideoInfo).toHaveBeenCalledWith(sourceVideoPath, '');
expect(extractLegacyThumbnail).toHaveBeenCalledWith(sourceVideoPath, thumbnailPath);
expect(path.extname(thumbnailPath)).toBe('.png');
expect((await readFile(thumbnailPath)).subarray(0, PNG_HEADER.length)).toEqual(PNG_HEADER);
expect(element.videoElement.fileTime).toBe(3.6);
expect('fileFormat' in element.videoElement).toBe(false);
expect('fileWidth' in element.videoElement).toBe(false);
expect('fileHeight' in element.videoElement).toBe(false);
});
it('keeps JPEG thumbnails and complete metadata for packet forward uploads', async () => {
const getVideoInfo = vi
.spyOn(FFmpegService, 'getVideoInfo')
.mockImplementation(async (videoPath, thumbnailPath) => {
await writeFile(thumbnailPath, JPEG_HEADER);
return {
width: 480,
height: 852,
time: 3.6,
format: 'jpg',
size: MP4_HEADER.length,
filePath: videoPath,
};
});
const extractLegacyThumbnail = vi.spyOn(FFmpegService, 'extractLegacyVideoThumbnail');
const context = {
deleteAfterSentFiles: [],
peer: {},
usePacketVideoMetadata: true,
} as unknown as Parameters<OneBotFileApi['createValidSendVideoElement']>[0];
const element = await fileApi.createValidSendVideoElement(context, sourceVideoPath);
const thumbnailPath = element.videoElement.thumbPath?.get(0) as string;
expect(getVideoInfo).toHaveBeenCalledWith(sourceVideoPath, thumbnailPath);
expect(extractLegacyThumbnail).not.toHaveBeenCalled();
expect(path.extname(thumbnailPath)).toBe('.jpg');
expect((await readFile(thumbnailPath)).subarray(0, JPEG_HEADER.length)).toEqual(JPEG_HEADER);
expect(element.videoElement.fileTime).toBe(4);
expect(element.videoElement.fileFormat).toBe(NTVideoType.VIDEO_FORMAT_MP4);
expect(element.videoElement.fileWidth).toBe(480);
expect(element.videoElement.fileHeight).toBe(852);
});
});