Add isLocal flag to uriToLocalFile and use it

Expose an isLocal boolean from uriToLocalFile to indicate user-owned files vs temporary downloads/decodes, and update callers to avoid deleting or cleaning up user local files. Update OneBot file APIs to accept the isLocal hint (including createValidSendFileElement/createValidSendPicElement/createValidSendVideoElement) and adjust temp-file handling for videos: local files are copied into the NapCat temp dir with a random UUID filename to avoid polluting user directories, while temporary files get an added extension in-place. Also adjust deleteAfterSentFiles usage, image/video thumb handling, and numeric parsing fallbacks for element fileSize to be more robust. Minor imports (randomUUID) and related callsites were updated accordingly.
This commit is contained in:
手瓜一十雪 committed 2026-03-12 15:36:44 +08:00
1 parent 7a974d38d4
commit 07d4d80ab7
11 files changed
+76 -44

No files matched your search

+7 -7
View File
@@ -12,11 +12,12 @@ export interface HttpDownloadOptions {
proxy?: string; proxy?: string;
} }
type Uri2LocalRes = { export type Uri2LocalRes = {
success: boolean, success: boolean,
errMsg: string, errMsg: string,
fileName: string, fileName: string,
path: string; path: string;
isLocal: boolean; // true=用户本地文件(不可删除),false=临时下载/解码文件(需清理)
}; };
// 定义一个异步函数来检查文件是否存在 // 定义一个异步函数来检查文件是否存在
@@ -416,25 +417,24 @@ export async function uriToLocalFile (dir: string, uri: string, filename: string
case FileUriType.Local: { case FileUriType.Local: {
const fileExt = path.extname(HandledUri); const fileExt = path.extname(HandledUri);
const localFileName = path.basename(HandledUri, fileExt) + fileExt; const localFileName = path.basename(HandledUri, fileExt) + fileExt;
const tempFilePath = path.join(dir, filename + fileExt); // 直接返回原始路径,不复制,避免不必要的 IO
fs.copyFileSync(HandledUri, tempFilePath); return { success: true, errMsg: '', fileName: localFileName, path: HandledUri, isLocal: true };
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
} }
case FileUriType.Remote: { case FileUriType.Remote: {
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy }); const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy });
fs.writeFileSync(filePath, buffer); fs.writeFileSync(filePath, buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath }; return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
} }
case FileUriType.Base64: { case FileUriType.Base64: {
const base64 = HandledUri.replace(/^base64:\/\//, ''); const base64 = HandledUri.replace(/^base64:\/\//, '');
const base64Buffer = Buffer.from(base64, 'base64'); const base64Buffer = Buffer.from(base64, 'base64');
fs.writeFileSync(filePath, base64Buffer); fs.writeFileSync(filePath, base64Buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath }; return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
} }
default: default:
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' }; return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '', isLocal: false };
} }
} }
@@ -26,7 +26,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
override returnExample = ExtendsActionsExamples.OCRImage.response; override returnExample = ExtendsActionsExamples.OCRImage.response;
async _handle (payload: PayloadType): Promise<ReturnType> { async _handle (payload: PayloadType): Promise<ReturnType> {
const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image); const { path, success, isLocal } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
if (!success) { if (!success) {
throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`); throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
} }
@@ -39,7 +39,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
} }
return ret.result; return ret.result;
} finally { } finally {
fs.unlink(path, () => { }); if (!isLocal) fs.unlink(path, () => { });
} }
} }
throw new Error(`OCR ${payload.image}失败, 文件可能不存在`); throw new Error(`OCR ${payload.image}失败, 文件可能不存在`);
@@ -27,14 +27,14 @@ export default class SetAvatar extends OneBotAction<PayloadType, ReturnType> {
override returnExample = ExtendsActionsExamples.SetQQAvatar.response; override returnExample = ExtendsActionsExamples.SetQQAvatar.response;
async _handle (payload: PayloadType): Promise<ReturnType> { async _handle (payload: PayloadType): Promise<ReturnType> {
const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file)); const { path, success, isLocal } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
if (!success) { if (!success) {
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`); throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
} }
if (path) { if (path) {
await checkFileExist(path, 5000);// 避免崩溃 await checkFileExist(path, 5000);// 避免崩溃
const ret = await this.core.apis.UserApi.setQQAvatar(path); const ret = await this.core.apis.UserApi.setQQAvatar(path);
fs.unlink(path).catch(() => { }); if (!isLocal) fs.unlink(path).catch(() => { });
if (!ret) { if (!ret) {
throw new Error(`头像${payload.file}设置失败,api无返回`); throw new Error(`头像${payload.file}设置失败,api无返回`);
} }
@@ -45,7 +45,6 @@ export default class SetAvatar extends OneBotAction<PayloadType, ReturnType> {
throw new Error(`头像${payload.file}设置失败,未知的错误,${ret.result}:${ret.errMsg}`); throw new Error(`头像${payload.file}设置失败,未知的错误,${ret.result}:${ret.errMsg}`);
} }
} else { } else {
fs.unlink(path).catch(() => { });
throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`); throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
} }
return null; return null;
@@ -41,7 +41,7 @@ export class UploadImageToQunAlbum extends OneBotAction<PayloadType, ReturnType>
try { try {
return await this.core.apis.WebApi.uploadImageToQunAlbum(payload.group_id, payload.album_id, payload.album_name, downloadResult.path); return await this.core.apis.WebApi.uploadImageToQunAlbum(payload.group_id, payload.album_id, payload.album_name, downloadResult.path);
} finally { } finally {
if (downloadResult.path && existsSync(downloadResult.path)) { if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
await unlink(downloadResult.path); await unlink(downloadResult.path);
} }
} }
@@ -40,6 +40,7 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
const { const {
path, path,
success, success,
isLocal,
} = (await uriToLocalFile(this.core.NapCatTempPath, payload.image)); } = (await uriToLocalFile(this.core.NapCatTempPath, payload.image));
if (!success) { if (!success) {
throw new Error(`群公告${payload.image}设置失败,image字段可能格式不正确`); throw new Error(`群公告${payload.image}设置失败,image字段可能格式不正确`);
@@ -53,7 +54,7 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
throw new Error(`群公告${payload.image}设置失败,图片上传失败 , 错误信息:${ImageUploadResult.errMsg}`); throw new Error(`群公告${payload.image}设置失败,图片上传失败 , 错误信息:${ImageUploadResult.errMsg}`);
} }
unlink(path).catch(() => { }); if (!isLocal) unlink(path).catch(() => { });
UploadImage = ImageUploadResult.picInfo; UploadImage = ImageUploadResult.picInfo;
} }
@@ -30,14 +30,14 @@ export default class SetGroupPortrait extends OneBotAction<SetGroupPortraitPaylo
override returnExample = GoCQHTTPActionsExamples.SetGroupPortrait.response; override returnExample = GoCQHTTPActionsExamples.SetGroupPortrait.response;
async _handle (payload: SetGroupPortraitPayload): Promise<ReturnType> { async _handle (payload: SetGroupPortraitPayload): Promise<ReturnType> {
const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file)); const { path, success, isLocal } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
if (!success) { if (!success) {
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`); throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
} }
if (path) { if (path) {
await checkFileExistV2(path, 5000); // 文件不存在QQ会崩溃,需要提前判断 await checkFileExistV2(path, 5000); // 文件不存在QQ会崩溃,需要提前判断
const ret = await this.core.apis.GroupApi.setGroupAvatar(payload.group_id.toString(), path); const ret = await this.core.apis.GroupApi.setGroupAvatar(payload.group_id.toString(), path);
fs.unlink(path).catch(() => { }); if (!isLocal) fs.unlink(path).catch(() => { });
if (!ret) { if (!ret) {
throw new Error(`头像${payload.file}设置失败,api无返回`); throw new Error(`头像${payload.file}设置失败,api无返回`);
} }
@@ -51,7 +51,6 @@ export default class SetGroupPortrait extends OneBotAction<SetGroupPortraitPaylo
errMsg: ret.errMsg, errMsg: ret.errMsg,
}; };
} else { } else {
fs.unlink(path).catch(() => { });
throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`); throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
} }
} }
@@ -51,8 +51,10 @@ export default class GoCQHTTPUploadGroupFile extends OneBotAction<GoCQHTTPUpload
peer, peer,
deleteAfterSentFiles: [], deleteAfterSentFiles: [],
}; };
const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id, payload.upload_file); const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id, payload.upload_file, downloadResult.isLocal);
msgContext.deleteAfterSentFiles.push(downloadResult.path); if (!downloadResult.isLocal) {
msgContext.deleteAfterSentFiles.push(downloadResult.path);
}
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, [sendFileEle], msgContext.deleteAfterSentFiles); const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, [sendFileEle], msgContext.deleteAfterSentFiles);
const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE); const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE);
@@ -61,8 +61,10 @@ export default class GoCQHTTPUploadPrivateFile extends OneBotAction<GoCQHTTPUplo
}, ContextMode.Private), }, ContextMode.Private),
deleteAfterSentFiles: [], deleteAfterSentFiles: [],
}; };
const sendFileEle: SendFileElement = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, '', payload.upload_file); const sendFileEle: SendFileElement = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, '', payload.upload_file, downloadResult.isLocal);
msgContext.deleteAfterSentFiles.push(downloadResult.path); if (!downloadResult.isLocal) {
msgContext.deleteAfterSentFiles.push(downloadResult.path);
}
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(await this.getPeer(payload), [sendFileEle], msgContext.deleteAfterSentFiles); const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(await this.getPeer(payload), [sendFileEle], msgContext.deleteAfterSentFiles);
const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE); const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE);
+22 -7
View File
@@ -10,6 +10,7 @@ import { fileTypeFromFile } from 'file-type';
import pathLib from 'node:path'; import pathLib from 'node:path';
import fsPromises from 'fs/promises'; import fsPromises from 'fs/promises';
import fs from 'fs'; import fs from 'fs';
import { randomUUID } from 'crypto';
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video'; import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
export class OneBotFileApi { export class OneBotFileApi {
obContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
@@ -19,7 +20,7 @@ export class OneBotFileApi {
this.core = core; this.core = core;
} }
async createValidSendFileElement (context: SendMessageContext, filePath: string, fileName: string = '', folderId: string = '', uploadGroupFile: boolean = false): Promise<SendFileElement> { async createValidSendFileElement (context: SendMessageContext, filePath: string, fileName: string = '', folderId: string = '', uploadGroupFile: boolean = false, _isLocal: boolean = false): Promise<SendFileElement> {
const { const {
fileName: _fileName, fileName: _fileName,
path, path,
@@ -43,7 +44,7 @@ export class OneBotFileApi {
}; };
} }
async createValidSendPicElement (context: SendMessageContext, picPath: string, summary: string = '', subType: PicSubType = 0): Promise<SendPicElement> { async createValidSendPicElement (context: SendMessageContext, picPath: string, summary: string = '', subType: PicSubType = 0, _isLocal: boolean = false): Promise<SendPicElement> {
const { md5, fileName, path, fileSize } = await this.core.apis.FileApi.uploadFile(picPath, ElementType.PIC, subType); const { md5, fileName, path, fileSize } = await this.core.apis.FileApi.uploadFile(picPath, ElementType.PIC, subType);
if (fileSize === 0) { if (fileSize === 0) {
throw new Error('文件异常,大小为0'); throw new Error('文件异常,大小为0');
@@ -71,7 +72,7 @@ export class OneBotFileApi {
}; };
} }
async createValidSendVideoElement (context: SendMessageContext, filePath: string, fileName: string = '', _diyThumbPath: string = ''): Promise<SendVideoElement> { async createValidSendVideoElement (context: SendMessageContext, filePath: string, fileName: string = '', _diyThumbPath: string = '', isLocal: boolean = false): Promise<SendVideoElement> {
let videoInfo = { let videoInfo = {
width: 1920, width: 1920,
height: 1080, height: 1080,
@@ -87,10 +88,24 @@ export class OneBotFileApi {
} catch (e) { } catch (e) {
this.core.context.logger.logError('获取文件类型失败', e); this.core.context.logger.logError('获取文件类型失败', e);
} }
const newFilePath = `${filePath}.${fileExt}`; const currentExt = pathLib.extname(filePath).slice(1).toLowerCase();
fs.copyFileSync(filePath, newFilePath); const needsExtCopy = currentExt !== fileExt.toLowerCase();
context.deleteAfterSentFiles.push(newFilePath); if (needsExtCopy) {
filePath = newFilePath; if (isLocal) {
// 本地文件缺少正确扩展名:拷贝到临时目录,避免污染用户目录
const tempFilePath = pathLib.join(this.core.NapCatTempPath, `${randomUUID()}.${fileExt}`);
fs.copyFileSync(filePath, tempFilePath);
context.deleteAfterSentFiles.push(tempFilePath);
filePath = tempFilePath;
} else {
// 临时文件缺少正确扩展名:在原位置加扩展名
const newFilePath = `${filePath}.${fileExt}`;
fs.copyFileSync(filePath, newFilePath);
context.deleteAfterSentFiles.push(newFilePath);
filePath = newFilePath;
}
}
// 扩展名已匹配时:本地文件直接用原始路径(零拷贝),临时文件也无需额外操作
const { fileName: _fileName, path, fileSize, md5 } = await this.core.apis.FileApi.uploadFile(filePath, ElementType.VIDEO); const { fileName: _fileName, path, fileSize, md5 } = await this.core.apis.FileApi.uploadFile(filePath, ElementType.VIDEO);
context.deleteAfterSentFiles.push(path); context.deleteAfterSentFiles.push(path);
+20 -14
View File
@@ -736,32 +736,36 @@ export class OneBotMsgApi {
// File service // File service
[OB11MessageDataType.image]: async (sendMsg, context) => { [OB11MessageDataType.image]: async (sendMsg, context) => {
const result = await this.handleOb11FileLikeMessage(sendMsg, context);
return await this.obContext.apis.FileApi.createValidSendPicElement( return await this.obContext.apis.FileApi.createValidSendPicElement(
context, context,
(await this.handleOb11FileLikeMessage(sendMsg, context)).path, result.path,
sendMsg.data.summary, sendMsg.data.summary,
sendMsg.data.sub_type sendMsg.data.sub_type,
result.isLocal
); );
}, },
[OB11MessageDataType.file]: async (sendMsg, context) => { [OB11MessageDataType.file]: async (sendMsg, context) => {
const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context); const { path, fileName, isLocal } = await this.handleOb11FileLikeMessage(sendMsg, context);
return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName); return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName, '', false, isLocal);
}, },
[OB11MessageDataType.video]: async (sendMsg, context) => { [OB11MessageDataType.video]: async (sendMsg, context) => {
const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context); const { path, fileName, isLocal } = await this.handleOb11FileLikeMessage(sendMsg, context);
let thumb = sendMsg.data.thumb; let thumb = sendMsg.data.thumb;
if (thumb) { if (thumb) {
const uri2LocalRes = await uriToLocalFile(this.core.NapCatTempPath, thumb); const uri2LocalRes = await uriToLocalFile(this.core.NapCatTempPath, thumb);
if (uri2LocalRes.success) { if (uri2LocalRes.success) {
thumb = uri2LocalRes.path; thumb = uri2LocalRes.path;
context.deleteAfterSentFiles.push(thumb); if (!uri2LocalRes.isLocal) {
context.deleteAfterSentFiles.push(thumb);
}
} }
} }
return await this.obContext.apis.FileApi.createValidSendVideoElement(context, path, fileName, thumb); return await this.obContext.apis.FileApi.createValidSendVideoElement(context, path, fileName, thumb, isLocal);
}, },
[OB11MessageDataType.voice]: async (sendMsg, context) => [OB11MessageDataType.voice]: async (sendMsg, context) =>
@@ -1255,13 +1259,13 @@ export class OneBotMsgApi {
const totalSize = sendElements.reduce((total, element) => { const totalSize = sendElements.reduce((total, element) => {
switch (element.elementType) { switch (element.elementType) {
case ElementType.PTT: case ElementType.PTT:
return total + (parseInt(element.pttElement.fileSize) || 0); return total + (+(element.pttElement.fileSize || '3000'));
case ElementType.FILE: case ElementType.FILE:
return total + (parseInt(element.fileElement.fileSize) || 0); return total + (+(element.fileElement.fileSize || '3000'));
case ElementType.VIDEO: case ElementType.VIDEO:
return total + (parseInt(element.videoElement.fileSize) || 0); return total + (+(element.videoElement.fileSize || '3000'));
case ElementType.PIC: case ElementType.PIC:
return total + (parseInt(element.picElement.fileSize) || 0); return total + (+(element.picElement.fileSize || '3000'));
default: default:
return total; return total;
} }
@@ -1307,13 +1311,15 @@ export class OneBotMsgApi {
realUri = await this.handleObfuckName(realUri) ?? realUri; realUri = await this.handleObfuckName(realUri) ?? realUri;
try { try {
const proxy = this.obContext.configLoader.configData.imageDownloadProxy || undefined; const proxy = this.obContext.configLoader.configData.imageDownloadProxy || undefined;
const { path, fileName, errMsg, success } = await uriToLocalFile(this.core.NapCatTempPath, realUri, undefined, undefined, proxy); const { path, fileName, errMsg, success, isLocal } = await uriToLocalFile(this.core.NapCatTempPath, realUri, undefined, undefined, proxy);
if (!success) { if (!success) {
this.core.context.logger.logError('文件处理失败', errMsg); this.core.context.logger.logError('文件处理失败', errMsg);
throw new Error('文件处理失败: ' + errMsg); throw new Error('文件处理失败: ' + errMsg);
} }
deleteAfterSentFiles.push(path); if (!isLocal) {
return { path, fileName: inputdata.name ?? fileName }; deleteAfterSentFiles.push(path);
}
return { path, fileName: inputdata.name ?? fileName, isLocal };
} catch (e: unknown) { } catch (e: unknown) {
throw new Error((e as Error).message); throw new Error((e as Error).message);
} }
@@ -7,7 +7,7 @@ const HttpServerConfigSchema = Type.Object({
port: Type.Number({ default: 3000 }), port: Type.Number({ default: 3000 }),
host: Type.String({ default: '127.0.0.1' }), host: Type.String({ default: '127.0.0.1' }),
enableCors: Type.Boolean({ default: true }), enableCors: Type.Boolean({ default: true }),
enableWebsocket: Type.Boolean({ default: true }), enableWebsocket: Type.Boolean({ default: false }),
messagePostFormat: Type.String({ default: 'array' }), messagePostFormat: Type.String({ default: 'array' }),
token: Type.String({ default: '' }), token: Type.String({ default: '' }),
debug: Type.Boolean({ default: false }), debug: Type.Boolean({ default: false }),
@@ -19,7 +19,7 @@ const HttpSseServerConfigSchema = Type.Object({
port: Type.Number({ default: 3000 }), port: Type.Number({ default: 3000 }),
host: Type.String({ default: '127.0.0.1' }), host: Type.String({ default: '127.0.0.1' }),
enableCors: Type.Boolean({ default: true }), enableCors: Type.Boolean({ default: true }),
enableWebsocket: Type.Boolean({ default: true }), enableWebsocket: Type.Boolean({ default: false }),
messagePostFormat: Type.String({ default: 'array' }), messagePostFormat: Type.String({ default: 'array' }),
token: Type.String({ default: '' }), token: Type.String({ default: '' }),
debug: Type.Boolean({ default: false }), debug: Type.Boolean({ default: false }),
@@ -78,12 +78,20 @@ const NetworkConfigSchema = Type.Object({
plugins: Type.Array(PluginConfigSchema, { default: [] }), plugins: Type.Array(PluginConfigSchema, { default: [] }),
}, { default: {} }); }, { default: {} });
const TimeoutConfigSchema = Type.Object({
baseTimeout: Type.Number({ default: 10000 }),
uploadSpeedKBps: Type.Number({ default: 256 }),
downloadSpeedKBps: Type.Number({ default: 256 }),
maxTimeout: Type.Number({ default: 1800000 }),
}, { default: {} });
export const OneBotConfigSchema = Type.Object({ export const OneBotConfigSchema = Type.Object({
network: NetworkConfigSchema, network: NetworkConfigSchema,
musicSignUrl: Type.String({ default: '' }), musicSignUrl: Type.String({ default: '' }),
enableLocalFile2Url: Type.Boolean({ default: false }), enableLocalFile2Url: Type.Boolean({ default: false }),
parseMultMsg: Type.Boolean({ default: false }), parseMultMsg: Type.Boolean({ default: false }),
imageDownloadProxy: Type.String({ default: '' }), imageDownloadProxy: Type.String({ default: '' }),
timeout: TimeoutConfigSchema,
}); });
export type OneBotConfig = Static<typeof OneBotConfigSchema>; export type OneBotConfig = Static<typeof OneBotConfigSchema>;