一些底层方法修改

This commit is contained in:
yoimiya-kokomi 2022-09-04 17:33:14 +08:00
parent 96544840cb
commit fee0c25e7d
14 changed files with 113 additions and 130 deletions

View File

@ -1,7 +1,7 @@
import fs from 'fs' import fs from 'fs'
import lodash from 'lodash' import lodash from 'lodash'
import { exec } from 'child_process' import { exec } from 'child_process'
import { Cfg, Common } from '../components/index.js' import { Cfg, Common, Data } from '../components/index.js'
let cfgMap = { let cfgMap = {
角色: 'char.char', 角色: 'char.char',
@ -175,10 +175,10 @@ export async function updateMiaoPlugin (e) {
} }
e.reply('喵喵更新成功正在尝试重新启动Yunzai以应用更新...') e.reply('喵喵更新成功正在尝试重新启动Yunzai以应用更新...')
timer && clearTimeout(timer) timer && clearTimeout(timer)
redis.set('miao:restart-msg', JSON.stringify({ Data.setCacheJSON('miao:restart-msg', {
msg: '重启成功,新版喵喵已经生效', msg: '重启成功,新版喵喵已经生效',
qq: e.user_id qq: e.user_id
}), { EX: 30 }) }, 30)
timer = setTimeout(function () { timer = setTimeout(function () {
let command = 'npm run start' let command = 'npm run start'
if (process.argv[1].includes('pm2')) { if (process.argv[1].includes('pm2')) {

View File

@ -57,7 +57,7 @@ async function saveImages (e, name, imageMessages) {
let path = resPath + pathSuffix let path = resPath + pathSuffix
if (!fs.existsSync(path)) { if (!fs.existsSync(path)) {
Data.createDir(resPath, pathSuffix) Data.createDir(pathSuffix, resPath)
} }
let senderName = lodash.truncate(e.sender.card, { length: 8 }) let senderName = lodash.truncate(e.sender.card, { length: 8 })
let imgCount = 0 let imgCount = 0
@ -124,13 +124,13 @@ async function isAllowedToUploadCharacterImage (e) {
if (!groupId) { if (!groupId) {
return false return false
} }
if (e.groupConfig.imgAddLimit === 2) { if (e.groupConfig?.imgAddLimit === 2) {
if (!e.isMaster) { if (!e.isMaster) {
e.reply('只有主人才能添加。') e.reply('只有主人才能添加。')
return false return false
} }
} }
if (e.groupConfig.imgAddLimit === 1 && !e.isMaster) { if (e.groupConfig?.imgAddLimit === 1 && !e.isMaster) {
if (!(e.sender.role === 'owner' || e.sender.role === 'admin')) { if (!(e.sender.role === 'owner' || e.sender.role === 'admin')) {
e.reply('只有管理员才能添加。') e.reply('只有管理员才能添加。')
return false return false

View File

@ -5,6 +5,7 @@
* */ * */
import fetch from 'node-fetch' import fetch from 'node-fetch'
import { Data } from '../../components/index.js'
const host = 'http://49.232.91.210:88/miaoPlugin/hutaoApi' const host = 'http://49.232.91.210:88/miaoPlugin/hutaoApi'
@ -14,9 +15,9 @@ function getApi (api) {
let HutaoApi = { let HutaoApi = {
async req (url, param = {}) { async req (url, param = {}) {
let cacheData = await redis.get(`hutao:${url}`) let cacheData = await Data.getCacheJSON(`hutao:${url}`)
if (cacheData && param.method !== 'POST') { if (cacheData && param.method !== 'POST') {
return JSON.parse(cacheData) return cacheData
} }
let response = await fetch(getApi(`${url}`), { let response = await fetch(getApi(`${url}`), {
@ -27,7 +28,7 @@ let HutaoApi = {
if (retData && retData.data && param.method !== 'POST') { if (retData && retData.data && param.method !== 'POST') {
let d = new Date() let d = new Date()
retData.lastUpdate = `${d.toLocaleDateString()} ${d.toTimeString().substr(0, 5)}` retData.lastUpdate = `${d.toLocaleDateString()} ${d.toTimeString().substr(0, 5)}`
await redis.set(`hutao:${url}`, JSON.stringify(retData), { EX: 3600 }) await Data.setCacheJSON(`hutao:${url}`, retData, 3600)
} }
return retData return retData
}, },

View File

@ -105,7 +105,7 @@ let Cal = {
} }
} catch (e) { } catch (e) {
} }
await redis.set('cache:calendar:detail', JSON.stringify(timeMap), { EX: 60 * 10 }) Data.setCacheJSON('cache:calendar:detail', timeMap, 60 * 10)
} }
return { listData, timeMap } return { listData, timeMap }
}, },

View File

@ -11,7 +11,7 @@ export const render = async function (path, params, cfg) {
let { e } = cfg let { e } = cfg
let layoutPath = process.cwd() + '/plugins/miao-plugin/resources/common/layout/' let layoutPath = process.cwd() + '/plugins/miao-plugin/resources/common/layout/'
let resPath = `../../../../../plugins/${plugin}/resources/` let resPath = `../../../../../plugins/${plugin}/resources/`
Data.createDir(_path + '/data/', `html/${plugin}/${app}/${tpl}`) Data.createDir(`data/html/${plugin}/${app}/${tpl}`, 'root')
let data = { let data = {
...params, ...params,
_plugin: plugin, _plugin: plugin,

View File

@ -2,15 +2,24 @@ import lodash from 'lodash'
import fs from 'fs' import fs from 'fs'
const _path = process.cwd() const _path = process.cwd()
const getRoot = (root = '') => {
if (root === 'root' || root === 'yunzai') {
root = _path
} else if (!root) {
root = `${_path}/plugins/miao-plugin/`
}
return root
}
let Data = { let Data = {
/* /*
* 根据指定的path依次检查与创建目录 * 根据指定的path依次检查与创建目录
* */ * */
createDir (rootPath = '', path = '', includeFile = false) { createDir (path = '', root = '', includeFile = false) {
root = getRoot(root)
let pathList = path.split('/') let pathList = path.split('/')
let nowPath = rootPath let nowPath = root
pathList.forEach((name, idx) => { pathList.forEach((name, idx) => {
name = name.trim() name = name.trim()
if (!includeFile && idx <= pathList.length - 1) { if (!includeFile && idx <= pathList.length - 1) {
@ -27,15 +36,14 @@ let Data = {
/* /*
* 读取json * 读取json
* */ * */
readJSON (root, path) { readJSON (file = '', root = '') {
if (!/\.json$/.test(path)) { root = getRoot(root)
path = path + '.json' if (fs.existsSync(`${root}/${file}`)) {
} try {
// 检查并创建目录 return JSON.parse(fs.readFileSync(`${root}/${file}`, 'utf8'))
Data.createDir(root, path, true) } catch (e) {
if (fs.existsSync(`${root}/${path}`)) { console.log(e)
let jsonRet = fs.readFileSync(`${root}/${path}`, 'utf8') }
return JSON.parse(jsonRet)
} }
return {} return {}
}, },
@ -43,38 +51,54 @@ let Data = {
/* /*
* 写JSON * 写JSON
* */ * */
writeJson (path, file, data, space = '\t') { writeJSON (file, data, space = '\t', root = '') {
if (!/\.json$/.test(file)) {
file = file + '.json'
}
// 检查并创建目录 // 检查并创建目录
Data.createDir(_path, path, false) Data.createDir(file, root, true)
console.log(data) root = getRoot(root)
delete data._res delete data._res
return fs.writeFileSync(`${_path}/${path}/${file}`, JSON.stringify(data, null, space)) return fs.writeFileSync(`${root}/${file}`, JSON.stringify(data, null, space))
}, },
async importModule (path, file, rootPath = _path) { async getCacheJSON (key) {
try {
let txt = await redis.get(key)
if (txt) {
return JSON.parse(txt)
}
} catch (e) {
console.log(e)
}
return {}
},
async setCacheJSON (key, data, EX = 3600 * 24 * 90) {
await redis.set(key, JSON.stringify(data), { EX })
},
async importModule (file, root = '') {
root = getRoot(root)
if (!/\.js$/.test(file)) { if (!/\.js$/.test(file)) {
file = file + '.js' file = file + '.js'
} }
// 检查并创建目录 // 检查并创建目录
Data.createDir(_path, path, true) if (fs.existsSync(`${root}/${file}`)) {
if (fs.existsSync(`${_path}/${path}/${file}`)) { try {
let data = await import(`file://${_path}/${path}/${file}`) let data = await import(`file://${root}/${file}`)
return data || {} return data || {}
} catch (e) {
console.log(e)
}
} }
return {} return {}
}, },
async import (name) { async import (name) {
return await Data.importModule('plugins/miao-plugin/components/optional-lib/', `${name}.js`) return await Data.importModule(`components/optional-lib/${name}.js`)
}, },
async importCfg (key) { async importCfg (key) {
let sysCfg = await Data.importModule('plugins/miao-plugin/config/system', `${key}.js`) let sysCfg = await Data.importModule(`config/system/${key}.js`)
let diyCfg = await Data.importModule('plugins/miao-plugin/config/', `${key}.js`) let diyCfg = await Data.importModule(`config/${key}.js`)
if (diyCfg.isSys) { if (diyCfg.isSys) {
console.error(`miao-plugin: config/${key}.js无效已忽略`) console.error(`miao-plugin: config/${key}.js无效已忽略`)
console.error(`如需配置请复制config/${key}_default.js为config/${key}.js请勿复制config/system下的系统文件`) console.error(`如需配置请复制config/${key}_default.js为config/${key}.js请勿复制config/system下的系统文件`)
@ -128,35 +152,7 @@ let Data = {
return lodash.get(target, keyFrom, defaultValue) return lodash.get(target, keyFrom, defaultValue)
}, },
getUrlPath (url) { // 异步池,聚合请求
let reg = /^https*:\/\/(.*)\/(\w+\.(png|jpg|jpeg|webp))(\?.*)?$/
let ret = reg.exec(url)
if (!ret) {
return false
}
return {
path: ret[1],
filename: ret[2],
type: ret[3],
url
}
},
pathExists (root, path) {
if (fs.existsSync(root + '/' + path)) {
return true
}
path = path.replace('\\', '/')
const dirList = path.split('/')
let currentDir = root
for (let dir of dirList) {
currentDir = currentDir + '/' + dir
if (!fs.existsSync(currentDir)) {
fs.mkdirSync(currentDir)
}
}
return true
},
async asyncPool (poolLimit, array, iteratorFn) { async asyncPool (poolLimit, array, iteratorFn) {
const ret = [] // 存储所有的异步任务 const ret = [] // 存储所有的异步任务
const executing = [] // 存储正在执行的异步任务 const executing = [] // 存储正在执行的异步任务
@ -180,10 +176,12 @@ let Data = {
return Promise.all(ret) return Promise.all(ret)
}, },
// sleep
sleep (ms) { sleep (ms) {
return new Promise((resolve) => setTimeout(resolve, ms)) return new Promise((resolve) => setTimeout(resolve, ms))
}, },
// 获取默认值
def () { def () {
for (let idx in arguments) { for (let idx in arguments) {
if (!lodash.isUndefined(arguments[idx])) { if (!lodash.isUndefined(arguments[idx])) {
@ -192,6 +190,7 @@ let Data = {
} }
}, },
// 循环字符串回调
eachStr: (arr, fn) => { eachStr: (arr, fn) => {
if (lodash.isString(arr)) { if (lodash.isString(arr)) {
arr = arr.replace(/\s*(;||、|)\s*/, ',') arr = arr.replace(/\s*(;||、|)\s*/, ',')

View File

@ -11,7 +11,7 @@ export const artiIdx = {
理之冠: 5 理之冠: 5
} }
let relis = Data.readJSON(`${_path}/plugins/miao-plugin/resources/meta/reliquaries/`, 'data.json') || {} let relis = Data.readJSON('resources/meta/reliquaries/data.json')
let setMap = {} let setMap = {}
lodash.forEach(relis, (ds) => { lodash.forEach(relis, (ds) => {

View File

@ -3,7 +3,7 @@ import { Data, Version } from './components/index.js'
export * from './apps/index.js' export * from './apps/index.js'
let index = { miao: {} } let index = { miao: {} }
if (Version.isV3) { if (Version.isV3) {
index = await Data.importModule('/plugins/miao-plugin/adapter', 'v3-entrance.js') index = await Data.importModule('adapter/v3-entrance.js')
} }
export const miao = index.miao || {} export const miao = index.miao || {}
if (Bot?.logger?.info) { if (Bot?.logger?.info) {
@ -18,7 +18,7 @@ setTimeout(async function () {
let relpyPrivate = async function () { let relpyPrivate = async function () {
} }
if (!Version.isV3) { if (!Version.isV3) {
let common = await Data.importModule('/lib', 'common.js') let common = await Data.importModule('lib/common.js')
if (common && common.default && common.default.relpyPrivate) { if (common && common.default && common.default.relpyPrivate) {
relpyPrivate = common.default.relpyPrivate relpyPrivate = common.default.relpyPrivate
} }

View File

@ -5,8 +5,7 @@ import { Data } from '../components/index.js'
let artisMap = {} let artisMap = {}
async function init () { async function init () {
let _path = process.cwd() let artis = Data.readJSON('resources/meta/reliquaries/data.json')
let artis = Data.readJSON(`${_path}/plugins/miao-plugin/resources/meta/reliquaries/`, 'data.json') || {}
lodash.forEach(artis, (ds) => { lodash.forEach(artis, (ds) => {
artisMap[ds.name] = ds artisMap[ds.name] = ds

View File

@ -65,11 +65,7 @@ export default class Avatars extends Base {
} }
async getTalentData (ids, MysApi = false) { async getTalentData (ids, MysApi = false) {
let avatarTalent = {} let avatarTalent = await Data.getCacheJSON(`genshin:avatar-talent:${this.uid}`)
let talentCache = await redis.get(`genshin:avatar-talent:${this.uid}`)
if (talentCache) {
avatarTalent = JSON.parse(talentCache)
}
let needReq = {} let needReq = {}
lodash.forEach(ids, (id) => { lodash.forEach(ids, (id) => {
if (!avatarTalent[id]) { if (!avatarTalent[id]) {
@ -93,7 +89,7 @@ export default class Avatars extends Base {
lodash.forEach(skillRet, (talent) => { lodash.forEach(skillRet, (talent) => {
avatarTalent[talent.id] = talent avatarTalent[talent.id] = talent
}) })
await redis.set(`genshin:avatar-talent:${this.uid}`, JSON.stringify(avatarTalent), { EX: 3600 * 2 }) await Data.setCacheJSON(`genshin:avatar-talent:${this.uid}`, avatarTalent, 3600 * 2)
} }
let ret = this.getData(ids) let ret = this.getData(ids)
lodash.forEach(ret, (avatar, id) => { lodash.forEach(ret, (avatar, id) => {

View File

@ -113,7 +113,7 @@ class Character extends Base {
return costume.includes(id * 1) return costume.includes(id * 1)
} }
// 获取Character图像资源 // 获取角色插画
getImgs (costume = '') { getImgs (costume = '') {
let costumeId = this.checkCostume(costume) ? '2' : '' let costumeId = this.checkCostume(costume) ? '2' : ''
let cacheId = `costume${costumeId}` let cacheId = `costume${costumeId}`
@ -135,13 +135,13 @@ class Character extends Base {
if (this.isCustom) { if (this.isCustom) {
return {} return {}
} }
const path = `${_path}/plugins/miao-plugin/resources/meta/character/` const path = 'resources/meta/character'
try { try {
if (this.isTraveler) { if (this.isTraveler) {
this._detail = Data.readJSON(`${path}/旅行者/${this.elem}`, 'detail.json') || {} this._detail = Data.readJSON(`${path}/旅行者/${this.elem}/detail.json`)
} else { } else {
this._detail = Data.readJSON(`${path}/${this.name}`, 'detail.json') || {} this._detail = Data.readJSON(`${path}/${this.name}/detail.json`)
} }
} catch (e) { } catch (e) {
console.log(e) console.log(e)
@ -151,23 +151,16 @@ class Character extends Base {
setTraveler (uid = '') { setTraveler (uid = '') {
if (this.isTraveler && uid && uid.toString().length === 9) { if (this.isTraveler && uid && uid.toString().length === 9) {
redis.set(`genshin:uid-traveler:${uid}`, JSON.stringify({ Data.setCacheJSON(`genshin:uid-traveler:${uid}`, {
id: CharId.getTravelerId(this.id), id: CharId.getTravelerId(this.id),
elem: this.elem elem: this.elem
}), { EX: 3600 * 24 * 120 }) }, 3600 * 24 * 120)
} }
} }
async getTraveler (uid) { async getTraveler (uid) {
if (this.isTraveler) { if (this.isTraveler) {
let tData = {} let tData = await Data.getCacheJSON(`genshin:uid-traveler:${uid}`)
let uidData = await redis.get(`genshin:uid-traveler:${uid}`)
if (uidData) {
try {
tData = JSON.parse(uidData) || tData
} catch (e) {
}
}
return Character.get({ return Character.get({
id: CharId.getTravelerId(tData.id || this.id), id: CharId.getTravelerId(tData.id || this.id),
elem: tData.elem || (this.elem !== 'multi' ? this.elem : 'anemo') elem: tData.elem || (this.elem !== 'multi' ? this.elem : 'anemo')
@ -198,7 +191,7 @@ class Character extends Base {
} }
let getMeta = function (name) { let getMeta = function (name) {
return Data.readJSON(`${_path}/plugins/miao-plugin/resources/meta/character/${name}/`, 'data.json') || {} return Data.readJSON(`resources/meta/character/${name}/data.json`)
} }
Character.get = function (val) { Character.get = function (val) {

View File

@ -3,6 +3,8 @@ import lodash from 'lodash'
import sizeOf from 'image-size' import sizeOf from 'image-size'
const CharImg = { const CharImg = {
// 获取角色的插画
getCardImg (names, se = false, def = true) { getCardImg (names, se = false, def = true) {
let list = [] let list = []
let addImg = function (charImgPath, disable = false) { let addImg = function (charImgPath, disable = false) {
@ -48,21 +50,24 @@ const CharImg = {
return ret return ret
}, },
getImgs (name, cId = '', elem = '') { // 获取角色的图像资源数据
getImgs (name, costumeId = '', travelerElem = '') {
let imgs = {} let imgs = {}
if (!['空', '荧', '旅行者'].includes(name)) {
travelerElem = ''
}
const nPath = `/meta/character/${name}/` const nPath = `/meta/character/${name}/`
const tPath = `/meta/character/旅行者/${elem}` const tPath = `/meta/character/旅行者/${travelerElem}/`
let add = (key, path, traveler = false) => { let add = (key, path, traveler = false) => {
imgs[key] = `${traveler ? tPath : nPath}${path}.webp` imgs[key] = `${traveler ? tPath : nPath}${path}.webp`
} }
let tAdd = (key, path) => { let tAdd = (key, path) => {
add(key, path, !!elem) add(key, path, !!travelerElem)
} }
add('face', `imgs/face${cId}`) add('face', `imgs/face${costumeId}`)
add('side', `imgs/side${cId}`) add('side', `imgs/side${costumeId}`)
add('gacha', 'imgs/gacha') add('gacha', 'imgs/gacha')
add('splash', `imgs/splash${cId}`) add('splash', `imgs/splash${costumeId}`)
tAdd('card', 'imgs/card') tAdd('card', 'imgs/card')
tAdd('banner', 'imgs/banner') tAdd('banner', 'imgs/banner')
for (let i = 1; i <= 6; i++) { for (let i = 1; i <= 6; i++) {

View File

@ -507,15 +507,15 @@
"type": "talent", "type": "talent",
"star": 4, "star": 4,
"items": { "items": {
"「诗文」的教导": { "「自由」的教导": {
"id": 401, "id": 421,
"name": "「诗文」的教导", "name": "「自由」的教导",
"type": "talent", "type": "talent",
"star": 2 "star": 2
}, },
"「诗文」的指引": { "「抗争」的指引": {
"id": 402, "id": 452,
"name": "「诗文」的指引", "name": "「抗争」的指引",
"type": "talent", "type": "talent",
"star": 3 "star": 3
}, },

View File

@ -95,7 +95,6 @@ let getCharData = async function (id, key, name = '') {
dendro: 8 dendro: 8
} }
let cid = `1000000${id}-${id}0${te[tElems[idx]]}` let cid = `1000000${id}-${id}0${te[tElems[idx]]}`
console.log(cid)
lodash.forEach(tId[cid].ProudMap || {}, (v, k) => { lodash.forEach(tId[cid].ProudMap || {}, (v, k) => {
talentId[k] = v talentId[k] = v
}) })
@ -127,27 +126,18 @@ let getCharData = async function (id, key, name = '') {
} }
function checkName (name) { function checkName (name) {
let charPath = `${_path}/plugins/miao-plugin/resources/meta/character/${name}/` let charPath = `resources/meta/character/${name}/`
if (!fs.existsSync(charPath)) { Data.createDir(charPath)
fs.mkdirSync(charPath) if (name === '旅行者') {
}
if (name === '空' || name === '荧' || name === '旅行者') {
for (let idx in tElems) { for (let idx in tElems) {
Data.createDir(charPath, `${tElems[idx]}/icons`) Data.createDir(`${charPath}${tElems[idx]}/icons`)
} }
} else { } else {
Data.createDir(charPath, 'icons') Data.createDir(`${charPath}/icons`)
}
Data.createDir(charPath, 'imgs')
if (fs.existsSync(`${charPath}data.json`)) {
try {
let data = JSON.parse(fs.readFileSync(`${charPath}data.json`, 'utf8'))
if (data && data.ver * 1 === ver * 1) {
return true
}
} catch (e) {
}
} }
Data.createDir(`${charPath}/imgs`)
let data = Data.readJSON(`${charPath}/data.json`)
return data.ver * 1 > 1
} }
async function saveCharData (id, key, name = '', force = false) { async function saveCharData (id, key, name = '', force = false) {
@ -171,7 +161,7 @@ async function saveCharData (id, key, name = '', force = false) {
fs.writeFileSync(`${charPath}data.json`, JSON.stringify(data, '', 2)) fs.writeFileSync(`${charPath}data.json`, JSON.stringify(data, '', 2))
if (details.length === 1) { if (details.length === 1) {
fs.writeFileSync(`${charPath}detail.json`, JSON.stringify(details[0], '', 2)) fs.writeFileSync(`${charPath}detail.json`, JSON.stringify(details[0], '', 2))
} else { } else if (data.id === 20000000) {
for (let idx in details) { for (let idx in details) {
let detail = details[idx] let detail = details[idx]
fs.writeFileSync(`${charPath}/${detail.elem}/detail.json`, JSON.stringify(detail, '', 2)) fs.writeFileSync(`${charPath}/${detail.elem}/detail.json`, JSON.stringify(detail, '', 2))
@ -179,12 +169,12 @@ async function saveCharData (id, key, name = '', force = false) {
} }
console.log(data.name + '数据下载完成') console.log(data.name + '数据下载完成')
await imgs.download() if (![10000005, 10000007].includes(data.id)) {
console.log(data.name + '图像全部下载完成') await imgs.download()
console.log(data.name + '图像全部下载完成')
}
} }
const ver = 1
async function down (name = '', force = false) { async function down (name = '', force = false) {
if (name === '') { if (name === '') {
name = lodash.keys(charData).join(',') name = lodash.keys(charData).join(',')
@ -261,4 +251,4 @@ const charData = {
71: { key: 'cyno', name: '赛诺' }, 71: { key: 'cyno', name: '赛诺' },
72: { key: 'candace', name: '坎蒂丝' } 72: { key: 'candace', name: '坎蒂丝' }
} }
await down('', true) await down('4,5,7', true)