重构CK与UID管理逻辑

This commit is contained in:
Kokomi 2023-05-09 11:03:38 +08:00
parent 03896f035d
commit 9980cc6be4
16 changed files with 646 additions and 663 deletions

View File

@ -1,3 +1,9 @@
# 3.1.0 Dev
* !!!暂未完成,会有很多错误,不建议升级!!!
* 重构CK与UID管理逻辑
* 底层对星铁查询进行支持
# 3.0.2 # 3.0.2
* 3.6卡池以及图像武器别名等数据更新 **@cvs** * 3.6卡池以及图像武器别名等数据更新 **@cvs**

View File

@ -14,7 +14,7 @@ export default class blueprint extends base {
let uid = await MysInfo.getUid(this.e, false) let uid = await MysInfo.getUid(this.e, false)
if (!uid) return false if (!uid) return false
/** 判断是否绑定了ck */ /** 判断是否绑定了ck */
let ck = await MysInfo.checkUidBing(uid) let ck = await MysInfo.checkUidBing(uid, this.e)
if (!ck) { if (!ck) {
await this.e.reply(MysInfo.tips) await this.e.reply(MysInfo.tips)
return false return false

View File

@ -18,7 +18,7 @@ export default class Calculator extends base {
if (!uid) return false if (!uid) return false
/** 判断是否绑定了ck */ /** 判断是否绑定了ck */
let ck = await MysInfo.checkUidBing(uid) let ck = await MysInfo.checkUidBing(uid, this.e)
if (!ck) { if (!ck) {
await this.e.reply(MysInfo.tips) await this.e.reply(MysInfo.tips)
return false return false

View File

@ -37,16 +37,17 @@ class MysUserDB extends BaseModel {
return mys || false return mys || false
} }
static async findByCK (ck = '') { async saveDB (mys) {
let ltuid = 0 if (!mys.ck || !mys.device || !mys.db) {
let mys = await MysUserDB.find(ltuid) return false
if (!mys) {
mys = await MysUserDB.build({
ltuid,
ck
})
} }
return mys._cacheThis() let db = this
this.ck = mys.ck
this.type = mys.type
this.device = mys.device
this.gsUids = (mys.gsUids || []).join(',')
this.srUids = (mys.srUids || []).join(',')
await db.save()
} }
} }

View File

@ -1,4 +1,5 @@
import BaseModel from './BaseModel.js' import BaseModel from './BaseModel.js'
import lodash from 'lodash'
const { Types } = BaseModel const { Types } = BaseModel
@ -47,6 +48,22 @@ class UserDB extends BaseModel {
} }
return user return user
} }
async saveDB (user) {
let db = this
let ltuids = []
lodash.forEach(user.mysUsers, (mys) => {
if (mys.ck) {
ltuids.push(mys.ltuid)
}
})
db.ltuids = ltuids.join(',')
lodash.forEach(['gs', 'sr'], (key) => {
db[`${key}Uid`] = user[`${key}Uid`] ? user[`${key}Uid`] : user.uids[key]?.[0] || ''
db[`${key}RegUids`] = JSON.stringify(user.uidMap[key])
})
await this.save()
}
} }
BaseModel.initDB(UserDB, COLUMNS) BaseModel.initDB(UserDB, COLUMNS)

View File

@ -1,6 +1,8 @@
/** /**
* 基础类提供实例缓存等一些基础方法 * 基础类提供实例缓存等一些基础方法
*/ */
import MysUtil from './MysUtil.js'
let cacheMap = {} let cacheMap = {}
let reFn = {} let reFn = {}
@ -54,13 +56,14 @@ export default class BaseModel {
} }
gameKey (game = 'gs') { gameKey (game = 'gs') {
if (game.user_id) { return MysUtil.getGameKey(game)
return game.isSr ? 'sr' : 'gs'
}
return ['sr', 'star'].includes(game) ? 'sr' : 'gs'
} }
isGs (game = 'gs') { isGs (game = 'gs') {
return this.gameKey(game) === 'gs' return this.gameKey(game) === 'gs'
} }
isSr (game = 'gs') {
return this.gameKey(game) === 'sr'
}
} }

View File

@ -7,7 +7,7 @@ const EX = 3600 * 24
const redisKeyRoot = 'Yz:cache:' const redisKeyRoot = 'Yz:cache:'
export default class DailyCache extends BaseModel { export default class DailyCache extends BaseModel {
constructor (uid, game = 'cache') { constructor (uid, game = 'config') {
super() super()
const storeKey = DailyCache.getStoreKey(uid, game) const storeKey = DailyCache.getStoreKey(uid, game)
// 检查实例缓存 // 检查实例缓存
@ -22,30 +22,28 @@ export default class DailyCache extends BaseModel {
/** /**
* 传入UID或server标示返回当日存储对象 * 传入UID或server标示返回当日存储对象
* @param uid * @param uid
* @param game
* * 为空则返回与serv无关的dailyCache * * 为空则返回与serv无关的dailyCache
* * 传入UID会返回UID对应serv的cache对象 * * 传入UID会返回UID对应serv的cache对象
* * 传入servKey (mys/hoyolab)会返回指定的servCache * * 传入servKey (mys/hoyolab)会返回指定的servCache
* @returns {DailyCache} * @returns {DailyCache}
*/ */
static create (uid, game = 'common') { static create (uid, game = 'config') {
return new DailyCache(uid) return new DailyCache(uid, game)
}
// 内部方法获取server key
static getServKey (uid, game = 'common') {
// 不传入uid为默认cache
if (!uid || game === 'common') {
return `common`
}
// 传入uid或sever key判断是mys还是hoyolab
return `${game}:${/^[6-9]|^hoyo|^os/i.test(uid) ? servs[1] : servs[0]}`
} }
// 内部方法获取redis表前缀 // 内部方法获取redis表前缀
static getStoreKey (uid, game = 'cache') { static getStoreKey (uid, game = 'config') {
const serv = DailyCache.getServKey(uid, game = 'cache') let key
if (!uid || game === 'config') {
key = 'sys:config'
} else {
game = game === 'sr' ? 'sr' : 'gs'
let serv = /^[6-9]|^hoyo|^os/i.test(uid) ? servs[1] : servs[0]
key = `${game}:${serv}`
}
const date = moment().format('MM-DD') const date = moment().format('MM-DD')
return `${serv}-${date}` return `${key}-${date}`
} }
/** /**
@ -68,8 +66,8 @@ export default class DailyCache extends BaseModel {
static async clearOutdatedData () { static async clearOutdatedData () {
let keys = await redis.keys(`${redisKeyRoot}*`) let keys = await redis.keys(`${redisKeyRoot}*`)
const date = moment().format('MM-DD') const date = moment().format('MM-DD')
const testReg = new RegExp(`^${redisKeyRoot}(mys|hoyo|hoyolab|cache)-\\d{2}-\\d{2}`) const testReg = new RegExp(`^${redisKeyRoot}(mys|hoyolab|config)-\\d{2}-\\d{2}`)
const todayReg = new RegExp(`^${redisKeyRoot}(mys|hoyo|hoyolab|cache)-${date}`) const todayReg = new RegExp(`^${redisKeyRoot}(mys|hoyolab|config)-${date}`)
for (let key of keys) { for (let key of keys) {
if (testReg.test(key) && !todayReg.test(key)) { if (testReg.test(key) && !todayReg.test(key)) {
await redis.del(key) await redis.del(key)

View File

@ -9,9 +9,11 @@ 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 lodash from 'lodash' import lodash from 'lodash'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import { MysUserDB } from '../db/index.js' import { MysUserDB, UserDB } from '../db/index.js'
import { Data } from '../../../miao-plugin/components/index.js'
const tables = { const tables = {
// ltuid-uid 查询表 // ltuid-uid 查询表
@ -37,6 +39,7 @@ const tables = {
} }
export default class MysUser extends BaseModel { export default class MysUser extends BaseModel {
constructor (ltuid) { constructor (ltuid) {
super() super()
if (!ltuid) { if (!ltuid) {
@ -53,34 +56,27 @@ export default class MysUser extends BaseModel {
// 可传入ltuid、cookie、ck对象来创建MysUser实例 // 可传入ltuid、cookie、ck对象来创建MysUser实例
// 在仅传入ltuid时必须是之前传入过的才能被识别 // 在仅传入ltuid时必须是之前传入过的才能被识别
static async create (ltuid) { static async create (ltuid, db = false) {
ltuid = MysUser.getLtuid(ltuid) ltuid = MysUtil.getLtuid(ltuid)
if (!ltuid) { if (!ltuid) {
return false return false
} }
let mys = new MysUser(ltuid) let mys = new MysUser(ltuid)
await mys.initDB() await mys.initDB(db)
mys.initCacheObj()
return mys return mys
} }
static getLtuid (data) { static async forEach (fn) {
if (!data) { let dbs = await MysUserDB.findAll()
return false await Data.forEach(dbs, async (db) => {
} let mys = await MysUser.create(db.ltuid, db)
if (/^\d{4,9}$/.test(data)) { return await fn(mys)
return data })
}
let testRet = /ltuid=(\d{4,9})/g.exec(data.ck || data)
if (testRet && testRet[1]) {
return testRet[1]
}
return false
} }
// 根据uid获取查询MysUser // 根据uid获取查询MysUser
static async getByQueryUid (uid, onlySelfCk = false) { static async getByQueryUid (uid, game = 'gs', onlySelfCk = false) {
let servCache = DailyCache.create(uid) let servCache = DailyCache.create(uid, game)
// 查找已经查询过的ltuid || 分配最少查询的ltuid // 查找已经查询过的ltuid || 分配最少查询的ltuid
// 根据ltuid获取mysUser 封装 // 根据ltuid获取mysUser 封装
@ -94,7 +90,7 @@ export default class MysUser extends BaseModel {
} }
// 若声明只获取自己ck则判断uid是否为本人所有 // 若声明只获取自己ck则判断uid是否为本人所有
if (onlySelfCk && !await ckUser.ownUid(uid)) { if (onlySelfCk && !ckUser.ownUid(uid, game)) {
return false return false
} }
@ -122,11 +118,12 @@ export default class MysUser extends BaseModel {
} }
static async eachServ (fn) { static async eachServ (fn) {
let servs = ['mys', 'hoyolab'] await MysUtil.eachServ(async (serv) => {
for (let serv of servs) { await MysUtil.eachGame(async (game) => {
let servCache = DailyCache.create(serv) let servCache = DailyCache.create(serv, game)
await fn(servCache, serv) await fn(servCache, serv, game)
} })
})
} }
// 清除当日缓存 // 清除当日缓存
@ -197,70 +194,6 @@ export default class MysUser extends BaseModel {
return count return count
} }
/**
* 获取ck对应uid列表
* @param ck 需要获取的ck
* @param withMsg false:uids / true: {uids, msg}
* @param force 忽略缓存强制更新
* @returns {Promise<{msg: *, uids}>}
*/
static async getCkUid (ck, withMsg = false, force = false) {
let ltuid = ''
let testRet = /ltuid=(\w{0,9})/g.exec(ck)
if (testRet && testRet[1]) {
ltuid = testRet[1]
}
let uids = []
let ret = (msg, retUid) => {
retUid = lodash.map(retUid, (a) => a + '')
return withMsg ? { msg, uids: retUid } : retUid
}
if (!ltuid) {
return ret('无ltuid', false)
}
if (!force) {
// 此处不使用DailyCache做长期存储
uids = await redis.get(`Yz:genshin:mys:ltuid-uids:${ltuid}`)
if (uids) {
uids = DailyCache.decodeValue(uids, true)
if (uids && uids.length > 0) {
return ret('', uids)
}
}
}
uids = []
let res = null
let msg = 'error'
for (let serv of ['mys', 'hoyolab']) {
let roleRes = await MysUser.getGameRole(ck, serv)
if (roleRes?.retcode === 0) {
res = roleRes
break
}
if (roleRes.retcode * 1 === -100) {
msg = '该ck已失效请重新登录获取'
}
msg = roleRes.message || 'error'
}
if (!res) return ret(msg, false)
if (!res.data.list || res.data.list.length <= 0) {
return ret('该账号尚未绑定原神或星穹角色', false)
}
for (let val of res.data.list) {
if (/\d{9}/.test(val.game_uid) && val.game_biz === 'hk4e_cn') {
uids.push(val.game_uid + '')
}
}
if (uids.length > 0) {
await redis.set(`Yz:genshin:mys:ltuid-uids:${ltuid}`, JSON.stringify(uids), { EX: 3600 * 24 * 90 })
return ret('', uids)
}
return ret(msg, false)
}
/** /**
* 检查CK状态 * 检查CK状态
* @param ck 需要检查的CK * @param ck 需要检查的CK
@ -314,12 +247,68 @@ export default class MysUser extends BaseModel {
} }
} }
static getDeviceGuid () { // 不建议使用,为了兼容老数据格式,后续废弃
function S4 () { getCkInfo (game = 'gs') {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) let gameKey = this.gameKey(game)
return {
ck: this.ck,
uid: this.getUid(game),
qq: '',
ltuid: this.ltuid
}
} }
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()) getUid (game = 'gs') {
return this.getUids(game)[0]
}
getUids (game = 'gs') {
let gameKey = this.gameKey(game)
return this[`${gameKey}Uids`] || []
}
/**
* 刷新mysUser的UID列表
* @returns {Promise<{msg: string, status: number}>}
*/
async reqMysUid () {
let err = (msg = 'error', status = 1) => {
return { status, msg }
}
let res = null
let msg = 'error'
for (let serv of ['mys', 'hoyolab']) {
let roleRes = await this.getGameRole(serv)
if (roleRes?.retcode === 0) {
res = roleRes
if (serv === 'hoyolab') {
this.type = 'hoyolab'
}
break
}
if (roleRes.retcode * 1 === -100) {
msg = '该ck已失效请重新登录获取'
}
msg = roleRes.message || 'error'
}
if (!res) return err(msg)
let playerList = res?.data?.list || []
playerList = playerList.filter(v => ['hk4e_cn', 'hkrpg_cn', 'hk4e_global', 'hkrpg_global'].includes(v.game_biz))
if (!playerList || playerList.length <= 0) {
return err('该账号尚未绑定原神或星穹角色')
}
this.gsUids = []
this.srUids = []
/** 米游社默认展示的角色 */
for (let val of playerList) {
this.addUid(val.game_uid, ['hk4e_cn', 'hk4e_global'].includes(val.game_biz) ? 'gs' : 'sr')
}
await this.save()
return { status: 0, msg: '' }
} }
async getGameRole (serv = 'mys') { async getGameRole (serv = 'mys') {
@ -356,56 +345,49 @@ export default class MysUser extends BaseModel {
}) })
if (!res.ok) return res if (!res.ok) return res
res = await res.json() res = await res.json()
return res return res
} }
initCacheObj () { getCache (game = 'gs') {
if (this.cache) { if (!this.cache) {
return true this.cache = {}
} }
this.cache = { const { cache } = this
cache: DailyCache.create(), if (game !== 'config') {
gs: DailyCache.create(this.type, 'gs'), game = this.gameKey(game)
sr: DailyCache.create(this.type, 'sr')
} }
if (!cache[game]) {
cache[game] = DailyCache.create(this.type, game)
} }
return cache[game]
}
// 初始化数据 // 初始化数据
async initDB () { async initDB (db = false) {
if (this.db) { if (this.db && !db) {
return return
} }
let db = await MysUserDB.find(this.ltuid, true) db = db && db !== true ? db : await MysUserDB.find(this.ltuid, true)
this.db = db this.db = db
this.ck = db.ck || '' this.setCkData(db)
this.type = db.type || 'mys'
this.gsUids = (db.gsUids || '').split(',')
this.srUids = (db.srUids || '').split(',')
this.setCkData()
} }
// 设置ck数据
setCkData (data = {}) { setCkData (data = {}) {
this.ck = data.ck || this.ck || '' this.ck = data.ck || this.ck || ''
this.device = data.device || this.device || MysUser.getDeviceGuid()
this.type = data.type || this.type || 'mys' this.type = data.type || this.type || 'mys'
this.gsUids = lodash.isArray(data.gsUids) ? data.gsUids : this.gsUids || [] this.device = data.device || this.device || MysUtil.getDeviceGuid()
this.srUids = lodash.isArray(data.srUids) ? data.srUids : this.srUids || [] let self = this
MysUtil.eachGame((game) => {
let key = `${game}Uids`
self[key] = lodash.isString(data[key]) ? (data[key] || '').split(',') : (lodash.isArray(data[key]) ? data[key] : (self[key] || []))
})
} }
async saveDB () { async save () {
if (!this.ck || !this.device || !this.db) { await this.db.saveDB(this)
return false
} }
let db = this.db
db.ck = this.ck
db.type = this.type
db.device = this.device
db.gsUids = this.gsUids.join(',')
db.srUids = this.srUids.join(',')
await db.save()
}
// 为当前MysUser绑定uid // 为当前MysUser绑定uid
addUid (uid, game = 'gs') { addUid (uid, game = 'gs') {
@ -426,72 +408,38 @@ export default class MysUser extends BaseModel {
return true return true
} }
hasUid (uid, game = 'gs') {
}
hasGame (game = 'gs') { hasGame (game = 'gs') {
return (this.isGs(game) ? this.gsUids : this.srUids).length > 0 return (this.isGs(game) ? this.gsUids : this.srUids).length > 0
} }
// 初始化当前MysUser缓存记录 // 初始化当前MysUser缓存记录
async initCache (user) { async initCache () {
if (!this.ltuid || !this.servCache || !this.ck) { if (!this.ltuid || !this.ck) {
return return
} }
let self = this
// 为当前MysUser添加uid查询记录 await MysUtil.eachGame(async (game) => {
if (!lodash.isEmpty(this.uids)) { let uids = self[`${game}Uids`]
for (let uid of this.uids) { await this.addQueryUid(uids, game)
if (uid !== 'pub') { let cache = self.getCache(game)
await this.addQueryUid(uid) let cacheSearchList = await cache.get(tables.del, this.ltuid, true)
// 添加ltuid-uid记录用于判定ltuid绑定个数及自ltuid查询
await this.cache.zAdd(tables.uid, this.ltuid, uid)
}
}
} else {
console.log(`ltuid:${this.ltuid}暂无uid信息请检查...`)
// 公共ck暂无uid信息不添加
if (user?.qq === 'pub') {
return false
}
}
// 缓存ckData供后续缓存使用
// ltuid关系存储到与server无关的cache中方便后续检索
if (this.ckData && this.ckData.ck) {
await this.cache.kSet(tables.ck, this.ltuid, this.ckData)
}
// 缓存qq用于删除ltuid时查找
if (user && user.qq) {
let qq = user.qq === 'pub' ? 'pub' : user.qq * 1
let qqArr = await this.cache.kGet(tables.qq, this.ltuid, true)
if (!lodash.isArray(qqArr)) {
qqArr = []
}
if (!qqArr.includes(qq)) {
qqArr.push(qq)
await this.cache.kSet(tables.qq, this.ltuid, qqArr)
}
}
// 从删除记录中查找并恢复查询记录
let cacheSearchList = await this.servCache.get(tables.del, this.ltuid, true)
// 这里不直接插入,只插入当前查询记录中没有的值 // 这里不直接插入,只插入当前查询记录中没有的值
if (cacheSearchList && cacheSearchList.length > 0) { if (cacheSearchList && cacheSearchList.length > 0) {
for (let searchedUid of cacheSearchList) { for (let searchedUid of cacheSearchList) {
// 检查对应uid是否有新的查询记录 // 检查对应uid是否有新的查询记录
if (!await this.getQueryLtuid(searchedUid)) { if (!await this.getQueryLtuid(searchedUid, game)) {
await this.addQueryUid(searchedUid) await this.addQueryUid(searchedUid, game)
} }
} }
} }
})
return true return true
} }
async disable () { async disable (game = 'gs') {
await this.servCache.zDel(tables.detail, this.ltuid) let cache = this.getCache(game)
logger.mark(`[标记无效ck][ltuid:${this.ltuid}]`) await cache.zDel(tables.detail, this.ltuid)
logger.mark(`[标记无效ck][game:${game}, ltuid:${this.ltuid}`)
} }
// //
@ -539,28 +487,38 @@ export default class MysUser extends BaseModel {
} }
// 为当前用户添加uid查询记录 // 为当前用户添加uid查询记录
async addQueryUid (uid) { async addQueryUid (uid, game = 'gs') {
if (lodash.isArray(uid)) {
for (let u of uid) {
await this.addQueryUid(u, game)
}
return
}
if (uid) { if (uid) {
await this.servCache.zAdd(tables.detail, this.ltuid, uid) let cache = this.getCache(game)
await cache.zAdd(tables.detail, this.ltuid, uid)
} }
} }
// 获取当前用户已查询uid列表 // 获取当前用户已查询uid列表
async getQueryUids () { async getQueryUids (game = 'gs') {
return await this.servCache.zList(tables.detail, this.ltuid) let cache = this.getCache('game')
return await cache.zList(tables.detail, this.ltuid)
} }
// 根据uid获取查询ltuid // 根据uid获取查询ltuid
async getQueryLtuid (uid) { async getQueryLtuid (uid, game = 'gs') {
return await this.servCache.zKey(tables.detail, uid) let cache = this.getCache('game')
return await cache.zKey(tables.detail, uid)
} }
// 检查指定uid是否为当前MysUser所有 // 检查指定uid是否为当前MysUser所有
async ownUid (uid) { ownUid (uid, game = 'gs') {
if (!uid) { if (!uid) {
return false return false
} }
let uidArr = await this.cache.zList(tables.uid, this.ltuid) || [] let gameKey = this.gameKey(game)
return uid && uidArr.join(',').split(',').includes(uid + '') let uids = this[`${gameKey}Uids`]
return uids.includes(uid + '')
} }
} }

View File

@ -0,0 +1,47 @@
import { Data } from '#miao'
const MysUtil = {
// 获取标准ltuid
getLtuid (data) {
if (!data) {
return false
}
if (/^\d{4,9}$/.test(data)) {
return data
}
let testRet = /ltuid=(\d{4,9})/g.exec(data.ck || data)
if (testRet && testRet[1]) {
return testRet[1]
}
return false
},
// 获取标准gameKey
getGameKey (game) {
// 兼容e的处理
if (game.user_id) {
return game.isSr ? 'sr' : 'gs'
}
return ['sr', 'star'].includes(game) ? 'sr' : 'gs'
},
// 生成设备guid
getDeviceGuid () {
function S4 () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
},
// 循环game
async eachGame (fn) {
await Data.forEach(['gs', 'sr'], fn)
},
// 循环server
async eachServ (fn) {
await Data.forEach(['mys', 'hoyolab'], fn)
}
}
export default MysUtil

View File

@ -10,9 +10,10 @@ import lodash from 'lodash'
import MysUser from './MysUser.js' import MysUser from './MysUser.js'
import gsCfg from '../gsCfg.js' import gsCfg from '../gsCfg.js'
import { UserDB } from '../db/index.js' import { UserDB } from '../db/index.js'
import { Data } from '#miao'
export default class NoteUser extends BaseModel { export default class NoteUser extends BaseModel {
constructor (qq, data = null) { constructor (qq) {
super() super()
// 检查实例缓存 // 检查实例缓存
let cacheObj = this._getThis('user', qq) let cacheObj = this._getThis('user', qq)
@ -65,19 +66,20 @@ export default class NoteUser extends BaseModel {
* @returns { {ltuid:{ckData, ck, uids}} } * @returns { {ltuid:{ckData, ck, uids}} }
*/ */
get cks () { get cks () {
console.log('NoteUser.cks 即将废弃')
let game = 'gs'
let cks = {} let cks = {}
if (!this.hasCk) { if (!this.hasCk) {
return cks return cks
} }
for (let uid in this.ckData) { for (let ltuid in this.mysUsers) {
let ck = this.ckData[uid] let mys = this.mysUsers[ltuid]
if (ck && ck.ltuid && ck.uid) { if (mys && mys.ltuid && mys.uid) {
cks[ck.ltuid] = cks[ck.ltuid] || { cks[ltuid] = cks[ltuid] || {
ckData: ck, ckData: mys.getCkInfo(game),
ck: ck.ck, ck: mys.ck,
uids: [] uids: mys.getUids(game)
} }
cks[ck.ltuid].uids.push(ck.uid)
} }
} }
return cks return cks
@ -90,7 +92,7 @@ export default class NoteUser extends BaseModel {
* @param data 用户对应MysCookie数据为空则自动读取 * @param data 用户对应MysCookie数据为空则自动读取
* @returns {Promise<NoteUser|*>} * @returns {Promise<NoteUser|*>}
*/ */
static async create (qq, data = null) { static async create (qq, db) {
// 兼容处理传入e // 兼容处理传入e
if (qq && qq.user_id) { if (qq && qq.user_id) {
let e = qq let e = qq
@ -99,8 +101,8 @@ export default class NoteUser extends BaseModel {
return user return user
} }
let user = new NoteUser(qq, data) let user = new NoteUser(qq)
await user.initDB() await user.initDB(db)
// 检查绑定uid (regUid) // 检查绑定uid (regUid)
await user.getRegUid() await user.getRegUid()
@ -109,29 +111,21 @@ export default class NoteUser extends BaseModel {
} }
static async forEach (fn) { static async forEach (fn) {
// 初始化用户缓存 let dbs = await UserDB.findAll()
let res = await gsCfg.getBingCk() await Data.forEach(users, async (db) => {
for (let qq in res.noteCk) { let user = await NoteUser.create(db.id, db)
let cks = res.noteCk[qq] return await fn(user)
if (!lodash.isEmpty(cks)) { })
let user = await NoteUser.create(qq, cks)
if (user && fn) {
if (await fn(user) === false) {
break
}
}
}
}
} }
// 初始化数据 // 初始化数据
async initDB (force = false) { async initDB (db = false) {
if (this.db && !force) { if (this.db && !db) {
return return
} }
// 为后续多类型用户兼容 // 为后续多类型用户兼容
this.db = await UserDB.find(this.qq, 'qq') this.db = db && db !== true ? db : await UserDB.find(this.qq, 'qq')
await this.initMysUser(force) await this.initMysUser()
this.initUids() this.initUids()
} }
@ -184,21 +178,8 @@ export default class NoteUser extends BaseModel {
}) })
} }
async saveDB () { async save () {
let db = this.db await this.db.saveDB(this)
let ltuids = []
lodash.forEach(this.mysUsers, (mys) => {
if (mys.ck) {
ltuids.push(mys.ltuid)
}
})
db.ltuids = ltuids.join(',')
lodash.forEach(['gs', 'sr'], (key) => {
db[`${key}Uid`] = this[`${key}Uid`] ? this[`${key}Uid`] : this.uids[key]?.[0] || ''
db[`${key}RegUids`] = JSON.stringify(this.uidMap[key])
console.log(this.uidMap[key])
})
await db.save()
} }
// 获取当前UID // 获取当前UID
@ -206,6 +187,16 @@ export default class NoteUser extends BaseModel {
return this.isGs(game) ? this.gsUid : this.srUid return this.isGs(game) ? this.gsUid : this.srUid
} }
getSelfUid (game = 'gs') {
let gameKey = this.gameKey(game)
let uids = this[`${gameKey}UidMap`].filter((v) => v.type === 'ck')
if (uids.length === 0) {
return false
}
let find = lodash.find(uids, (v) => v.uid + '' === uid + '', 0)
return find ? find.uid : uids[0].uid
}
// 获取UID列表 // 获取UID列表
getUidList (game = 'gs') { getUidList (game = 'gs') {
let ret = [] let ret = []
@ -262,16 +253,22 @@ export default class NoteUser extends BaseModel {
* @returns {Promise<*>} * @returns {Promise<*>}
*/ */
async getRegUid (game = 'gs') { async getRegUid (game = 'gs') {
console.log('getRegUid 废弃') let gameKey = this.gameKey(game)
return this[`${gameKey}Uid`] || ''
} }
/** /**
* 设置当前用户的绑定uid * 设置当前用户的绑定uid
* @param uid 要绑定的uid * @param uid 要绑定的uid
* @param game
* @param force 若已存在绑定uid关系是否强制更新 * @param force 若已存在绑定uid关系是否强制更新
*/ */
async setRegUid (uid = '', force = false) { async setRegUid (uid = '', game = 'gs', force = false) {
console.log('setRegUid 废弃') if (this.getRegUid(game) && false) {
return uid
}
await this.addRegUid(uid, game)
return uid
} }
// 切换绑定CK生效的UID // 切换绑定CK生效的UID
@ -343,15 +340,4 @@ export default class NoteUser extends BaseModel {
} }
return ret return ret
} }
// 内部方法读取CK数据
_getCkData () {
this.ckData = gsCfg.getBingCkSingle(this.qq)
return this.ckData
}
// 内部方法写入CK数据
_saveCkData () {
gsCfg.saveBingCk(this.qq, this.ckData)
}
} }

View File

@ -10,21 +10,21 @@ export default class apiTool {
* @param {区服} server * @param {区服} server
* @param {是否为星穹铁道或其他游戏? type(bool or string)} isSr * @param {是否为星穹铁道或其他游戏? type(bool or string)} isSr
*/ */
constructor(uid, server, isSr = false) { constructor (uid, server, isSr = false) {
this.uid = uid this.uid = uid
this.isSr = isSr this.isSr = isSr
this.server = server this.server = server
this.game='genshin' this.game = 'genshin'
if(isSr) this.game='honkaisr' if (isSr) this.game = 'honkaisr'
if(typeof isSr !== 'boolean'){ if (typeof isSr !== 'boolean') {
this.game=isSr this.game = isSr
} }
} }
getUrlMap = (data = {}) => { getUrlMap = (data = {}) => {
let host, hostRecord let host, hostRecord
if (['cn_gf01', 'cn_qd01', 'prod_gf_cn','prod_qd_cn'].includes(this.server)) { if (['cn_gf01', 'cn_qd01', 'prod_gf_cn', 'prod_qd_cn'].includes(this.server)) {
host = 'https://api-takumi.mihoyo.com/' host = 'https://api-takumi.mihoyo.com/'
hostRecord = 'https://api-takumi-record.mihoyo.com/' hostRecord = 'https://api-takumi-record.mihoyo.com/'
} else if (['os_usa', 'os_euro', 'os_asia', 'os_cht'].includes(this.server)) { } else if (['os_usa', 'os_euro', 'os_asia', 'os_cht'].includes(this.server)) {
@ -99,16 +99,16 @@ export default class apiTool {
url: `${hostRecord}game_record/app/hkrpg/api/index`, url: `${hostRecord}game_record/app/hkrpg/api/index`,
query: `role_id=${this.uid}&server=${this.server}` query: `role_id=${this.uid}&server=${this.server}`
}, },
UserGame:{ UserGame: {
url:`${host}common/badge/v1/login/account`, url: `${host}common/badge/v1/login/account`,
body: { uid: this.uid, region: this.server,lang:'zh-cn',game_biz:'hkrpg_cn' } body: { uid: this.uid, region: this.server, lang: 'zh-cn', game_biz: 'hkrpg_cn' }
}, },
/** /**
* 开拓阅历接口 * 开拓阅历接口
*/ */
ys_ledger:{ ys_ledger: {
url:`${host}/event/srledger/month_info`, url: `${host}/event/srledger/month_info`,
query:`region=${this.server}&uid=${this.uid}&month=${data.month}` query: `region=${this.server}&uid=${this.uid}&month=${data.month}`
}, },
/** 角色详情 */ /** 角色详情 */
character: { character: {
@ -119,7 +119,7 @@ export default class apiTool {
dailyNote: { dailyNote: {
url: `${hostRecord}game_record/app/hkrpg/api/note`, url: `${hostRecord}game_record/app/hkrpg/api/note`,
query: `role_id=${this.uid}&server=${this.server}` query: `role_id=${this.uid}&server=${this.server}`
}, }
} }
} }

View File

@ -25,7 +25,7 @@ export default class MysInfo {
} }
// ck对应MysUser对象 // ck对应MysUser对象
this.ckUser = null this.ckUser = null
this.auth = ['dailyNote', 'bbs_sign_info', 'bbs_sign_home', 'bbs_sign', 'ys_ledger', 'compute', 'avatarSkill', 'detail', 'blueprint'] this.auth = ['dailyNote', 'bbs_sign_info', 'bbs_sign_home', 'bbs_sign', 'ys_ledger', 'compute', 'avatarSkill', 'detail', 'blueprint', 'UserGame']
} }
static async init (e, api) { static async init (e, api) {
@ -62,7 +62,7 @@ export default class MysInfo {
mysInfo.e.uid = mysInfo.uid mysInfo.e.uid = mysInfo.uid
/** 获取ck */ /** 获取ck */
await mysInfo.getCookie(onlySelfCk) await mysInfo.getCookie(e, onlySelfCk)
/** 判断回复 */ /** 判断回复 */
await mysInfo.checkReply() await mysInfo.checkReply()
@ -75,7 +75,7 @@ export default class MysInfo {
let user = await NoteUser.create(e) let user = await NoteUser.create(e)
if (user) { if (user) {
// 强制读取一次ck防止一些问题 // 强制读取一次ck防止一些问题
user._getCkData() user.initDB(true)
return user return user
} }
return false return false
@ -91,7 +91,7 @@ export default class MysInfo {
let user = await NoteUser.create(e) let user = await NoteUser.create(e)
if (e.uid && matchMsgUid) { if (e.uid && matchMsgUid) {
/** 没有绑定的自动绑定 */ /** 没有绑定的自动绑定 */
return await user.setRegUid(e.uid, false) return await user.setRegUid(e.uid, e, false)
} }
let { msg = '', at = '' } = e let { msg = '', at = '' } = e
@ -143,24 +143,7 @@ export default class MysInfo {
return false return false
} }
return selfUser.uid return selfUser.getUid(e)
}
/** 判断绑定ck才能查询 */
checkAuth (api) {
if (api === 'cookie') {
return true
}
if (lodash.isObject(api)) {
for (let i in api) {
if (this.auth.includes(i)) {
return true
}
}
} else if (this.auth.includes(api)) {
return true
}
return false
} }
/** /**
@ -187,7 +170,7 @@ export default class MysInfo {
if (!mysInfo.uid || !mysInfo.ckInfo.ck) return false if (!mysInfo.uid || !mysInfo.ckInfo.ck) return false
e.uid = mysInfo.uid e.uid = mysInfo.uid
let mysApi = new MysApi(mysInfo.uid, mysInfo.ckInfo.ck, option,e.isSr) let mysApi = new MysApi(mysInfo.uid, mysInfo.ckInfo.ck, option, e.isSr)
let res let res
if (lodash.isObject(api)) { if (lodash.isObject(api)) {
@ -220,50 +203,11 @@ export default class MysInfo {
return res return res
} }
async checkReply () {
if (this.e.noTips === true) return
if (!this.uid) {
this.e.reply('请先#绑定uid')
}
if (!this.ckInfo.ck) {
this.e.reply('暂无可用CK请绑定更多用户或设置公共ck..')
}
this.e.noTips = true
}
/* 获取请求所需ck */
/**
* 获取请求所需CK
* @param onlySelfCk 是否只获取uid自己对应的ck为true则只获取uid对应ck若无则返回为空
* @returns {Promise<string|string|*>} 查询ck获取失败则返回空
*/
async getCookie(onlySelfCk = false) {
if (this.ckInfo.ck) return this.ckInfo.ck
let mysUser = await MysUser.getByQueryUid(this.uid, onlySelfCk)
if (mysUser) {
if (mysUser.ckData?.ck) {
this.ckInfo = mysUser.ckData
this.ckUser = mysUser
// 暂时直接记录请求uid后期优化分析MysApi请求结果分状态记录结果
await mysUser.addQueryUid(this.uid)
} else {
// 重新分配
await mysUser.disable()
return onlySelfCk ? '' : await this.getCookie()
}
}
return this.ckInfo.ck
}
/** /**
* 初始化公共CK * 初始化公共CK
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
static async initPubCk() { static async initPubCk () {
// 初始化公共CK // 初始化公共CK
let pubCount = 0 let pubCount = 0
let pubCks = GsCfg.getConfig('mys', 'pubCk') || [] let pubCks = GsCfg.getConfig('mys', 'pubCk') || []
@ -287,11 +231,14 @@ export default class MysInfo {
* 默认会将用户CK加入查询池 * 默认会将用户CK加入查询池
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
static async initUserCk() { static async initUserCk () {
// 初始化用户缓存 // 初始化用户缓存
let userCount = 0 let userCount = 0
await NoteUser.forEach(async function (user) { await MysUser.forEach(async (mys) => {
// userCount += await user.initCache(true) let ret = await mys.initCache()
if (ret) {
userCount++
}
}) })
logger.mark(`加载用户UID${userCount}个,加入查询池`) logger.mark(`加载用户UID${userCount}个,加入查询池`)
} }
@ -302,7 +249,7 @@ export default class MysInfo {
* @param clearData 强制初始化时是否清除已有数据 (刷新/重置) * @param clearData 强制初始化时是否清除已有数据 (刷新/重置)
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
static async initCache(force = false, clearData = false) { static async initCache (force = false, clearData = false) {
// 检查缓存标记 // 检查缓存标记
let cache = DailyCache.create() let cache = DailyCache.create()
if (!force && await cache.get('cache-ready')) { if (!force && await cache.get('cache-ready')) {
@ -325,7 +272,82 @@ export default class MysInfo {
return true return true
} }
async checkCode(res, type) { static async getBingCkUid () {
let res = await GsCfg.getBingCk()
return { ...res.ck }
}
// 获取uid绑定的ck信息
static async checkUidBing (uid, game = 'gs') {
let ckUser = await MysUser.getByQueryUid(uid, game, true)
if (ckUser && ckUser.ck) {
return ckUser
}
return false
}
static async delDisable () {
return await MysUser.delDisable()
}
/** 判断绑定ck才能查询 */
checkAuth (api) {
if (api === 'cookie') {
return true
}
if (lodash.isObject(api)) {
for (let i in api) {
if (this.auth.includes(i)) {
return true
}
}
} else if (this.auth.includes(api)) {
return true
}
return false
}
async checkReply () {
if (this.e.noTips === true) return
if (!this.uid) {
this.e.reply('请先#绑定uid')
}
if (!this.ckInfo.ck) {
this.e.reply('暂无可用CK请绑定更多用户或设置公共ck..')
}
this.e.noTips = true
}
/* 获取请求所需ck */
/**
* 获取请求所需CK
* @param game 游戏
* @param onlySelfCk 是否只获取uid自己对应的ck为true则只获取uid对应ck若无则返回为空
* @returns {Promise<string|string|*>} 查询ck获取失败则返回空
*/
async getCookie (game = 'gs', onlySelfCk = false) {
if (this.ckUser?.ck) return this.ckUser?.ck
let mysUser = await MysUser.getByQueryUid(this.uid, game, onlySelfCk)
if (mysUser) {
if (mysUser.ck) {
this.ckInfo = mysUser.getCkInfo()
this.ckUser = mysUser
// 暂时直接记录请求uid后期优化分析MysApi请求结果分状态记录结果
await mysUser.addQueryUid(this.uid, game)
} else {
// 重新分配
await mysUser.disable(game)
return onlySelfCk ? '' : await this.getCookie()
}
}
return this.ckUser?.ck
}
async checkCode (res, type) {
if (!res) { if (!res) {
this.e.reply('米游社接口请求失败,暂时无法查询') this.e.reply('米游社接口请求失败,暂时无法查询')
return false return false
@ -394,7 +416,7 @@ export default class MysInfo {
} }
/** 删除失效ck */ /** 删除失效ck */
async delCk() { async delCk () {
if (!this.ckUser) { if (!this.ckUser) {
return false return false
} }
@ -404,26 +426,8 @@ export default class MysInfo {
} }
/** 查询次数满,今日内标记失效 */ /** 查询次数满,今日内标记失效 */
async disableToday() { async disableToday (game = 'gs') {
/** 统计次数设为超限 */ /** 统计次数设为超限 */
await this.ckUser.disable() await this.ckUser.disable(game)
}
static async getBingCkUid() {
let res = await GsCfg.getBingCk()
return { ...res.ck }
}
// 获取uid绑定的ck信息
static async checkUidBing(uid) {
let ckUser = await MysUser.getByQueryUid(uid, true)
if (ckUser && ckUser.ckData) {
return ckUser.ckData
}
return false
}
static async delDisable() {
return await MysUser.delDisable()
} }
} }

View File

@ -1,182 +1,187 @@
import moment from "moment"; import moment from 'moment'
import lodash from "lodash"; import lodash from 'lodash'
import base from "./base.js"; import base from './base.js'
import MysInfo from "./mys/mysInfo.js"; import MysInfo from './mys/mysInfo.js'
export default class Note extends base { export default class Note extends base {
constructor(e) { constructor (e) {
super(e); super(e)
this.model = "dailyNote"; this.model = 'dailyNote'
} }
/** 生成体力图片 */ /** 生成体力图片 */
static async get(e) { static async get (e) {
let note = new Note(e); let note = new Note(e)
return await note.getData(); return await note.getData()
} }
async getData() { async getData () {
let res = await MysInfo.get(this.e, "dailyNote"); let res = await MysInfo.get(this.e, 'dailyNote')
let resUser; let resUser
if (!res || res.retcode !== 0) return false; if (!res || res.retcode !== 0) return false
console.log(this.e.isSr, res)
/** 截图数据 */ /** 截图数据 */
let data = this.e.isSr ? this.noteSr(res) : this.noteData(res); let data = this.e.isSr ? this.noteSr(res) : this.noteData(res)
let screenData = this.screenData; console.log(data)
let screenData = this.screenData
if (this.e.isSr) { if (this.e.isSr) {
screenData.tplFile = "./plugins/genshin/resources/StarRail/html/dailyNote/dailyNote.html"; screenData.tplFile = './plugins/genshin/resources/StarRail/html/dailyNote/dailyNote.html'
resUser = await MysInfo.get(this.e,'UserGame') resUser = await MysInfo.get(this.e, 'UserGame')
if (!resUser || resUser.retcode !== 0) return false; console.log('resUser', resUser)
if (!resUser || resUser.retcode !== 0) return false
} }
return { return {
name: this.e.sender.card, name: this.e.sender.card,
quality: 80, quality: 80,
...screenData, ...screenData,
...data,...resUser?.data ...data, ...resUser?.data
};
} }
noteSr(res) { }
let { data } = res;
let nowDay = moment().date(); noteSr (res) {
let nowUnix = Number(moment().format("X")); let { data } = res
let nowDay = moment().date()
let nowUnix = Number(moment().format('X'))
/** 树脂 */ /** 树脂 */
let resinMaxTime; let resinMaxTime
if (data.stamina_recover_time > 0) { if (data.stamina_recover_time > 0) {
let d = moment.duration(data.stamina_recover_time, 'seconds'); let d = moment.duration(data.stamina_recover_time, 'seconds')
let day= Math.floor(d.asDays()); let day = Math.floor(d.asDays())
let hours =d.hours() let hours = d.hours()
let minutes =d.minutes() let minutes = d.minutes()
let seconds =d.seconds() let seconds = d.seconds()
resinMaxTime = hours+'小时'+minutes+'分钟'+seconds+'秒' resinMaxTime = hours + '小时' + minutes + '分钟' + seconds + '秒'
//精确到秒。。。。 //精确到秒。。。。
if(day>0){ if (day > 0) {
resinMaxTime =day+'天'+hours+'小时'+minutes+'分钟'+seconds+'秒' resinMaxTime = day + '天' + hours + '小时' + minutes + '分钟' + seconds + '秒'
}else if(hours>0){ } else if (hours > 0) {
resinMaxTime = hours+'小时'+minutes+'分钟'+seconds+'秒' resinMaxTime = hours + '小时' + minutes + '分钟' + seconds + '秒'
}else if(minutes>0){ } else if (minutes > 0) {
resinMaxTime = minutes+'分钟'+seconds+'秒' resinMaxTime = minutes + '分钟' + seconds + '秒'
}else if(seconds>0){ } else if (seconds > 0) {
resinMaxTime = seconds+'秒' resinMaxTime = seconds + '秒'
} }
} }
data.bfStamina = data.current_stamina / data.max_stamina * 100 +'%'; data.bfStamina = data.current_stamina / data.max_stamina * 100 + '%'
/** 派遣 */ /** 派遣 */
for(let item of data.expeditions){ for (let item of data.expeditions) {
let d = moment.duration(item.remaining_time, 'seconds'); let d = moment.duration(item.remaining_time, 'seconds')
let day= Math.floor(d.asDays()); let day = Math.floor(d.asDays())
let hours =d.hours() let hours = d.hours()
let minutes =d.minutes() let minutes = d.minutes()
item.dateTime=([day+'天',hours+'时',minutes+'分'].filter(v => !['0天','0时','0分'].includes(v))).join('') item.dateTime = ([day + '天', hours + '时', minutes + '分'].filter(v => !['0天', '0时', '0分'].includes(v))).join('')
item.bfTime=(72000-item.remaining_time)/72000 *100 +'%' item.bfTime = (72000 - item.remaining_time) / 72000 * 100 + '%'
if(item.avatars.length==1){ if (item.avatars.length == 1) {
item.avatars.push('派遣头像') item.avatars.push('派遣头像')
} }
} }
// 标识属性图标~ // 标识属性图标~
let icon = lodash.sample(['希儿','白露','艾丝妲','布洛妮娅','姬子','卡芙卡','克拉拉','停云','佩拉','黑塔','希露瓦','银狼']) let icon = lodash.sample(['希儿', '白露', '艾丝妲', '布洛妮娅', '姬子', '卡芙卡', '克拉拉', '停云', '佩拉', '黑塔', '希露瓦', '银狼'])
let week = [ let week = [
"星期日", '星期日',
"星期一", '星期一',
"星期二", '星期二',
"星期三", '星期三',
"星期四", '星期四',
"星期五", '星期五',
"星期六", '星期六'
]; ]
let day = `${week[moment().day()]}`; let day = `${week[moment().day()]}`
return { return {
uid: this.e.uid, uid: this.e.uid,
saveId: this.e.uid,icon,day, saveId: this.e.uid, icon, day,
resinMaxTime,nowDay:moment(new Date()).format('YYYY年MM月DD日'), resinMaxTime, nowDay: moment(new Date()).format('YYYY年MM月DD日'),
...data, ...data
}; }
} }
noteData(res) {
let { data } = res;
let nowDay = moment().date(); noteData (res) {
let nowUnix = Number(moment().format("X")); let { data } = res
let nowDay = moment().date()
let nowUnix = Number(moment().format('X'))
/** 树脂 */ /** 树脂 */
let resinMaxTime; let resinMaxTime
if (data.resin_recovery_time > 0) { if (data.resin_recovery_time > 0) {
resinMaxTime = nowUnix + Number(data.resin_recovery_time); resinMaxTime = nowUnix + Number(data.resin_recovery_time)
let maxDate = moment.unix(resinMaxTime); let maxDate = moment.unix(resinMaxTime)
resinMaxTime = maxDate.format("HH:mm"); resinMaxTime = maxDate.format('HH:mm')
if (maxDate.date() != nowDay) { if (maxDate.date() != nowDay) {
resinMaxTime = `明天 ${resinMaxTime}`; resinMaxTime = `明天 ${resinMaxTime}`
} else { } else {
resinMaxTime = ` ${resinMaxTime}`; resinMaxTime = ` ${resinMaxTime}`
} }
} }
/** 派遣 */ /** 派遣 */
let remainedTime = ""; let remainedTime = ''
if (data.expeditions && data.expeditions.length >= 1) { if (data.expeditions && data.expeditions.length >= 1) {
remainedTime = lodash.map(data.expeditions, "remained_time"); remainedTime = lodash.map(data.expeditions, 'remained_time')
remainedTime = lodash.min(remainedTime); remainedTime = lodash.min(remainedTime)
if (remainedTime > 0) { if (remainedTime > 0) {
remainedTime = nowUnix + Number(remainedTime); remainedTime = nowUnix + Number(remainedTime)
let remainedDate = moment.unix(remainedTime); let remainedDate = moment.unix(remainedTime)
remainedTime = remainedDate.format("HH:mm"); remainedTime = remainedDate.format('HH:mm')
if (remainedDate.date() != nowDay) { if (remainedDate.date() != nowDay) {
remainedTime = `明天 ${remainedTime}`; remainedTime = `明天 ${remainedTime}`
} else { } else {
remainedTime = ` ${remainedTime}`; remainedTime = ` ${remainedTime}`
} }
} }
} }
/** 宝钱 */ /** 宝钱 */
let coinTime = ""; let coinTime = ''
if (data.home_coin_recovery_time > 0) { if (data.home_coin_recovery_time > 0) {
let coinDay = Math.floor(data.home_coin_recovery_time / 3600 / 24); let coinDay = Math.floor(data.home_coin_recovery_time / 3600 / 24)
let coinHour = Math.floor((data.home_coin_recovery_time / 3600) % 24); let coinHour = Math.floor((data.home_coin_recovery_time / 3600) % 24)
let coinMin = Math.floor((data.home_coin_recovery_time / 60) % 60); let coinMin = Math.floor((data.home_coin_recovery_time / 60) % 60)
if (coinDay > 0) { if (coinDay > 0) {
coinTime = `${coinDay}${coinHour}小时${coinMin}分钟`; coinTime = `${coinDay}${coinHour}小时${coinMin}分钟`
} else { } else {
let coinDate = moment.unix( let coinDate = moment.unix(
nowUnix + Number(data.home_coin_recovery_time) nowUnix + Number(data.home_coin_recovery_time)
); )
if (coinDate.date() != nowDay) { if (coinDate.date() != nowDay) {
coinTime = `明天 ${coinDate.format("HH:mm")}`; coinTime = `明天 ${coinDate.format('HH:mm')}`
} else { } else {
coinTime = coinDate.format("HH:mm"); coinTime = coinDate.format('HH:mm')
} }
} }
} }
let week = [ let week = [
"星期日", '星期日',
"星期一", '星期一',
"星期二", '星期二',
"星期三", '星期三',
"星期四", '星期四',
"星期五", '星期五',
"星期六", '星期六'
]; ]
let day = `${moment().format("MM-DD HH:mm")} ${week[moment().day()]}`; let day = `${moment().format('MM-DD HH:mm')} ${week[moment().day()]}`
/** 参量质变仪 */ /** 参量质变仪 */
if (data?.transformer?.obtained) { if (data?.transformer?.obtained) {
data.transformer.reached = data.transformer.recovery_time.reached; data.transformer.reached = data.transformer.recovery_time.reached
let recoveryTime = ""; let recoveryTime = ''
if (data.transformer.recovery_time.Day > 0) { if (data.transformer.recovery_time.Day > 0) {
recoveryTime += `${data.transformer.recovery_time.Day}`; recoveryTime += `${data.transformer.recovery_time.Day}`
} }
if (data.transformer.recovery_time.Hour > 0) { if (data.transformer.recovery_time.Hour > 0) {
recoveryTime += `${data.transformer.recovery_time.Hour}小时`; recoveryTime += `${data.transformer.recovery_time.Hour}小时`
} }
if (data.transformer.recovery_time.Minute > 0) { if (data.transformer.recovery_time.Minute > 0) {
recoveryTime += `${data.transformer.recovery_time.Minute}分钟`; recoveryTime += `${data.transformer.recovery_time.Minute}分钟`
} }
data.transformer.recovery_time = recoveryTime; data.transformer.recovery_time = recoveryTime
} }
return { return {
@ -186,7 +191,7 @@ export default class Note extends base {
remainedTime, remainedTime,
coinTime, coinTime,
day, day,
...data, ...data
}; }
} }
} }

View File

@ -28,7 +28,7 @@ export default class RoleList extends base {
if (avatars.length <= 0) return false if (avatars.length <= 0) return false
/** 判断是否绑定了ck */ /** 判断是否绑定了ck */
this.ck = await MysInfo.checkUidBing(uid) this.ck = await MysInfo.checkUidBing(uid, this.e)
let skill = [] let skill = []
if (this.ck) { if (this.ck) {

View File

@ -145,7 +145,7 @@ export default class Today extends base {
} }
/** 判断是否绑定了ck */ /** 判断是否绑定了ck */
this.ck = await MysInfo.checkUidBing(this.e.uid) this.ck = await MysInfo.checkUidBing(this.e.uid, this.e)
let skill = {} let skill = {}
if (this.ck) { if (this.ck) {

View File

@ -68,6 +68,9 @@ export default class User extends base {
flagV2 = true flagV2 = true
data.ck = `account_mid_v2=${param.account_mid_v2};cookie_token_v2=${param.cookie_token_v2};ltoken_v2=${param.ltoken_v2};ltmid_v2=${param.ltmid_v2};` data.ck = `account_mid_v2=${param.account_mid_v2};cookie_token_v2=${param.cookie_token_v2};ltoken_v2=${param.ltoken_v2};ltmid_v2=${param.ltmid_v2};`
} }
if (param.mi18nLang) {
data.ck += ` mi18nLang=${param.mi18nLang};`
}
/** 拼接ck */ /** 拼接ck */
data.ltuid = param.ltuid || param.ltmid_v2 data.ltuid = param.ltuid || param.ltmid_v2
@ -77,10 +80,11 @@ export default class User extends base {
mys.setCkData(data) mys.setCkData(data)
/** 检查ck是否失效 */ /** 检查ck是否失效 */
if (!await this.checkCk(mys, param)) { let uidRet = await mys.reqMysUid()
console.log('uidRet', uidRet)
if (uidRet.status !== 0) {
logger.mark(`绑定cookie错误1${this.checkMsg || 'cookie错误'}`) logger.mark(`绑定cookie错误1${this.checkMsg || 'cookie错误'}`)
await this.e.reply(`绑定cookie失败${this.checkMsg || 'cookie错误'}`) return await this.e.reply(`绑定cookie失败${this.checkMsg || 'cookie错误'}`)
return
} }
if (flagV2) { if (flagV2) {
@ -94,15 +98,14 @@ export default class User extends base {
*/ */
} else { } else {
logger.mark(`绑定cookie错误2${userFullInfo.message || 'cookie错误'}`) logger.mark(`绑定cookie错误2${userFullInfo.message || 'cookie错误'}`)
await this.e.reply(`绑定cookie失败${userFullInfo.message || 'cookie错误'}`) return await this.e.reply(`绑定cookie失败${userFullInfo.message || 'cookie错误'}`)
return
} }
} }
logger.mark(`${this.e.logFnc} 检查cookie正常 [ltuid:${mys.ltuid}]`) logger.mark(`${this.e.logFnc} 检查cookie正常 [ltuid:${mys.ltuid}]`)
await user.addMysUser(mys) await user.addMysUser(mys)
await user.saveDB() await user.save()
logger.mark(`${this.e.logFnc} 保存cookie成功 [ltuid:${mys.ltuid}]`) logger.mark(`${this.e.logFnc} 保存cookie成功 [ltuid:${mys.ltuid}]`)
@ -152,9 +155,7 @@ export default class User extends base {
} }
if (!res) return false if (!res) return false
let playerList = res?.data?.list || [] let playerList = res?.data?.list || []
if (!playerList || playerList.length <= 0) { if (!playerList || playerList.length <= 0) {
this.checkMsg = '该账号尚未绑定原神或星穹角色!' this.checkMsg = '该账号尚未绑定原神或星穹角色!'
return false return false
@ -162,57 +163,14 @@ export default class User extends base {
playerList = playerList.filter(v => ['hk4e_cn', 'hkrpg_cn', 'hk4e_global', 'hkrpg_global'].includes(v.game_biz)) playerList = playerList.filter(v => ['hk4e_cn', 'hkrpg_cn', 'hk4e_global', 'hkrpg_global'].includes(v.game_biz))
} }
//避免同时多个默认展示角色时候只绑定一个
/** 米游社默认展示的角色 */ /** 米游社默认展示的角色 */
for (let val of playerList) { for (let val of playerList) {
mys.addUid(val.game_uid, ['hk4e_cn', 'hk4e_global'].includes(val.game_biz) ? 'gs' : 'sr') mys.addUid(val.game_uid, ['hk4e_cn', 'hk4e_global'].includes(val.game_biz) ? 'gs' : 'sr')
} }
await mys.save()
console.log('MYS', mys)
await mys.saveDB()
return mys return mys
} }
// 获取米游社通行证id
async getUserInfo (server = 'mys') {
return await MysUser.getUserFullInfo(this.ck, server)
}
/** 保存ck */
getCk () {
let ck = gsCfg.getBingCkSingle(this.e.user_id)
lodash.map(ck, o => {
o.isMain = false
return o
})
ck[this.uid] = {
uid: this.uid,
qq: this.e.user_id,
ck: this.ck,
ltuid: this.ltuid,
login_ticket: this.login_ticket,
region_name: this.region_name,
isMain: true
}
this.allUid.forEach((v) => {
if (!v.uid) return
ck[v.uid] = {
uid: v.uid,
qq: this.e.user_id,
ck: this.ck,
ltuid: this.ltuid,
region_name: v.region_name,
isMain: false
}
})
return ck
}
/** 删除绑定ck */ /** 删除绑定ck */
async delCk (uid = '') { async delCk (uid = '') {
let user = await this.user() let user = await this.user()
@ -227,7 +185,7 @@ export default class User extends base {
uid = uid[0] uid = uid[0]
let user = await this.user() let user = await this.user()
user.addRegUid(uid, this.e) user.addRegUid(uid, this.e)
await user.saveDB() await user.save()
return await this.showUid() return await this.showUid()
} }
@ -263,7 +221,7 @@ export default class User extends base {
} }
index = Number(index) - 1 index = Number(index) - 1
await user.setMainUid(index, game) await user.setMainUid(index, game)
await user.saveDB() await user.save()
return await this.showUid() return await this.showUid()
} }
@ -379,11 +337,11 @@ export default class User extends base {
data.gsUids = lodash.keys(data.genshin) data.gsUids = lodash.keys(data.genshin)
data.srUids = lodash.keys(data.star) data.srUids = lodash.keys(data.star)
mys.setCkData(data) mys.setCkData(data)
await mys.saveDB() await mys.save()
user.addMysUser(mys) user.addMysUser(mys)
} }
} }
await user.saveDB() await user.save()
if (fs.existsSync(`./data/MysCookie/${qq}.yaml`)) { if (fs.existsSync(`./data/MysCookie/${qq}.yaml`)) {
/* fs.rename(`./data/MysCookie/${qq}.yaml`, `./data/MysCookieBak/${qq}.yaml`, (err) => { /* fs.rename(`./data/MysCookie/${qq}.yaml`, `./data/MysCookieBak/${qq}.yaml`, (err) => {
if (err) { if (err) {