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

View File

@ -1,5 +1,5 @@
import YAML from 'yaml'
import chokidar from 'chokidar'
import { watch } from 'chokidar'
import { parse } from 'yaml'
import { join } from 'node:path'
import { readFileSync, } from 'node:fs'
/**
@ -166,7 +166,7 @@ class ConfigController {
const file = `config/${type}/${name}.yaml`
const key = `${type}.${name}`
if (this.config[key]) return this.config[key]
this.config[key] = YAML.parse(
this.config[key] = parse(
readFileSync(file, 'utf8')
)
this.watch(file, name, type)
@ -183,7 +183,7 @@ class ConfigController {
watch(file: string, name: string, type = 'default_config') {
const key = `${type}.${name}`
if (this.watcher[key]) return
const watcher = chokidar.watch(file)
const watcher = watch(file)
watcher.on('change', () => {
delete this.config[key]
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 chalk from 'chalk'
import {
@ -104,19 +104,19 @@ export async function createLogin() {
*/
const file = `./${CONFIG_INIT_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(/pwd:/g, `pwd: '${ret.pwd}'`)
qq = qq.replace(/platform: [1-6]/g, 'platform: ' + Number(ret.platform))
fs.writeFileSync(`${file}qq.yaml`, qq, 'utf8')
let bot = fs.readFileSync(`${fileDef}bot.yaml`, 'utf8')
writeFileSync(`${file}qq.yaml`, qq, 'utf8')
let bot = readFileSync(`${fileDef}bot.yaml`, 'utf8')
/**
*
*/
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}`)
fs.writeFileSync(`${file}other.yaml`, other, 'utf8')
writeFileSync(`${file}other.yaml`, other, 'utf8')
}
/**
*
@ -124,7 +124,7 @@ export async function createLogin() {
if (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(
`\nQQ配置完成正在登录\n后续修改账号可以运行命令 ${chalk.green('npm run login')}\n`
)

View File

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

View File

@ -1,5 +1,5 @@
import util from 'node:util'
import lodash from 'lodash'
import { types } from 'node:util'
import { orderBy } from 'lodash-es'
/**
*
@ -15,7 +15,7 @@ const Handler = {
* @param cfg
* @returns
*/
add (cfg) {
add(cfg) {
let { ns, fn, self, property = 50 } = cfg
let key = cfg.key || cfg.event
if (!key || !fn) {
@ -31,7 +31,7 @@ const Handler = {
self,
key
})
events[key] = lodash.orderBy(events[key], ['priority'], ['asc'])
events[key] = orderBy(events[key], ['priority'], ['asc'])
},
/**
*
@ -39,7 +39,7 @@ const Handler = {
* @param key
* @returns
*/
del (ns, key = '') {
del(ns, key = '') {
if (!key) {
for (let key in events) {
Handler.del(ns, key)
@ -53,7 +53,7 @@ const Handler = {
let handler = events[key][idx]
if (handler.ns === ns) {
events[key].splice(idx, 1)
events[key] = lodash.orderBy(events[key], ['priority'], ['asc'])
events[key] = orderBy(events[key], ['priority'], ['asc'])
}
}
},
@ -63,7 +63,7 @@ const Handler = {
* @param e
* @param args
*/
async callAll (_, __, ___) {
async callAll(_, __, ___) {
// 暂时屏蔽调用
// return Handler.call(key, e, args, true)
},
@ -75,7 +75,7 @@ const Handler = {
* @param allHandler
* @returns
*/
async call (key, e, args, allHandler = false) {
async call(key, e, args, allHandler = false) {
let ret
for (let obj of events[key]) {
let fn = obj.fn
@ -87,7 +87,7 @@ const Handler = {
done = false
}
ret = fn.call(obj.self, e, args, reject)
if (util.types.isPromise(ret)) {
if (types.isPromise(ret)) {
ret = await ret
}
if (done && !allHandler) {
@ -102,7 +102,7 @@ const Handler = {
* @param key
* @returns
*/
has (key) {
has(key) {
return !!events[key]
}
}

View File

@ -1,7 +1,6 @@
import { Common } from '../../mys/miao.js'
import { EventType } from './types.js'
import { type EventMap } from 'icqq'
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 {
gsCfg,
@ -243,7 +243,7 @@ export default class Runtime {
*/
async render(
plugin_name: string,
path: string,
basePath: string,
data: {
[key: string]: any
saveId?: any,
@ -257,9 +257,9 @@ export default class Runtime {
} = {}
) {
// 处理传入的path
path = path.replace(/.html$/, '')
let paths = lodash.filter(path.split('/'), (p) => !!p)
path = paths.join('/')
basePath = basePath.replace(/.html$/, '')
let paths = filter(basePath.split('/'), (p) => !!p)
basePath = paths.join('/')
// 创建目录
const mkdir = (check) => {
let currDir = `${process.cwd()}/temp`
@ -271,10 +271,10 @@ export default class Runtime {
}
return currDir
}
mkdir(`html/${plugin_name}/${path}`)
mkdir(`html/${plugin_name}/${basePath}`)
// 自动计算pluResPath
const pluResPath = `../../../${lodash.repeat('../', paths.length)}plugins/${plugin_name}/resources/`
const miaoResPath = `../../../${lodash.repeat('../', paths.length)}plugins/miao-plugin/resources/`
const pluResPath = `../../../${repeat('../', paths.length)}plugins/${plugin_name}/resources/`
const miaoResPath = `../../../${repeat('../', paths.length)}plugins/miao-plugin/resources/`
const layoutPath = process.cwd() + '/plugins/miao-plugin/resources/common/layout/'
// 渲染data
data = {
@ -293,9 +293,9 @@ export default class Runtime {
/** 默认参数 **/
_plugin: plugin_name,
_htmlPath: path,
_htmlPath: basePath,
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],
pageGotoParams: {
waitUntil: 'networkidle2'
@ -314,7 +314,7 @@ export default class Runtime {
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') {
return base64
}

View File

@ -1,5 +1,5 @@
import { createRequire } from 'module'
import path from 'path'
import { resolve } from 'path'
const require = createRequire(import.meta.url)
/**
*
@ -40,6 +40,6 @@ const CustomExtensions = [
*/
for (const ext of CustomExtensions) {
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 DailyCache from './DailyCache.js'
import BaseModel from './BaseModel.js'
import NoteUser from './NoteUser.js'
// 循环引用
// import NoteUser from './NoteUser.js'
import MysApi from './mysApi.js'
import MysUtil from './MysUtil.js'
import { MysUserDB } from '../db/index.js'
@ -665,19 +668,22 @@ export default class MysUser extends BaseModel {
* @param game
*/
async delWithUser(game = 'gs') {
logger.info('错误行为,尝试进行循环引用!')
logger.info('这是设计错误,请等待修复....')
// 查找用户
let cache = this.getCache(game)
let qqArr = await cache.kGet(tables.qq, this.ltuid, true)
if (qqArr && qqArr.length > 0) {
for (let qq of qqArr) {
let user = await NoteUser.create(qq)
if (user) {
// 调用user删除ck
await user.delCk(this.ltuid, false)
}
}
}
await this.del()
// let cache = this.getCache(game)
// let qqArr = await cache.kGet(tables.qq, this.ltuid, true)
// if (qqArr && qqArr.length > 0) {
// for (let qq of qqArr) {
// let user = await NoteUser.create(qq)
// if (user) {
// // 调用user删除ck
// await user.delCk(this.ltuid, false)
// }
// }
// }
// await this.del()
}
/**

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
import template from 'art-template'
import chokidar from 'chokidar'
import path from 'node:path'
import fs, { writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
/**
*
@ -34,12 +34,12 @@ export default class Renderer {
* @param dirname
* @returns
*/
createDir(dirname: string) {
if (fs.existsSync(dirname)) {
createDir(name: string) {
if (existsSync(name)) {
return true
} else {
if (this.createDir(path.dirname(dirname))) {
fs.mkdirSync(dirname)
if (this.createDir(dirname(name))) {
mkdirSync(name)
return true
}
}
@ -57,7 +57,7 @@ export default class Renderer {
if (!this.html[tplFile]) {
this.createDir(`./temp/html/${name}`)
try {
this.html[tplFile] = fs.readFileSync(tplFile, 'utf8')
this.html[tplFile] = readFileSync(tplFile, 'utf8')
} catch (error) {
logger.error(`加载html错误${tplFile}`)
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 lodash from 'lodash'
import { ConfigController as cfg } from '../../config/index.js'
@ -47,8 +47,8 @@ class RendererLoader {
'config',
'puppeteer.yaml'
)
const rendererCfg = fs.existsSync(configFile)
? yaml.parse(fs.readFileSync(configFile, 'utf8'))
const rendererCfg = existsSync(configFile)
? yaml.parse(readFileSync(configFile, 'utf8'))
: {}
const renderer = rendererFn.default(rendererCfg)
if (