wuhu-torn-helper/src/ts/class/action/CompanyHelper.ts
2023-01-09 18:07:20 +08:00

85 lines
3.8 KiB
TypeScript

import WuhuBase from "../WuhuBase";
import WuhuConfig from "../WuhuConfig";
import Log from "../Log";
import CommonUtils from "../utils/CommonUtils";
import FetchUtils from "../utils/FetchUtils";
import InfoUtils from "../utils/InfoUtils";
import Alert from "../utils/Alert";
import TRAVEL_STATE from "../../enum/TravelState";
/**
* 公司助手
*/
export default class CompanyHelper extends WuhuBase {
className = 'CompanyHelper';
public constructor() {
super();
WuhuConfig.get('CHTrainsDetectSwitch') && this.trainsDetect().then();
}
public detectNow(): void {
this.trainsDetect(true).then();
}
/**
* 火车检测
* 每日判断一次,非公司老板跳过检测
* TODO 优化、URL判断
*/
private async trainsDetect(test: boolean = false): Promise<null> {
// 通过用户的icon判断公司老板
if ((await InfoUtils.getInstance().getSessionData()).statusIcons.icons.company.iconID !== 'icon73') {
Log.info('火车检测跳过:非公司老板');
return;
}
// 上次检测时间戳
let lastDetect: number = WuhuConfig.get('CHTrainsDetect') || 0;
// 检测是否过了一天
if (test || CommonUtils.getInstance().isNewDay(lastDetect, -6)) {
let travelStage = CommonUtils.getInstance().getTravelStage(),
userStatus = (await InfoUtils.getInstance().getUserState()).status;
test && Log.info({ travelStage, userStatus });
if (travelStage === TRAVEL_STATE.IN_TORN && userStatus === 'ok')
FetchUtils.getInstance().fetchText('/companies.php')
.then(res => {
let tmp: HTMLElement = document.createElement('div');
let bodyTagStart = CommonUtils.getInstance().matchOne(res, /<body.+>/);
if (!bodyTagStart) {
Log.warn('火车检测: 无法获取数据');
throw new Error('火车检测: 无法获取数据');
}
tmp.innerHTML = res.split(bodyTagStart)[1].split('</body>')[0].trim()
.replaceAll('rel="stylesheet"', '')
.replaceAll('.css', '?404')
.replaceAll('type="text/javascript"', 'type="application/json"');
let trainsNode = tmp.querySelector('span.trains');
if (!trainsNode) {
Log.error('火车检测出错: 无法获取火车数');
throw new Error('火车检测出错: 无法获取火车数');
}
let trains: number = parseInt(trainsNode.innerText);
let stars: number = tmp.querySelectorAll('.company-rating .active').length / 2 || 1;
WuhuConfig.set('CHTrainsDetect', Date.now());
Log.info('火车检测: 火车/星级: ' + trains + '/' + stars);
Log.info({ tmp });
if (trains + stars > 20) {
new Alert(`公司助手<br/><br/>火车检测:火车明日将溢出!${ trains }/20火车`, {
timeout: 15,
force: true,
sysNotify: true
});
}
tmp.remove();
tmp = null;
})
.catch(error => {
Log.error('火车检测出错', error);
});
else Log.warn('[火车检测] 用户状态错误,跳过火车检测', { travelStage, userStatus });
} else {
Log.info('火车检测:今日已提醒,跳过');
}
}
}