diff --git a/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts b/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts index dace10227..3ecb0cd71 100644 --- a/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts +++ b/packages/napcat-core/helper/ffmpeg/ffmpeg-addon.ts @@ -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; } diff --git a/packages/napcat-core/packet/context/operationContext.ts b/packages/napcat-core/packet/context/operationContext.ts index 1ac482cb2..6b8fea888 100644 --- a/packages/napcat-core/packet/context/operationContext.ts +++ b/packages/napcat-core/packet/context/operationContext.ts @@ -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; }) ); diff --git a/packages/napcat-core/packet/context/uploadResult.ts b/packages/napcat-core/packet/context/uploadResult.ts new file mode 100644 index 000000000..4ac41b97e --- /dev/null +++ b/packages/napcat-core/packet/context/uploadResult.ts @@ -0,0 +1,26 @@ +export interface UploadResultLogger { + warn (message: string): unknown; + error (message: string): unknown; +} + +export function assertUploadResults ( + results: PromiseSettledResult[], + 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}` + ); +} diff --git a/packages/napcat-core/packet/highway/highwayContext.ts b/packages/napcat-core/packet/highway/highwayContext.ts index 1d5d3212f..a29270f8b 100644 --- a/packages/napcat-core/packet/highway/highwayContext.ts +++ b/packages/napcat-core/packet/highway/highwayContext.ts @@ -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 { @@ -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 { + 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 { 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; } diff --git a/packages/napcat-core/packet/message/converter.ts b/packages/napcat-core/packet/message/converter.ts index e185ba0bd..b7ed2a1d7 100644 --- a/packages/napcat-core/packet/message/converter.ts +++ b/packages/napcat-core/packet/message/converter.ts @@ -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[]): [MessageElement, NapProtoDecodeStructType | 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); diff --git a/packages/napcat-core/packet/message/element.ts b/packages/napcat-core/packet/message/element.ts index 92a1e6dcc..96c8ee4fe 100644 --- a/packages/napcat-core/packet/message/element.ts +++ b/packages/napcat-core/packet/message/element.ts @@ -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 { } static override parseElement = (elem: NapProtoDecodeStructType): 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 { summary: '[图片]', thumbPath: new Map(), }, - elementType: ElementType.UNKNOWN, + elementType: ElementType.PIC, elementId: '', }, elem]; } @@ -446,8 +451,13 @@ export class PacketMsgPicElement extends IPacketMsgElement { } export class PacketMsgVideoElement extends IPacketMsgElement { + 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 { thumbSha1?: string; thumbWidth?: number; thumbHeight?: number; + businessType: 11 | 21 = 21; msgInfo: NapProtoEncodeStructType | 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 { commonElem: { serviceType: 48, pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo), - businessType: 21, + businessType: this.businessType, }, }]; } + static override parseElement = (elem: NapProtoDecodeStructType): 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 '[视频]'; } diff --git a/packages/napcat-core/packet/transformer/highway/UploadGroupVideo.ts b/packages/napcat-core/packet/transformer/highway/UploadGroupVideo.ts index 64dbbb983..af4f2828c 100644 --- a/packages/napcat-core/packet/transformer/highway/UploadGroupVideo.ts +++ b/packages/napcat-core/packet/transformer/highway/UploadGroupVideo.ts @@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer 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 fileSize: +video.thumbSize, fileHash: video.thumbMd5, fileSha1: video.thumbSha1, - fileName: 'nya.jpg', + fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`, type: { type: 1, picFormat: 0, diff --git a/packages/napcat-core/packet/transformer/highway/UploadPrivateVideo.ts b/packages/napcat-core/packet/transformer/highway/UploadPrivateVideo.ts index b6a8e3fa1..6d7b122ab 100644 --- a/packages/napcat-core/packet/transformer/highway/UploadPrivateVideo.ts +++ b/packages/napcat-core/packet/transformer/highway/UploadPrivateVideo.ts @@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer> = { + 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, diff --git a/packages/napcat-test/videoPacket.test.ts b/packages/napcat-test/videoPacket.test.ts new file mode 100644 index 000000000..745333ea9 --- /dev/null +++ b/packages/napcat-test/videoPacket.test.ts @@ -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 { + 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 +): NapProtoDecodeStructType { + const codec = new NapProtoMsg(Elem); + return codec.decode(codec.encode(elem)); +} + +function createCommonVideoElem (businessType: 11 | 21): NapProtoDecodeStructType { + 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(); + }); +});