TS重构、错误修正

This commit is contained in:
李万一 2022-09-02 21:48:07 +08:00
parent 347b343e8d
commit 3b32ab27bf
22 changed files with 21170 additions and 9507 deletions

2778
dictionary/translation.ts Normal file

File diff suppressed because it is too large Load Diff

7
enum/Device.ts Normal file
View File

@ -0,0 +1,7 @@
enum Device {
PC = 'pc',
MOBILE = 'mobile',
TABLET = 'tablet',
}
export default Device

7
enum/UserScriptEngine.ts Normal file
View File

@ -0,0 +1,7 @@
enum UserScriptEngine {
RAW = 'raw',
GM = 'gm',
PDA = 'pda',
}
export default UserScriptEngine

799
function/eventsTrans.ts Normal file
View File

@ -0,0 +1,799 @@
import {eventsDict, ocList, gymList} from "../dictionary/translation";
import log from "./utils/log";
export default function eventsTrans(events: JQuery = $('span.mail-link')) {
const index = window.location.href.indexOf('events.php#/step=received') >= 0 ? 1 : 0;
const isReceived = index === 1;
// 通知的类型选择栏
$('ul.mailbox-action-wrapper a').contents().each((i, e) => {
if (e.nodeValue)
if (eventsDict[e.nodeValue.trim()])
e.nodeValue = eventsDict[e.nodeValue.trim()];
});
// 桌面版右边按钮浮动提示消息
$('div.mailbox-container i[title]').each((i, e) => {
if (eventsDict[$(e).attr('title')]) {
$(e).attr('title', eventsDict[$(e).attr('title')]);
}
});
// 手机版底部按钮
$('.mobile-mail-actions-wrapper div:nth-child(2)').each((i, e) => {
if (eventsDict[$(e).text().trim()])
$(e).text(eventsDict[$(e).text().trim()]);
});
// 黑框标题
$('#events-main-wrapper .title-black').each((i, e) => {
if (eventsDict[$(e).text().trim()]) {
$(e).text(eventsDict[$(e).text().trim()]);
}
});
// 发送的两个按钮 + user id
$('#events-main-wrapper div.send-to a.btn').each((i, e) => {
if (eventsDict[$(e).text().trim()]) {
$(e).text(eventsDict[$(e).text().trim()]);
}
});
$('#events-main-wrapper div.send-to span.cancel a').each((i, e) => {
if (eventsDict[$(e).text().trim()]) {
$(e).text(eventsDict[$(e).text().trim()]);
}
});
$('#events-main-wrapper div.send-to span.name').each((i, e) => {
if (eventsDict[$(e).text().trim()]) {
$(e).text(eventsDict[$(e).text().trim()]);
}
});
// 通知翻译的开关
if (!$('div#event-trans-msg').get(0) && !window.location.href.contains(/index\.php/)) {
// msgBox(`<div id="event-trans-msg">插件暂时不能翻译全部通知。<br>
// 如发现问题请发送通知并联系 <a href="profiles.php?XID=2687093">Woohoo[2687093]</a><br>
// <input type="checkbox" id="eventTransCheck" name="eventTransCheck" /><label for="eventTransCheck">开启通知翻译</label> 可能会出现卡顿,默认开启</div>`);
$('input#eventTransCheck').attr('checked', localStorage.getItem('wh_trans_event') === 'true');
$('input#eventTransCheck').change(function () {
if ($(this).attr('checked') === undefined) {
localStorage.setItem('wh_trans_event', 'false');
} else {
localStorage.setItem('wh_trans_event', 'true');
}
eventsTrans();
});
}
if (localStorage.getItem('wh_trans_event') === 'false') return;
if (events.length === 0) return;
events.each((i, e) => {
// todo “收到的信息” 暂时删除发送人节点 不影响显示
if (isReceived) {
$(e).children('a.sender-name').remove();
}
if (eventsDict[$(e).text().trim()]) {
$(e).text(eventsDict[$(e).text().trim()]);
return;
}
/**
*
* You finished 5th in the Hammerhead race. Your best lap was 01:14.87.
* You finished 1st in the Docks race. Your best lap was 04:01.33.
* You finished 1st in the Hammerhead race and have received 3 racing points! Your best lap was 01:06.92.
* You finished 4th in the Docks race. Your best lap was 03:29.27 beating your previous best lap record of 03:35.77 by 00:06.50.
* You have crashed your Honda NSX on the Sewage race! The upgrades Paddle Shift Gearbox (Short Ratio) and Carbon Fiber Roof were lost.
* You have crashed your Ford Mustang on the Docks race! Your car has been recovered.
*/
if ($(e).text().indexOf('finished') >= 0) {
if ($(e).text().indexOf('crashed') >= 0) return; // todo 撞车
const isGainRacingPoint = $(e).text().indexOf('racing point');
let racingPoint = isGainRacingPoint >= 0 ? $(e).text()[isGainRacingPoint - 2] : null;
const isBeat = $(e).text().indexOf('beating') >= 0;
let record, bestBy;
if (isBeat) {
record = $(e).text().split('record of ')[1].split(' by ')[0];
bestBy = $(e).text().split('record of ')[1].split(' by ')[1].split('. ')[0];
}
const pos = e.childNodes[1].firstChild.nodeValue.match(/[0-9]+/)[0];
const splitList = e.childNodes[2].nodeValue.split(' ');
const bestLap = e.childNodes[2].nodeValue.split(' best lap was ')[1].slice(0, 8);//.split(' ')[0];
let map = splitList[3];
map = map === 'Two' ? 'Two Islands' : map;
map = map === 'Stone' ? 'Stone Park' : map;
e.firstChild.nodeValue = '你在赛车比赛 ' + map + ' 中获得第 ';
e.childNodes[1].firstChild.nodeValue = pos;
e.childNodes[2].nodeValue = ' 名,';
if (isGainRacingPoint >= 0) {
e.childNodes[2].nodeValue += '获得' + racingPoint + '赛车点数 (Racing Points)。';
}
e.childNodes[2].nodeValue += '你的最佳圈速是 ' + bestLap;
if (isBeat) e.childNodes[2].nodeValue += ',比之前最佳 ' + record + ' 快 ' + bestBy;
e.childNodes[2].nodeValue += '。'
e.childNodes[2].nodeValue += '[';
e.childNodes[3].firstChild.nodeValue = '查看';
return;
}
/**
*
*/
if ($(e).text().contains(/You have been charged \$[\d,]+ for your loan/)) {
const node1Value = e.firstChild.nodeValue; // You have been charged $29,000 for your loan. You can pay this by visiting the
//e.childNodes[1].firstChild.nodeValue; // <a href="loan.php">Loan Shark</a>
// const node3Value=e.childNodes[2].nodeValue; 内容是 ". "
let charge = node1Value.split(' ')[4];
let replace;
replace = '你需要支付 ';
replace += charge;
replace += ' 贷款利息,点此支付:';
e.firstChild.nodeValue = replace;
e.childNodes[1].firstChild.nodeValue = '鲨客借贷';
e.childNodes[2].nodeValue = '。';
return;
}
/**
*
* You were sent $21,000,000 from
* <a href="profiles.php?XID=2703642">JNZR</a>
* .
* with the message: Manuscript fee OCT
* e.firstChild.nodeValue
* e.childNodes[1].firstChild.nodeValue
* e.childNodes[2].nodeValue
*
* You were sent 4x Xanax from RaichuQ with the message: Manuscript fee OCT
* You were sent $21,000,000 from JNZR.
* You were sent some Xanax from runningowl
* You were sent 1x Present from Duke with the message: Is it your birthday?
* You were sent Duke's Safe from DUKE
* You were sent a Diamond Bladed Knife from charapower
*/
if ($(e).text().contains(/You were sent .+ from/)) {
// 数量 物品 信息
// spl = [You were sent 1x Birthday Present from]
const spl = $(e).contents().get(0).nodeValue.trim().split(' ');
const msgSpl = $(e).text().trim().split('with the message: ');
const num = /^\$[0-9,]+\b/.test(spl[3]) ? '' : spl[3].numWordTrans();
const item = num === '' ? spl[3] : spl.slice(4, -1).join(' ');
const msg = msgSpl[1] ? msgSpl[1] : null;
e.childNodes[0].nodeValue = `你收到了 ${num} ${item},来自 `;
if (e.childNodes[2]) {
e.childNodes[2].nodeValue = ``;
}
if (msg) {
e.childNodes[2].nodeValue = `,附带信息:${msg}`;
}
return;
}
/**
* bazaar
* Dewei3 bought 2 x Toyota MR2 from your bazaar for $56,590.
* ['', 'bought', '2', 'x', 'Toyota', 'MR2', 'from', 'your', 'bazaar', 'for', '$56,590.\n']
* e.childNodes[1].nodeValue
*/
if ($(e).text().contains(/bought .+ from your bazaar for/)) {
const bazEN = e.childNodes[1].nodeValue;
const spl = bazEN.split(' ');
const num = spl[2];
const item = spl.slice(4, spl.indexOf('from')).join(' ');
const money = spl[spl.length - 1].replace('.', '');
e.childNodes[1].nodeValue = ' 花费 ' + money + ' 从你的店铺购买了 ' + num + ' 个 ' + ' ' + item + '。';
return;
}
/**
*
*/
if ($(e).text().indexOf('trade') >= 0) {
const PCHC = '点此继续';
if ($(e).text().indexOf('You must now accept') >= 0) {
/**
*
* <a href="profiles.php?XID=2703642">JNZR</a>
* has accepted the trade titled "g't". You must now accept to finalize it.
* <a href="trade.php#step=view&amp;ID=6567058" i-data="i_598_654_156_14">Please click here to continue.</a>
* JNZR已经接受了名为 "g't "
*/
const firstWords = e.childNodes[1].nodeValue.split('. You must')[0];
const tradeName = firstWords.slice(31, firstWords.length);
e.childNodes[1].nodeValue = ' 已经接受了名为 ' + tradeName + ' 的交易。你现在必须接受以完成它。';
e.childNodes[2].firstChild.nodeValue = PCHC;
return;
}
if ($(e).text().indexOf('expired') >= 0) {
/**
*
* The trade with
* <a href="profiles.php?XID=2696209" i-data="i_278_269_71_14">sabrina_devil</a>
* has expired
* sabrina_devil的交易已经过期
*/
e.firstChild.nodeValue = '与 ';
e.childNodes[2].nodeValue = ' 的交易已过期。';
return;
}
if ($(e).text().indexOf('initiated') >= 0) {
/**
*
* <a href="profiles.php?XID=2696209" i-data="i_199_374_71_14">sabrina_devil</a>
* has initiated a trade titled "gt".
* <a href="trade.php#step=view&amp;ID=6563577" i-data="i_435_374_156_14">Please click here to continue.</a>
* sabrina_devil发起了一项名为 "gt "
*/
const node2 = e.childNodes[1].nodeValue;
const tradeName = node2.slice(30, node2.length - 2);
e.childNodes[1].nodeValue = ' 发起了标题为 ' + tradeName + ' 的交易。';
e.childNodes[2].firstChild.nodeValue = PCHC;
return;
}
if ($(e).text().indexOf('now complete') >= 0) {
/**
*
* <a href="profiles.php?XID=2692672" i-data="i_199_829_51_14">Tmipimlie</a>
* has accepted the trade. The trade is now complete.
* Tmipimlie已经接受交易
*/
e.childNodes[1].nodeValue = ' 已经接受交易。该交易现已完成。';
return;
}
if ($(e).text().indexOf('canceled') >= 0) {
/**
*
* <a href="profiles.php?XID=2431991">WOW</a>
* has canceled the trade.
* WOW已经取消了这项交易
*/
e.childNodes[1].nodeValue = ' 已经取消了这个交易。';
return;
}
if ($(e).text().indexOf('commented') >= 0) {
/**
*
* <a href="profiles.php?XID=2567772">QIJI</a>
* commented on your
* <a href="/trade.php#step=view&amp;ID=6405880" i-data="i_334_968_73_14">pending trade</a>
* : "Thank you for trading with me! The total is $19,461,755 and you can view your receipt here: https://www.tornexchange.com/receipt/mhWuuL7hrE"
*/
e.childNodes[1].nodeValue = ' 对';
e.childNodes[2].firstChild.nodeValue = '进行中的交易';
e.childNodes[3].nodeValue = '添加了一条评论' + e.childNodes[3].nodeValue;
return;
}
return;
}
/**
* mug
*/
if ($(e).text().indexOf('mugged') >= 0) {
const spl = $(e).text().trim().split(' ');
if (spl.length > 7) return; // todo 多人运动暂时跳过
const money = spl[spl.length - 2];
if (spl[0] === 'Someone') { // 被匿名mug
e.firstChild.nodeValue = '有人打劫你并抢走了 ' + money + ' [';
e.childNodes[1].firstChild.nodeValue = '查看';
} else {
e.childNodes[1].nodeValue = ' 打劫你并抢走了 ' + money + ' [';
e.childNodes[2].firstChild.nodeValue = '查看';
}
return;
}
/**
*
*/
if ($(e).text().indexOf('attacked') >= 0) { // 被打
/**
* =spl.length
* 4 Someone attacked you [view]
* - hosp 6 Someone attacked and hospitalized you [view]
* --
* 4 EternalSoulFire attacked you [view]
* - lost 6 EternalSoulFire attacked you but lost [view]
* - hosp 6
* - esc 6 Dr_Bugsy_Siegel attacked you but escaped [view]
* - 25stale 6 Tharizdun attacked you but stalemated [view]
* - bug 6 Mrew tried to attack you [view]
*
* You attacked Cherreh but timed out [view]
*
* todo
* 10 Pual (and 2 others) attached you and hospitalized you [view]
* 9 Argozdoc attacked you but Norm fought him off [view]
*/
const spl = $(e).text().trim().split(' ');
if (spl.length > 6) { // 多人运动暂时跳过
/**
*
*/
if (spl[4] === 'timed') {
if (e.firstChild.firstChild) { // 由第一个节点是否有子节点判断 被攻击
e.childNodes[1].nodeValue = ' 袭击你但是超时了 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
}
e.firstChild.nodeValue = '你袭击 ';
e.childNodes[2].nodeValue = ' 但是超时了 [';
e.childNodes[3].firstChild.nodeValue = '查看';
return;
}
return;
}
if ($(e).find('a').text().toLowerCase().indexOf('someone') < 0 && // 避免玩家名带有someone字样
$(e).text().split(' ')[0].toLowerCase() === 'someone') { // 被匿名
if (spl.length === 6 && spl[3] === 'hospitalized') { // 匿名hos
e.firstChild.nodeValue = '有人袭击你并将你强制住院 [';
e.childNodes[1].firstChild.nodeValue = '查看';
return;
}
e.firstChild.nodeValue = '有人袭击了你 [';
e.childNodes[1].firstChild.nodeValue = '查看';
return;
}
if (spl.length === 4) { // 实名leave
e.childNodes[1].nodeValue = ' 袭击了你 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
}
if (spl.length === 6) { // 实名的情况
switch (spl[4]) {
case 'lost':
e.childNodes[1].nodeValue = ' 袭击你但输了 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
case 'escaped':
e.childNodes[1].nodeValue = ' 袭击你但逃跑了 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
case 'stalemated':
e.childNodes[1].nodeValue = ' 袭击你但打成了平手 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
}
switch (spl[3]) {
case 'attack': // Mrew tried to attack you [view]
e.childNodes[1].nodeValue = ' 尝试袭击你 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
case 'hospitalized':
e.childNodes[1].nodeValue = ' 袭击你并将你强制住院 [';
e.childNodes[2].firstChild.nodeValue = '查看';
return;
}
}
}
/**
*
* Lucky Shot彩票中赢得11,832,100,000!
* zstorm won $5,574,200 in the Daily Dime lottery!
*/
if ($(e).text().indexOf('lottery') >= 0) {
const split = e.childNodes[1].nodeValue.split(' ');
const type = split[split.length - 3] + ' ' + split[split.length - 2];
const money = split[2];
e.childNodes[1].nodeValue = ' 在 ' + type + ' 彩票中赢得了 ' + money + '';
return;
}
/**
*
*/
if ($(e).text().contains(/, the director of .+, has/)) {
$(e).contents().each((i, e) => {
if (e.nodeType === 3) {
if (eventsDict[e.nodeValue.trim()]) {
e.nodeValue = eventsDict[e.nodeValue.trim()];
} else {
// 工资改变
if (e.nodeValue.contains(/wage/)) {
const money = e.nodeValue.trim().slice(27, -9);
e.nodeValue = ` 的老板) 将你的每日工资改为 ${money}`;
return;
}
// 职位改变
if (e.nodeValue.contains(/rank/)) {
const pos = e.nodeValue.trim().slice(27, -1);
e.nodeValue = ` 的老板) 将你的公司职位改为 ${pos}`;
return;
}
if (e.nodeValue.contains(/assigned/)) {
e.nodeValue = ` 的老板) 将你指派为新的公司老板。`;
return;
}
// 火车
if (e.nodeValue.contains(/trained/)) {
const spl = e.nodeValue.trim().split(' ');
const pri = spl[10];
const sec = spl[13].slice(0, -1);
e.nodeValue = ` 的老板) 从公司训练了你。你获得了 50 ${eventsDict[pri]} 和 25 ${eventsDict[sec]}`;
}
}
}
});
return;
}
/**
*
*/
if ($(e).text().contains(/bounty reward/)) {
$(e).contents().each((i, e) => {
if (e.nodeType === 3) {
if (eventsDict[e.nodeValue.trim()]) {
e.nodeValue = ` ${eventsDict[e.nodeValue.trim()]} `;
} else {
if (e.nodeValue.contains(/bounty reward/)) {
const bountyAmount = e.nodeValue.trim().split(' ')[3];
if (eventsDict['and earned your'] && eventsDict['bounty reward']) {
e.nodeValue = ` ${eventsDict['and earned your']} ${bountyAmount} ${eventsDict['bounty reward']}`;
}
}
}
}
});
return;
}
/**
* oc开启
* You have been selected by
* <a href="profiles.php?XID=2537542" class="h" i-data="i_346_233_63_14">endlessway</a>
* to participate in an organized crime. You, along with 2 others will make up the team to
* <a href="organisedcrimes.php" i-data="i_312_248_107_14">make a bomb threat</a>
* in 72 hours.
*
* endlessway选中参与一项有组织的犯罪活动72
*/
if ($(e).text().indexOf('organized crime') >= 0) {
const time = e.childNodes[4].nodeValue.split(' ')[2];
const OCName = e.childNodes[3].firstChild.nodeValue;
let others = e.childNodes[2].nodeValue.split(' ')[10];
others = others === 'one' ? '1' : others;
e.firstChild.nodeValue = '你被 ';
e.childNodes[2].nodeValue = ` 选中参与一项组织犯罪(OC)。你和另外${others}人将组成一个团队,在${time}小时后进行 `;
e.childNodes[3].firstChild.nodeValue = ocList[OCName] ? ocList[OCName] : OCName;
e.childNodes[4].nodeValue = '。';
return;
}
/**
* oc结束
* - You and your team tried to make a bomb threat but failed! View the details
* - You and your team successfully blackmailed someone! View the details
* <a href="organisedcrimes.php?step=log&amp;ID=9404419" i-data="i_595_234_24_14">here</a>
* !
*/
if ($(e).text().indexOf('You and your team') >= 0) {
let rs = '成功';
let OCName = e.firstChild.nodeValue.slice(31, -19);
if ($(e).text().indexOf('fail') >= 0) {
rs = '失败';
OCName = e.firstChild.nodeValue.slice(27, -30);
}
e.firstChild.nodeValue = `你和团队的组织犯罪(OC) ${ocList[OCName] ? ocList[OCName] : OCName} ${rs}了!`;
e.childNodes[1].firstChild.nodeValue = '点此查看详情';
e.childNodes[2].nodeValue = '';
return;
}
/**
* bust
* <a href="profiles.php?XID=2208715">Spookyt</a>
* failed to bust you out of jail.
*/
if ($(e).text().indexOf('bust') >= 0) {
if (e.childNodes[1].nodeValue[1] === 'f') { // 失败
e.childNodes[1].nodeValue = ' 没能把你从监狱救出来。';
return;
}
if (e.childNodes[1].nodeValue[1] === 'w') { // 失败被抓
e.childNodes[1].nodeValue = ' 在尝试救你出狱时被抓了。';
return;
}
if (e.childNodes[1].nodeValue[1] === 's') {
e.childNodes[1].nodeValue = ' 成功把你从监狱里救了出来。';
return;
}
}
/**
*
*/
if ($(e).text().indexOf('bailed') >= 0) {
const cost = e.childNodes[1].nodeValue.trim().slice(27, -1);
e.childNodes[1].nodeValue = ' 花费 ' + cost + ' 保释了你。';
return;
}
/**
*
*/
if ($(e).text().contains(/You were given \$[\d,]+ from your faction/)) {
const money = e.firstChild.nodeValue.split(' ')[3];
let isNamed = e.childNodes.length > 1;
if (isNamed) {
e.firstChild.nodeValue = '';
e.childNodes[2].nodeValue = ' 为你从帮派取了 ' + money + '。';
} else {
e.firstChild.nodeValue = '你得到了从帮派取出的 ' + money + '。';
}
return;
}
/**
*
*/
if ($(e).text().contains(/has placed .+ bount.+ on you/)) {
// 是否匿名 悬赏个数 悬赏单价 原因
const spl = $(e).text().trim().split(' ');
const reasonSpl = $(e).text().trim().split(' and the reason: ');
const someone = !e.children.length;
const num = spl[3] === 'a' ? '1' : spl[3];
const price = reasonSpl[0].split(' ').slice(-1)[0];
const reason = reasonSpl[1] ? reasonSpl[1] : null;
const trans = `${someone ? '某人' : ' '}对你进行了 ${num} 次赏金为 ${price} 的悬赏${reason ? ',原因:' + reason : ''}`;
// 匿名悬赏
if (someone) {
$(e).text(trans);
}
// 实名悬赏
else {
$(e).contents().get(1).nodeValue = trans;
}
return;
}
/**
*
*/
if ($(e).text().contains(/successfully revived you/)) {
if (e.children.length !== 1) return;
if (eventsDict[$(e).contents().get(1).nodeValue.trim()]) {
$(e).contents().get(1).nodeValue = eventsDict[$(e).contents().get(1).nodeValue.trim()]
}
return;
}
/**
*
*/
if ($(e).text().contains(/failed to revive you/)) {
if (e.children.length !== 1) return;
if (eventsDict[$(e).contents().get(1).nodeValue.trim()]) {
$(e).contents().get(1).nodeValue = eventsDict[$(e).contents().get(1).nodeValue.trim()]
}
return;
}
/**
* pt
*/
if ($(e).text().contains(/You were given [\d,]+ points? from your faction/)) {
const pt = e.firstChild.nodeValue.split(' ')[3];
e.firstChild.nodeValue = '你得到了从帮派取出的 ' + pt + ' PT。'
return;
}
/**
* 西
*/
if ($(e).text().contains(/loaned you .+ from the faction armory/)) {
const [num, item] = (() => {
const spl = e.lastChild.nodeValue.trim().slice().slice(11, -25).split(' ');
return spl.length === 1 ? [spl[0], null] : [spl[0], spl.slice(1).join(' ')];
})();
if (num && item) {
e.lastChild.nodeValue = ` 从帮派军械库中借给你 ${num.numWordTrans()} ${item}`;
}
return;
}
/**
*
* <a href="/education.php" i-data="i_199_234_363_14">The education course you were taking has ended. Please click here.</a>
*/
if ($(e).text().indexOf('edu') >= 0) {
if ($(e).text().trim().split(' '))
e.firstChild.firstChild.nodeValue = '你的课程已学习结束,请点此继续。';
return;
}
/**
* LSD od
*/
if ($(e).text().contains(/LSD .+ overdosed/)) {
if (eventsDict[$(e).text().trim()]) $(e).text(eventsDict[$(e).text().trim()]);
return;
}
/**
*
*/
if ($(e).text().contains(/Your application to join the company .+ has been/)) {
$(e).contents().each((i, e) => {
if (e.nodeType === 3) {
if (eventsDict[e.nodeValue.trim()]) {
e.nodeValue = eventsDict[e.nodeValue.trim()];
}
}
});
return;
}
/**
*
*/
if ($(e).text().contains(/Your bank investment has ended/)) {
$(e).children().text('你的银行投资已经结束。请点击这里领取你的资金。');
return;
}
/**
*
* <span class="mail-link" id="event-865162632">Congratulations! You upgraded your level to 31!
</span>
*/
if ($(e).text().indexOf('upgraded') >= 0) {
const level = e.firstChild.nodeValue.slice(44, -2);
e.firstChild.nodeValue = '恭喜!你已升至' + level + '级!';
return;
}
/**
*
* <span class="mail-link" id="event-855834754">You have successfully purchased membership in Deep Burn.</span>
* Deep Burn的健身房会员卡
*/
if ($(e).text().contains(/You have successfully purchased membership in/)) {
const gymName = e.firstChild.nodeValue.trim().slice(46, -1);
e.firstChild.nodeValue = `你已购买【${gymList[gymName]}】健身房会员卡。`;
return;
}
/**
*
*/
if ($(e).text().contains(/You are now known in the city as a/)) {
const trans = '现在你在这个城市中被称为';
const title = $(e).text().trim().split(' ').slice(9).join(' ').slice(0, -1);
$(e).text(`${trans} ${title}`);
return;
}
/**
* 线
*/
if ($(e).text().contains(/You have successfully referred/)) {
$(e).contents().each((i, e) => {
// 文字
if (e.nodeType === 3) {
if (eventsDict[e.nodeValue.trim()]) {
e.nodeValue = eventsDict[e.nodeValue.trim()];
}
}
// referral list
else if (e.nodeType === 1) {
if (eventsDict[$(e).text().trim()]) {
$(e).text(eventsDict[$(e).text().trim()]);
}
}
});
return;
}
/**
* new virus病毒
* You completed the Simple Virus which is now in your inventory. You can begin programming a new virus
* <a href="pc.php">here</a>
* .
*
* "简单病毒"
*/
if ($(e).text().indexOf('new virus') >= 0) {
const virusName = e.firstChild.nodeValue.split(' ').slice(3, 5).join(' ');
e.firstChild.nodeValue = `你完成了 ${virusName},它现在在你的物品库存中。你可以`;
e.childNodes[1].firstChild.nodeValue = '点此';
e.childNodes[2].nodeValue = '开始编程一个新的病毒。';
return;
}
/**
*
*/
if ($(e).text().contains(/You found .+ and .+ on your doorstep/)) {
const [item1, item2] = $(e).text().trim().slice(10, -18).split(' and ');
const bookTitle = item2.contains(/a book titled/) ? item2.slice(15, -1) : null;
if (bookTitle) {
$(e).text(`你在家门口发现了 ${item1.numWordTrans()} 和《${bookTitle}》。`);
} else {
$(e).text(`你在家门口发现了 ${item1.numWordTrans()}${item2.numWordTrans()}`);
}
return;
}
/**
*
if ($(e).text().contains(/used the reward bonus code/)) {
const code = $(e).text().trim().split(' ')[7];
if (eventsDict[$(e).text().trim().replace(code, '{$}')])
$(e).text(eventsDict[$(e).text().trim().replace(code, '{$}')]
.replace('{$}', code));
return;
}
/**
*
*/
if ($(e).text().contains(/accepted your proposal, you are now engaged/)) {
const spouse = $(e).children(':first').text().trim();
if (e.childNodes[1]) {
e.childNodes[1].nodeValue = ` 接受了你的求婚,你现在和 ${spouse} 订婚了!前往`;
}
if (e.childNodes[2] && e.childNodes[2].firstChild) {
e.childNodes[2].firstChild.nodeValue = `这里`;
}
if (e.childNodes[3]) {
e.childNodes[3].nodeValue = `完成仪式。`;
}
return;
}
/**
*
* Your position in
* <a href="factions.php?step=profile&amp;ID=36134" i-data="i_92_242_62_14">Silver Hand</a>
* changed from Recruit to Knight.
*/
if ($(e).text().indexOf('position') >= 0) {
let prePos, curPos;
const node3Spl = e.childNodes[2].nodeValue.split(' to ');
if (node3Spl.length === 2) {
prePos = node3Spl[0].slice(14, node3Spl[0].length);
curPos = node3Spl[1].slice(0, node3Spl[1].length - 2);
} else {
log('职位出现" to "');// todo
return;
}
e.firstChild.nodeValue = '你在 ';
e.childNodes[2].nodeValue = ` 的职位从 ${prePos} 变为 ${curPos}`;
return;
}
/**
*
*/
if ($(e).text().indexOf('join the faction') >= 0) {
const rsName = e.childNodes[2].nodeValue.trim().split(' ')[2];
const rsDict = {'accepted': '通过', 'declined': '拒绝',};
e.firstChild.nodeValue = '加入帮派 ';
e.childNodes[2].nodeValue = ` 的申请已${rsDict[rsName]}`;
return;
}
});
}

View File

@ -0,0 +1,11 @@
// mini profile 翻译
import playerStatusTrans from "./playerStatusTrans";
function miniprofTrans() {
// 迷你资料卡状态
playerStatusTrans($('div.profile-mini-root div.description span'));
// 转钱
sendCashTrans('div.profile-mini-root');
}
export default miniprofTrans

View File

@ -0,0 +1,30 @@
import {hosDict, statusDict} from "../../dictionary/translation";
/**
*
*/
function playerStatusTrans(slt) {
if (!slt) return;
slt.contents().each((i, e) => {
if (e.nodeType === 3) {
if (statusDict[e.nodeValue.trim()]) {
e.nodeValue = statusDict[e.nodeValue.trim()];
} else if (hosDict[e.nodeValue.trim()]) {
e.nodeValue = hosDict[e.nodeValue.trim()];
}
// 医院 监狱
else {
if (e.nodeValue.contains(/In hospital for/))
e.nodeValue = e.nodeValue
.replace('In hospital for', '住院')
.replaceHMS();
else if (e.nodeValue.contains(/In jail for/))
e.nodeValue = e.nodeValue
.replace('In jail for', '坐牢')
.replaceHMS();
}
}
});
}
export default playerStatusTrans

View File

@ -0,0 +1,26 @@
import {sendCashDict} from "../../dictionary/translation";
/**
*
*/
function sendCashTrans(domPath = '', buttonClass = '.send-cash') {
const sc = $(`${domPath} ${buttonClass} *`);
if (sc.length === 0) return;
sc.contents().each((i, e) => {
if (e.nodeType === 1) {
if (sendCashDict[$(e).attr('placeholder')]) {
$(e).attr('placeholder', sendCashDict[$(e).attr('placeholder')]);
return;
}
if (sendCashDict[$(e).attr('title')]) {
$(e).attr('title', sendCashDict[$(e).attr('title')]);
}
} else if (e.nodeType === 3) {
if (sendCashDict[e.nodeValue.trim()]) {
e.nodeValue = sendCashDict[e.nodeValue.trim()];
}
}
});
}
export default sendCashDict

63
function/utils/COFetch.ts Normal file
View File

@ -0,0 +1,63 @@
// 跨域get请求 返回text
import UserScriptEngine from "../../enum/UserScriptEngine";
function COFetch(url, method = 'get', body = null) {
const engine = getScriptEngine();
switch (engine) {
case UserScriptEngine.RAW: {
return new Promise((_, reject) => {
console.error(`[wh] 跨域请求错误:${UserScriptEngine.RAW}环境下无法进行跨域请求`);
reject(`错误:${UserScriptEngine.RAW}环境下无法进行跨域请求`);
});
}
case UserScriptEngine.PDA: {
const {PDA_httpGet, PDA_httpPost} = window;
return method === 'get' ?
// get
new Promise((resolve, reject) => {
if (typeof PDA_httpGet !== 'function') {
console.error('[wh] 跨域请求错误PDA版本不支持');
reject('错误PDA版本不支持');
}
PDA_httpGet(url)
.catch(e => {
console.error('[wh] 网络错误', e);
reject(`[wh] 网络错误 ${e}`);
})
.then(res => resolve(res.responseText));
}) :
// post
new Promise((resolve, reject) => {
if (typeof PDA_httpPost !== 'function') {
console.error('[wh] 跨域请求错误PDA版本不支持');
reject('错误PDA版本不支持');
}
PDA_httpPost(url, {'content-type': 'application/json'}, body)
.catch(e => {
console.error('[wh] 网络错误', e);
reject(`[wh] 网络错误 ${e}`);
})
.then(res => resolve(res.responseText));
});
}
case UserScriptEngine.GM: {
return new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'function') {
console.error('[wh] 跨域请求错误用户脚本扩展API错误');
reject('错误用户脚本扩展API错误');
}
GM_xmlhttpRequest({
method: method,
url: url,
data: method === 'get' ? null : body,
headers: method === 'get' ? null : {'content-type': 'application/json'},
onload: res => resolve(res.response),
onerror: res => reject(`连接错误 ${JSON.stringify(res)}`),
ontimeout: res => reject(`连接超时 ${JSON.stringify(res)}`),
});
});
}
}
}
export default COFetch

View File

@ -0,0 +1,25 @@
/**
* json对象
* @param dest
* @param time
*/
function autoFetchJSON(dest, time = 30) {
let obj;
const res = COFetch(dest);
setInterval(async () => {
if (!isWindowActive()) return;
const res = await COFetch(dest);
obj = JSON.parse(res);
}, time * 1000);
return {
get: async function () {
if (!obj) {
const str = await res
return obj = JSON.parse(str);
}
return obj;
}
};
}
export default autoFetchJSON

View File

@ -0,0 +1,20 @@
/**
* user
* @return {PlayerInfo} rs
*/
function getPlayerInfo(): PlayerInfo {
let rs = new PlayerInfo();
const node = document.querySelector('script[uid]');
if (node) {
rs.playername = node.getAttribute('name');
rs.userID = node.getAttribute('uid') as unknown as number;
}
return rs;
}
class PlayerInfo {
playername: string
userID: number
}
export default getPlayerInfo

View File

@ -0,0 +1,6 @@
// 插件的配置 getter
const getWhSettingObj = function (): Object {
return JSON.parse(localStorage.getItem('wh_trans_settings')) || {}
}
export default getWhSettingObj

12
function/utils/isDev.ts Normal file
View File

@ -0,0 +1,12 @@
import getWhSettingObj from "./getWhSettingObj";
const isDev = function () : boolean {
try {
return getWhSettingObj()['isDev'] || false;
} catch (e) {
console.error(`[wh] dev状态错误 ${e}`);
return false;
}
}
export default isDev

9
function/utils/log.ts Normal file
View File

@ -0,0 +1,9 @@
// console.log改写
import isDev from "./isDev";
const log = (...o) => (isDev()) && (console.log('[WH]', ...o))
log.error = (...o) => (isDev()) && (console.error('[WH]', ...o))
log.info = (...o) => (isDev()) && (console.log('[WH]', ...o))
export default log

7
global.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
declare interface String {
contains(keywords: RegExp): boolean
contains(keywords: String): boolean
}

67
init.ts Normal file
View File

@ -0,0 +1,67 @@
import './global'
import log from "./function/utils/log";
import getWhSettingObj from "./function/utils/getWhSettingObj";
import miniprofTrans from "./function/translate/miniprofTrans";
export default function init() {
const UWCopy: Window & typeof globalThis = window["unsafeWindow"];
try {
window = UWCopy || window;
} catch {
}
// 防止脚本重复运行
if (window["WHTRANS"]) throw new DOMException('已在运行');
window["WHTRANS"] = true;
// 脚本版本
const version = '$$WUHU_DEV_VERSION$$';
// iframe运行
const isIframe = self !== top;
const $ = window['jQuery'];
// PDA
const PDA_APIKey = '###PDA-APIKEY###';
const isPDA = PDA_APIKey.slice(-1) !== '#';
// 通知权限
if (window.Notification) {
Notification.requestPermission().then(status => {
// 这将使我们能在 Chrome/Safari 中使用 Notification.permission
if (Notification.permission !== status) {
// @ts-ignore
Notification['permission'] = status;
}
})
}
// regexp test
String.prototype.contains = function (keywords: RegExp) {
let that: String = this;
if ('string' === typeof keywords) {
return new RegExp(keywords).test(that);
}
if (keywords.test) {
return keywords.test(that);
}
};
// region 监听fetch
const ori_fetch = window.fetch;
window.fetch = async (url, init) => {
if (url.contains('newsTickers')) {
// 阻止获取新闻横幅
return new Response('{}');
}
const res = await ori_fetch(url, init);
// mini profile 翻译
if (url.includes('profiles.php?step=getUserNameContextMenu') && getWhSettingObj()['transEnable']) {
setTimeout(() => miniprofTrans(), 200);
}
let clone = res.clone();
let text = await res.text();
log({url, init, text});
return clone;
};
// endregion
return {version, isIframe, $, PDA_APIKey, isPDA};
}

2
main.ts Normal file
View File

@ -0,0 +1,2 @@
import userscript from "./userscript";
userscript();

24
package-lock.json generated
View File

@ -1,8 +1,30 @@
{ {
"name": "wuhu-torn-helper", "name": "wuhu-torn-helper",
"requires": true, "version": "0.4.6",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true,
"dependencies": { "dependencies": {
"@types/jquery": {
"version": "3.5.14",
"resolved": "https://registry.npmmirror.com/@types/jquery/-/jquery-3.5.14.tgz",
"integrity": "sha512-X1gtMRMbziVQkErhTQmSe2jFwwENA/Zr+PprCkF63vFq+Yt5PZ4AlKqgmeNlwgn7dhsXEK888eIW2520EpC+xg==",
"dev": true,
"requires": {
"@types/sizzle": "*"
}
},
"@types/node": {
"version": "18.0.6",
"resolved": "https://registry.npmmirror.com/@types/node/-/node-18.0.6.tgz",
"integrity": "sha512-/xUq6H2aQm261exT6iZTMifUySEt4GR5KX8eYyY+C4MSNPqSh9oNIP7tz2GLKTlFaiBbgZNxffoR3CVRG+cljw==",
"dev": true
},
"@types/sizzle": {
"version": "2.3.3",
"resolved": "https://registry.npmmirror.com/@types/sizzle/-/sizzle-2.3.3.tgz",
"integrity": "sha512-JYM8x9EGF163bEyhdJBpR2QX1R5naCJHC8ucJylJ3w9/CVBaskdQ8WqBf8MmQrd1kRvp/a4TS8HJ+bxzR7ZJYQ==",
"dev": true
},
"uglify-js": { "uglify-js": {
"version": "3.16.1", "version": "3.16.1",
"resolved": "https://registry.npmmirror.com/uglify-js/-/uglify-js-3.16.1.tgz", "resolved": "https://registry.npmmirror.com/uglify-js/-/uglify-js-3.16.1.tgz",

View File

@ -1,6 +1,6 @@
{ {
"name": "wuhu-torn-helper", "name": "wuhu-torn-helper",
"version": "0.4.6", "version": "0.4.7",
"dependencies": { "dependencies": {
"uglify-js": "^3.16.1" "uglify-js": "^3.16.1"
}, },
@ -9,5 +9,9 @@
"minify": "uglifyjs wuhu-torn-helper.js -o release.min.user.js -m", "minify": "uglifyjs wuhu-torn-helper.js -o release.min.user.js -m",
"serve": "", "serve": "",
"build": "" "build": ""
},
"devDependencies": {
"@types/jquery": "^3.5.14",
"@types/node": "^18.0.6"
} }
} }

File diff suppressed because one or more lines are too long

10
tsconfig.json Normal file
View File

@ -0,0 +1,10 @@
{
"compilerOptions": {
"lib": [
"es6",
"dom",
"es2015"
],
"target": "es5"
}
}

7750
userscript.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2794,7 +2794,7 @@
} }
let clone = res.clone(); let clone = res.clone();
let text = await res.text(); let text = await res.text();
log({ url, init, text }); log({url, init, text});
return clone; return clone;
}; };
// endregion // endregion
@ -2830,7 +2830,7 @@
let beer = buyBeer(); let beer = buyBeer();
let popup_node = null; let popup_node = null;
// 当窗口关闭时关闭所有还存在的通知 // 当窗口关闭时关闭所有还存在的通知
let notifies = { count: 0 }; let notifies = {count: 0};
window.addEventListener( window.addEventListener(
'beforeunload', 'beforeunload',
() => { () => {
@ -2850,62 +2850,62 @@
// 对新值应用「默认」设置 // 对新值应用「默认」设置
[ [
// 开启翻译 // 开启翻译
{ key: 'transEnable', val: false }, {key: 'transEnable', val: false},
// 快速犯罪 // 快速犯罪
{ key: 'quickCrime', val: true }, {key: 'quickCrime', val: true},
// 任务助手 // 任务助手
{ key: 'missionHint', val: true }, {key: 'missionHint', val: true},
// 小镇攻略 // 小镇攻略
{ key: 'xmasTownWT', val: true }, {key: 'xmasTownWT', val: true},
// 小镇提醒 // 小镇提醒
{ key: 'xmasTownNotify', val: true }, {key: 'xmasTownNotify', val: true},
// 起飞爆e // 起飞爆e
{ key: 'energyAlert', val: true }, {key: 'energyAlert', val: true},
// 飞行闹钟 // 飞行闹钟
{ key: 'trvAlarm', val: true }, {key: 'trvAlarm', val: true},
// 啤酒提醒 // 啤酒提醒
{ key: '_15Alarm', val: true }, {key: '_15Alarm', val: true},
// 捡垃圾助手 // 捡垃圾助手
{ key: 'cityFinder', val: false }, {key: 'cityFinder', val: false},
// 叠E保护 // 叠E保护
{ key: 'SEProtect', val: false }, {key: 'SEProtect', val: false},
// PT一键购买 // PT一键购买
{ key: 'ptQuickBuy', val: false }, {key: 'ptQuickBuy', val: false},
// 光速拔刀 6-关闭 // 光速拔刀 6-关闭
{ key: 'quickAttIndex', val: 2 }, {key: 'quickAttIndex', val: 2},
// 光速跑路 0-leave 1-mug 2-hos 3-关闭 // 光速跑路 0-leave 1-mug 2-hos 3-关闭
{ key: 'quickFinishAtt', val: 3 }, {key: 'quickFinishAtt', val: 3},
// 自动开打和结束 // 自动开打和结束
{ key: 'autoStartFinish', val: false }, {key: 'autoStartFinish', val: false},
// 废弃 // 废弃
{ key: 'attRelocate', val: true }, {key: 'attRelocate', val: true},
// 攻击自刷新 0-无间隔 1-5s 6-关闭 // 攻击自刷新 0-无间隔 1-5s 6-关闭
{ key: 'attReload', val: 6 }, {key: 'attReload', val: 6},
// 价格监视 // 价格监视
{ key: 'priceWatcher', val: { xan: -1, pt: -1 } }, {key: 'priceWatcher', val: {xan: -1, pt: -1}},
// 开发者模式 // 开发者模式
{ key: 'isDev', val: false }, {key: 'isDev', val: false},
// 啤酒提醒时间 // 啤酒提醒时间
{ key: '_15AlarmTime', val: 50 }, {key: '_15AlarmTime', val: 50},
// 4条转跳 // 4条转跳
{ key: 'barsRedirect', val: true }, {key: 'barsRedirect', val: true},
// 浮动存钱框 // 浮动存钱框
{ key: 'floatDepo', val: true }, {key: 'floatDepo', val: true},
// 公司转跳存钱 // 公司转跳存钱
{ key: 'companyRedirect', val: true }, {key: 'companyRedirect', val: true},
// 收起公司冰蛙效率表 // 收起公司冰蛙效率表
{ key: 'companyBWCollapse', val: true }, {key: 'companyBWCollapse', val: true},
// 清除多余的脚本 // 清除多余的脚本
{ key: 'removeScripts', val: true }, {key: 'removeScripts', val: true},
// 海外警告 // 海外警告
{ key: 'abroadWarning', val: true }, {key: 'abroadWarning', val: true},
// 落地转跳 // 落地转跳
{ key: 'landedRedirect', val: '' }, {key: 'landedRedirect', val: ''},
// 任何位置一键存钱 // 任何位置一键存钱
{ key: 'companyDepositAnywhere', val: false }, {key: 'companyDepositAnywhere', val: false},
// 危险行为⚠️ // 危险行为⚠️
{ key: 'dangerZone', val: false }, {key: 'dangerZone', val: false},
].forEach(df => { ].forEach(df => {
if (typeof getWhSettingObj()[df.key] !== typeof df.val) setWhSetting(df.key, df.val); if (typeof getWhSettingObj()[df.key] !== typeof df.val) setWhSetting(df.key, df.val);
}); });
@ -3076,7 +3076,7 @@
tip: '海外落地后每30秒通知警告', tip: '海外落地后每30秒通知警告',
}); });
// 落地转跳 // 落地转跳
setting_list.push({ domType: 'button', domId: '', domText: '落地转跳', clickFunc: landedRedirect }); setting_list.push({domType: 'button', domId: '', domText: '落地转跳', clickFunc: landedRedirect});
// 公司 // 公司
setting_list.push({ setting_list.push({
@ -3330,22 +3330,22 @@
let fest_date_html = '<button>节日</button>: '; let fest_date_html = '<button>节日</button>: ';
{ {
const fest_date_dict = { const fest_date_dict = {
'0105': { name: '周末自驾游', eff: '获得双倍的赛车点数与赛车技能等级增益' }, '0105': {name: '周末自驾游', eff: '获得双倍的赛车点数与赛车技能等级增益'},
'0114': { name: '情人节', eff: '使用爱情果汁(Love Juice)后获得降低攻击与复活的能量消耗的增益' }, '0114': {name: '情人节', eff: '使用爱情果汁(Love Juice)后获得降低攻击与复活的能量消耗的增益'},
'0204': { name: '员工激励日', eff: '获得三倍的工作点数与火车增益' }, '0204': {name: '员工激励日', eff: '获得三倍的工作点数与火车增益'},
'0217': { name: '圣帕特里克日', eff: '获得双倍的酒类效果增益,城市中可以捡到绿色世涛(Green Stout)' }, '0217': {name: '圣帕特里克日', eff: '获得双倍的酒类效果增益,城市中可以捡到绿色世涛(Green Stout)'},
'0320': { name: '420日', eff: '获得三倍的大麻(Cannabis)效果增益' }, '0320': {name: '420日', eff: '获得三倍的大麻(Cannabis)效果增益'},
'0418': { name: '博物馆日', eff: '获得10%提高的博物馆PT兑换增益' }, '0418': {name: '博物馆日', eff: '获得10%提高的博物馆PT兑换增益'},
'0514': { name: '世界献血日', eff: '获得减半的抽血CD和扣血增益' }, '0514': {name: '世界献血日', eff: '获得减半的抽血CD和扣血增益'},
'0611': { name: '世界人口日', eff: '获得双倍的通过攻击获取的经验的增益' }, '0611': {name: '世界人口日', eff: '获得双倍的通过攻击获取的经验的增益'},
'0629': { name: '世界老虎日', eff: '获得5倍的狩猎技能增益' }, '0629': {name: '世界老虎日', eff: '获得5倍的狩猎技能增益'},
'0705': { name: '国际啤酒节', eff: '获得5倍的啤酒物品效果增益' }, '0705': {name: '国际啤酒节', eff: '获得5倍的啤酒物品效果增益'},
'0827': { name: '旅游节', eff: '获得双倍的起飞后物品携带容量增益' }, '0827': {name: '旅游节', eff: '获得双倍的起飞后物品携带容量增益'},
'0915': { name: '饮料节', eff: '获得双倍的能量饮料效果增益' }, '0915': {name: '饮料节', eff: '获得双倍的能量饮料效果增益'},
'1014': { name: '世界糖尿病日', eff: '获得三倍的糖类效果增益' }, '1014': {name: '世界糖尿病日', eff: '获得三倍的糖类效果增益'},
'1015': { name: '周年庆', eff: '左上角的TORN图标可以食用' }, '1015': {name: '周年庆', eff: '左上角的TORN图标可以食用'},
'1025': { name: '黑色星期五', eff: '某些商家将提供1元购活动' }, '1025': {name: '黑色星期五', eff: '某些商家将提供1元购活动'},
'1114': { name: '住院日', eff: '获得降低75%的住院时间增益' }, '1114': {name: '住院日', eff: '获得降低75%的住院时间增益'},
}; };
menu_list.fest_date_dict = fest_date_dict; menu_list.fest_date_dict = fest_date_dict;
menu_list.fest_date_list = Object.keys(fest_date_dict); menu_list.fest_date_list = Object.keys(fest_date_dict);
@ -3901,9 +3901,9 @@ background-size: 100% auto !important;
new MutationObserver((m, o) => { new MutationObserver((m, o) => {
o.disconnect(); o.disconnect();
if (!elem.querySelector('.wh-translate')) elem.prepend(mobile_prepend_node); if (!elem.querySelector('.wh-translate')) elem.prepend(mobile_prepend_node);
o.observe(elem, { childList: true, subtree: true }); o.observe(elem, {childList: true, subtree: true});
}) })
.observe(elem, { childList: true, subtree: true }); .observe(elem, {childList: true, subtree: true});
}); });
// 隐藏返回顶部按钮 // 隐藏返回顶部按钮
elementReady('#go-to-top-btn button', ifDocu).then(e => e.style.display = 'none'); elementReady('#go-to-top-btn button', ifDocu).then(e => e.style.display = 'none');
@ -4003,7 +4003,7 @@ background-size: 100% auto !important;
<tr><td>URL</td><td>${window.location.href}</td></tr> <tr><td>URL</td><td>${window.location.href}</td></tr>
<tr><td>页面尺寸</td><td>${window.innerWidth}x${window.innerHeight}</td></tr> <tr><td>页面尺寸</td><td>${window.innerWidth}x${window.innerHeight}</td></tr>
<tr><td>设备类型</td><td>${getDeviceType().toUpperCase()}</td></tr> <tr><td>设备类型</td><td>${getDeviceType().toUpperCase()}</td></tr>
<tr><td>脚本运行方式</td><td>${{ 'gm': '', 'raw': '', 'pda': 'TornPDA' }[getScriptEngine()]}</td></tr> <tr><td>脚本运行方式</td><td>${{'gm': '', 'raw': '', 'pda': 'TornPDA'}[getScriptEngine()]}</td></tr>
<tr><td>时间</td><td>${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}</td></tr> <tr><td>时间</td><td>${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}</td></tr>
<tr><td>插件版本</td><td>${version}</td></tr> <tr><td>插件版本</td><td>${version}</td></tr>
<tr><td>操作系统</td><td>${os}</td></tr> <tr><td>操作系统</td><td>${os}</td></tr>
@ -4029,7 +4029,7 @@ color:black;
domId: '', domId: '',
domText: '📐️ 测试', domText: '📐️ 测试',
clickFunc: function () { clickFunc: function () {
WHNotify('芜湖助手', { sysNotify: true, timeout: 15 }) WHNotify('芜湖助手', {sysNotify: true, timeout: 15})
}, },
}); });
// endregion // endregion
@ -4252,7 +4252,7 @@ cursor:pointer;
// region 存钱 不终止 // region 存钱 不终止
let depo_channel; let depo_channel;
const depo_selector = { CMPY: "div#funds div.deposit", FAC: "div#armoury-donate div.cash" }; const depo_selector = {CMPY: "div#funds div.deposit", FAC: "div#armoury-donate div.cash"};
// 公司 // 公司
if (href.includes('companies.php')) { if (href.includes('companies.php')) {
depo_channel = "CMPY"; depo_channel = "CMPY";
@ -4330,11 +4330,11 @@ z-index: 999999;}`);
let getTraceMoney = async () => { let getTraceMoney = async () => {
if (typeof addRFC === 'function') { if (typeof addRFC === 'function') {
let url = addRFC('/trade.php?step=getFullMoney&ID=' + traceId); let url = addRFC('/trade.php?step=getFullMoney&ID=' + traceId);
return (await ajaxFetch({ url: url, method: 'GET', referrer: 'trade.php' })).text(); return (await ajaxFetch({url: url, method: 'GET', referrer: 'trade.php'})).text();
} }
}; };
// 监听jquery ajax请求 // 监听jquery ajax请求
if (isDev()) $(document).ajaxComplete((_, xhr, settings) => log({ xhr, settings })); if (isDev()) $(document).ajaxComplete((_, xhr, settings) => log({xhr, settings}));
// react 加载完成后将节点加入视图中 // react 加载完成后将节点加入视图中
elementReady('#trade-container').then(() => elementReady('#trade-container').then(() =>
document.querySelector('#trade-container').before(node) document.querySelector('#trade-container').before(node)
@ -4377,7 +4377,7 @@ z-index: 999999;}`);
return; return;
} }
let money = await getTraceMoney(); let money = await getTraceMoney();
let int = { 'input': inputMoney.value | 0, 'all': money | 0 }; let int = {'input': inputMoney.value | 0, 'all': money | 0};
let diff = int.all - int.input; let diff = int.all - int.input;
if (diff < 1) { if (diff < 1) {
WHNotify('无法定额取钱,原因:数不对'); WHNotify('无法定额取钱,原因:数不对');
@ -4442,7 +4442,7 @@ z-index: 999999;}`);
const wh_trv_alarm = localStorage.getItem('wh_trv_alarm') const wh_trv_alarm = localStorage.getItem('wh_trv_alarm')
? JSON.parse(localStorage.getItem('wh_trv_alarm')) ? JSON.parse(localStorage.getItem('wh_trv_alarm'))
: { 'enable': true, 'alert_time': 30, 'node_pos': [240, 240] }; : {'enable': true, 'alert_time': 30, 'node_pos': [240, 240]};
const save_trv_settings = () => localStorage.setItem('wh_trv_alarm', JSON.stringify(wh_trv_alarm)); const save_trv_settings = () => localStorage.setItem('wh_trv_alarm', JSON.stringify(wh_trv_alarm));
const wh_trv_alarm_node = document.createElement('div'); const wh_trv_alarm_node = document.createElement('div');
@ -4655,7 +4655,7 @@ display:none;
// 落地转跳 // 落地转跳
if (getWhSettingObj()['landedRedirect'] && document.querySelector('#tcLogo[title]') === null) { if (getWhSettingObj()['landedRedirect'] && document.querySelector('#tcLogo[title]') === null) {
window.addEventListener('beforeunload', () => { window.addEventListener('beforeunload', () => {
let obj = { url: getWhSettingObj()['landedRedirect'], timestamp: Date.now() }; let obj = {url: getWhSettingObj()['landedRedirect'], timestamp: Date.now()};
sessionStorage['wh-landed-redirect'] = JSON.stringify(obj); sessionStorage['wh-landed-redirect'] = JSON.stringify(obj);
}); });
} }
@ -4668,7 +4668,7 @@ display:none;
// 海外警告 // 海外警告
if (getWhSettingObj()['abroadWarning']) { if (getWhSettingObj()['abroadWarning']) {
let c = 1; let c = 1;
setInterval(() => WHNotify(`警告:您已海外落地${c++ * 30}`, { timeout: 30, sysNotify: true }), 30000); setInterval(() => WHNotify(`警告:您已海外落地${c++ * 30}`, {timeout: 30, sysNotify: true}), 30000);
} }
// 解毒提醒 // 解毒提醒
if (getSidebarData()['rehabilitation']) { if (getSidebarData()['rehabilitation']) {
@ -4688,7 +4688,7 @@ display:none;
} }
// 落地转跳 // 落地转跳
else if (href.includes('index.php') && getSidebarData()['home'] && sessionStorage['wh-landed-redirect']) { else if (href.includes('index.php') && getSidebarData()['home'] && sessionStorage['wh-landed-redirect']) {
let { url, timestamp } = JSON.parse(sessionStorage['wh-landed-redirect']); let {url, timestamp} = JSON.parse(sessionStorage['wh-landed-redirect']);
if (Date.now() - timestamp < 30000) { if (Date.now() - timestamp < 30000) {
sessionStorage.removeItem('wh-landed-redirect'); sessionStorage.removeItem('wh-landed-redirect');
location.href = url; location.href = url;
@ -4752,7 +4752,7 @@ display:none;
// 攻击页面 // 攻击页面
if (href.contains(/loader\.php\?sid=attack/)) { if (href.contains(/loader\.php\?sid=attack/)) {
let stop_reload = false; let stop_reload = false;
const { quickAttIndex, quickFinishAtt, attReload } = getWhSettingObj(); const {quickAttIndex, quickFinishAtt, attReload} = getWhSettingObj();
// 光速刷新按钮 // 光速刷新按钮
addActionBtn('光速刷新', doAttackReload, $zhongNode); addActionBtn('光速刷新', doAttackReload, $zhongNode);
@ -4975,7 +4975,7 @@ display:none;
} }
} }
}); });
}).observe(wrap, { subtree: true, attributes: true, childList: true }); }).observe(wrap, {subtree: true, attributes: true, childList: true});
} }
return; return;
} }
@ -5067,7 +5067,7 @@ display:inline-block;
const finder_item = document.createElement('span'); const finder_item = document.createElement('span');
finder_item.id = 'wh-city-finder-item' + item_id; finder_item.id = 'wh-city-finder-item' + item_id;
finder_item.innerHTML = item_id; finder_item.innerHTML = item_id;
founds.push({ 'id': item_id, 'node': finder_item, 'map_item': node }); founds.push({'id': item_id, 'node': finder_item, 'map_item': node});
container.append(finder_item); container.append(finder_item);
}); });
// 未发现物品 返回 // 未发现物品 返回
@ -5146,7 +5146,7 @@ display:inline-block;
'LI' === e.tagName && rmv_cfm(e) 'LI' === e.tagName && rmv_cfm(e)
} }
} }
}).observe(points_sales, { childList: true }); }).observe(points_sales, {childList: true});
} }
// 叠e助手 // 叠e助手
@ -5259,8 +5259,8 @@ $<span class="total">1,000</span>
}); });
// 监听啤酒购买 // 监听啤酒购买
$(document).ajaxComplete((_, xhr, settings) => { $(document).ajaxComplete((_, xhr, settings) => {
log({ xhr, settings }); log({xhr, settings});
let { data } = settings, { responseText } = xhr; let {data} = settings, {responseText} = xhr;
let response = JSON.parse(responseText); let response = JSON.parse(responseText);
if (data.includes('step=buyShopItem') && data.includes('ID=180') && response['success']) { if (data.includes('step=buyShopItem') && data.includes('ID=180') && response['success']) {
WHNotify('已检测成功购买啤酒') WHNotify('已检测成功购买啤酒')
@ -5410,7 +5410,7 @@ $<span class="total">1,000</span>
// 圣诞小镇 // 圣诞小镇
if (href.contains(/christmas_town\.php/)) { if (href.contains(/christmas_town\.php/)) {
let $root = document.querySelector('#christmastownroot'); let $root = document.querySelector('#christmastownroot');
const { xmasTownWT, xmasTownNotify } = getWhSettingObj() const {xmasTownWT, xmasTownNotify} = getWhSettingObj()
// 解密攻略 // 解密攻略
if (xmasTownWT) { if (xmasTownWT) {
const insert_html = `<div id="wh-xmas-cont"> const insert_html = `<div id="wh-xmas-cont">
@ -5447,7 +5447,7 @@ margin: 0 0 3px;
} }
</style>`; </style>`;
const wt_dict = { const wt_dict = {
"None": { title: '', wt: ``, }, "None": {title: '', wt: ``,},
"Christmas Town": { "Christmas Town": {
title: '圣诞小镇', wt: `<ul> title: '圣诞小镇', wt: `<ul>
<li>旧攻略提到的驯鹿车已被移除只能手动找一条蓝色的小路[94,3]</li> <li>旧攻略提到的驯鹿车已被移除只能手动找一条蓝色的小路[94,3]</li>
@ -5716,16 +5716,16 @@ margin: 0 0 3px;
} }
// 宝箱检测 // 宝箱检测
if (xmasTownNotify) { if (xmasTownNotify) {
const chestTypeDict = { '1': '金', '2': '银', '3': '铜', }; const chestTypeDict = {'1': '金', '2': '银', '3': '铜',};
const chestTypeColorDict = { '1': 'gold', '2': 'silver', '3': 'sandybrown', }; const chestTypeColorDict = {'1': 'gold', '2': 'silver', '3': 'sandybrown',};
const lootTypeDict = { 'chests': '钥匙箱', 'gifts': '礼物', 'combinationChest': '密码箱', 'keys': '钥匙', }; const lootTypeDict = {'chests': '钥匙箱', 'gifts': '礼物', 'combinationChest': '密码箱', 'keys': '钥匙',};
const keyTypeDict = { 'b': '铜', 's': '银', 'g': '金', }; const keyTypeDict = {'b': '铜', 's': '银', 'g': '金',};
let dropHist = localStorage.getItem('wh-loot-store') let dropHist = localStorage.getItem('wh-loot-store')
? JSON.parse(localStorage.getItem('wh-loot-store')) ? JSON.parse(localStorage.getItem('wh-loot-store'))
: {}; : {};
const alertSettings = localStorage.getItem('wh-loot-setting') const alertSettings = localStorage.getItem('wh-loot-setting')
? JSON.parse(localStorage.getItem('wh-loot-setting')) ? JSON.parse(localStorage.getItem('wh-loot-setting'))
: { blink: 'y', sound: 'y', chest: 'y' }; : {blink: 'y', sound: 'y', chest: 'y'};
let $ct_wrap; let $ct_wrap;
let soundLoopFlag = false; let soundLoopFlag = false;
const getDOMOb = new MutationObserver(() => { const getDOMOb = new MutationObserver(() => {
@ -5836,7 +5836,7 @@ margin: 0 0 3px;
const soundIntervalID = window.setInterval(() => { const soundIntervalID = window.setInterval(() => {
if (soundLoopFlag) $audio.play().then(); if (soundLoopFlag) $audio.play().then();
}, 1200); }, 1200);
ob.observe($root, { childList: true, subtree: true }); ob.observe($root, {childList: true, subtree: true});
} }
}); });
const ob = new MutationObserver(() => { const ob = new MutationObserver(() => {
@ -5845,13 +5845,13 @@ margin: 0 0 3px;
$root = document.querySelector('#christmastownroot'); $root = document.querySelector('#christmastownroot');
$ct_wrap = $root.querySelector('#ct-wrap'); $ct_wrap = $root.querySelector('#ct-wrap');
if (!$ct_wrap) { if (!$ct_wrap) {
ob.observe($root, { childList: true, subtree: true }); ob.observe($root, {childList: true, subtree: true});
return; return;
} }
const $ct_title = $ct_wrap.querySelector('.status-title'); const $ct_title = $ct_wrap.querySelector('.status-title');
const $pos = $ct_wrap.querySelector('.map-title span[class^="position___"]') || $ct_wrap.querySelector('.status-title span[class^="position___"]'); const $pos = $ct_wrap.querySelector('.map-title span[class^="position___"]') || $ct_wrap.querySelector('.status-title span[class^="position___"]');
if (!$pos) { if (!$pos) {
ob.observe($root, { childList: true, subtree: true }); ob.observe($root, {childList: true, subtree: true});
return; return;
} }
const $pos_spl = $pos.innerText.trim().split(','); const $pos_spl = $pos.innerText.trim().split(',');
@ -5861,7 +5861,7 @@ margin: 0 0 3px;
const $wh_loot_container = $root.querySelector('#wh-loot-container'); const $wh_loot_container = $root.querySelector('#wh-loot-container');
if (!$wh_loot_container) { if (!$wh_loot_container) {
console.error('掉落助手未找到DOM容器'); console.error('掉落助手未找到DOM容器');
ob.observe($root, { childList: true, subtree: true }); ob.observe($root, {childList: true, subtree: true});
return; return;
} }
const $blink = $wh_loot_container.querySelector('#wh-loot-setting-blink'); const $blink = $wh_loot_container.querySelector('#wh-loot-setting-blink');
@ -5872,7 +5872,7 @@ margin: 0 0 3px;
const items = $root.querySelectorAll('div.grid-layer div.items-layer div.ct-item'); const items = $root.querySelectorAll('div.grid-layer div.items-layer div.ct-item');
// 附近的所有物品 // 附近的所有物品
items.forEach(el => { items.forEach(el => {
const item_props = { x: 0, y: 0, name: '', type: '', url: '', }; const item_props = {x: 0, y: 0, name: '', type: '', url: '',};
item_props.x = parseInt(el.style.left.replaceAll('px', '')) / 30; item_props.x = parseInt(el.style.left.replaceAll('px', '')) / 30;
item_props.y = -parseInt(el.style.top.replaceAll('px', '')) / 30; item_props.y = -parseInt(el.style.top.replaceAll('px', '')) / 30;
item_props.url = el.firstElementChild.src; item_props.url = el.firstElementChild.src;
@ -5946,9 +5946,9 @@ margin: 0 0 3px;
}); });
$tbody.innerHTML = table_html; $tbody.innerHTML = table_html;
localStorage.setItem('wh-loot-store', JSON.stringify(dropHist)); localStorage.setItem('wh-loot-store', JSON.stringify(dropHist));
ob.observe($root, { childList: true, subtree: true }); ob.observe($root, {childList: true, subtree: true});
}); });
getDOMOb.observe($root, { childList: true, subtree: true }); getDOMOb.observe($root, {childList: true, subtree: true});
} }
} }
@ -6825,7 +6825,7 @@ margin: 0 0 3px;
*/ */
if ($(e).text().indexOf('join the faction') >= 0) { if ($(e).text().indexOf('join the faction') >= 0) {
const rsName = e.childNodes[2].nodeValue.trim().split(' ')[2]; const rsName = e.childNodes[2].nodeValue.trim().split(' ')[2];
const rsDict = { 'accepted': '通过', 'declined': '拒绝', }; const rsDict = {'accepted': '通过', 'declined': '拒绝',};
e.firstChild.nodeValue = '加入帮派 '; e.firstChild.nodeValue = '加入帮派 ';
e.childNodes[2].nodeValue = ` 的申请已${rsDict[rsName]}`; e.childNodes[2].nodeValue = ` 的申请已${rsDict[rsName]}`;
return; return;
@ -7202,7 +7202,7 @@ margin: 0 0 3px;
observer.disconnect(); observer.disconnect();
}); });
}) })
.observe(content.documentElement, { childList: true, subtree: true }); .observe(content.documentElement, {childList: true, subtree: true});
}); });
} }
@ -7236,7 +7236,7 @@ margin: 0 0 3px;
}); });
} }
case UserScriptEngine.PDA: { case UserScriptEngine.PDA: {
const { PDA_httpGet, PDA_httpPost } = window; const {PDA_httpGet, PDA_httpPost} = window;
return method === 'get' ? return method === 'get' ?
// get // get
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
@ -7257,7 +7257,7 @@ margin: 0 0 3px;
console.error('[wh] 跨域请求错误PDA版本不支持'); console.error('[wh] 跨域请求错误PDA版本不支持');
reject('错误PDA版本不支持'); reject('错误PDA版本不支持');
} }
PDA_httpPost(url, { 'content-type': 'application/json' }, body) PDA_httpPost(url, {'content-type': 'application/json'}, body)
.catch(e => { .catch(e => {
console.error('[wh] 网络错误', e); console.error('[wh] 网络错误', e);
reject(`[wh] 网络错误 ${e}`); reject(`[wh] 网络错误 ${e}`);
@ -7275,7 +7275,7 @@ margin: 0 0 3px;
method: method, method: method,
url: url, url: url,
data: method === 'get' ? null : body, data: method === 'get' ? null : body,
headers: method === 'get' ? null : { 'content-type': 'application/json' }, headers: method === 'get' ? null : {'content-type': 'application/json'},
onload: res => resolve(res.response), onload: res => resolve(res.response),
onerror: res => reject(`连接错误 ${JSON.stringify(res)}`), onerror: res => reject(`连接错误 ${JSON.stringify(res)}`),
ontimeout: res => reject(`连接超时 ${JSON.stringify(res)}`), ontimeout: res => reject(`连接超时 ${JSON.stringify(res)}`),
@ -7489,7 +7489,7 @@ z-index:100001;
_window.GM_setValue("gsp_x", 10); _window.GM_setValue("gsp_x", 10);
_window.GM_setValue("gsp_y", 10); _window.GM_setValue("gsp_y", 10);
notify.del(); notify.del();
notify = WHNotify('飞贼小助手已加载', { timeout: 1 }); notify = WHNotify('飞贼小助手已加载', {timeout: 1});
const gsp = _docu.querySelector('#gsp'); const gsp = _docu.querySelector('#gsp');
const init = () => { const init = () => {
ifr.style.height = `${gsp.offsetHeight + 10}px`; ifr.style.height = `${gsp.offsetHeight + 10}px`;
@ -7497,7 +7497,7 @@ z-index:100001;
gsp.style.top = '10px'; gsp.style.top = '10px';
gsp.style.left = '10px'; gsp.style.left = '10px';
}; };
new MutationObserver(init).observe(gsp, { childList: true, subtree: true }); new MutationObserver(init).observe(gsp, {childList: true, subtree: true});
init(); init();
if (isDev()) _window.GM_setValue("gsp_showContent", true) if (isDev()) _window.GM_setValue("gsp_showContent", true)
}); });
@ -7574,7 +7574,7 @@ z-index:100001;
* @return {{playername: string, userID: number}} * @return {{playername: string, userID: number}}
*/ */
function getPlayerInfo() { function getPlayerInfo() {
const rs = { playername: '未知', userID: -1 }; const rs = {playername: '未知', userID: -1};
// const headerData = JSON.parse(sessionStorage['headerData']); // const headerData = JSON.parse(sessionStorage['headerData']);
// if (!headerData['user']['state']['isLoggedIn']) return rs; // if (!headerData['user']['state']['isLoggedIn']) return rs;
// // string // // string
@ -7637,7 +7637,7 @@ z-index:100001;
if (price_conf['pt'] !== -1) priceWatcherPt(apikey, price_conf['pt']).then(); if (price_conf['pt'] !== -1) priceWatcherPt(apikey, price_conf['pt']).then();
if (price_conf['xan'] !== -1) priceWatcherXan(apikey, price_conf['xan']).then(); if (price_conf['xan'] !== -1) priceWatcherXan(apikey, price_conf['xan']).then();
}, 10000) }, 10000)
return { status: true }; return {status: true};
} }
// pt价格监视 // pt价格监视
@ -7811,7 +7811,7 @@ z-index:100001;
const headerOB = new MutationObserver(_ => { const headerOB = new MutationObserver(_ => {
headerOB.disconnect(); headerOB.disconnect();
headerTrans(); headerTrans();
headerOB.observe($('div#header-root')[0], { childList: true, subtree: true, attributes: true }); headerOB.observe($('div#header-root')[0], {childList: true, subtree: true, attributes: true});
}); });
const headerTrans = function headerTrans() { const headerTrans = function headerTrans() {
@ -7885,7 +7885,7 @@ z-index:100001;
}); });
}; };
headerTrans(); headerTrans();
headerOB.observe($('div#header-root')[0], { childList: true, subtree: true, attributes: true }); headerOB.observe($('div#header-root')[0], {childList: true, subtree: true, attributes: true});
} }
// chatbox // chatbox
@ -7893,7 +7893,7 @@ z-index:100001;
const chatOB = new MutationObserver(_ => { const chatOB = new MutationObserver(_ => {
chatOB.disconnect(); chatOB.disconnect();
chatTrans(); chatTrans();
chatOB.observe($('div#chatRoot').get(0), { childList: true, subtree: true, attributes: true }); chatOB.observe($('div#chatRoot').get(0), {childList: true, subtree: true, attributes: true});
}); });
const chatTrans = function chatTrans() { const chatTrans = function chatTrans() {
// 聊天框的标题 // 聊天框的标题
@ -7943,7 +7943,7 @@ z-index:100001;
} }
}; };
chatTrans(); chatTrans();
chatOB.observe($('div#chatRoot').get(0), { childList: true, subtree: true, attributes: true }); chatOB.observe($('div#chatRoot').get(0), {childList: true, subtree: true, attributes: true});
} }
// 搜索玩家的4个分类按钮 // 搜索玩家的4个分类按钮
@ -7977,7 +7977,7 @@ z-index:100001;
function travelOBInit() { function travelOBInit() {
travelOB.disconnect(); travelOB.disconnect();
travelTrans(); travelTrans();
travelOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); travelOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
} }
function travelTrans() { function travelTrans() {
@ -8002,7 +8002,7 @@ z-index:100001;
} }
travelTrans(); travelTrans();
travelOB.observe(document.querySelector('div.content-wrapper'), { childList: true, subtree: true }); travelOB.observe(document.querySelector('div.content-wrapper'), {childList: true, subtree: true});
} }
// 主页 // 主页
@ -8059,7 +8059,7 @@ z-index:100001;
function cityOBInit() { function cityOBInit() {
cityOB.disconnect(); cityOB.disconnect();
cityTrans(); cityTrans();
cityOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); cityOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
} }
function cityTrans() { function cityTrans() {
@ -8129,7 +8129,7 @@ z-index:100001;
} }
cityTrans(); cityTrans();
cityOB.observe(document.querySelector('div.content-wrapper'), { childList: true, subtree: true }); cityOB.observe(document.querySelector('div.content-wrapper'), {childList: true, subtree: true});
return; return;
} }
@ -8140,7 +8140,7 @@ z-index:100001;
function gymOBInit() { function gymOBInit() {
gymOB.disconnect(); gymOB.disconnect();
gymTrans(); gymTrans();
gymOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true, attributes: true }); gymOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true, attributes: true});
} }
function gymTrans() { function gymTrans() {
@ -8244,7 +8244,7 @@ z-index:100001;
} }
gymTrans(); gymTrans();
gymOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true, attributes: true }); gymOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true, attributes: true});
return; return;
} }
@ -8252,7 +8252,7 @@ z-index:100001;
if (href.contains(/item\.php/)) { if (href.contains(/item\.php/)) {
if (href.includes('item.php?temp=')) return; if (href.includes('item.php?temp=')) return;
// 标题和右边的链接 // 标题和右边的链接
initOB(document.querySelector('.content-title'), { childList: true }, initOB(document.querySelector('.content-title'), {childList: true},
() => { () => {
titleTrans(); titleTrans();
contentTitleLinksTrans(); contentTitleLinksTrans();
@ -8260,7 +8260,7 @@ z-index:100001;
// 套装预览中间的文字 // 套装预览中间的文字
const $loadouts_root = document.getElementById('loadoutsRoot'); const $loadouts_root = document.getElementById('loadoutsRoot');
if ($loadouts_root) { if ($loadouts_root) {
initOB($loadouts_root, { subtree: true, attributes: true }, () => { initOB($loadouts_root, {subtree: true, attributes: true}, () => {
const el = $loadouts_root.querySelector('div[class^="type___"]'); const el = $loadouts_root.querySelector('div[class^="type___"]');
if (el && itemPageDict[el.innerText.trim()]) { if (el && itemPageDict[el.innerText.trim()]) {
el.innerText = itemPageDict[el.innerText.trim()]; el.innerText = itemPageDict[el.innerText.trim()];
@ -8273,8 +8273,8 @@ z-index:100001;
subtree: true, subtree: true,
attributeFilter: ["aria-hidden",] attributeFilter: ["aria-hidden",]
}; };
const translated = { cat: '', count: -1 }; const translated = {cat: '', count: -1};
const translatedOnce = { item_opt: -1, opt_icon_count: -1 }; const translatedOnce = {item_opt: -1, opt_icon_count: -1};
initOB(document.getElementById('category-wrap'), options, () => { initOB(document.getElementById('category-wrap'), options, () => {
// 手机操作选项 // 手机操作选项
const $item_opt = document.querySelectorAll(`ul.itemsList span.opt-name`); const $item_opt = document.querySelectorAll(`ul.itemsList span.opt-name`);
@ -8343,7 +8343,7 @@ z-index:100001;
} }
// 黑框分类标题 // 黑框分类标题
const $items_type_name = $title_black.querySelector('span.items-name'); const $items_type_name = $title_black.querySelector('span.items-name');
initOB($items_type_name, { childList: true }, () => { initOB($items_type_name, {childList: true}, () => {
if (itemPageDict[$items_type_name.innerText.trim()]) { if (itemPageDict[$items_type_name.innerText.trim()]) {
$items_type_name.innerText = itemPageDict[$items_type_name.innerText.trim()]; $items_type_name.innerText = itemPageDict[$items_type_name.innerText.trim()];
} }
@ -8363,7 +8363,7 @@ z-index:100001;
if (href.contains(/(shops|bigalgunshop)\.php/)) { if (href.contains(/(shops|bigalgunshop)\.php/)) {
// 标题和右边的链接 // 标题和右边的链接
const $cont_title = document.querySelector('.content-title'); const $cont_title = document.querySelector('.content-title');
initOB($cont_title, { childList: true, subtree: true }, () => { initOB($cont_title, {childList: true, subtree: true}, () => {
titleTrans(); titleTrans();
contentTitleLinksTrans(); contentTitleLinksTrans();
}); });
@ -8416,7 +8416,7 @@ z-index:100001;
}); });
}); });
// 展开的物品详情 // 展开的物品详情
initOB($wrapper, { childList: true, subtree: true }, () => { initOB($wrapper, {childList: true, subtree: true}, () => {
const $item_desc = $wrapper.querySelector('.show-item-info') || $wrapper.querySelector('.view-item-info'); const $item_desc = $wrapper.querySelector('.show-item-info') || $wrapper.querySelector('.view-item-info');
showItemInfoTrans($item_desc); showItemInfoTrans($item_desc);
}); });
@ -8458,7 +8458,7 @@ z-index:100001;
// select btn // select btn
const $select_btn = $sell_items_wrapper.querySelector('li.select button.wai-btn'); const $select_btn = $sell_items_wrapper.querySelector('li.select button.wai-btn');
if ($select_btn) { if ($select_btn) {
initOB($select_btn, { childList: true }, () => { initOB($select_btn, {childList: true}, () => {
if ($select_btn && npcShopDict[$select_btn.innerText.trim()]) { if ($select_btn && npcShopDict[$select_btn.innerText.trim()]) {
$select_btn.innerText = npcShopDict[$select_btn.innerText.trim()]; $select_btn.innerText = npcShopDict[$select_btn.innerText.trim()];
} }
@ -8612,7 +8612,7 @@ z-index:100001;
function eduOBInit() { function eduOBInit() {
eduOB.disconnect(); eduOB.disconnect();
eduTrans(); eduTrans();
eduOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); eduOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
} }
function eduTrans() { function eduTrans() {
@ -8697,7 +8697,7 @@ z-index:100001;
} }
eduTrans(); eduTrans();
eduOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); eduOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
return; return;
} }
@ -8928,7 +8928,7 @@ z-index:100001;
const newspaperOB = new MutationObserver(() => { const newspaperOB = new MutationObserver(() => {
newspaperOB.disconnect(); newspaperOB.disconnect();
newspaperTrans(); newspaperTrans();
newspaperOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); newspaperOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
}); });
function newspaperTrans() { function newspaperTrans() {
@ -8948,7 +8948,7 @@ z-index:100001;
if ($date_label && $date_label.innerText.trim().contains(date_reg)) { if ($date_label && $date_label.innerText.trim().contains(date_reg)) {
const date_format = $date_label.innerText.trim().replaceAll(',', ''); const date_format = $date_label.innerText.trim().replaceAll(',', '');
const date_spl = date_format.split(' '); const date_spl = date_format.split(' ');
const date = { w: date_spl[0], m: date_spl[1], d: date_spl[2], y: date_spl[3] }; const date = {w: date_spl[0], m: date_spl[1], d: date_spl[2], y: date_spl[3]};
const month_trans = { const month_trans = {
'Jan': 1, 'Jan': 1,
'Feb': 2, 'Feb': 2,
@ -9107,7 +9107,7 @@ z-index:100001;
} }
newspaperTrans(); newspaperTrans();
newspaperOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); newspaperOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
return; return;
} }
@ -9134,7 +9134,7 @@ z-index:100001;
titleTrans(); titleTrans();
contentTitleLinksTrans(); contentTitleLinksTrans();
propertyTrans(); propertyTrans();
propertyOB.observe($('div.content-wrapper').get(0), { childList: true, subtree: true }); propertyOB.observe($('div.content-wrapper').get(0), {childList: true, subtree: true});
}); });
const propertyTrans = function propertyTrans() { const propertyTrans = function propertyTrans() {
// 从玩家处租或买 // 从玩家处租或买
@ -9260,7 +9260,7 @@ z-index:100001;
}; };
propertyTrans(); propertyTrans();
propertyOB.observe($('div.content-wrapper').get(0), { childList: true, subtree: true }); propertyOB.observe($('div.content-wrapper').get(0), {childList: true, subtree: true});
return; return;
} }
@ -9271,10 +9271,10 @@ z-index:100001;
titleTrans(); titleTrans();
contentTitleLinksTrans(); contentTitleLinksTrans();
eventsTrans(); eventsTrans();
ob.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); ob.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
}); });
eventsTrans(); eventsTrans();
ob.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); ob.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
return; return;
// let events; // let events;
// const eventMutation = new MutationObserver(() => { // const eventMutation = new MutationObserver(() => {
@ -9302,7 +9302,7 @@ z-index:100001;
const awOB = new MutationObserver(() => { const awOB = new MutationObserver(() => {
awOB.disconnect(); awOB.disconnect();
awTrans(); awTrans();
awOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true, attributes: true }); awOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true, attributes: true});
}); });
const awTrans = function awTrans() { const awTrans = function awTrans() {
titleTrans(); titleTrans();
@ -9428,7 +9428,7 @@ z-index:100001;
}); });
}; };
awTrans(); awTrans();
awOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true, attributes: true }); awOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true, attributes: true});
return; return;
} }
@ -9548,7 +9548,7 @@ z-index:100001;
function hosOBInit() { function hosOBInit() {
hospitalOB.disconnect(); hospitalOB.disconnect();
hospTrans(); hospTrans();
hospitalOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); hospitalOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
} }
function hospTrans() { function hospTrans() {
@ -9595,7 +9595,7 @@ z-index:100001;
} }
hospTrans(); hospTrans();
hospitalOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); hospitalOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
return; return;
} }
@ -9606,7 +9606,7 @@ z-index:100001;
function factionOBInit() { function factionOBInit() {
factionOB.disconnect(); factionOB.disconnect();
factionTrans(); factionTrans();
factionOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); factionOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
} }
const factionDict = { const factionDict = {
@ -9716,7 +9716,7 @@ z-index:100001;
} }
factionTrans(); factionTrans();
factionOB.observe($('div.content-wrapper')[0], { childList: true, subtree: true }); factionOB.observe($('div.content-wrapper')[0], {childList: true, subtree: true});
return; return;
} }
@ -9756,7 +9756,7 @@ z-index:100001;
if (href.contains(/calendar\.php/)) { if (href.contains(/calendar\.php/)) {
const $root = document.querySelectorAll('#calendar-root'); const $root = document.querySelectorAll('#calendar-root');
$root.forEach(el => { $root.forEach(el => {
initOB(el, { childList: true, subtree: true }, () => { initOB(el, {childList: true, subtree: true}, () => {
// 页标题 // 页标题
const $h4_title = el.querySelectorAll('h4[class^="title___"]'); const $h4_title = el.querySelectorAll('h4[class^="title___"]');
titleTransReact($h4_title); titleTransReact($h4_title);
@ -9780,7 +9780,7 @@ z-index:100001;
let $root = document.querySelector('#christmastownroot'); let $root = document.querySelector('#christmastownroot');
const $title_wrapper = $root.querySelector('div[class^="appHeaderWrapper___"]'); const $title_wrapper = $root.querySelector('div[class^="appHeaderWrapper___"]');
// 标题和右边的链接 // 标题和右边的链接
initOB($title_wrapper, { childList: true, subtree: true }, () => { initOB($title_wrapper, {childList: true, subtree: true}, () => {
titleTransReact(); titleTransReact();
contentTitleLinksTransReact(); contentTitleLinksTransReact();
}); });
@ -9943,47 +9943,47 @@ z-index:100001;
const dest = [ const dest = [
{ {
name: 'mex', show: '墨西哥', name: 'mex', show: '墨西哥',
stocks: { 'Dahlia': '花', 'Jaguar Plushie': '偶' } stocks: {'Dahlia': '花', 'Jaguar Plushie': '偶'}
}, },
{ {
name: 'cay', show: '开曼', name: 'cay', show: '开曼',
stocks: { 'Banana Orchid': '花', 'Stingray Plushie': '偶' } stocks: {'Banana Orchid': '花', 'Stingray Plushie': '偶'}
}, },
{ {
name: 'can', show: '加拿大', name: 'can', show: '加拿大',
stocks: { 'Crocus': '花', 'Wolverine Plushie': '偶' } stocks: {'Crocus': '花', 'Wolverine Plushie': '偶'}
}, },
{ {
name: 'haw', show: '夏威夷', name: 'haw', show: '夏威夷',
stocks: { 'Orchid': '花', 'Large Suitcase': '大箱' } stocks: {'Orchid': '花', 'Large Suitcase': '大箱'}
}, },
{ {
name: 'uni', show: '嘤国', name: 'uni', show: '嘤国',
stocks: { 'Heather': '花', 'Red Fox Plushie': '赤狐', 'Nessie Plushie': '水怪' } stocks: {'Heather': '花', 'Red Fox Plushie': '赤狐', 'Nessie Plushie': '水怪'}
}, },
{ {
name: 'arg', show: '阿根廷', name: 'arg', show: '阿根廷',
stocks: { 'Ceibo Flower': '花', 'Monkey Plushie': '偶', 'Tear Gas': '催泪弹' }, stocks: {'Ceibo Flower': '花', 'Monkey Plushie': '偶', 'Tear Gas': '催泪弹'},
}, },
{ {
name: 'swi', show: '瑞士', name: 'swi', show: '瑞士',
stocks: { 'Edelweiss': '花', 'Chamois Plushie': '偶' }, stocks: {'Edelweiss': '花', 'Chamois Plushie': '偶'},
}, },
{ {
name: 'jap', show: '日本', name: 'jap', show: '日本',
stocks: { 'Cherry Blossom': '花' }, stocks: {'Cherry Blossom': '花'},
}, },
{ {
name: 'chi', show: '祖国', name: 'chi', show: '祖国',
stocks: { 'Peony': '花', 'Panda Plushie': '偶' }, stocks: {'Peony': '花', 'Panda Plushie': '偶'},
}, },
{ {
name: 'uae', show: '迪拜', name: 'uae', show: '迪拜',
stocks: { 'Tribulus Omanense': '花', 'Camel Plushie': '偶' }, stocks: {'Tribulus Omanense': '花', 'Camel Plushie': '偶'},
}, },
{ {
name: 'sou', show: '南非', name: 'sou', show: '南非',
stocks: { 'African Violet': '花', 'Lion Plushie': '偶', 'Xanax': 'XAN' }, stocks: {'African Violet': '花', 'Lion Plushie': '偶', 'Xanax': 'XAN'},
}]; }];
const now = new Date(); const now = new Date();
const res = await fstock.get(); const res = await fstock.get();
@ -10028,12 +10028,12 @@ z-index:100001;
// 元素生成器 // 元素生成器
function elemGenerator(setting, root_node) { function elemGenerator(setting, root_node) {
let { tip, domType } = setting; let {tip, domType} = setting;
let new_node = null; let new_node = null;
switch (domType) { switch (domType) {
case 'checkbox': { case 'checkbox': {
new_node = document.createElement('div'); new_node = document.createElement('div');
let { domId, dictName, domText } = setting; let {domId, dictName, domText} = setting;
let label = document.createElement('label'); let label = document.createElement('label');
(tip) && (label.setAttribute('title', tip)); (tip) && (label.setAttribute('title', tip));
let input = document.createElement('input'); let input = document.createElement('input');
@ -10051,7 +10051,7 @@ z-index:100001;
} }
case 'button': { case 'button': {
new_node = document.createElement('div'); new_node = document.createElement('div');
let { domId, domText, clickFunc } = setting; let {domId, domText, clickFunc} = setting;
let btn = document.createElement('button'); let btn = document.createElement('button');
(tip) && (btn.setAttribute('title', tip)); (tip) && (btn.setAttribute('title', tip));
btn.id = domId; btn.id = domId;
@ -10062,14 +10062,14 @@ z-index:100001;
} }
case 'select': { case 'select': {
new_node = document.createElement('div'); new_node = document.createElement('div');
let { domSelectOpt, dictName, domId, domText } = setting; let {domSelectOpt, dictName, domId, domText} = setting;
let label = document.createElement('label'); let label = document.createElement('label');
(tip) && (label.setAttribute('title', tip)); (tip) && (label.setAttribute('title', tip));
let text = document.createTextNode(domText); let text = document.createTextNode(domText);
let select = document.createElement('select'); let select = document.createElement('select');
select.id = domId; select.id = domId;
domSelectOpt.forEach((opt, i) => { domSelectOpt.forEach((opt, i) => {
let { domVal, domText } = opt; let {domVal, domText} = opt;
let option = document.createElement('option'); let option = document.createElement('option');
option.value = domVal; option.value = domVal;
option.innerHTML = domText; option.innerHTML = domText;
@ -10110,7 +10110,7 @@ z-index:100001;
} }
started = setInterval(() => { started = setInterval(() => {
// 海外取消提醒 // 海外取消提醒
let { isTravelling, isAbroad } = getUserState(); let {isTravelling, isAbroad} = getUserState();
if (isTravelling || isAbroad) { if (isTravelling || isAbroad) {
loop.stop(); loop.stop();
return; return;
@ -10318,7 +10318,7 @@ z-index:100001;
let res = await (await fetch(addRFC('https://www.torn.com/factions.php'), { let res = await (await fetch(addRFC('https://www.torn.com/factions.php'), {
method: 'POST', method: 'POST',
body: dataStr, body: dataStr,
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded' } headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'}
})).json(); })).json();
if (res.success === true) { if (res.success === true) {
WHNotify('存钱成功'); WHNotify('存钱成功');
@ -10336,7 +10336,7 @@ z-index:100001;
method: 'POST', method: 'POST',
referrer: 'companies.php', referrer: 'companies.php',
body: 'deposit=' + money, body: 'deposit=' + money,
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded' } headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'}
})).text(); })).text();
log(res); log(res);
let node = document.createElement('div'); let node = document.createElement('div');
@ -10400,7 +10400,7 @@ z-index:100001;
let updateRecordsDOM = function () { let updateRecordsDOM = function () {
let html = '战斗记录:<br/>'; let html = '战斗记录:<br/>';
records.list.forEach(rid => { records.list.forEach(rid => {
let { TimeCreated, attackID, attackerID, attackerItemID, result, text } = records.details[rid]; let {TimeCreated, attackID, attackerID, attackerItemID, result, text} = records.details[rid];
html += `[${TimeCreated}] [${attackerID}] [${attackerItemID}] ${result} ${text}<br/>`; html += `[${TimeCreated}] [${attackerID}] [${attackerItemID}] ${result} ${text}<br/>`;
}); });
records.innerHTML = html; records.innerHTML = html;
@ -10416,7 +10416,7 @@ z-index:100001;
let popup_close = popup.close; let popup_close = popup.close;
popup.close = () => { popup.close = () => {
if (loop_id === null) popup_close(); if (loop_id === null) popup_close();
else WHNotify('守望者运行中,请先停止', { timeout: 2 }); else WHNotify('守望者运行中,请先停止', {timeout: 2});
} }
popup.appendChild(p); popup.appendChild(p);
@ -10438,13 +10438,13 @@ z-index:100001;
// 记录当前循环的id // 记录当前循环的id
let that_id = loop_id; let that_id = loop_id;
let res = await (await fetch(url + uid.value, { let res = await (await fetch(url + uid.value, {
headers: { 'X-Requested-With': 'XMLHttpRequest' }, headers: {'X-Requested-With': 'XMLHttpRequest'},
referrer: "loader.php?sid=attack&user2ID=" + uid.value referrer: "loader.php?sid=attack&user2ID=" + uid.value
})).text(); })).text();
if (loop_id !== that_id) return; if (loop_id !== that_id) return;
let data = JSON.parse(res.split('<div')[0]); let data = JSON.parse(res.split('<div')[0]);
log(count++, data); log(count++, data);
let { DB, currentFightStatistics, histLog } = data; let {DB, currentFightStatistics, histLog} = data;
// 攻击人 // 攻击人
// 格式currentFightStatistics = {uid: {...}, uid2: {...}} // 格式currentFightStatistics = {uid: {...}, uid2: {...}}
Object.keys(currentFightStatistics || {}).forEach(id => { Object.keys(currentFightStatistics || {}).forEach(id => {
@ -10457,15 +10457,15 @@ z-index:100001;
// 攻击历史 // 攻击历史
(DB['currentFightHistory'] || []).forEach(record => { (DB['currentFightHistory'] || []).forEach(record => {
if (records.list.includes(record['ID'])) return; if (records.list.includes(record['ID'])) return;
let { ID, TimeCreated, attackID, attackerID, attackerItemID, result, text } = record; let {ID, TimeCreated, attackID, attackerID, attackerItemID, result, text} = record;
records.list.push(ID); records.list.push(ID);
records.details[ID] = { TimeCreated, attackID, attackerID, attackerItemID, result, text }; records.details[ID] = {TimeCreated, attackID, attackerID, attackerItemID, result, text};
updateRecordsDOM(); updateRecordsDOM();
}); });
// 攻击历史日志 // 攻击历史日志
if (histLog && histLog[uid.value]) histLog[uid.value].forEach(log => { if (histLog && histLog[uid.value]) histLog[uid.value].forEach(log => {
if (records.list.includes(log['ID'])) return; if (records.list.includes(log['ID'])) return;
let { ID, TimeCreated, attackID, attackResult, userID } = log; let {ID, TimeCreated, attackID, attackResult, userID} = log;
records.list.push(ID); records.list.push(ID);
records.details[ID] = { records.details[ID] = {
TimeCreated, TimeCreated,
@ -10524,9 +10524,17 @@ z-index:100001;
} }
} }
// 边栏信息 /**
* 边栏信息
* @deprecated
* @returns {any}
*/
function getSidebarData() { function getSidebarData() {
return JSON.parse(document.querySelector('#sidebar_data').innerHTML) // return JSON.parse(document.querySelector('#sidebar_data').innerHTML)
let obj = {};
const sidebar_menu_list = document.querySelectorAll('#sidebar a span[class*="linkName___"]');
sidebar_menu_list.forEach(node => obj[node.innerHTML.trim().toLowerCase()] = true);
return obj;
} }
/** /**
@ -10582,9 +10590,9 @@ z-index:100001;
* @returns {Promise<Response>} * @returns {Promise<Response>}
*/ */
function ajaxFetch(opt) { function ajaxFetch(opt) {
let { url, referrer, method, body = null } = opt; let {url, referrer, method, body = null} = opt;
let req_params = { let req_params = {
headers: { 'X-Requested-With': 'XMLHttpRequest' }, headers: {'X-Requested-With': 'XMLHttpRequest'},
referrer, referrer,
method, method,
}; };