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:
1 parent
7a974d38d4
commit
07d4d80ab7
11 files changed
+76
-44
No files matched your search
@@ -12,11 +12,12 @@ export interface HttpDownloadOptions {
|
||||
proxy?: string;
|
||||
}
|
||||
|
||||
type Uri2LocalRes = {
|
||||
export type Uri2LocalRes = {
|
||||
success: boolean,
|
||||
errMsg: string,
|
||||
fileName: string,
|
||||
path: string;
|
||||
isLocal: boolean; // true=用户本地文件(不可删除),false=临时下载/解码文件(需清理)
|
||||
};
|
||||
|
||||
// 定义一个异步函数来检查文件是否存在
|
||||
@@ -416,25 +417,24 @@ export async function uriToLocalFile (dir: string, uri: string, filename: string
|
||||
case FileUriType.Local: {
|
||||
const fileExt = path.extname(HandledUri);
|
||||
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
|
||||
const tempFilePath = path.join(dir, filename + fileExt);
|
||||
fs.copyFileSync(HandledUri, tempFilePath);
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
|
||||
// 直接返回原始路径,不复制,避免不必要的 IO
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: HandledUri, isLocal: true };
|
||||
}
|
||||
|
||||
case FileUriType.Remote: {
|
||||
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy });
|
||||
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: {
|
||||
const base64 = HandledUri.replace(/^base64:\/\//, '');
|
||||
const base64Buffer = Buffer.from(base64, 'base64');
|
||||
fs.writeFileSync(filePath, base64Buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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) {
|
||||
throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
|
||||
}
|
||||
return ret.result;
|
||||
} finally {
|
||||
fs.unlink(path, () => { });
|
||||
if (!isLocal) fs.unlink(path, () => { });
|
||||
}
|
||||
}
|
||||
throw new Error(`OCR ${payload.image}失败, 文件可能不存在`);
|
||||
|
||||
@@ -27,14 +27,14 @@ export default class SetAvatar extends OneBotAction<PayloadType, ReturnType> {
|
||||
override returnExample = ExtendsActionsExamples.SetQQAvatar.response;
|
||||
|
||||
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) {
|
||||
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
|
||||
}
|
||||
if (path) {
|
||||
await checkFileExist(path, 5000);// 避免崩溃
|
||||
const ret = await this.core.apis.UserApi.setQQAvatar(path);
|
||||
fs.unlink(path).catch(() => { });
|
||||
if (!isLocal) fs.unlink(path).catch(() => { });
|
||||
if (!ret) {
|
||||
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}`);
|
||||
}
|
||||
} else {
|
||||
fs.unlink(path).catch(() => { });
|
||||
throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -41,7 +41,7 @@ export class UploadImageToQunAlbum extends OneBotAction<PayloadType, ReturnType>
|
||||
try {
|
||||
return await this.core.apis.WebApi.uploadImageToQunAlbum(payload.group_id, payload.album_id, payload.album_name, downloadResult.path);
|
||||
} finally {
|
||||
if (downloadResult.path && existsSync(downloadResult.path)) {
|
||||
if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
|
||||
await unlink(downloadResult.path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
|
||||
const {
|
||||
path,
|
||||
success,
|
||||
isLocal,
|
||||
} = (await uriToLocalFile(this.core.NapCatTempPath, payload.image));
|
||||
if (!success) {
|
||||
throw new Error(`群公告${payload.image}设置失败,image字段可能格式不正确`);
|
||||
@@ -53,7 +54,7 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
|
||||
throw new Error(`群公告${payload.image}设置失败,图片上传失败 , 错误信息:${ImageUploadResult.errMsg}`);
|
||||
}
|
||||
|
||||
unlink(path).catch(() => { });
|
||||
if (!isLocal) unlink(path).catch(() => { });
|
||||
|
||||
UploadImage = ImageUploadResult.picInfo;
|
||||
}
|
||||
|
||||
@@ -30,14 +30,14 @@ export default class SetGroupPortrait extends OneBotAction<SetGroupPortraitPaylo
|
||||
override returnExample = GoCQHTTPActionsExamples.SetGroupPortrait.response;
|
||||
|
||||
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) {
|
||||
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
|
||||
}
|
||||
if (path) {
|
||||
await checkFileExistV2(path, 5000); // 文件不存在QQ会崩溃,需要提前判断
|
||||
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) {
|
||||
throw new Error(`头像${payload.file}设置失败,api无返回`);
|
||||
}
|
||||
@@ -51,7 +51,6 @@ export default class SetGroupPortrait extends OneBotAction<SetGroupPortraitPaylo
|
||||
errMsg: ret.errMsg,
|
||||
};
|
||||
} else {
|
||||
fs.unlink(path).catch(() => { });
|
||||
throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +51,10 @@ export default class GoCQHTTPUploadGroupFile extends OneBotAction<GoCQHTTPUpload
|
||||
peer,
|
||||
deleteAfterSentFiles: [],
|
||||
};
|
||||
const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id, payload.upload_file);
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id, payload.upload_file, downloadResult.isLocal);
|
||||
if (!downloadResult.isLocal) {
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
}
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, [sendFileEle], msgContext.deleteAfterSentFiles);
|
||||
|
||||
const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE);
|
||||
|
||||
@@ -61,8 +61,10 @@ export default class GoCQHTTPUploadPrivateFile extends OneBotAction<GoCQHTTPUplo
|
||||
}, ContextMode.Private),
|
||||
deleteAfterSentFiles: [],
|
||||
};
|
||||
const sendFileEle: SendFileElement = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, '', payload.upload_file);
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
const sendFileEle: SendFileElement = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, '', payload.upload_file, downloadResult.isLocal);
|
||||
if (!downloadResult.isLocal) {
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { fileTypeFromFile } from 'file-type';
|
||||
import pathLib from 'node:path';
|
||||
import fsPromises from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
export class OneBotFileApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
@@ -19,7 +20,7 @@ export class OneBotFileApi {
|
||||
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 {
|
||||
fileName: _fileName,
|
||||
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);
|
||||
if (fileSize === 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 = {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
@@ -87,10 +88,24 @@ export class OneBotFileApi {
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError('获取文件类型失败', e);
|
||||
}
|
||||
const newFilePath = `${filePath}.${fileExt}`;
|
||||
fs.copyFileSync(filePath, newFilePath);
|
||||
context.deleteAfterSentFiles.push(newFilePath);
|
||||
filePath = newFilePath;
|
||||
const currentExt = pathLib.extname(filePath).slice(1).toLowerCase();
|
||||
const needsExtCopy = currentExt !== fileExt.toLowerCase();
|
||||
if (needsExtCopy) {
|
||||
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);
|
||||
context.deleteAfterSentFiles.push(path);
|
||||
|
||||
@@ -736,32 +736,36 @@ export class OneBotMsgApi {
|
||||
|
||||
// File service
|
||||
[OB11MessageDataType.image]: async (sendMsg, context) => {
|
||||
const result = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
return await this.obContext.apis.FileApi.createValidSendPicElement(
|
||||
context,
|
||||
(await this.handleOb11FileLikeMessage(sendMsg, context)).path,
|
||||
result.path,
|
||||
sendMsg.data.summary,
|
||||
sendMsg.data.sub_type
|
||||
sendMsg.data.sub_type,
|
||||
result.isLocal
|
||||
);
|
||||
},
|
||||
|
||||
[OB11MessageDataType.file]: async (sendMsg, context) => {
|
||||
const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName);
|
||||
const { path, fileName, isLocal } = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName, '', false, isLocal);
|
||||
},
|
||||
|
||||
[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;
|
||||
if (thumb) {
|
||||
const uri2LocalRes = await uriToLocalFile(this.core.NapCatTempPath, thumb);
|
||||
if (uri2LocalRes.success) {
|
||||
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) =>
|
||||
@@ -1255,13 +1259,13 @@ export class OneBotMsgApi {
|
||||
const totalSize = sendElements.reduce((total, element) => {
|
||||
switch (element.elementType) {
|
||||
case ElementType.PTT:
|
||||
return total + (parseInt(element.pttElement.fileSize) || 0);
|
||||
return total + (+(element.pttElement.fileSize || '3000'));
|
||||
case ElementType.FILE:
|
||||
return total + (parseInt(element.fileElement.fileSize) || 0);
|
||||
return total + (+(element.fileElement.fileSize || '3000'));
|
||||
case ElementType.VIDEO:
|
||||
return total + (parseInt(element.videoElement.fileSize) || 0);
|
||||
return total + (+(element.videoElement.fileSize || '3000'));
|
||||
case ElementType.PIC:
|
||||
return total + (parseInt(element.picElement.fileSize) || 0);
|
||||
return total + (+(element.picElement.fileSize || '3000'));
|
||||
default:
|
||||
return total;
|
||||
}
|
||||
@@ -1307,13 +1311,15 @@ export class OneBotMsgApi {
|
||||
realUri = await this.handleObfuckName(realUri) ?? realUri;
|
||||
try {
|
||||
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) {
|
||||
this.core.context.logger.logError('文件处理失败', errMsg);
|
||||
throw new Error('文件处理失败: ' + errMsg);
|
||||
}
|
||||
deleteAfterSentFiles.push(path);
|
||||
return { path, fileName: inputdata.name ?? fileName };
|
||||
if (!isLocal) {
|
||||
deleteAfterSentFiles.push(path);
|
||||
}
|
||||
return { path, fileName: inputdata.name ?? fileName, isLocal };
|
||||
} catch (e: unknown) {
|
||||
throw new Error((e as Error).message);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ const HttpServerConfigSchema = Type.Object({
|
||||
port: Type.Number({ default: 3000 }),
|
||||
host: Type.String({ default: '127.0.0.1' }),
|
||||
enableCors: Type.Boolean({ default: true }),
|
||||
enableWebsocket: Type.Boolean({ default: true }),
|
||||
enableWebsocket: Type.Boolean({ default: false }),
|
||||
messagePostFormat: Type.String({ default: 'array' }),
|
||||
token: Type.String({ default: '' }),
|
||||
debug: Type.Boolean({ default: false }),
|
||||
@@ -19,7 +19,7 @@ const HttpSseServerConfigSchema = Type.Object({
|
||||
port: Type.Number({ default: 3000 }),
|
||||
host: Type.String({ default: '127.0.0.1' }),
|
||||
enableCors: Type.Boolean({ default: true }),
|
||||
enableWebsocket: Type.Boolean({ default: true }),
|
||||
enableWebsocket: Type.Boolean({ default: false }),
|
||||
messagePostFormat: Type.String({ default: 'array' }),
|
||||
token: Type.String({ default: '' }),
|
||||
debug: Type.Boolean({ default: false }),
|
||||
@@ -78,12 +78,20 @@ const NetworkConfigSchema = Type.Object({
|
||||
plugins: Type.Array(PluginConfigSchema, { 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({
|
||||
network: NetworkConfigSchema,
|
||||
musicSignUrl: Type.String({ default: '' }),
|
||||
enableLocalFile2Url: Type.Boolean({ default: false }),
|
||||
parseMultMsg: Type.Boolean({ default: false }),
|
||||
imageDownloadProxy: Type.String({ default: '' }),
|
||||
timeout: TimeoutConfigSchema,
|
||||
});
|
||||
|
||||
export type OneBotConfig = Static<typeof OneBotConfigSchema>;
|
||||
|
||||
Reference in new issue
Block a user