import Alert from "./Alert"; import ISidebarData from "../../interface/ISidebarData"; import FetchUtils from "./FetchUtils"; import ClassName from "../../container/ClassName"; import { Injectable } from "../../container/Injectable"; import Logger from "../Logger"; @ClassName('InfoUtils') @Injectable() export default class InfoUtils { constructor( // TODO 循环依赖 // private readonly commonUtils: CommonUtils, private readonly fetchUtils: FetchUtils, private readonly logger: Logger, ) { } /** * 返回玩家信息的对象 { playername: string, userID: number } * @return {PlayerInfo} rs */ public getPlayerInfo(): PlayerInfo { const node = document.querySelector('script[uid]'); if (node) { return { playername: node.getAttribute('name'), userID: parseInt(node.getAttribute('uid')), } } else { (() => new Alert('严重错误:芜湖助手无法获取用户数据,已退出'))(); throw '芜湖助手无法获取用户数据'; } } /** * 返回玩家的部分实时数据 */ public async getSessionData(): Promise { let field: string = 'sidebarData' + this.getPlayerInfo().userID; let ret: ISidebarData = {}; return new Promise(async resolve => { let c = 0; while (!sessionStorage.getItem(field) && c < 50) { c++; // await (async () => await this.commonUtils.sleep(10))(); await (async () => window.setTimeout(() => Promise.resolve(), 10))(); } if (sessionStorage.getItem(field)) { try { ret = JSON.parse(sessionStorage.getItem(field)); } catch (e) { this.logger.error('解析出错', e.stack || e.message || e); ret = {}; } } else { this.logger.info('无法从sessionStorage获取数据') ret = await (await this.fetchUtils.ajaxFetch({ url: window.addRFC('/sidebarAjaxAction.php?q=getSidebarData'), method: 'POST', })).json(); sessionStorage.setItem(field, JSON.stringify(ret)); } try { ret.headerData = JSON.parse(sessionStorage.getItem('headerData')); } catch (e) { this.logger.error('解析出错', e.stack || e.message || e); ret.headerData = null; } resolve(ret); }); } /** * 返回玩家当前的边栏菜单列表 如gym crimes */ public async getSidebarData() { return (await this.getSessionData()).areas; } /** * 玩家的基础信息 * {status: string, isLoggedIn: boolean, isDonator: boolean, isTravelling: boolean, isAbroad: boolean} */ public async getUserState() { return (await this.getSessionData()).headerData.user.state; } }