From 5fcdc95b1a98016eeebadac29279ec0a04adfceb Mon Sep 17 00:00:00 2001 From: zhiyu1998 <542716863@qq.com> Date: Wed, 11 Sep 2024 11:26:04 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20=E5=A2=9E=E5=8A=A0=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=A4=84=E7=90=86=E5=92=8C=E6=97=A5=E5=BF=97=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在 switchers.js 中,为 setOversea 和 setLagrange 方法添加了 try-catch 错误处理结构,并在捕获到错误时向用户发送错误消息。同时,对 autoclearTrash 函数进行了重构,使其成为异步函数,并添加了错误日志记录。 此外,对 file.js 中的日志记录语句进行了格式调整,以提高代码的可读性和一致性。 ``` --- apps/switchers.js | 232 +++++++++++++++++++++------------------------- utils/file.js | 14 +-- 2 files changed, 111 insertions(+), 135 deletions(-) diff --git a/apps/switchers.js b/apps/switchers.js index 79a868e..f3fa272 100644 --- a/apps/switchers.js +++ b/apps/switchers.js @@ -2,12 +2,12 @@ import config from "../model/config.js"; import schedule from 'node-schedule'; import { REDIS_YUNZAI_ISOVERSEA, REDIS_YUNZAI_LAGRANGE, REDIS_YUNZAI_WHITELIST } from "../constants/constant.js"; import { deleteFolderRecursive, readCurrentDir } from "../utils/file.js"; -import { redisExistAndGetKey, redisExistKey, redisGetKey, redisSetKey } from "../utils/redis-util.js"; +import { redisExistAndGetKey, redisGetKey, redisSetKey } from "../utils/redis-util.js"; -//自动清理定时 -const autotime = config.getConfig("tools").autoclearTrashtime +// 自动清理定时 +const autotime = config.getConfig("tools").autoclearTrashtime; // 视频保存路径 -const defaultPath = config.getConfig("tools").defaultPath +const defaultPath = config.getConfig("tools").defaultPath; export class switchers extends plugin { constructor() { @@ -61,22 +61,23 @@ export class switchers extends plugin { * @returns {Promise} */ async setOversea(e) { - // 查看当前设置 - let os = (await redisGetKey(REDIS_YUNZAI_ISOVERSEA))?.os; - // 如果是第一次 - if (os === undefined) { - await redisSetKey(REDIS_YUNZAI_ISOVERSEA, { - os: false, - }); - os = false; + try { + // 查看当前设置 + let os = (await redisGetKey(REDIS_YUNZAI_ISOVERSEA))?.os; + // 如果是第一次 + if (os === undefined) { + await redisSetKey(REDIS_YUNZAI_ISOVERSEA, { os: false }); + os = false; + } + // 设置 + os = ~os; + await redisSetKey(REDIS_YUNZAI_ISOVERSEA, { os }); + e.reply(`当前服务器:${ os ? '海外服务器' : '国内服务器' }`); + return true; + } catch (err) { + e.reply(`设置海外模式时发生错误: ${ err.message }`); + return false; } - // 设置 - os = ~os; - await redisSetKey(REDIS_YUNZAI_ISOVERSEA, { - os: os, - }); - e.reply(`当前服务器:${ os ? '海外服务器' : '国内服务器' }`) - return true; } /** @@ -85,26 +86,27 @@ export class switchers extends plugin { * @returns {Promise} */ async setLagrange(e) { - // 查看当前设置 - let driver = (await redisGetKey(REDIS_YUNZAI_LAGRANGE))?.driver; - // 如果是第一次 - if (driver === undefined) { - await redisSetKey(REDIS_YUNZAI_LAGRANGE, { - driver: 1, - }) - driver = 1; + try { + // 查看当前设置 + let driver = (await redisGetKey(REDIS_YUNZAI_LAGRANGE))?.driver; + // 如果是第一次 + if (driver === undefined) { + await redisSetKey(REDIS_YUNZAI_LAGRANGE, { driver: 1 }); + driver = 1; + } + // 异常检测,之前算法出现问题,如果出现异常就检测纠正 + if (driver === -1) { + driver = 1; + } + // 设置 + driver ^= 1; + await redisSetKey(REDIS_YUNZAI_LAGRANGE, { driver }); + e.reply(`当前驱动:${ driver ? '拉格朗日' : '其他驱动' }`); + return true; + } catch (err) { + e.reply(`设置拉格朗日时发生错误: ${ err.message }`); + return false; } - // 异常检测,之前算法出现问题,如果出现异常就检测纠正 - if (driver === -1) { - driver = 1; - } - // 设置 - driver ^= 1; - await redisSetKey(REDIS_YUNZAI_LAGRANGE, { - driver: driver, - }) - e.reply(`当前驱动:${ driver ? '拉格朗日' : '其他驱动' }`) - return true; } /** @@ -129,33 +131,27 @@ export class switchers extends plugin { * @returns {Promise} */ async setWhiteList(e) { - let trustUserId; - // 判断是不是回复用户命令 - if (e?.reply_id !== undefined) { - trustUserId = (await e.getReply()).user_id; - } else { - // 如果不是回复就看发送内容 - trustUserId = e.msg.replace("#设置R信任用户", ""); + try { + let trustUserId = e?.reply_id !== undefined ? (await e.getReply()).user_id : e.msg.replace("#设置R信任用户", "").trim(); + trustUserId = trustUserId.toString(); + // 用户ID检测 + if (!trustUserId) { + e.reply("无效的R信任用户"); + return; + } + let whiteList = await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST) || []; + // 重复检测 + if (whiteList.includes(trustUserId)) { + e.reply("R信任用户已存在,无须添加!"); + return; + } + whiteList.push(trustUserId); + // 放置到Redis里 + await redisSetKey(REDIS_YUNZAI_WHITELIST, whiteList); + e.reply(`成功添加R信任用户:${ trustUserId }`); + } catch (err) { + e.reply(`设置R信任用户时发生错误: ${ err.message }`); } - // 用户ID检测 - if (trustUserId == null || trustUserId === "") { - e.reply("无效的R信任用户"); - return; - } - let whiteList = await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST); - // 不存在就创建 - if (whiteList == null) { - whiteList = []; - } - // 重复检测 - if (whiteList.includes(trustUserId)) { - e.reply("R信任用户已存在,无须添加!"); - return; - } - whiteList = [...whiteList, trustUserId]; - // 放置到Redis里 - await redisSetKey(REDIS_YUNZAI_WHITELIST, whiteList); - e.reply(`成功添加R信任用户:${ trustUserId }`); } /** @@ -164,16 +160,17 @@ export class switchers extends plugin { * @returns {Promise} */ async getWhiteList(e) { - let whiteList = await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST); - if (whiteList == null) { - whiteList = []; - } - const message = `R信任用户列表:${ whiteList.join(",\n") }`; - if (this.e.isGroup) { - await Bot.pickUser(this.e.user_id).sendMsg(await this.e.runtime.common.makeForwardMsg(this.e, message)); - await this.reply('R插件的信任用户名单已发送至您的私信了~'); - } else { - await e.reply(await makeForwardMsg(this.e, message)); + try { + let whiteList = await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST) || []; + const message = `R信任用户列表:\n${ whiteList.join(",\n") }`; + if (this.e.isGroup) { + await Bot.pickUser(this.e.user_id).sendMsg(await this.e.runtime.common.makeForwardMsg(this.e, message)); + await this.reply('R插件的信任用户名单已发送至您的私信了~'); + } else { + await e.reply(await makeForwardMsg(this.e, message)); + } + } catch (err) { + e.reply(`获取R信任用户时发生错误: ${ err.message }`); } } @@ -183,64 +180,46 @@ export class switchers extends plugin { * @returns {Promise} */ async searchWhiteList(e) { - let trustUserId; - // 判断是不是回复用户命令 - if (e?.reply_id !== undefined) { - trustUserId = (await e.getReply()).user_id; - } else { - // 如果不是回复就看发送内容 - trustUserId = e.msg.replace("#设置R信任用户", ""); + try { + let trustUserId = e?.reply_id !== undefined ? (await e.getReply()).user_id : e.msg.replace("#查询R信任用户", "").trim(); + let whiteList = await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST) || []; + const isInWhiteList = whiteList.includes(trustUserId); + e.reply(isInWhiteList ? `✅ ${ trustUserId }已经是R插件的信任用户哦~` : `⚠️ ${ trustUserId }不是R插件的信任用户哦~`); + } catch (err) { + e.reply(`查询R信任用户时发生错误: ${ err.message }`); } - let whiteList = await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST); - if (whiteList == null) { - e.reply("R插件当前没有任何信任用户!"); - return; - } - const isInWhiteList = whiteList.includes(trustUserId); - if (isInWhiteList) { - e.reply(`✅ ${trustUserId}已经是R插件的信任用户哦~`); - } else { - e.reply(`⚠️ ${trustUserId}不是R插件的信任用户哦~`); - } - return true; } + /** + * 删除信任用户 + * @param e + * @returns {Promise} + */ async deleteWhiteList(e) { - let trustUserId; - // 判断是不是回复用户命令 - if (e?.reply_id !== undefined) { - trustUserId = (await e.getReply()).user_id; - } else { - // 如果不是回复就看发送内容 - trustUserId = e.msg.replace("#删除R信任用户", ""); + try { + let trustUserId = e?.reply_id !== undefined ? (await e.getReply()).user_id : e.msg.replace("#删除R信任用户", "").trim(); + // 校准不是string的用户 + let whiteList = (await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST))?.map(item => item.toString()) || []; + // 重复检测 + if (!whiteList.includes(trustUserId)) { + e.reply("R信任用户不存在,无须删除!"); + return; + } + whiteList = whiteList.filter(item => item !== trustUserId); + // 放置到Redis里 + await redisSetKey(REDIS_YUNZAI_WHITELIST, whiteList); + e.reply(`成功删除R信任用户:${ trustUserId }`); + } catch (err) { + e.reply(`删除R信任用户时发生错误: ${ err.message }`); } - // 校准不是string的用户 - let whiteList = (await redisExistAndGetKey(REDIS_YUNZAI_WHITELIST)).map(item => - typeof item === 'string' ? item : item.toString() - ); - if (whiteList == null) { - e.reply("R插件当前没有任何信任用户:"); - return; - } - // 重复检测 - if (!whiteList.includes(trustUserId)) { - e.reply("R信任用户不存在,无须删除!"); - return; - } - whiteList = whiteList.filter((item) => item !== trustUserId); - // 放置到Redis里 - await redisSetKey(REDIS_YUNZAI_WHITELIST, whiteList); - e.reply(`成功删除R信任用户:${ trustUserId }`); } } - /** * 清理垃圾文件 - * @param e - * @returns {Promise} + * @returns {Promise} */ -async function autoclearTrash(e) { +async function autoclearTrash() { const dataDirectory = "./data/"; try { const files = await readCurrentDir(dataDirectory); @@ -252,10 +231,7 @@ async function autoclearTrash(e) { } } const rTempFileLen = await deleteFolderRecursive(defaultPath); - return { - dataClearFileLen, - rTempFileLen - }; + return { dataClearFileLen, rTempFileLen }; } catch (err) { logger.error(err); throw err; @@ -272,8 +248,8 @@ function autoclear(time) { } catch (err) { console.error(`自动清理垃圾时发生错误: ${ err.message }`); } - }) + }); } -//自动清理垃圾 -autoclear(autotime) +// 自动清理垃圾 +autoclear(autotime); diff --git a/utils/file.js b/utils/file.js index 222ce29..f584de3 100644 --- a/utils/file.js +++ b/utils/file.js @@ -14,7 +14,7 @@ const mimeTypes = { // 通用错误处理函数 function handleError(err) { - logger.error(`错误: ${err.message}\n堆栈: ${err.stack}`); + logger.error(`错误: ${ err.message }\n堆栈: ${ err.stack }`); throw err; } @@ -27,7 +27,7 @@ export async function checkAndRemoveFile(file) { try { await fs.access(file); await fs.unlink(file); - logger.info(`文件 ${file} 删除成功。`); + logger.info(`文件 ${ file } 删除成功。`); } catch (err) { if (err.code !== 'ENOENT') { handleError(err); @@ -46,7 +46,7 @@ export async function mkdirIfNotExists(dir) { } catch (err) { if (err.code === 'ENOENT') { await fs.mkdir(dir, { recursive: true }); - logger.info(`目录 ${dir} 创建成功。`); + logger.info(`目录 ${ dir } 创建成功。`); } else { handleError(err); } @@ -72,7 +72,7 @@ export async function deleteFolderRecursive(folderPath) { }); await Promise.allSettled(actions); - logger.info(`文件夹 ${folderPath} 中的所有文件删除成功。`); + logger.info(`文件夹 ${ folderPath } 中的所有文件删除成功。`); return files.length; } catch (error) { handleError(error); @@ -109,7 +109,7 @@ export async function copyFiles(srcDir, destDir, specificFiles = []) { ? files.filter(file => specificFiles.includes(file)) : files; - logger.info(`[R插件][拷贝文件] 正在将 ${srcDir} 的文件拷贝到 ${destDir} 中`); + logger.info(`[R插件][拷贝文件] 正在将 ${ srcDir } 的文件拷贝到 ${ destDir } 中`); const copiedFiles = []; @@ -138,7 +138,7 @@ export async function toBase64(filePath) { try { const fileData = await fs.readFile(filePath); const base64Data = fileData.toString('base64'); - return `data:${getMimeType(filePath)};base64,${base64Data}`; + return `data:${ getMimeType(filePath) };base64,${ base64Data }`; } catch (error) { handleError(error); } @@ -184,4 +184,4 @@ export async function getMediaFilesAndOthers(folderPath) { } catch (err) { handleError(err); } -} \ No newline at end of file +}