fix: 修复循环错误设计和简化导入写法

This commit is contained in:
ningmengchongshui 2024-06-18 22:22:46 +08:00
parent 773f85a168
commit 209699f64d
16 changed files with 108 additions and 87 deletions

View File

@ -7,7 +7,6 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"app": "node app.js", "app": "node app.js",
"dev": "ts-node-dev src/main.ts",
"login": "node index.js login", "login": "node index.js login",
"build": "rollup --config rollup.config.js", "build": "rollup --config rollup.config.js",
"start": "pm2 startOrRestart pm2.config.cjs", "start": "pm2 startOrRestart pm2.config.cjs",
@ -36,6 +35,7 @@
"koa-router": "^12.0.1", "koa-router": "^12.0.1",
"koa-static": "^5.0.0", "koa-static": "^5.0.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"log4js": "^6.9.1", "log4js": "^6.9.1",
"md5": "^2.3.0", "md5": "^2.3.0",
"moment": "^2.30.1", "moment": "^2.30.1",
@ -62,6 +62,7 @@
"@types/koa-router": "^7.4.8", "@types/koa-router": "^7.4.8",
"@types/koa-static": "^4.0.4", "@types/koa-static": "^4.0.4",
"@types/lodash": "^4.14.200", "@types/lodash": "^4.14.200",
"@types/lodash-es": "^4.17.12",
"@types/node": "^20.8.5", "@types/node": "^20.8.5",
"@types/node-schedule": "^2.1.7", "@types/node-schedule": "^2.1.7",
"@types/react-dom": "^18.2.22", "@types/react-dom": "^18.2.22",

View File

@ -1,5 +1,5 @@
import YAML from 'yaml' import { watch } from 'chokidar'
import chokidar from 'chokidar' import { parse } from 'yaml'
import { join } from 'node:path' import { join } from 'node:path'
import { readFileSync, } from 'node:fs' import { readFileSync, } from 'node:fs'
/** /**
@ -166,7 +166,7 @@ class ConfigController {
const file = `config/${type}/${name}.yaml` const file = `config/${type}/${name}.yaml`
const key = `${type}.${name}` const key = `${type}.${name}`
if (this.config[key]) return this.config[key] if (this.config[key]) return this.config[key]
this.config[key] = YAML.parse( this.config[key] = parse(
readFileSync(file, 'utf8') readFileSync(file, 'utf8')
) )
this.watch(file, name, type) this.watch(file, name, type)
@ -183,7 +183,7 @@ class ConfigController {
watch(file: string, name: string, type = 'default_config') { watch(file: string, name: string, type = 'default_config') {
const key = `${type}.${name}` const key = `${type}.${name}`
if (this.watcher[key]) return if (this.watcher[key]) return
const watcher = chokidar.watch(file) const watcher = watch(file)
watcher.on('change', () => { watcher.on('change', () => {
delete this.config[key] delete this.config[key]
if (typeof Bot == 'undefined') return if (typeof Bot == 'undefined') return

View File

@ -1,4 +1,4 @@
import fs from 'fs' import { readFileSync, writeFileSync } from 'fs'
import inquirer from 'inquirer' import inquirer from 'inquirer'
import chalk from 'chalk' import chalk from 'chalk'
import { import {
@ -104,19 +104,19 @@ export async function createLogin() {
*/ */
const file = `./${CONFIG_INIT_PATH}` const file = `./${CONFIG_INIT_PATH}`
const fileDef = `./${CONFIG_DEFAULT_PATH}` const fileDef = `./${CONFIG_DEFAULT_PATH}`
let qq = fs.readFileSync(`${fileDef}qq.yaml`, 'utf8') let qq = readFileSync(`${fileDef}qq.yaml`, 'utf8')
qq = qq.replace(/qq:/g, 'qq: ' + ret.QQ) qq = qq.replace(/qq:/g, 'qq: ' + ret.QQ)
qq = qq.replace(/pwd:/g, `pwd: '${ret.pwd}'`) qq = qq.replace(/pwd:/g, `pwd: '${ret.pwd}'`)
qq = qq.replace(/platform: [1-6]/g, 'platform: ' + Number(ret.platform)) qq = qq.replace(/platform: [1-6]/g, 'platform: ' + Number(ret.platform))
fs.writeFileSync(`${file}qq.yaml`, qq, 'utf8') writeFileSync(`${file}qq.yaml`, qq, 'utf8')
let bot = fs.readFileSync(`${fileDef}bot.yaml`, 'utf8') let bot = readFileSync(`${fileDef}bot.yaml`, 'utf8')
/** /**
* *
*/ */
if (ret.masterQQ) { if (ret.masterQQ) {
let other = fs.readFileSync(`${fileDef}other.yaml`, 'utf8') let other = readFileSync(`${fileDef}other.yaml`, 'utf8')
other = other.replace(/masterQQ:/g, `masterQQ:\n - ${ret.masterQQ}`) other = other.replace(/masterQQ:/g, `masterQQ:\n - ${ret.masterQQ}`)
fs.writeFileSync(`${file}other.yaml`, other, 'utf8') writeFileSync(`${file}other.yaml`, other, 'utf8')
} }
/** /**
* *
@ -124,7 +124,7 @@ export async function createLogin() {
if (ret.signAPI) { if (ret.signAPI) {
bot = bot.replace(/sign_api_addr:/g, `sign_api_addr: ${ret.signAPI}`) bot = bot.replace(/sign_api_addr:/g, `sign_api_addr: ${ret.signAPI}`)
} }
fs.writeFileSync(`${file}bot.yaml`, bot, 'utf8') writeFileSync(`${file}bot.yaml`, bot, 'utf8')
logger.info( logger.info(
`\nQQ配置完成正在登录\n后续修改账号可以运行命令 ${chalk.green('npm run login')}\n` `\nQQ配置完成正在登录\n后续修改账号可以运行命令 ${chalk.green('npm run login')}\n`
) )

View File

@ -1,5 +1,5 @@
import { type Client } from 'icqq' import { type Client } from 'icqq'
import lodash from 'lodash' import { isArray } from 'lodash-es'
import * as Events from './events.js' import * as Events from './events.js'
/** /**
@ -31,7 +31,7 @@ class ListenerLoader {
* *
*/ */
const on = listener.once ? 'once' : 'on' const on = listener.once ? 'once' : 'on'
if (lodash.isArray(listener.event)) { if (isArray(listener.event)) {
listener.event.forEach(type => { listener.event.forEach(type => {
const e = listener[type] ? type : 'execute' const e = listener[type] ? type : 'execute'
this.client[on](listener.prefix + type, event => listener[e](event)) this.client[on](listener.prefix + type, event => listener[e](event))

View File

@ -1,15 +1,15 @@
import fs from 'node:fs/promises'
import lodash from 'lodash' import lodash from 'lodash'
import cfg from '../config/config.js' import cfg from '../config/config.js'
import schedule from 'node-schedule' import schedule from 'node-schedule'
import { segment } from 'icqq' import { segment } from 'icqq'
import chokidar from 'chokidar' import chokidar from 'chokidar'
import moment from 'moment' import moment from 'moment'
import path, { join } from 'node:path' import path, { basename, join } from 'node:path'
import Runtime from './plugins/runtime.js' import Runtime from './plugins/runtime.js'
import Handler from './plugins/handler.js' import Handler from './plugins/handler.js'
import { EventType } from './plugins/types.js' import { EventType } from './plugins/types.js'
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import { stat, readdir } from 'node:fs/promises'
/** /**
* *
@ -85,7 +85,7 @@ class PluginsLoader {
*/ */
#getPlugins = async () => { #getPlugins = async () => {
// 便利得到目录和文件 // 便利得到目录和文件
const files = await fs.readdir(this.dir, { withFileTypes: true }) const files = await readdir(this.dir, { withFileTypes: true })
const ret = [] const ret = []
for (const val of files) { for (const val of files) {
// 是文件 // 是文件
@ -95,7 +95,7 @@ class PluginsLoader {
if (!existsSync(dir)) { if (!existsSync(dir)) {
dir = `${this.dir}/${val.name}/index.js` dir = `${this.dir}/${val.name}/index.js`
} }
if (await fs.stat(dir)) { if (await stat(dir)) {
ret.push({ ret.push({
name: val.name, name: val.name,
path: dir path: dir
@ -1207,7 +1207,7 @@ class PluginsLoader {
* *
*/ */
watcher.on('add', async PluPath => { watcher.on('add', async PluPath => {
const appName = path.basename(PluPath) const appName = basename(PluPath)
/** /**
*/ */
if (!/^(.js|.ts)$/.test(appName)) return if (!/^(.js|.ts)$/.test(appName)) return

View File

@ -1,5 +1,5 @@
import util from 'node:util' import { types } from 'node:util'
import lodash from 'lodash' import { orderBy } from 'lodash-es'
/** /**
* *
@ -31,7 +31,7 @@ const Handler = {
self, self,
key key
}) })
events[key] = lodash.orderBy(events[key], ['priority'], ['asc']) events[key] = orderBy(events[key], ['priority'], ['asc'])
}, },
/** /**
* *
@ -53,7 +53,7 @@ const Handler = {
let handler = events[key][idx] let handler = events[key][idx]
if (handler.ns === ns) { if (handler.ns === ns) {
events[key].splice(idx, 1) events[key].splice(idx, 1)
events[key] = lodash.orderBy(events[key], ['priority'], ['asc']) events[key] = orderBy(events[key], ['priority'], ['asc'])
} }
} }
}, },
@ -87,7 +87,7 @@ const Handler = {
done = false done = false
} }
ret = fn.call(obj.self, e, args, reject) ret = fn.call(obj.self, e, args, reject)
if (util.types.isPromise(ret)) { if (types.isPromise(ret)) {
ret = await ret ret = await ret
} }
if (done && !allHandler) { if (done && !allHandler) {

View File

@ -1,7 +1,6 @@
import { Common } from '../../mys/miao.js' import { Common } from '../../mys/miao.js'
import { EventType } from './types.js' import { EventType } from './types.js'
import { type EventMap } from 'icqq' import { type EventMap } from 'icqq'
const State = {} const State = {}

View File

@ -1,4 +1,4 @@
import lodash from 'lodash' import { filter, repeat } from 'lodash-es'
import { existsSync, mkdirSync, writeFileSync } from 'node:fs' import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import { import {
gsCfg, gsCfg,
@ -243,7 +243,7 @@ export default class Runtime {
*/ */
async render( async render(
plugin_name: string, plugin_name: string,
path: string, basePath: string,
data: { data: {
[key: string]: any [key: string]: any
saveId?: any, saveId?: any,
@ -257,9 +257,9 @@ export default class Runtime {
} = {} } = {}
) { ) {
// 处理传入的path // 处理传入的path
path = path.replace(/.html$/, '') basePath = basePath.replace(/.html$/, '')
let paths = lodash.filter(path.split('/'), (p) => !!p) let paths = filter(basePath.split('/'), (p) => !!p)
path = paths.join('/') basePath = paths.join('/')
// 创建目录 // 创建目录
const mkdir = (check) => { const mkdir = (check) => {
let currDir = `${process.cwd()}/temp` let currDir = `${process.cwd()}/temp`
@ -271,10 +271,10 @@ export default class Runtime {
} }
return currDir return currDir
} }
mkdir(`html/${plugin_name}/${path}`) mkdir(`html/${plugin_name}/${basePath}`)
// 自动计算pluResPath // 自动计算pluResPath
const pluResPath = `../../../${lodash.repeat('../', paths.length)}plugins/${plugin_name}/resources/` const pluResPath = `../../../${repeat('../', paths.length)}plugins/${plugin_name}/resources/`
const miaoResPath = `../../../${lodash.repeat('../', paths.length)}plugins/miao-plugin/resources/` const miaoResPath = `../../../${repeat('../', paths.length)}plugins/miao-plugin/resources/`
const layoutPath = process.cwd() + '/plugins/miao-plugin/resources/common/layout/' const layoutPath = process.cwd() + '/plugins/miao-plugin/resources/common/layout/'
// 渲染data // 渲染data
data = { data = {
@ -293,9 +293,9 @@ export default class Runtime {
/** 默认参数 **/ /** 默认参数 **/
_plugin: plugin_name, _plugin: plugin_name,
_htmlPath: path, _htmlPath: basePath,
pluResPath, pluResPath,
tplFile: `./plugins/${plugin_name}/resources/${path}.html`, tplFile: `./plugins/${plugin_name}/resources/${basePath}.html`,
saveId: data.saveId || data.save_id || paths[paths.length - 1], saveId: data.saveId || data.save_id || paths[paths.length - 1],
pageGotoParams: { pageGotoParams: {
waitUntil: 'networkidle2' waitUntil: 'networkidle2'
@ -314,7 +314,7 @@ export default class Runtime {
writeFileSync(file, JSON.stringify(data)) writeFileSync(file, JSON.stringify(data))
} }
// 截图 // 截图
const base64 = await puppeteer.screenshot(`${plugin_name}/${path}`, data) const base64 = await puppeteer.screenshot(`${plugin_name}/${basePath}`, data)
if (cfg.retType === 'base64') { if (cfg.retType === 'base64') {
return base64 return base64
} }

View File

@ -1,5 +1,5 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import path from 'path' import { resolve } from 'path'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
/** /**
* *
@ -40,6 +40,6 @@ const CustomExtensions = [
*/ */
for (const ext of CustomExtensions) { for (const ext of CustomExtensions) {
require.extensions[ext] = (module, filename) => { require.extensions[ext] = (module, filename) => {
module.exports = path.resolve(filename) module.exports = resolve(filename)
} }
} }

View File

@ -9,7 +9,10 @@ import lodash from 'lodash'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import DailyCache from './DailyCache.js' import DailyCache from './DailyCache.js'
import BaseModel from './BaseModel.js' import BaseModel from './BaseModel.js'
import NoteUser from './NoteUser.js'
// 循环引用
// import NoteUser from './NoteUser.js'
import MysApi from './mysApi.js' import MysApi from './mysApi.js'
import MysUtil from './MysUtil.js' import MysUtil from './MysUtil.js'
import { MysUserDB } from '../db/index.js' import { MysUserDB } from '../db/index.js'
@ -665,19 +668,22 @@ export default class MysUser extends BaseModel {
* @param game * @param game
*/ */
async delWithUser(game = 'gs') { async delWithUser(game = 'gs') {
logger.info('错误行为,尝试进行循环引用!')
logger.info('这是设计错误,请等待修复....')
// 查找用户 // 查找用户
let cache = this.getCache(game) // let cache = this.getCache(game)
let qqArr = await cache.kGet(tables.qq, this.ltuid, true) // let qqArr = await cache.kGet(tables.qq, this.ltuid, true)
if (qqArr && qqArr.length > 0) { // if (qqArr && qqArr.length > 0) {
for (let qq of qqArr) { // for (let qq of qqArr) {
let user = await NoteUser.create(qq) // let user = await NoteUser.create(qq)
if (user) { // if (user) {
// 调用user删除ck // // 调用user删除ck
await user.delCk(this.ltuid, false) // await user.delCk(this.ltuid, false)
} // }
} // }
} // }
await this.del() // await this.del()
} }
/** /**

View File

@ -1,6 +1,10 @@
import BaseModel from './BaseModel.js' import BaseModel from './BaseModel.js'
import lodash from 'lodash' import lodash from 'lodash'
// tudp 循环引用
import MysUser from './MysUser.js' import MysUser from './MysUser.js'
//
import MysUtil from './MysUtil.js' import MysUtil from './MysUtil.js'
import { UserDB } from '../db/index.js' import { UserDB } from '../db/index.js'
import { Data } from './miao.js' import { Data } from './miao.js'

View File

@ -1,8 +1,9 @@
import YAML from 'yaml' import YAML from 'yaml'
import chokidar from 'chokidar' import chokidar from 'chokidar'
import fs from 'node:fs' import fs, { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
import lodash from 'lodash' import lodash from 'lodash'
import MysInfo from './mysInfo.js' // tudo 循环引用
// import MysInfo from './mysInfo.js'
import NoteUser from './NoteUser.js' import NoteUser from './NoteUser.js'
import { Character, Weapon } from './miao.js' import { Character, Weapon } from './miao.js'
@ -39,6 +40,7 @@ class GsCfg {
} }
/** /**
* tudo
* *
* @param app * @param app
* @param name * @param name
@ -68,7 +70,7 @@ class GsCfg {
if (this[type][key]) return this[type][key] if (this[type][key]) return this[type][key]
try { try {
this[type][key] = YAML.parse(fs.readFileSync(file, 'utf8')) this[type][key] = YAML.parse(readFileSync(file, 'utf8'))
} catch (error) { } catch (error) {
logger.error(`[${app}][${name}] 格式错误 ${error}`) logger.error(`[${app}][${name}] 格式错误 ${error}`)
return false return false
@ -120,6 +122,7 @@ class GsCfg {
} }
/** /**
* tudo
* ck * ck
* @param game * @param game
* @returns * @returns
@ -180,10 +183,15 @@ class GsCfg {
return obj.abbr || obj.name || '' return obj.abbr || obj.name || ''
} }
/** 公共配置ck文件修改hook */ /**
* ck文件修改hook
* //
*/
async change_myspubCk() { async change_myspubCk() {
await MysInfo.initCache() logger.info('操作失败,该方法在尝试循环引用!')
await MysInfo.initPubCk() logger.info('这是设计错误,请等待修复....')
// await MysInfo.initCache()
// await MysInfo.initPubCk()
} }
/** /**
@ -251,13 +259,13 @@ class GsCfg {
* @param name * @param name
*/ */
cpCfg(app, name) { cpCfg(app, name) {
if (!fs.existsSync('./plugins/genshin/config')) { if (!existsSync('./plugins/genshin/config')) {
fs.mkdirSync('./plugins/genshin/config') mkdirSync('./plugins/genshin/config')
} }
let set = `./plugins/genshin/config/${app}.${name}.yaml` let set = `./plugins/genshin/config/${app}.${name}.yaml`
if (!fs.existsSync(set)) { if (!existsSync(set)) {
fs.copyFileSync(`./plugins/genshin/defSet/${app}/${name}.yaml`, set) copyFileSync(`./plugins/genshin/defSet/${app}/${name}.yaml`, set)
} }
} }

View File

@ -1,5 +1,7 @@
import lodash from 'lodash' import lodash from 'lodash'
import MysApi from './mysApi.js' import MysApi from './mysApi.js'
// tudo 循环引用
import GsCfg from './gsCfg.js' import GsCfg from './gsCfg.js'
import NoteUser from './NoteUser.js' import NoteUser from './NoteUser.js'
import MysUser from './MysUser.js' import MysUser from './MysUser.js'
@ -302,6 +304,7 @@ export default class MysInfo {
static async initPubCk() { static async initPubCk() {
// 初始化公共CK // 初始化公共CK
let pubCount = 0 let pubCount = 0
// tudo
let pubCks = GsCfg.getConfig('mys', 'pubCk') || [] let pubCks = GsCfg.getConfig('mys', 'pubCk') || []
for (let ck of pubCks) { for (let ck of pubCks) {
let pubUser = await MysUser.create(ck) let pubUser = await MysUser.create(ck)
@ -369,6 +372,7 @@ export default class MysInfo {
* @returns * @returns
*/ */
static async getBingCkUid() { static async getBingCkUid() {
// tudo
let res = await GsCfg.getBingCk() let res = await GsCfg.getBingCk()
return { ...res.ck } return { ...res.ck }
} }

View File

@ -1,10 +1,9 @@
import { pipeline } from 'stream' import { pipeline } from 'stream'
import { promisify } from 'util' import { promisify } from 'util'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import fs from 'node:fs'
import path from 'node:path'
import { exec } from 'child_process' import { exec } from 'child_process'
import { join } from 'path' import { dirname, join } from 'path'
import { createWriteStream, existsSync, mkdirSync, readFileSync } from 'fs'
/** /**
* *
@ -22,11 +21,11 @@ export function sleep(ms: number) {
*/ */
export async function downFile(fileUrl: string, savePath: string, param = {}) { export async function downFile(fileUrl: string, savePath: string, param = {}) {
try { try {
mkdirs(path.dirname(savePath)) mkdirs(dirname(savePath))
logger.debug(`[下载文件] ${fileUrl}`) logger.debug(`[下载文件] ${fileUrl}`)
const response = await fetch(fileUrl, param) const response = await fetch(fileUrl, param)
const streamPipeline = promisify(pipeline) const streamPipeline = promisify(pipeline)
await streamPipeline(response.body, fs.createWriteStream(savePath)) await streamPipeline(response.body, createWriteStream(savePath))
return true return true
} catch (err) { } catch (err) {
logger.error(`下载文件错误:${err}`) logger.error(`下载文件错误:${err}`)
@ -36,15 +35,15 @@ export async function downFile(fileUrl: string, savePath: string, param = {}) {
/** /**
* *
* @param dirname * @param name
* @returns * @returns
*/ */
export function mkdirs(dirname: string) { export function mkdirs(name: string) {
if (fs.existsSync(dirname)) { if (existsSync(name)) {
return true return true
} else { } else {
if (mkdirs(path.dirname(dirname))) { if (mkdirs(dirname(name))) {
fs.mkdirSync(dirname) mkdirSync(name)
return true return true
} }
} }
@ -75,7 +74,7 @@ export function execAsync(cmd: string): Promise<{
*/ */
export function readJSON(dir: string) { export function readJSON(dir: string) {
try { try {
const cfg = fs.readFileSync(join(process.cwd(), dir), 'utf-8') const cfg = readFileSync(join(process.cwd(), dir), 'utf-8')
return JSON.parse(cfg) return JSON.parse(cfg)
} catch { } catch {
return false return false

View File

@ -1,7 +1,7 @@
import template from 'art-template' import template from 'art-template'
import chokidar from 'chokidar' import chokidar from 'chokidar'
import path from 'node:path' import { dirname } from 'node:path'
import fs, { writeFileSync } from 'node:fs' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
/** /**
* *
@ -34,12 +34,12 @@ export default class Renderer {
* @param dirname * @param dirname
* @returns * @returns
*/ */
createDir(dirname: string) { createDir(name: string) {
if (fs.existsSync(dirname)) { if (existsSync(name)) {
return true return true
} else { } else {
if (this.createDir(path.dirname(dirname))) { if (this.createDir(dirname(name))) {
fs.mkdirSync(dirname) mkdirSync(name)
return true return true
} }
} }
@ -57,7 +57,7 @@ export default class Renderer {
if (!this.html[tplFile]) { if (!this.html[tplFile]) {
this.createDir(`./temp/html/${name}`) this.createDir(`./temp/html/${name}`)
try { try {
this.html[tplFile] = fs.readFileSync(tplFile, 'utf8') this.html[tplFile] = readFileSync(tplFile, 'utf8')
} catch (error) { } catch (error) {
logger.error(`加载html错误${tplFile}`) logger.error(`加载html错误${tplFile}`)
return false return false

View File

@ -1,4 +1,4 @@
import fs from 'node:fs' import fs, { existsSync, readFileSync } from 'node:fs'
import yaml from 'yaml' import yaml from 'yaml'
import lodash from 'lodash' import lodash from 'lodash'
import { ConfigController as cfg } from '../../config/index.js' import { ConfigController as cfg } from '../../config/index.js'
@ -47,8 +47,8 @@ class RendererLoader {
'config', 'config',
'puppeteer.yaml' 'puppeteer.yaml'
) )
const rendererCfg = fs.existsSync(configFile) const rendererCfg = existsSync(configFile)
? yaml.parse(fs.readFileSync(configFile, 'utf8')) ? yaml.parse(readFileSync(configFile, 'utf8'))
: {} : {}
const renderer = rendererFn.default(rendererCfg) const renderer = rendererFn.default(rendererCfg)
if ( if (