fix: 修复合并转发视频过期及移动端延迟显示问题 (#1983)
* fix: 修复合并转发视频过期问题 * fix: 修复移动端合并转发内容延迟显示问题 * fix: 同步 ffmpegAddon 视频封面处理产物
This commit is contained in:
1 parent
33546b936e
commit
5ee1150277
15 files changed
+413
-101
No files matched your search
@@ -21,13 +21,13 @@ export interface VideoInfo {
|
||||
/** Video duration in seconds */
|
||||
duration: number;
|
||||
|
||||
/** Container format name (e.g., "mp4", "mkv", "avi") */
|
||||
/** Generated thumbnail image format */
|
||||
format: string;
|
||||
|
||||
/** Video codec name (e.g., "h264", "hevc", "vp9") */
|
||||
videoCodec: string;
|
||||
|
||||
/** First frame thumbnail as BMP image buffer */
|
||||
/** First frame thumbnail as JPEG image buffer */
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
|
||||
import { gunzipSync } from 'zlib';
|
||||
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
|
||||
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
|
||||
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
|
||||
|
||||
export class PacketOperationContext {
|
||||
private readonly context: PacketContext;
|
||||
@@ -105,15 +106,7 @@ export class PacketOperationContext {
|
||||
.filter(Boolean)
|
||||
);
|
||||
const res = await Promise.allSettled(reqList);
|
||||
const failedCount = res.filter((r) => r.status === 'rejected').length;
|
||||
if (failedCount > 0) {
|
||||
this.context.logger.warn(`上传资源${res.length}个,失败${failedCount}个`);
|
||||
res.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
assertUploadResults(res, this.context.logger);
|
||||
}
|
||||
|
||||
async UploadImage (img: PacketMsgPicElement) {
|
||||
@@ -240,9 +233,10 @@ export class PacketOperationContext {
|
||||
}
|
||||
|
||||
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
|
||||
// await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源(跳过已有原始数据的项)
|
||||
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
|
||||
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
|
||||
await this.SendPreprocess(item.actionMsg!, groupUin);
|
||||
}));
|
||||
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
@@ -370,6 +364,23 @@ export class PacketOperationContext {
|
||||
}
|
||||
return element;
|
||||
}
|
||||
if (element.videoElement && rawElem?.commonElem?.pbElem) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
|
||||
const index = extra?.msgInfoBody[0]?.index;
|
||||
if (!index) return element;
|
||||
if (msg?.responseHead.grp !== undefined) {
|
||||
element.videoElement = {
|
||||
...element.videoElement,
|
||||
filePath: await this.GetGroupVideoUrl(msg.responseHead.grp.groupUin ?? 0, index),
|
||||
};
|
||||
} else {
|
||||
element.videoElement = {
|
||||
...element.videoElement,
|
||||
filePath: await this.GetVideoUrl(this.context.napcore.basicInfo.uid, index),
|
||||
};
|
||||
}
|
||||
return element;
|
||||
}
|
||||
return element;
|
||||
})
|
||||
);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface UploadResultLogger {
|
||||
warn (message: string): unknown;
|
||||
error (message: string): unknown;
|
||||
}
|
||||
|
||||
export function assertUploadResults (
|
||||
results: PromiseSettledResult<unknown>[],
|
||||
logger: UploadResultLogger
|
||||
): void {
|
||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||
if (failures.length === 0) return;
|
||||
|
||||
logger.warn(`上传资源${results.length}个,失败${failures.length}个`);
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
const reason = result.reason instanceof Error
|
||||
? result.reason.stack ?? result.reason.message
|
||||
: String(result.reason);
|
||||
logger.error(`上传第${index + 1}个资源失败:${reason}`);
|
||||
}
|
||||
});
|
||||
throw new AggregateError(
|
||||
failures.map(result => result.reason),
|
||||
`上传转发消息资源失败:${failures.length}/${results.length}`
|
||||
);
|
||||
}
|
||||
@@ -21,8 +21,11 @@ import { PacketClientContext } from '@/napcat-core/packet/context/clientContext'
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
import { calculateFileMD5 } from 'napcat-common/src/file';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { imageSizeFallBack } from 'napcat-image-size/src/index';
|
||||
|
||||
export const BlockSize = 1024 * 1024;
|
||||
const VIDEO_THUMBNAIL_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
interface HighwayServerAddr {
|
||||
ip: string;
|
||||
@@ -110,22 +113,37 @@ export class PacketHighwayContext {
|
||||
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
|
||||
}
|
||||
|
||||
// 如果缺少视频缩略图,自动生成一个
|
||||
let tempThumbPath: string | null = null;
|
||||
let thumbExists = false;
|
||||
if (video.thumbPath) {
|
||||
try {
|
||||
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
|
||||
thumbExists = true;
|
||||
} catch {
|
||||
thumbExists = false;
|
||||
}
|
||||
}
|
||||
if (!video.thumbPath || !thumbExists) {
|
||||
tempThumbPath = await this.ensureVideoThumb(video);
|
||||
}
|
||||
|
||||
const cleanupThumbPaths: string[] = [];
|
||||
try {
|
||||
let thumbExists = false;
|
||||
if (video.thumbPath) {
|
||||
try {
|
||||
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
|
||||
thumbExists = true;
|
||||
} catch {
|
||||
thumbExists = false;
|
||||
}
|
||||
}
|
||||
|
||||
let shouldGenerateThumb = !video.thumbPath || !thumbExists;
|
||||
if (!shouldGenerateThumb) {
|
||||
try {
|
||||
await this.updateVideoThumbInfo(video);
|
||||
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
|
||||
this.logger.warn(`[Highway] Video thumbnail is too large: ${video.thumbSize} bytes, regenerating`);
|
||||
shouldGenerateThumb = true;
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`[Highway] Failed to inspect video thumbnail, regenerating. Reason: ${e instanceof Error ? e.message : e}`);
|
||||
shouldGenerateThumb = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldGenerateThumb) {
|
||||
cleanupThumbPaths.push(await this.ensureVideoThumb(video));
|
||||
}
|
||||
video.businessType = peer.chatType === ChatType.KCHATTYPEGROUP ? 21 : 11;
|
||||
|
||||
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
|
||||
await this.uploadGroupVideo(+peer.peerUid, video);
|
||||
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
|
||||
@@ -134,23 +152,21 @@ export class PacketHighwayContext {
|
||||
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
|
||||
}
|
||||
} finally {
|
||||
// 清理临时生成的缩略图文件
|
||||
if (tempThumbPath) {
|
||||
const thumbToClean = tempThumbPath;
|
||||
fs.promises.unlink(thumbToClean)
|
||||
.then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`))
|
||||
.catch((e) => {
|
||||
// 文件不存在时忽略错误
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
await Promise.allSettled(cleanupThumbPaths.map(async (thumbToClean) => {
|
||||
try {
|
||||
await fs.promises.unlink(thumbToClean);
|
||||
this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保视频缩略图存在,如果不存在则自动生成
|
||||
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
|
||||
* @returns 生成的临时缩略图路径,用于后续清理
|
||||
*/
|
||||
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
|
||||
@@ -161,9 +177,10 @@ export class PacketHighwayContext {
|
||||
// 生成缩略图路径
|
||||
const videoDir = path.dirname(video.filePath);
|
||||
const videoBasename = path.basename(video.filePath, path.extname(video.filePath));
|
||||
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
|
||||
const thumbPath = path.join(videoDir, `${videoBasename}_thumb_${randomUUID()}.jpg`);
|
||||
|
||||
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
|
||||
video.thumbPath = thumbPath;
|
||||
|
||||
try {
|
||||
// 尝试使用 FFmpeg 提取视频缩略图
|
||||
@@ -174,26 +191,36 @@ export class PacketHighwayContext {
|
||||
} catch {
|
||||
throw new Error('FFmpeg failed to generate thumbnail');
|
||||
}
|
||||
await this.updateVideoThumbInfo(video);
|
||||
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
|
||||
throw new Error(`generated thumbnail is too large: ${video.thumbSize} bytes`);
|
||||
}
|
||||
} catch (e) {
|
||||
// FFmpeg 失败时(包括未初始化的情况)使用默认缩略图
|
||||
this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
|
||||
await fs.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
|
||||
await this.updateVideoThumbInfo(video);
|
||||
}
|
||||
|
||||
// 更新视频元素的缩略图信息
|
||||
video.thumbPath = thumbPath;
|
||||
const thumbStat = await fs.promises.stat(thumbPath);
|
||||
video.thumbSize = thumbStat.size;
|
||||
video.thumbMd5 = await calculateFileMD5(thumbPath);
|
||||
// 默认缩略图尺寸(与 defaultVideoThumbB64 匹配的尺寸)
|
||||
if (!video.thumbWidth) video.thumbWidth = 240;
|
||||
if (!video.thumbHeight) video.thumbHeight = 383;
|
||||
|
||||
this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
|
||||
|
||||
return thumbPath;
|
||||
}
|
||||
|
||||
private async updateVideoThumbInfo (video: PacketMsgVideoElement): Promise<void> {
|
||||
if (!video.thumbPath) {
|
||||
throw new Error('video.thumbPath is empty, cannot inspect thumbnail');
|
||||
}
|
||||
const [thumbStat, thumbMd5, dimensions] = await Promise.all([
|
||||
fs.promises.stat(video.thumbPath),
|
||||
calculateFileMD5(video.thumbPath),
|
||||
imageSizeFallBack(video.thumbPath),
|
||||
]);
|
||||
video.thumbSize = thumbStat.size;
|
||||
video.thumbMd5 = thumbMd5;
|
||||
video.thumbWidth = dimensions.width;
|
||||
video.thumbHeight = dimensions.height;
|
||||
this.logger.debug(`[Highway] Video thumbnail ready: ${dimensions.width}x${dimensions.height}, ${thumbStat.size} bytes`);
|
||||
}
|
||||
|
||||
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
|
||||
await this.checkAvailable();
|
||||
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
|
||||
@@ -296,13 +323,17 @@ export class PacketHighwayContext {
|
||||
const req = trans.UploadGroupVideo.build(groupUin, video);
|
||||
const resp = await this.client.sendOidbPacket(req, true);
|
||||
const preRespData = trans.UploadGroupVideo.parse(resp);
|
||||
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
|
||||
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
|
||||
if (!videoIndex || !thumbIndex) {
|
||||
throw new Error('[Highway] uploadGroupVideo response is missing video or thumbnail MsgInfo');
|
||||
}
|
||||
const ukey = preRespData.upload.uKey;
|
||||
if (ukey && ukey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
uKey: ukey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
|
||||
@@ -324,16 +355,15 @@ export class PacketHighwayContext {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
|
||||
}
|
||||
const subFile = preRespData.upload.subFileInfos[0];
|
||||
if (subFile!.uKey && subFile!.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
|
||||
if (subFile?.uKey && subFile.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
|
||||
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
uKey: subFile!.uKey,
|
||||
fileUuid: thumbIndex.fileUuid,
|
||||
uKey: subFile.uKey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
|
||||
},
|
||||
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
|
||||
blockSize: BlockSize,
|
||||
@@ -349,7 +379,7 @@ export class PacketHighwayContext {
|
||||
extend
|
||||
);
|
||||
} else {
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
|
||||
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
|
||||
}
|
||||
video.msgInfo = preRespData.upload.msgInfo;
|
||||
}
|
||||
@@ -361,13 +391,17 @@ export class PacketHighwayContext {
|
||||
const req = trans.UploadPrivateVideo.build(peerUid, video);
|
||||
const resp = await this.client.sendOidbPacket(req, true);
|
||||
const preRespData = trans.UploadPrivateVideo.parse(resp);
|
||||
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
|
||||
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
|
||||
if (!videoIndex || !thumbIndex) {
|
||||
throw new Error('[Highway] uploadC2CVideo response is missing video or thumbnail MsgInfo');
|
||||
}
|
||||
const ukey = preRespData.upload.uKey;
|
||||
if (ukey && ukey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
uKey: ukey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
|
||||
@@ -389,16 +423,15 @@ export class PacketHighwayContext {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
|
||||
}
|
||||
const subFile = preRespData.upload.subFileInfos[0];
|
||||
if (subFile!.uKey && subFile!.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
|
||||
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
|
||||
const md5 = Buffer.from(index.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
|
||||
if (subFile?.uKey && subFile.uKey !== '') {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
|
||||
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
|
||||
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
|
||||
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
|
||||
fileUuid: index.fileUuid,
|
||||
uKey: subFile!.uKey,
|
||||
fileUuid: thumbIndex.fileUuid,
|
||||
uKey: subFile.uKey,
|
||||
network: {
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
|
||||
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
|
||||
},
|
||||
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
|
||||
blockSize: BlockSize,
|
||||
@@ -414,7 +447,7 @@ export class PacketHighwayContext {
|
||||
extend
|
||||
);
|
||||
} else {
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
|
||||
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
|
||||
}
|
||||
video.msgInfo = preRespData.upload.msgInfo;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
MessageElement,
|
||||
Peer,
|
||||
RawMessage,
|
||||
} from '@/napcat-core/types/msg';
|
||||
import {
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
@@ -15,7 +17,7 @@ import {
|
||||
SendReplyElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
} from '@/napcat-core/index';
|
||||
} from '@/napcat-core/types/element';
|
||||
import {
|
||||
IPacketMsgElement,
|
||||
PacketMsgAtElement,
|
||||
@@ -158,7 +160,8 @@ export class PacketMsgConverter {
|
||||
|
||||
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
|
||||
const converters = [PacketMsgTextElement.parseElement,
|
||||
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
|
||||
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
|
||||
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
|
||||
return msg.map((element) => {
|
||||
for (const converter of converters) {
|
||||
const result = converter(element);
|
||||
|
||||
@@ -20,7 +20,11 @@ import {
|
||||
FaceType,
|
||||
MessageElement,
|
||||
NTMsgAtType,
|
||||
NTVideoType,
|
||||
PicType,
|
||||
Peer,
|
||||
} from '@/napcat-core/types/msg';
|
||||
import {
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
@@ -32,8 +36,7 @@ import {
|
||||
SendMultiForwardMsgElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
Peer,
|
||||
} from '@/napcat-core/index';
|
||||
} from '@/napcat-core/types/element';
|
||||
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
|
||||
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
|
||||
|
||||
@@ -387,8 +390,10 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
}
|
||||
|
||||
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
|
||||
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
|
||||
if (elem?.commonElem?.serviceType === 48 &&
|
||||
[10, 20].includes(elem.commonElem.businessType ?? 0) &&
|
||||
elem.commonElem.pbElem) {
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
|
||||
const msgInfoBody = extra.msgInfoBody[0];
|
||||
const index = msgInfoBody?.index;
|
||||
return [{
|
||||
@@ -406,7 +411,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
summary: '[图片]',
|
||||
thumbPath: new Map(),
|
||||
},
|
||||
elementType: ElementType.UNKNOWN,
|
||||
elementType: ElementType.PIC,
|
||||
elementId: '',
|
||||
}, elem];
|
||||
}
|
||||
@@ -446,8 +451,13 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
|
||||
}
|
||||
|
||||
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
fileName: string;
|
||||
fileSize?: string;
|
||||
filePath?: string;
|
||||
fileTime: number;
|
||||
fileFormat: NTVideoType;
|
||||
fileWidth?: number;
|
||||
fileHeight?: number;
|
||||
thumbSize?: number;
|
||||
thumbPath?: string;
|
||||
fileMd5?: string;
|
||||
@@ -456,12 +466,18 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
thumbSha1?: string;
|
||||
thumbWidth?: number;
|
||||
thumbHeight?: number;
|
||||
businessType: 11 | 21 = 21;
|
||||
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
|
||||
|
||||
constructor (element: SendVideoElement) {
|
||||
super(element);
|
||||
this.fileName = element.videoElement.fileName;
|
||||
this.fileSize = element.videoElement.fileSize;
|
||||
this.filePath = element.videoElement.filePath;
|
||||
this.fileTime = Math.max(0, Math.round(element.videoElement.fileTime ?? 0));
|
||||
this.fileFormat = element.videoElement.fileFormat ?? NTVideoType.VIDEO_FORMAT_MP4;
|
||||
this.fileWidth = element.videoElement.fileWidth;
|
||||
this.fileHeight = element.videoElement.fileHeight;
|
||||
this.thumbSize = element.videoElement.thumbSize;
|
||||
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
|
||||
this.fileMd5 = element.videoElement.videoMd5;
|
||||
@@ -480,11 +496,45 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
|
||||
businessType: 21,
|
||||
businessType: this.businessType,
|
||||
},
|
||||
}];
|
||||
}
|
||||
|
||||
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
|
||||
if (elem?.commonElem?.serviceType !== 48 ||
|
||||
![11, 21].includes(elem.commonElem.businessType ?? 0) ||
|
||||
!elem.commonElem.pbElem) {
|
||||
return undefined;
|
||||
}
|
||||
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
|
||||
const videoIndex = extra.msgInfoBody[0]?.index;
|
||||
const thumbIndex = extra.msgInfoBody[1]?.index;
|
||||
if (!videoIndex) return undefined;
|
||||
return [{
|
||||
videoElement: {
|
||||
filePath: '',
|
||||
fileName: videoIndex.info.fileName || videoIndex.info.fileHash,
|
||||
videoMd5: videoIndex.info.fileHash,
|
||||
thumbMd5: thumbIndex?.info.fileHash,
|
||||
fileTime: videoIndex.info.time,
|
||||
fileFormat: (videoIndex.info.type.videoFormat || NTVideoType.VIDEO_FORMAT_MP4) as NTVideoType,
|
||||
fileSize: String(videoIndex.info.fileSize),
|
||||
fileWidth: videoIndex.info.width,
|
||||
fileHeight: videoIndex.info.height,
|
||||
thumbWidth: thumbIndex?.info.width,
|
||||
thumbHeight: thumbIndex?.info.height,
|
||||
thumbSize: thumbIndex?.info.fileSize,
|
||||
thumbPath: new Map(),
|
||||
fileUuid: videoIndex.fileUuid,
|
||||
busiType: 0,
|
||||
subBusiType: 0,
|
||||
},
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
}, elem];
|
||||
};
|
||||
|
||||
override toPreview (): string {
|
||||
return '[视频]';
|
||||
}
|
||||
|
||||
@@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
|
||||
fileSize: +video.fileSize,
|
||||
fileHash: video.fileMd5,
|
||||
fileSha1: video.fileSha1,
|
||||
fileName: 'nya.mp4',
|
||||
fileName: video.fileName || 'video.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
picFormat: 0,
|
||||
videoFormat: 0,
|
||||
videoFormat: video.fileFormat,
|
||||
voiceFormat: 0,
|
||||
},
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
height: video.fileHeight ?? 0,
|
||||
width: video.fileWidth ?? 0,
|
||||
time: video.fileTime,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
@@ -51,7 +51,7 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
|
||||
fileSize: +video.thumbSize,
|
||||
fileHash: video.thumbMd5,
|
||||
fileSha1: video.thumbSha1,
|
||||
fileName: 'nya.jpg',
|
||||
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
|
||||
@@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
|
||||
fileSize: +video.fileSize,
|
||||
fileHash: video.fileMd5,
|
||||
fileSha1: video.fileSha1,
|
||||
fileName: 'nya.mp4',
|
||||
fileName: video.fileName || 'video.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
picFormat: 0,
|
||||
videoFormat: 0,
|
||||
videoFormat: video.fileFormat,
|
||||
voiceFormat: 0,
|
||||
},
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
height: video.fileHeight ?? 0,
|
||||
width: video.fileWidth ?? 0,
|
||||
time: video.fileTime,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
@@ -52,7 +52,7 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
|
||||
fileSize: +video.thumbSize,
|
||||
fileHash: video.thumbMd5,
|
||||
fileSha1: video.thumbSha1,
|
||||
fileName: 'nya.jpg',
|
||||
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
|
||||
@@ -118,6 +118,8 @@ export interface VideoElement {
|
||||
thumbSize?: number; // byte
|
||||
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
|
||||
fileSize?: string; // byte
|
||||
fileWidth?: number;
|
||||
fileHeight?: number;
|
||||
thumbWidth?: number;
|
||||
thumbHeight?: number;
|
||||
busiType?: 0; //
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -2,7 +2,7 @@ import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
import { encodeSilk } from '@/napcat-core/helper/audio';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { calculateFileMD5 } from 'napcat-common/src/file';
|
||||
import { ElementType, NapCatCore, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
|
||||
import { ElementType, NapCatCore, NTVideoType, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
|
||||
import { getFileTypeForSendType } from 'napcat-core/helper/msg';
|
||||
import { imageSizeFallBack } from 'napcat-image-size';
|
||||
import { SendMessageContext } from './msg';
|
||||
@@ -12,6 +12,21 @@ import fsPromises from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
|
||||
const videoFormatByExtension: Partial<Record<string, NTVideoType>> = {
|
||||
afs: NTVideoType.VIDEO_FORMAT_AFS,
|
||||
avi: NTVideoType.VIDEO_FORMAT_AVI,
|
||||
mkv: NTVideoType.VIDEO_FORMAT_MKV,
|
||||
mod: NTVideoType.VIDEO_FORMAT_MOD,
|
||||
mov: NTVideoType.VIDEO_FORMAT_MOV,
|
||||
mp4: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
mts: NTVideoType.VIDEO_FORMAT_MTS,
|
||||
rm: NTVideoType.VIDEO_FORMAT_RM,
|
||||
rmvb: NTVideoType.VIDEO_FORMAT_RMVB,
|
||||
ts: NTVideoType.VIDEO_FORMAT_TS,
|
||||
wmv: NTVideoType.VIDEO_FORMAT_WMV,
|
||||
};
|
||||
|
||||
export class OneBotFileApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
core: NapCatCore;
|
||||
@@ -114,7 +129,7 @@ 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.png`);
|
||||
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.jpg`);
|
||||
try {
|
||||
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
|
||||
if (!fs.existsSync(thumbPath)) {
|
||||
@@ -135,7 +150,6 @@ export class OneBotFileApi {
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
const thumbSize = (await fsPromises.stat(thumbPath)).size;
|
||||
const thumbMd5 = await calculateFileMD5(thumbPath);
|
||||
context.deleteAfterSentFiles.push(thumbPath);
|
||||
|
||||
const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? (fileName || _fileName) : `${fileName || _fileName}.${fileExt}`;
|
||||
return {
|
||||
@@ -146,7 +160,10 @@ export class OneBotFileApi {
|
||||
filePath: path,
|
||||
videoMd5: md5,
|
||||
thumbMd5,
|
||||
fileTime: videoInfo.time,
|
||||
fileTime: Math.max(0, Math.round(videoInfo.time)),
|
||||
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
|
||||
fileWidth: videoInfo.width,
|
||||
fileHeight: videoInfo.height,
|
||||
thumbPath: new Map([[0, thumbPath]]),
|
||||
thumbSize,
|
||||
thumbWidth: videoInfo.width,
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import { ElementType, NTVideoType } from '@/napcat-core/types/msg';
|
||||
import { SendVideoElement } from '@/napcat-core/types/element';
|
||||
import {
|
||||
PacketMsgPicElement,
|
||||
PacketMsgVideoElement,
|
||||
} from '@/napcat-core/packet/message/element';
|
||||
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
|
||||
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
|
||||
import { Elem, MsgInfo } from '@/napcat-core/packet/transformer/proto';
|
||||
import { NTV2RichMediaReq } from '@/napcat-core/packet/transformer/proto/oidb/common/Ntv2.RichMediaReq';
|
||||
import UploadGroupVideo from '@/napcat-core/packet/transformer/highway/UploadGroupVideo';
|
||||
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
function createVideoMsgInfo (): NapProtoEncodeStructType<typeof MsgInfo> {
|
||||
return {
|
||||
msgInfoBody: [
|
||||
{
|
||||
index: {
|
||||
info: {
|
||||
fileSize: 1024,
|
||||
fileHash: '00112233445566778899aabbccddeeff',
|
||||
fileSha1: '00112233445566778899aabbccddeeff00112233',
|
||||
fileName: 'clip.mp4',
|
||||
type: {
|
||||
type: 2,
|
||||
videoFormat: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
},
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
time: 12,
|
||||
},
|
||||
fileUuid: 'video-uuid',
|
||||
},
|
||||
},
|
||||
{
|
||||
index: {
|
||||
info: {
|
||||
fileSize: 2048,
|
||||
fileHash: 'ffeeddccbbaa99887766554433221100',
|
||||
fileSha1: 'ffeeddccbbaa99887766554433221100ffeeddcc',
|
||||
fileName: 'thumb.jpg',
|
||||
type: {
|
||||
type: 1,
|
||||
picFormat: 0,
|
||||
},
|
||||
width: 640,
|
||||
height: 360,
|
||||
},
|
||||
fileUuid: 'thumb-uuid',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function createSendVideoElement (): SendVideoElement {
|
||||
return {
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: '',
|
||||
videoElement: {
|
||||
filePath: 'clip.mp4',
|
||||
fileName: 'clip.mp4',
|
||||
videoMd5: '00112233445566778899aabbccddeeff',
|
||||
thumbMd5: 'ffeeddccbbaa99887766554433221100',
|
||||
fileTime: 12,
|
||||
fileFormat: NTVideoType.VIDEO_FORMAT_MP4,
|
||||
fileSize: '1024',
|
||||
fileWidth: 1920,
|
||||
fileHeight: 1080,
|
||||
thumbWidth: 640,
|
||||
thumbHeight: 360,
|
||||
thumbSize: 2048,
|
||||
thumbPath: new Map([[0, 'thumb.jpg']]),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function decodeElem (
|
||||
elem: NapProtoEncodeStructType<typeof Elem>
|
||||
): NapProtoDecodeStructType<typeof Elem> {
|
||||
const codec = new NapProtoMsg(Elem);
|
||||
return codec.decode(codec.encode(elem));
|
||||
}
|
||||
|
||||
function createCommonVideoElem (businessType: 11 | 21): NapProtoDecodeStructType<typeof Elem> {
|
||||
return decodeElem({
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
businessType,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(createVideoMsgInfo()),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('packet video forwarding', () => {
|
||||
it('emits only the common rich-media element so mobile rendering is not blocked', () => {
|
||||
const video = new PacketMsgVideoElement(createSendVideoElement());
|
||||
video.msgInfo = createVideoMsgInfo();
|
||||
video.businessType = 11;
|
||||
|
||||
const elems = video.buildElement();
|
||||
|
||||
expect(elems).toHaveLength(1);
|
||||
expect(elems[0]?.videoFile).toBeUndefined();
|
||||
expect(elems[0]?.commonElem?.serviceType).toBe(48);
|
||||
expect(elems[0]?.commonElem?.businessType).toBe(11);
|
||||
expect(video.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('parses common business type 11/21 as video instead of image', () => {
|
||||
for (const businessType of [11, 21] as const) {
|
||||
const commonElem = createCommonVideoElem(businessType);
|
||||
expect(PacketMsgPicElement.parseElement(commonElem)).toBeUndefined();
|
||||
|
||||
const parsed = new PacketMsgConverter().packetMsgToRaw([commonElem]);
|
||||
|
||||
expect(parsed).toHaveLength(1);
|
||||
expect(parsed[0]?.[0].elementType).toBe(ElementType.VIDEO);
|
||||
expect(parsed[0]?.[0].picElement).toBeUndefined();
|
||||
expect(parsed[0]?.[0].videoElement).toMatchObject({
|
||||
fileName: 'clip.mp4',
|
||||
fileTime: 12,
|
||||
fileWidth: 1920,
|
||||
fileHeight: 1080,
|
||||
thumbWidth: 640,
|
||||
thumbHeight: 360,
|
||||
fileUuid: 'video-uuid',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves video metadata in the rich-media upload request', () => {
|
||||
const video = new PacketMsgVideoElement(createSendVideoElement());
|
||||
video.fileSha1 = '00112233445566778899aabbccddeeff00112233';
|
||||
video.thumbSha1 = 'ffeeddccbbaa99887766554433221100ffeeddcc';
|
||||
|
||||
const packet = UploadGroupVideo.build(123456, video);
|
||||
const envelope = OidbBase.parse(packet.data);
|
||||
const request = new NapProtoMsg(NTV2RichMediaReq).decode(envelope.body);
|
||||
const videoInfo = request.upload?.uploadInfo[0]?.fileInfo;
|
||||
const thumbInfo = request.upload?.uploadInfo[1]?.fileInfo;
|
||||
|
||||
expect(videoInfo).toMatchObject({
|
||||
fileName: 'clip.mp4',
|
||||
fileSize: 1024,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
time: 12,
|
||||
});
|
||||
expect(videoInfo?.type.videoFormat).toBe(NTVideoType.VIDEO_FORMAT_MP4);
|
||||
expect(thumbInfo?.fileName).toBe('ffeeddccbbaa99887766554433221100.jpg');
|
||||
});
|
||||
|
||||
it('propagates resource upload failures instead of silently continuing', () => {
|
||||
const uploadError = new Error('thumb upload failed');
|
||||
const logger = {
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
};
|
||||
|
||||
expect(() => assertUploadResults([
|
||||
{ status: 'fulfilled', value: undefined },
|
||||
{ status: 'rejected', reason: uploadError },
|
||||
], logger)).toThrow('上传转发消息资源失败');
|
||||
expect(logger.warn).toHaveBeenCalledWith('上传资源2个,失败1个');
|
||||
expect(logger.error).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user