From d52f16bc885a53f93d854dcb20fd157bd8b4008b Mon Sep 17 00:00:00 2001 From: idranme Date: Sun, 11 Aug 2024 19:42:44 +0800 Subject: [PATCH] opt --- src/common/config.ts | 4 +- src/common/data.ts | 43 +++++++++-- src/common/db.ts | 1 - src/common/utils/log.ts | 6 +- src/main/main.ts | 83 +++++----------------- src/ntqqapi/api/msg.ts | 13 ++-- src/ntqqapi/api/user.ts | 12 ++-- src/ntqqapi/api/webapi.ts | 52 +++++++------- src/ntqqapi/hook.ts | 12 ++-- src/onebot11/action/msg/SendMsg.ts | 12 ++-- src/onebot11/action/system/GetLoginInfo.ts | 7 +- src/onebot11/action/system/GetStatus.ts | 4 +- src/onebot11/constructor.ts | 14 ++-- src/onebot11/event/OB11BaseEvent.ts | 4 +- src/onebot11/server/http.ts | 6 +- src/onebot11/server/post-ob11-event.ts | 7 +- src/onebot11/server/ws/ReverseWebsocket.ts | 3 +- src/onebot11/server/ws/WebsocketServer.ts | 4 +- 18 files changed, 139 insertions(+), 148 deletions(-) diff --git a/src/common/config.ts b/src/common/config.ts index d2da049..3ef929c 100644 --- a/src/common/config.ts +++ b/src/common/config.ts @@ -2,7 +2,7 @@ import fs from 'node:fs' import { Config, OB11Config } from './types' import { mergeNewProperties } from './utils/helper' import path from 'node:path' -import { selfInfo } from './data' +import { getSelfUin } from './data' import { DATA_DIR } from './utils' export const HOOK_LOG = false @@ -97,6 +97,6 @@ export class ConfigUtil { } export function getConfigUtil() { - const configFilePath = path.join(DATA_DIR, `config_${selfInfo.uin}.json`) + const configFilePath = path.join(DATA_DIR, `config_${getSelfUin()}.json`) return new ConfigUtil(configFilePath) } diff --git a/src/common/data.ts b/src/common/data.ts index dbb5c68..3f8f85a 100644 --- a/src/common/data.ts +++ b/src/common/data.ts @@ -8,14 +8,8 @@ import { type LLOneBotError } from './types' import { NTQQGroupApi } from '../ntqqapi/api/group' import { log } from './utils/log' import { isNumeric } from './utils/helper' -import { NTQQFriendApi } from '../ntqqapi/api' +import { NTQQFriendApi, NTQQUserApi } from '../ntqqapi/api' -export const selfInfo: SelfInfo = { - uid: '', - uin: '', - nick: '', - online: true, -} export let groups: Group[] = [] export let friends: Friend[] = [] export const llonebotError: LLOneBotError = { @@ -98,4 +92,39 @@ export async function getGroupMember(groupQQ: string | number, memberUinOrUid: s member = getMember() } return member +} + +const selfInfo: SelfInfo = { + uid: '', + uin: '', + nick: '', + online: true, +} + +export async function getSelfNick(force = false): Promise { + if (!selfInfo.nick || force) { + const userInfo = await NTQQUserApi.getUserDetailInfo(selfInfo.uid) + if (userInfo) { + selfInfo.nick = userInfo.nick + return userInfo.nick + } + } + + return selfInfo.nick +} + +export function getSelfInfo() { + return selfInfo +} + +export function setSelfInfo(data: Partial) { + Object.assign(selfInfo, data) +} + +export function getSelfUid() { + return selfInfo['uid'] +} + +export function getSelfUin() { + return selfInfo['uin'] } \ No newline at end of file diff --git a/src/common/db.ts b/src/common/db.ts index 0449b91..b27b7a3 100644 --- a/src/common/db.ts +++ b/src/common/db.ts @@ -1,7 +1,6 @@ import { Level } from 'level' import { type GroupNotify, RawMessage } from '../ntqqapi/types' import { DATA_DIR } from './utils' -import { selfInfo } from './data' import { FileCache } from './types' import { log } from './utils/log' diff --git a/src/common/utils/log.ts b/src/common/utils/log.ts index e06593f..537b3eb 100644 --- a/src/common/utils/log.ts +++ b/src/common/utils/log.ts @@ -1,4 +1,4 @@ -import { selfInfo } from '../data' +import { getSelfInfo } from '../data' import fs from 'fs' import path from 'node:path' import { DATA_DIR, truncateString } from './index' @@ -15,7 +15,7 @@ export function log(...msg: any[]) { if (!getConfigUtil().getConfig().log) { return //console.log(...msg); } - + const selfInfo = getSelfInfo() const userInfo = selfInfo.uin ? `${selfInfo.nick}(${selfInfo.uin})` : '' let logMsg = '' for (let msgItem of msg) { @@ -31,5 +31,5 @@ export function log(...msg: any[]) { logMsg = `${currentDateTime} ${userInfo}: ${logMsg}\n\n` // sendLog(...msg); // console.log(msg) - fs.appendFile(path.join(logDir, logFileName), logMsg, (err: any) => {}) + fs.appendFile(path.join(logDir, logFileName), logMsg, () => {}) } diff --git a/src/main/main.ts b/src/main/main.ts index 440119c..cf4e8aa 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -17,7 +17,10 @@ import { DATA_DIR } from '../common/utils' import { getGroupMember, llonebotError, - selfInfo, + setSelfInfo, + getSelfInfo, + getSelfUid, + getSelfUin } from '../common/data' import { hookNTQQApiCall, hookNTQQApiReceive, ReceiveCmdS, registerReceiveHook, startHook } from '../ntqqapi/hook' import { OB11Constructor } from '../onebot11/constructor' @@ -45,7 +48,6 @@ import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '../onebot11/event/ import '../ntqqapi/wrapper' import { NTEventDispatch } from '../common/utils/EventTask' import { wrapperConstructor, getSession } from '../ntqqapi/wrapper' -import { sleep } from '../common/utils/helper' let mainWindow: BrowserWindow | null = null @@ -160,7 +162,7 @@ function onLoad() { if (!debug && msg.message.length === 0) { return } - const isSelfMsg = msg.user_id.toString() == selfInfo.uin + const isSelfMsg = msg.user_id.toString() === getSelfUin() if (isSelfMsg && !reportSelfMessage) { return } @@ -278,39 +280,6 @@ function onLoad() { log('收到群通知', notify) await dbUtil.addGroupNotify(notify) const flag = notify.group.groupCode + '|' + notify.seq + '|' + notify.type - // let member2: GroupMember; - // if (notify.user2.uid) { - // member2 = await getGroupMember(notify.group.groupCode, null, notify.user2.uid); - // } - // 原本的群管变更通知事件处理 - // if ( - // [GroupNotifyTypes.ADMIN_SET, GroupNotifyTypes.ADMIN_UNSET, GroupNotifyTypes.ADMIN_UNSET_OTHER].includes( - // notify.type, - // ) - // ) { - // const member1 = await getGroupMember(notify.group.groupCode, notify.user1.uid) - // log('有管理员变动通知') - // refreshGroupMembers(notify.group.groupCode).then() - // let groupAdminNoticeEvent = new OB11GroupAdminNoticeEvent() - // groupAdminNoticeEvent.group_id = parseInt(notify.group.groupCode) - // log('开始获取变动的管理员') - // if (member1) { - // log('变动管理员获取成功') - // groupAdminNoticeEvent.user_id = parseInt(member1.uin) - // groupAdminNoticeEvent.sub_type = [ - // GroupNotifyTypes.ADMIN_UNSET, - // GroupNotifyTypes.ADMIN_UNSET_OTHER, - // ].includes(notify.type) - // ? 'unset' - // : 'set' - // // member1.role = notify.type == GroupNotifyTypes.ADMIN_SET ? GroupMemberRole.admin : GroupMemberRole.normal; - // postOb11Event(groupAdminNoticeEvent, true) - // } - // else { - // log('获取群通知的成员信息失败', notify, getGroup(notify.group.groupCode)) - // } - // } - // else if (notify.type == GroupNotifyTypes.MEMBER_EXIT || notify.type == GroupNotifyTypes.KICK_MEMBER) { log('有成员退出通知', notify) try { @@ -419,7 +388,7 @@ function onLoad() { let startTime = 0 // 毫秒 - async function start() { + async function start(uid: string, uin: string) { log('llonebot pid', process.pid) const config = getConfigUtil().getConfig() if (!config.enableLLOB) { @@ -428,8 +397,9 @@ function onLoad() { } llonebotError.otherError = '' startTime = Date.now() - dbUtil.init(selfInfo.uin) NTEventDispatch.init({ ListenerMap: wrapperConstructor, WrapperSession: getSession()! }) + dbUtil.init(uin) + log('start activate group member info') NTQQGroupApi.activateMemberInfoChange().then().catch(log) NTQQGroupApi.activateMemberListChange().then().catch(log) @@ -451,35 +421,18 @@ function onLoad() { log('LLOneBot start') } - let getSelfNickCount = 0 const init = async () => { - if (!selfInfo.uin) { - selfInfo.uin = globalThis.authData?.uin - selfInfo.uid = globalThis.authData?.uid - selfInfo.nick = selfInfo.uin + const current = getSelfInfo() + if (!current.uin) { + setSelfInfo({ + uin: globalThis.authData?.uin, + uid: globalThis.authData?.uid, + nick: current.uin, + }) } //log('self info', selfInfo, globalThis.authData) - if (selfInfo.uin) { - async function getUserNick() { - try { - getSelfNickCount++ - const userInfo = await NTQQUserApi.getUserDetailInfo(selfInfo.uid) - log('self info', userInfo) - if (userInfo) { - selfInfo.nick = userInfo.nick - return - } - } catch (e: any) { - log('get self nickname failed', e.stack) - } - if (getSelfNickCount < 10) { - await sleep(1000) - return await getUserNick() - } - } - - await getUserNick() - start() + if (current.uin) { + start(current.uid, current.uin) } else { setTimeout(init, 1000) @@ -490,7 +443,7 @@ function onLoad() { // 创建窗口时触发 function onBrowserWindowCreated(window: BrowserWindow) { - if (selfInfo.uid) { + if (getSelfUid()) { return } mainWindow = window diff --git a/src/ntqqapi/api/msg.ts b/src/ntqqapi/api/msg.ts index e70a1f9..b413271 100644 --- a/src/ntqqapi/api/msg.ts +++ b/src/ntqqapi/api/msg.ts @@ -1,6 +1,6 @@ import { callNTQQApi, GeneralCallResult, NTQQApiMethod } from '../ntcall' import { RawMessage, SendMessageElement, Peer, ChatType2 } from '../types' -import { selfInfo } from '../../common/data' +import { getSelfNick, getSelfUid } from '../../common/data' import { getBuildVersion } from '../../common/utils' import { getSession } from '@/ntqqapi/wrapper' import { NTEventDispatch } from '@/common/utils/EventTask' @@ -28,7 +28,7 @@ export class NTQQMsgApi { fromGroupCode: GroupCode, sig: '', selfPhone: '', - selfUid: selfInfo.uid, + selfUid: getSelfUid(), gameSession: TempGameSession }) } @@ -208,9 +208,10 @@ export class NTQQMsgApi { } static async multiForwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]): Promise { - const msgInfos = msgIds.map(id => { - return { msgId: id, senderShowName: selfInfo.nick } + const msgInfos = msgIds.map(async id => { + return { msgId: id, senderShowName: await getSelfNick() } }) + const selfUid = getSelfUid() let data = await NTEventDispatch.CallNormalEvent< (msgInfo: typeof msgInfos, srcPeer: Peer, destPeer: Peer, comment: Array, attr: Map,) => Promise, (msgList: RawMessage[]) => void @@ -221,7 +222,7 @@ export class NTQQMsgApi { 5000, (msgRecords: RawMessage[]) => { for (let msgRecord of msgRecords) { - if (msgRecord.peerUid == destPeer.peerUid && msgRecord.senderUid == selfInfo.uid) { + if (msgRecord.peerUid == destPeer.peerUid && msgRecord.senderUid == selfUid) { return true } } @@ -242,7 +243,7 @@ export class NTQQMsgApi { if (forwardData.app != 'com.tencent.multimsg') { continue } - if (msg.peerUid == destPeer.peerUid && msg.senderUid == selfInfo.uid) { + if (msg.peerUid == destPeer.peerUid && msg.senderUid == selfUid) { return msg } } diff --git a/src/ntqqapi/api/user.ts b/src/ntqqapi/api/user.ts index 37a1e4d..1bdd5fe 100644 --- a/src/ntqqapi/api/user.ts +++ b/src/ntqqapi/api/user.ts @@ -1,7 +1,7 @@ import { callNTQQApi, GeneralCallResult, NTQQApiClass, NTQQApiMethod } from '../ntcall' import { SelfInfo, User, UserDetailInfoByUin, UserDetailInfoByUinV2 } from '../types' import { ReceiveCmdS } from '../hook' -import { selfInfo, friends, groupMembers } from '@/common/data' +import { friends, groupMembers, getSelfUin } from '@/common/data' import { CacheClassFuncAsync, log, getBuildVersion } from '@/common/utils' import { getSession } from '@/ntqqapi/wrapper' import { RequestUtil } from '@/common/utils/request' @@ -10,8 +10,6 @@ import { NodeIKernelProfileListener } from '../listeners' import { NTEventDispatch } from '@/common/utils/EventTask' import { NTQQFriendApi } from './friend' -const userInfoCache: Record = {} // uid: User - export class NTQQUserApi { static async setQQAvatar(filePath: string) { return await callNTQQApi({ @@ -120,7 +118,8 @@ export class NTQQUserApi { } static async getQzoneCookies() { - const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + selfInfo.uin + '&clientkey=' + (await this.getClientKey()).clientKey + '&u1=https%3A%2F%2Fuser.qzone.qq.com%2F' + selfInfo.uin + '%2Finfocenter&keyindex=19%27' + const uin = getSelfUin() + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + uin + '&clientkey=' + (await this.getClientKey()).clientKey + '&u1=https%3A%2F%2Fuser.qzone.qq.com%2F' + uin + '%2Finfocenter&keyindex=19%27' let cookies: { [key: string]: string } = {} try { cookies = await RequestUtil.HttpsGetCookies(requestUrl) @@ -135,7 +134,7 @@ export class NTQQUserApi { if (clientKeyData.result !== 0) { throw new Error('获取clientKey失败') } - const url = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + selfInfo.uin + const url = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + getSelfUin() + '&clientkey=' + clientKeyData.clientKey + '&u1=https%3A%2F%2Fh5.qzone.qq.com%2Fqqnt%2Fqzoneinpcqq%2Ffriend%3Frefresh%3D0%26clientuin%3D0%26darkMode%3D0&keyindex=' + clientKeyData.keyIndex return (await RequestUtil.HttpsGetCookies(url))?.skey @@ -144,7 +143,8 @@ export class NTQQUserApi { @CacheClassFuncAsync(1800 * 1000) static async getCookies(domain: string) { const ClientKeyData = await NTQQUserApi.forceFetchClientKey() - const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + selfInfo.uin + '&clientkey=' + ClientKeyData.clientKey + '&u1=https%3A%2F%2F' + domain + '%2F' + selfInfo.uin + '%2Finfocenter&keyindex=19%27' + const uin = getSelfUin() + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + uin + '&clientkey=' + ClientKeyData.clientKey + '&u1=https%3A%2F%2F' + domain + '%2F' + uin + '%2Finfocenter&keyindex=19%27' const cookies: { [key: string]: string; } = await RequestUtil.HttpsGetCookies(requestUrl) return cookies } diff --git a/src/ntqqapi/api/webapi.ts b/src/ntqqapi/api/webapi.ts index 748eb36..d3f1aaf 100644 --- a/src/ntqqapi/api/webapi.ts +++ b/src/ntqqapi/api/webapi.ts @@ -1,4 +1,4 @@ -import { selfInfo } from '@/common/data' +import { getSelfUin } from '@/common/data' import { log } from '@/common/utils/log' import { NTQQUserApi } from './user' import { RequestUtil } from '@/common/utils/request' @@ -192,49 +192,47 @@ export class WebApi { static async setGroupNotice(GroupCode: string, Content: string = '') { //https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${bkn} //qid=${群号}&bkn=${bkn}&text=${内容}&pinned=0&type=1&settings={"is_show_edit_card":1,"tip_window_type":1,"confirm_required":1} - const _Pskey = (await NTQQUserApi.getPSkey(['qun.qq.com']))['qun.qq.com']; - const _Skey = await NTQQUserApi.getSkey(); - const CookieValue = 'p_skey=' + _Pskey + '; skey=' + _Skey + '; p_uin=o' + selfInfo.uin; - let ret: any = undefined; - //console.log(CookieValue); + const _Pskey = (await NTQQUserApi.getPSkey(['qun.qq.com']))['qun.qq.com'] + const _Skey = await NTQQUserApi.getSkey() + const CookieValue = 'p_skey=' + _Pskey + '; skey=' + _Skey + '; p_uin=o' + getSelfUin() + let ret: any = undefined + //console.log(CookieValue) if (!_Skey || !_Pskey) { //获取Cookies失败 - return undefined; + return undefined } - const Bkn = WebApi.genBkn(_Skey); - const data = 'qid=' + GroupCode + '&bkn=' + Bkn + '&text=' + Content + '&pinned=0&type=1&settings={"is_show_edit_card":1,"tip_window_type":1,"confirm_required":1}'; - const url = 'https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=' + Bkn; + const Bkn = WebApi.genBkn(_Skey) + const data = 'qid=' + GroupCode + '&bkn=' + Bkn + '&text=' + Content + '&pinned=0&type=1&settings={"is_show_edit_card":1,"tip_window_type":1,"confirm_required":1}' + const url = 'https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=' + Bkn try { - ret = await RequestUtil.HttpGetJson(url, 'GET', '', { 'Cookie': CookieValue }); - return ret; + ret = await RequestUtil.HttpGetJson(url, 'GET', '', { 'Cookie': CookieValue }) + return ret } catch (e) { - return undefined; + return undefined } - return undefined; } static async getGrouptNotice(GroupCode: string): Promise { - const _Pskey = (await NTQQUserApi.getPSkey(['qun.qq.com']))['qun.qq.com']; - const _Skey = await NTQQUserApi.getSkey(); - const CookieValue = 'p_skey=' + _Pskey + '; skey=' + _Skey + '; p_uin=o' + selfInfo.uin; - let ret: WebApiGroupNoticeRet | undefined = undefined; - //console.log(CookieValue); + const _Pskey = (await NTQQUserApi.getPSkey(['qun.qq.com']))['qun.qq.com'] + const _Skey = await NTQQUserApi.getSkey() + const CookieValue = 'p_skey=' + _Pskey + '; skey=' + _Skey + '; p_uin=o' + getSelfUin() + let ret: WebApiGroupNoticeRet | undefined = undefined + //console.log(CookieValue) if (!_Skey || !_Pskey) { //获取Cookies失败 - return undefined; + return undefined } - const Bkn = WebApi.genBkn(_Skey); - const url = 'https://web.qun.qq.com/cgi-bin/announce/get_t_list?bkn=' + Bkn + '&qid=' + GroupCode + '&ft=23&ni=1&n=1&i=1&log_read=1&platform=1&s=-1&n=20'; + const Bkn = WebApi.genBkn(_Skey) + const url = 'https://web.qun.qq.com/cgi-bin/announce/get_t_list?bkn=' + Bkn + '&qid=' + GroupCode + '&ft=23&ni=1&n=1&i=1&log_read=1&platform=1&s=-1&n=20' try { - ret = await RequestUtil.HttpGetJson(url, 'GET', '', { 'Cookie': CookieValue }); + ret = await RequestUtil.HttpGetJson(url, 'GET', '', { 'Cookie': CookieValue }) if (ret?.ec !== 0) { - return undefined; + return undefined } - return ret; + return ret } catch (e) { - return undefined; + return undefined } - return undefined; } static genBkn(sKey: string) { diff --git a/src/ntqqapi/hook.ts b/src/ntqqapi/hook.ts index b1432d2..781f04d 100644 --- a/src/ntqqapi/hook.ts +++ b/src/ntqqapi/hook.ts @@ -8,7 +8,8 @@ import { getFriend, getGroupMember, groups, - selfInfo, + getSelfUin, + setSelfInfo } from '@/common/data' import { OB11GroupDecreaseEvent } from '../onebot11/event/notice/OB11GroupDecreaseEvent' import { postOb11Event } from '../onebot11/server/post-ob11-event' @@ -282,12 +283,13 @@ async function processGroupEvent(payload: { groupList: Group[] }) { } // 判断bot是否是管理员,如果是管理员不需要从这里得知有人退群,这里的退群无法得知是主动退群还是被踢 - let bot = await getGroupMember(group.groupCode, selfInfo.uin) + const selfUin = getSelfUin() + const bot = await getGroupMember(group.groupCode, selfUin) if (bot?.role == GroupMemberRole.admin || bot?.role == GroupMemberRole.owner) { continue } for (const member of oldMembers) { - if (!newMembersSet.has(member.uin) && member.uin != selfInfo.uin) { + if (!newMembersSet.has(member.uin) && member.uin != selfUin) { postOb11Event( new OB11GroupDecreaseEvent( parseInt(group.groupCode), @@ -447,7 +449,9 @@ export async function startHook() { }) registerReceiveHook<{ info: { status: number } }>(ReceiveCmdS.SELF_STATUS, (info) => { - selfInfo.online = info.info.status !== 20 + setSelfInfo({ + online: info.info.status !== 20 + }) }) let activatedPeerUids: string[] = [] diff --git a/src/onebot11/action/msg/SendMsg.ts b/src/onebot11/action/msg/SendMsg.ts index 9e6ade3..d0c1c5c 100644 --- a/src/onebot11/action/msg/SendMsg.ts +++ b/src/onebot11/action/msg/SendMsg.ts @@ -7,7 +7,7 @@ import { RawMessage, SendMessageElement, } from '../../../ntqqapi/types' -import { getGroup, getGroupMember, selfInfo } from '../../../common/data' +import { getGroup, getGroupMember, getSelfUid, getSelfUin } from '../../../common/data' import { OB11MessageCustomMusic, OB11MessageData, @@ -101,7 +101,7 @@ export async function createSendElements( remainAtAllCount = (await NTQQGroupApi.getGroupAtAllRemainCount(groupCode)).atInfo .RemainAtAllCountForUin log(`群${groupCode}剩余at全体次数`, remainAtAllCount) - const self = await getGroupMember(groupCode, selfInfo.uin) + const self = await getGroupMember(groupCode, getSelfUin()) isAdmin = self?.role === GroupMemberRole.admin || self?.role === GroupMemberRole.owner } catch (e) { } @@ -457,7 +457,7 @@ export class SendMsg extends BaseAction { const nodeMsg = await NTQQMsgApi.sendMsg( { chatType: ChatType.friend, - peerUid: selfInfo.uid, + peerUid: getSelfUid(), }, sendElements, true, @@ -473,7 +473,7 @@ export class SendMsg extends BaseAction { private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]) { const selfPeer = { chatType: ChatType.friend, - peerUid: selfInfo.uid, + peerUid: getSelfUid(), } let nodeMsgIds: string[] = [] // 先判断一遍是不是id和自定义混用 @@ -489,7 +489,7 @@ export class SendMsg extends BaseAction { nodeMsgIds.push(nodeMsg?.msgId!) } else { - if (nodeMsg?.peerUid !== selfInfo.uid) { + if (nodeMsg?.peerUid !== selfPeer.peerUid) { const cloneMsg = await this.cloneMsg(nodeMsg!) if (cloneMsg) { nodeMsgIds.push(cloneMsg.msgId) @@ -562,7 +562,7 @@ export class SendMsg extends BaseAction { if (needSendSelf) { log('需要克隆转发消息') for (const [index, msg] of nodeMsgArray.entries()) { - if (msg.peerUid !== selfInfo.uid) { + if (msg.peerUid !== selfPeer.peerUid) { const cloneMsg = await this.cloneMsg(msg) if (cloneMsg) { nodeMsgIds[index] = cloneMsg.msgId diff --git a/src/onebot11/action/system/GetLoginInfo.ts b/src/onebot11/action/system/GetLoginInfo.ts index a247a76..c05fa33 100644 --- a/src/onebot11/action/system/GetLoginInfo.ts +++ b/src/onebot11/action/system/GetLoginInfo.ts @@ -1,6 +1,6 @@ import { OB11User } from '../../types' import { OB11Constructor } from '../../constructor' -import { selfInfo } from '../../../common/data' +import { getSelfInfo, getSelfNick } from '../../../common/data' import BaseAction from '../BaseAction' import { ActionName } from '../types' @@ -8,7 +8,10 @@ class GetLoginInfo extends BaseAction { actionName = ActionName.GetLoginInfo protected async _handle(payload: null) { - return OB11Constructor.selfInfo(selfInfo) + return OB11Constructor.selfInfo({ + ...getSelfInfo(), + nick: await getSelfNick(true) + }) } } diff --git a/src/onebot11/action/system/GetStatus.ts b/src/onebot11/action/system/GetStatus.ts index cac3008..c3aa3da 100644 --- a/src/onebot11/action/system/GetStatus.ts +++ b/src/onebot11/action/system/GetStatus.ts @@ -1,14 +1,14 @@ import BaseAction from '../BaseAction' import { OB11Status } from '../../types' import { ActionName } from '../types' -import { selfInfo } from '../../../common/data' +import { getSelfInfo } from '../../../common/data' export default class GetStatus extends BaseAction { actionName = ActionName.GetStatus protected async _handle(payload: any): Promise { return { - online: selfInfo.online!, + online: getSelfInfo().online!, good: true, } } diff --git a/src/onebot11/constructor.ts b/src/onebot11/constructor.ts index 599489c..9566fec 100644 --- a/src/onebot11/constructor.ts +++ b/src/onebot11/constructor.ts @@ -27,7 +27,7 @@ import { FriendV2, ChatType2 } from '../ntqqapi/types' -import { deleteGroup, getGroupMember, selfInfo } from '../common/data' +import { deleteGroup, getGroupMember, getSelfUin } from '../common/data' import { EventType } from './event/OB11BaseEvent' import { encodeCQCode } from './cqcode' import { dbUtil } from '../common/db' @@ -60,8 +60,9 @@ export class OB11Constructor { debug, ob11: { messagePostFormat }, } = config + const selfUin = getSelfUin() const resMsg: OB11Message = { - self_id: parseInt(selfInfo.uin), + self_id: parseInt(selfUin), user_id: parseInt(msg.senderUin!), time: parseInt(msg.msgTime) || Date.now(), message_id: msg.msgShortId!, @@ -78,7 +79,7 @@ export class OB11Constructor { sub_type: 'friend', message: messagePostFormat === 'string' ? '' : [], message_format: messagePostFormat === 'string' ? 'string' : 'array', - post_type: selfInfo.uin == msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE, + post_type: selfUin == msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE, } if (debug) { resMsg.raw = msg @@ -425,6 +426,7 @@ export class OB11Constructor { log(`收到我被踢出或退群提示, 群${msg.peerUid}`, groupElement) deleteGroup(msg.peerUid) NTQQGroupApi.quitGroup(msg.peerUid).then() + const selfUin = getSelfUin() try { const adminUin = (await getGroupMember(msg.peerUid, groupElement.adminUid))?.uin || @@ -432,13 +434,13 @@ export class OB11Constructor { if (adminUin) { return new OB11GroupDecreaseEvent( parseInt(msg.peerUid), - parseInt(selfInfo.uin), + parseInt(selfUin), parseInt(adminUin), 'kick_me', ) } } catch (e) { - return new OB11GroupDecreaseEvent(parseInt(msg.peerUid), parseInt(selfInfo.uin), 0, 'leave') + return new OB11GroupDecreaseEvent(parseInt(msg.peerUid), parseInt(selfUin), 0, 'leave') } } } @@ -565,7 +567,7 @@ export class OB11Constructor { const postMsg = await dbUtil.getMsgBySeqId(origMsg?.msgSeq!) ?? origMsg // 如果 senderUin 为 0,可能是 历史消息 或 自身消息 if (msgList[0].senderUin === '0') { - msgList[0].senderUin = postMsg?.senderUin ?? selfInfo.uin + msgList[0].senderUin = postMsg?.senderUin ?? getSelfUin() } return new OB11GroupEssenceEvent(parseInt(msg.peerUid), postMsg?.msgShortId!, parseInt(msgList[0].senderUin!)) // 获取MsgSeq+Peer可获取具体消息 diff --git a/src/onebot11/event/OB11BaseEvent.ts b/src/onebot11/event/OB11BaseEvent.ts index bcdd45b..88d3338 100644 --- a/src/onebot11/event/OB11BaseEvent.ts +++ b/src/onebot11/event/OB11BaseEvent.ts @@ -1,4 +1,4 @@ -import { selfInfo } from '../../common/data' +import { getSelfUin } from '../../common/data' export enum EventType { META = 'meta_event', @@ -10,6 +10,6 @@ export enum EventType { export abstract class OB11BaseEvent { time = Math.floor(Date.now() / 1000) - self_id = parseInt(selfInfo.uin) + self_id = parseInt(getSelfUin()) abstract post_type: EventType } diff --git a/src/onebot11/server/http.ts b/src/onebot11/server/http.ts index 79f3a2e..5c1db8d 100644 --- a/src/onebot11/server/http.ts +++ b/src/onebot11/server/http.ts @@ -1,11 +1,11 @@ import { Response } from 'express' import { OB11Response } from '../action/OB11Response' import { HttpServerBase } from '@/common/server/http' -import { actionHandlers, actionMap } from '../action' +import { actionMap } from '../action' import { getConfigUtil } from '@/common/config' import { postOb11Event } from './post-ob11-event' import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent' -import { selfInfo } from '@/common/data' +import { getSelfInfo } from '@/common/data' class OB11HTTPServer extends HttpServerBase { name = 'LLOneBot server' @@ -40,7 +40,7 @@ class HTTPHeart { } this.intervalId = setInterval(() => { // ws的心跳是ws自己维护的 - postOb11Event(new OB11HeartbeatEvent(selfInfo.online!, true, heartInterval!), false, false) + postOb11Event(new OB11HeartbeatEvent(getSelfInfo().online!, true, heartInterval!), false, false) }, heartInterval) } diff --git a/src/onebot11/server/post-ob11-event.ts b/src/onebot11/server/post-ob11-event.ts index f6d2cb4..f979dd4 100644 --- a/src/onebot11/server/post-ob11-event.ts +++ b/src/onebot11/server/post-ob11-event.ts @@ -1,5 +1,5 @@ import { OB11Message } from '../types' -import { selfInfo } from '@/common/data' +import { getSelfUin } from '@/common/data' import { OB11BaseMetaEvent } from '../event/meta/OB11BaseMetaEvent' import { OB11BaseNoticeEvent } from '../event/notice/OB11BaseNoticeEvent' import { WebSocket as WebSocketClass } from 'ws' @@ -35,9 +35,10 @@ export function postWsEvent(event: PostEventType) { export function postOb11Event(msg: PostEventType, reportSelf = false, postWs = true) { const config = getConfigUtil().getConfig() + const selfUin = getSelfUin() // 判断msg是否是event if (!config.reportSelfMessage && !reportSelf) { - if (msg.post_type === 'message' && (msg as OB11Message).user_id.toString() == selfInfo.uin) { + if (msg.post_type === 'message' && (msg as OB11Message).user_id.toString() == selfUin) { return } } @@ -48,7 +49,7 @@ export function postOb11Event(msg: PostEventType, reportSelf = false, postWs = t const sig = hmac.digest('hex') let headers = { 'Content-Type': 'application/json', - 'x-self-id': selfInfo.uin, + 'x-self-id': selfUin, } if (config.ob11.httpSecret) { headers['x-signature'] = 'sha1=' + sig diff --git a/src/onebot11/server/ws/ReverseWebsocket.ts b/src/onebot11/server/ws/ReverseWebsocket.ts index 47ab083..c7c0462 100644 --- a/src/onebot11/server/ws/ReverseWebsocket.ts +++ b/src/onebot11/server/ws/ReverseWebsocket.ts @@ -1,4 +1,4 @@ -import { selfInfo } from '../../../common/data' +import { getSelfInfo } from '../../../common/data' import { LifeCycleSubType, OB11LifeCycleEvent } from '../../event/meta/OB11LifeCycleEvent' import { ActionName } from '../../action/types' import { OB11Response } from '../../action/OB11Response' @@ -78,6 +78,7 @@ export class ReverseWebsocket { private connect() { const { token, heartInterval } = getConfigUtil().getConfig() + const selfInfo = getSelfInfo() this.websocket = new WebSocketClass(this.url, { maxPayload: 1024 * 1024 * 1024, handshakeTimeout: 2000, diff --git a/src/onebot11/server/ws/WebsocketServer.ts b/src/onebot11/server/ws/WebsocketServer.ts index eeb8b9f..4cff47e 100644 --- a/src/onebot11/server/ws/WebsocketServer.ts +++ b/src/onebot11/server/ws/WebsocketServer.ts @@ -9,7 +9,7 @@ import { OB11HeartbeatEvent } from '../../event/meta/OB11HeartbeatEvent' import { WebsocketServerBase } from '../../../common/server/websocket' import { IncomingMessage } from 'node:http' import { wsReply } from './reply' -import { selfInfo } from '../../../common/data' +import { getSelfInfo } from '../../../common/data' import { log } from '../../../common/utils/log' import { getConfigUtil } from '../../../common/config' @@ -59,7 +59,7 @@ class OB11WebsocketServer extends WebsocketServerBase { } const { heartInterval } = getConfigUtil().getConfig() const wsClientInterval = setInterval(() => { - postWsEvent(new OB11HeartbeatEvent(selfInfo.online!, true, heartInterval!)) + postWsEvent(new OB11HeartbeatEvent(getSelfInfo().online!, true, heartInterval!)) }, heartInterval) // 心跳包 wsClient.on('close', () => { log('event上报ws客户端已断开')