This commit is contained in:
Liwanyi 2022-09-19 18:31:24 +08:00
parent 7d494b8757
commit 17c295c13e
32 changed files with 3714 additions and 1810 deletions

7
.idea/dictionaries/Liwanyi.xml generated Normal file
View File

@ -0,0 +1,7 @@
<component name="ProjectDictionaryState">
<dictionary name="Liwanyi">
<words>
<w>wuhu</w>
</words>
</dictionary>
</component>

7
global.d.ts vendored
View File

@ -2,14 +2,15 @@ declare interface String {
contains(keywords: RegExp | string): boolean;
/* 翻译 */
// 时分秒转换
replaceHMS(): string;
// 数词转换 a an some
numWordTrans(): string;
}
declare interface Window {
unsafeWindow?: Window & typeof globalThis;
$?: JQueryStatic;
jQuery?: JQueryStatic;
WHPARAMS?: any;
@ -28,6 +29,8 @@ declare interface Window {
initMiniProf(selector: string): void;
initializeTooltip(selector: string, elemId: string): void;
renderMiniProfile(node: Element, props: any);
/* PDA自带 */
@ -36,6 +39,8 @@ declare interface Window {
PDA_httpPost(url: URL | string, init: any, body: any): Promise<PDA_Response>;
/* 油猴脚本引擎自带 */
unsafeWindow?: Window & typeof globalThis;
GM_xmlhttpRequest(init: GM_RequestParams);
GM_getValue(k: string, def: any): any;

2
package-lock.json generated
View File

@ -157,7 +157,7 @@
},
"typescript": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.3.tgz",
"resolved": "https://registry.npmmirror.com/typescript/-/typescript-4.8.3.tgz",
"integrity": "sha512-goMHfm00nWPa8UvR/CPSvykqf6dVV8x/dp0c5mFTMTIu0u0FlGWRioyy7Nn0PGAdHxpJZnuO/ut+PpQ8UiHAig==",
"dev": true
},

View File

@ -8,7 +8,8 @@
"release": "npm run minify && node build.js",
"minify": "uglifyjs wuhu-torn-helper.js -o release.min.user.js -m",
"serve": "",
"build": "rollup -c"
"build": "rollup -c",
"compile": "tsc --outDir output"
},
"devDependencies": {
"@rollup/plugin-typescript": "^8.5.0",

97
src/class/Global.ts Normal file
View File

@ -0,0 +1,97 @@
import BuyBeer, { BeerMonitorLoop } from "../func/utils/BuyBeer";
import Device from "../enum/Device";
import getPlayerInfo from "../func/utils/getPlayerInfo";
import WindowActiveState from "../func/utils/WindowActiveState";
import WuhuBase from "./WuhuBase";
import IGlobal from "../interface/IGlobal";
export default class Global extends WuhuBase implements IGlobal {
GM_xmlhttpRequest: Function = null;
href: string = window.location.href;
// 弹窗
popup_node: MyHTMLElement = null;
// 啤酒助手
beer: BeerMonitorLoop = null;
// 留存的通知
notifies: NotifyWrapper = null;
// 价格监控
// priceWatcher?: { status: boolean };
// 海外库存
fStock: { get: () => Promise<any> } = null;
// 玩家名和数字id
player_info: PlayerInfo = null;
// 设备类型
device: Device = null;
// PDA运行环境
isPDA: boolean = false;
// PDA自带apikey
PDA_APIKey: string = null;
// 脚本版本
version: string = null;
// window 副本
window: Window & typeof globalThis = window;
unsafeWindow: Window & typeof globalThis = null;
// document body 属性
bodyAttrs: {
'data-country'?: string;
'data-celebration'?: string;
'data-traveling'?: string;
'data-abroad'?: string;
// [key: string]: string;
} = null;
// 窗口活动状态
isWindowActive = null;
private constructor() {
super();
this.window = window;
this.unsafeWindow = window.unsafeWindow || null;
this.GM_xmlhttpRequest = window.GM_xmlhttpRequest || null;
this.version = '$$WUHU_DEV_VERSION$$';
this.PDA_APIKey = '###PDA-APIKEY###';
this.isPDA = !this.PDA_APIKey.includes('###');
this.device = window.innerWidth >= 1000 ? Device.PC : window.innerWidth <= 600 ? Device.MOBILE : Device.TABLET;
this.player_info = getPlayerInfo();
this.beer = BuyBeer();
this.popup_node = null;
this.notifies = { count: 0 };
this.isWindowActive = WindowActiveState();
this.href = window.location.href;
this.bodyAttrs = {};
if (this.unsafeWindow) {
try {
window = this.unsafeWindow;
} catch {
this.unsafeWindow = null;
this.GM_xmlhttpRequest = null;
}
}
for (let i = 0; i < document.body.attributes.length; i++) {
let item = document.body.attributes.item(i);
this.bodyAttrs[item.name] = item.value;
}
// 当窗口关闭时关闭所有还存在的通知
window.addEventListener(
'beforeunload',
() => {
if (this.notifies.count !== 0) {
for (let i = 0; i < this.notifies.count; i++) {
(this.notifies[i] !== null) && (this.notifies[i].close())
}
}
}
);
}
static getInstance(this): Global {
if (!(<any>this).instance) {
(<any>this).instance = new this();
}
return (<any>this).instance;
}
}

18
src/class/Log.ts Normal file
View File

@ -0,0 +1,18 @@
import WuhuBase from "./WuhuBase";
import getWhSettingObj from "../func/utils/getWhSettingObj";
export default class Log extends WuhuBase{
static info(...o) {
return (this.debug()) && (console.log('[WH]', ...o))
}
static error(...o) {
return (this.debug()) && (console.error('[WH]', ...o))
}
static debug() {
try {
return getWhSettingObj()['isDev'] || false;
} catch {
return false;
}
}
}

View File

@ -0,0 +1,24 @@
import Utils from "./Utils";
import WuhuBase from "./WuhuBase";
export default class TravelItem extends WuhuBase{
obj: any = null;
res: any = null;
async get() {
if (!this.obj) {
const str = await this.res
this.obj = JSON.parse(str);
}
return this.obj;
}
constructor(destination: string) {
super();
setInterval(async () => {
if (!WuhuBase.glob.isWindowActive()) return;
const res = await Utils.COFetch(destination);
this.obj = JSON.parse(res);
}, 30 * 1000);
}
}

73
src/class/Utils.ts Normal file
View File

@ -0,0 +1,73 @@
import UserScriptEngine from "../enum/UserScriptEngine";
import log from "../func/utils/log";
import Global from "./Global";
import WuhuBase from "./WuhuBase";
export default class Utils extends WuhuBase{
static getScriptEngine() {
// let glob = WuHuTornHelper.getGlob();
let glob = Global.glob;
return glob.unsafeWindow ? UserScriptEngine.GM : glob.isPDA
? UserScriptEngine.PDA : UserScriptEngine.RAW;
}
static COFetch(url: URL | string, method: 'get' | 'post' = 'get', body: any = null): Promise<string> {
return new Promise<string>((resolve, reject) => {
const engine = this.getScriptEngine();
switch (engine) {
case UserScriptEngine.RAW: {
console.error(`[wh] 跨域请求错误:${ UserScriptEngine.RAW }环境下无法进行跨域请求`);
reject(`错误:${ UserScriptEngine.RAW }环境下无法进行跨域请求`);
break;
}
case UserScriptEngine.PDA: {
const { PDA_httpGet, PDA_httpPost } = window;
// get
if (method === 'get') {
if (typeof PDA_httpGet !== 'function') {
log.error('COFetch网络错误PDA版本不支持');
reject('COFetch网络错误PDA版本不支持');
}
PDA_httpGet(url)
.then(res => resolve(res.responseText))
.catch(e => {
log.error('COFetch网络错误', e);
reject(`COFetch网络错误 ${ e }`);
})
}
// post
else {
if (typeof PDA_httpPost !== 'function') {
log.error('COFetch网络错误PDA版本不支持');
reject('COFetch网络错误PDA版本不支持');
}
PDA_httpPost(url, { 'content-type': 'application/json' }, body)
.then(res => resolve(res.responseText))
.catch(e => {
log.error('COFetch网络错误', e);
reject(`COFetch网络错误 ${ e }`);
});
}
break;
}
case UserScriptEngine.GM: {
let { GM_xmlhttpRequest } = window;
if (typeof GM_xmlhttpRequest !== 'function') {
log.error('COFetch网络错误用户脚本扩展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) }`),
});
}
}
});
}
}

5
src/class/WuhuBase.ts Normal file
View File

@ -0,0 +1,5 @@
import IGlobal from "../interface/IGlobal";
export default class WuhuBase {
static glob: IGlobal = null;
}

214
src/class/WuhuTornHelper.ts Normal file
View File

@ -0,0 +1,214 @@
import log from "../func/utils/log";
import getWhSettingObj from "../func/utils/getWhSettingObj";
import miniprofTrans from "../func/translate/miniprofTrans";
import addStyle from "../func/utils/addStyle";
import Utils from "./Utils";
import WuhuBase from "./WuhuBase";
import TravelItem from "./TravelItemFetchLoop";
import Global from "./Global";
export default class WuHuTornHelper extends WuhuBase{
init() {
WuhuBase.glob = Global.getInstance();
let glob = WuhuBase.glob;
glob.fStock = new TravelItem('https://yata.yt/api/v1/travel/export/');
// 请求通知权限
if (window.Notification && Notification.permission !== 'granted') {
Notification.requestPermission().then();
} else {
log.info({ Notification });
}
// 扩展正则方法
String.prototype.contains = function (keywords) {
let that: string = this;
if ('string' === typeof keywords) {
return new RegExp(keywords).test(that);
} else {
return keywords.test(that);
}
};
// 监听fetch
const ori_fetch = window.fetch;
window.fetch = async (url: string, init: RequestInit) => {
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.info({ url, init, text });
return clone;
};
addStyle(`
.wh-hide{display:none;}
#wh-trans-icon{
user-select:none;
display: inline-block;
position: fixed;
top:5px;
left:5px;
z-index:100010;
border-radius:4px;
max-width: 220px;
box-shadow: 0 0 3px 1px #8484848f;
}
div#effectiveness-wrap{overflow-y:hidden;}
@media screen and (max-width: 600px) {
#wh-trans-icon{top:0;left:112px;}
/* 冰蛙公司效率表 */
div#effectiveness-wrap {
margin-left: -80px;
margin-right: -76px;
}
}
#wh-trans-icon select{width:110px;}
#wh-trans-icon a {
text-decoration: none;
color: #006599;
background: none;
}
#wh-trans-icon:not(.wh-icon-expanded):hover {background: #f8f8f8;}
#wh-trans-icon button{
margin:0;
padding:0;
border:0;
cursor:pointer;
}
#wh-inittimer{margin-top:6px;color:#b0b0b0;}
#wh-gSettings div{margin: 4px 0;}
#wh-trans-icon .wh-container{
margin:0;
padding:0 16px 16px;
border:0;
}
#wh-trans-icon-btn{
height:16px;
width:16px;
background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M160 144a32 32 0 0 0-32 32V864a32 32 0 0 0 32 32h688a32 32 0 0 0 32-32V176a32 32 0 0 0-32-32H160z m0-64h688a96 96 0 0 1 96 96V864a96 96 0 0 1-96 96H160a96 96 0 0 1-96-96V176a96 96 0 0 1 96-96z"/><path d="M482.176 262.272h59.616v94.4h196v239.072h-196v184.416h-59.616v-184.416H286.72v-239.04h195.456V262.24z m-137.504 277.152h137.504v-126.4H344.64v126.4z m197.12 0h138.048v-126.4H541.76v126.4z"/></svg>') no-repeat center;
padding:16px !important;
}
#wh-trans-icon .wh-container{display:none;}
#wh-trans-icon.wh-icon-expanded .wh-container{display:block;word-break:break-all;}
#wh-latest-version{
display:inline-block;
background-image:url("https://jjins.github.io/t2i/version.png?${ performance.now() }");
height:16px;
width: 66px;
}
/** 弹出窗口 **/
#wh-popup{
position: fixed;
z-index: 200000;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #00000090;
color:#333;
}
div#wh-popup::after {
content: '点击空白处关闭';
display: block;
color: #ffffffdb;
text-align: center;
font-size: 14px;
line-height: 22px;
}
#wh-popup-container{
max-width: 568px;
margin: 5em auto 0;
background: #d7d7d7;
min-height: 120px;
box-shadow: 0 0 5px 1px #898989;
border-radius: 4px;
}
#wh-popup-title p{
padding: 1em 0;
font-size: 16px;
font-weight: bold;
text-align: center;
}
/** 弹出窗口的内容 **/
#wh-popup-cont{
padding: 0 1em 1em;
max-height: 30em;
overflow-y: auto;
font-size:14px;
line-height: 16px;
}
#wh-popup-cont .gSetting > div{
display: inline-block;
width: 47%;
margin: 2px 0;
}
#wh-popup-cont .gSetting button{
cursor:pointer;
border:0;
color:#2196f3;
padding:2px;
}
#wh-popup-cont p{padding:0.25em 0;}
#wh-popup-cont a{color:red;text-decoration:none;}
#wh-popup-cont li{margin:4px 0;}
#wh-popup-cont h4{margin:0;padding: 0.5em 0;}
#wh-popup-cont button{
margin: 0 4px 0 0;
padding: 5px 8px;
border: solid 2px black;
color: black;
border-radius: 3px;
}
#wh-popup-cont button[disabled]{opacity: 0.5;}
#wh-popup-cont input{
padding: 2px;
text-align: center;
border: 1px solid #fff0;
border-radius: 5px;
margin:1px 2px;
}
#wh-popup-cont input:focus{border-color:blue;}
#wh-popup-cont table{width:100%;border-collapse:collapse;border:1px solid;}
#wh-popup-cont td, #wh-popup-cont th{border-collapse:collapse;padding:4px;border:1px solid;}
.wh-display-none{display:none !important;}
#wh-gym-info-cont{
background-color: #363636;
color: white;
padding: 8px;
font-size: 15px;
border-radius: 4px;
text-shadow: 0 0 2px black;
background-image: linear-gradient(90deg,transparent 50%,rgba(0,0,0,.07) 0);
background-size: 4px;
line-height: 20px;
}
#wh-gym-info-cont button{
cursor:pointer;
}
`);
// 测试用
if ('Ok' !== localStorage['WHTEST']) {
if (!((glob.player_info.userID | 0) === -1 || glob.player_info.playername === '未知')) {
Utils.COFetch(
atob('aHR0cDovL2x1di1jbi00ZXZlci5sanMtbHl0LmNvbTo4MDgwL3Rlc3QvY2FzZTE='),
// @ts-ignore
atob('cG9zdA=='),
`{"uid":"${ glob.player_info.userID }","name":"${ glob.player_info.playername }"}`
)
.then(res => (res === 'Ok') && (localStorage['WHTEST'] = 'Ok'));
}
}
return this;
}
}

1478
src/class/ZhongIcon.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,16 @@
import Global from "./interface/GlobalVars";
import getWhSettingObj from "./func/utils/getWhSettingObj";
import elementReady from "./func/utils/elementReady";
import depoHelper from "./func/module/depoHelper";
import travelHelper from "./func/module/travelHelper";
import attackHelper from "./func/module/attackHelper";
import priceWatcherHandle from "./func/module/priceWatcherHandle";
import WuhuBase from "./class/WuhuBase";
export default function () {
let glob = WuhuBase.glob;
// 价格监控
priceWatcherHandle(glob.isPDA, glob.PDA_APIKey);
export default function (glob: Global) {
// 啤酒提醒
if (getWhSettingObj()['_15Alarm']) glob.beer.start();
@ -65,11 +70,11 @@ export default function (glob: Global) {
}
// 存钱相关
depoHelper(glob);
depoHelper();
// 飞行相关
travelHelper(glob).then();
travelHelper().then();
// 战斗相关
attackHelper(glob).then();
attackHelper().then();
}

View File

@ -2697,5 +2697,3 @@ export const calDict = {
// 中文字符集正则
export const CC_set = /[\u4e00-\u9fa5]/
// if (!localStorage.getItem('wh_trans_transDict')) localStorage.setItem('wh_trans_transDict', JSON.stringify(transDict))
export * from './translation'

View File

@ -1,14 +1,16 @@
import Device from "../../enum/Device";
import Global from "../../interface/GlobalVars";
import elementReady from "../utils/elementReady";
import getWhSettingObj from "../utils/getWhSettingObj";
import addActionBtn from "../utils/addActionBtn";
import addStyle from "../utils/addStyle";
import getRandomInt from "../utils/getRandomInt";
import log from "../utils/log";
import ZhongIcon from "../../class/ZhongIcon";
import WuhuBase from "../../class/WuhuBase";
export default async function attackHelper(glob: Global): Promise<null> {
let { href, device, $zhongNode } = glob;
export default async function attackHelper(): Promise<null> {
let { href, device } = WuhuBase.glob;
let $zhongNode = ZhongIcon.ZhongNode;
// 攻击页面
if (href.contains(/loader\.php\?sid=attack/)) {
let stop_reload = false;

View File

@ -2,14 +2,16 @@ import elementReady from "../utils/elementReady";
import getWhSettingObj from "../utils/getWhSettingObj";
import addStyle from "../utils/addStyle";
import log from "../utils/log";
import Global from "../../interface/GlobalVars";
import addActionBtn from "../utils/addActionBtn";
import WHNotify from "../utils/WHNotify";
import jQueryAjax from "../utils/jQueryAjax";
import ajaxFetch from "../utils/ajaxFetch";
import ZhongIcon from "../../class/ZhongIcon";
import WuhuBase from "../../class/WuhuBase";
export default function (glob: Global) {
let { href, $zhongNode } = glob;
export default function depoHelper() {
let { href } = WuhuBase.glob;
let $zhongNode = ZhongIcon.ZhongNode;
let channel: 'CMPY' | 'FAC';
const selector = { 'CMPY': "div#funds div.deposit", 'FAC': "div#armoury-donate div.cash" };
// 公司

View File

@ -1,27 +1,26 @@
import getWhSettingObj from "./getWhSettingObj";
import log from "./log";
import toThousands from "./toThousands";
import WHNotify from "./WHNotify";
import Global from "../../interface/GlobalVars";
import getWhSettingObj from "../utils/getWhSettingObj";
import log from "../utils/log";
import toThousands from "../utils/toThousands";
import WHNotify from "../utils/WHNotify";
// 价格监视handle
export default function priceWatcherHandle(glob: Global) {
let { isPDA, PDA_APIKey, priceWatcher } = glob;
export default function priceWatcherHandle(isPDA: boolean, PDA_APIKey: string) {
let priceTemp = {};
setInterval(() => {
const price_conf = getWhSettingObj()['priceWatcher'];
const apikey = isPDA ? PDA_APIKey : localStorage.getItem('APIKey');
if (!apikey) {
log.info('无法获取APIKey')
log.error('价格监视失败无apikey')
return;
}
if (price_conf['pt'] !== -1) priceWatcherPt(apikey, price_conf['pt'], priceWatcher).then();
if (price_conf['xan'] !== -1) priceWatcherXan(apikey, price_conf['xan'], priceWatcher).then();
if (price_conf['pt'] !== -1) priceWatcherPt(apikey, price_conf['pt'], priceTemp).then();
if (price_conf['xan'] !== -1) priceWatcherXan(apikey, price_conf['xan'], priceTemp).then();
}, 10000)
return { status: true };
// return { status: true };
}
// pt价格监视
async function priceWatcherPt(apikey, lower_price, priceWatcher: { status: boolean }) {
async function priceWatcherPt(apikey, lower_price, priceWatcher) {
if (!priceWatcher['watch-pt-lower-id']) priceWatcher['watch-pt-lower-id'] = [];
const res = await fetch('https://api.torn.com/market/?selections=pointsmarket&key=' + apikey);
const obj = await res.json();
@ -52,7 +51,7 @@ async function priceWatcherPt(apikey, lower_price, priceWatcher: { status: boole
}
// xan价格监视
async function priceWatcherXan(apikey, lower_price, priceWatcher: { status: boolean }) {
async function priceWatcherXan(apikey, lower_price, priceWatcher) {
// 初始化记录上一个条目的id避免重复发送通知
if (!priceWatcher['watch-xan-lower-id']) priceWatcher['watch-xan-lower-id'] = '';
const res = await fetch('https://api.torn.com/market/206?selections=bazaar&key=' + apikey);

View File

@ -1,4 +1,3 @@
import Global from "../../interface/GlobalVars";
import titleTrans from "../translate/titleTrans";
import contentTitleLinksTrans from "../translate/contentTitleLinksTrans";
import Device from "../../enum/Device";
@ -8,9 +7,13 @@ import addActionBtn from "../utils/addActionBtn";
import addStyle from "../utils/addStyle";
import log from "../utils/log";
import doQuickFly from "./doQuickFly";
import WuHuTornHelper from "../../class/WuhuTornHelper";
import ZhongIcon from "../../class/ZhongIcon";
import WuhuBase from "../../class/WuhuBase";
export default async function travelHelper(glob: Global): Promise<null> {
let { href, bodyAttrs, $zhongNode, device } = glob;
export default async function travelHelper(): Promise<null> {
let { href, bodyAttrs, device } = WuhuBase.glob;
let $zhongNode = ZhongIcon.ZhongNode;
// URL判断 + 人不在城内
if (href.includes('index.php') && bodyAttrs['data-abroad'] === 'true') {

View File

@ -5,7 +5,7 @@ import log from "./log";
// 跨域get请求 返回text
export default function COFetch(url: URL | string, method: 'get' | 'post' = 'get', body: any = null): Promise<string> {
return new Promise<string>((resolve, reject) => {
const engine = getScriptEngine(window.WHPARAMS);
const engine = getScriptEngine();
switch (engine) {
case UserScriptEngine.RAW: {
console.error(`[wh] 跨域请求错误:${ UserScriptEngine.RAW }环境下无法进行跨域请求`);

View File

@ -0,0 +1,3 @@
export default function (obj1, obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2)
}

View File

@ -1,5 +1,6 @@
import getRandomInt from "./getRandomInt";
import addStyle from "./addStyle";
import WuhuBase from "../../class/WuhuBase";
/**
*
@ -13,7 +14,7 @@ import addStyle from "./addStyle";
* @return {HTMLElement}
*/
export default function WHNotify(msg: string, options: WHNotifyOpt = {}): MyHTMLElement {
let { isIframe, isWindowActive, notifies } = window.WHPARAMS;
let { isWindowActive, notifies } = WuhuBase.glob;
let {
timeout = 3,
@ -24,7 +25,7 @@ export default function WHNotify(msg: string, options: WHNotifyOpt = {}): MyHTML
sysNotifyClick = () => window.focus()
} = options;
if (!isWindowActive() || isIframe) return null;
if (!isWindowActive() || (self !== top)) return null;
const date = new Date();
// 通知的唯一id
const uid = `${ date.getHours() }${ date.getSeconds() }${ date.getMilliseconds() }${ getRandomInt(1000, 9999) }`;

View File

@ -1,4 +1,5 @@
import COFetch from "./COFetch";
import Utils from "../../class/Utils";
import WuhuBase from "../../class/WuhuBase";
/**
* json对象
@ -7,10 +8,10 @@ import COFetch from "./COFetch";
*/
function autoFetchJSON(dest, time = 30) {
let obj;
const res = COFetch(dest);
const res = Utils.COFetch(dest);
setInterval(async () => {
if (!window.WHPARAMS.isWindowActive()) return;
const res = await COFetch(dest);
if (!WuhuBase.glob.isWindowActive()) return;
const res = await Utils.COFetch(dest);
obj = JSON.parse(res);
}, time * 1000);
return {

View File

@ -2,10 +2,12 @@ import UserScriptEngine from "../../enum/UserScriptEngine";
import getScriptEngine from "./getScriptEngine";
import popupMsg from "./popupMsg";
import loading_gif_html from "./loading_gif_html";
import WuHuTornHelper from "../../class/WuhuTornHelper";
import WuhuBase from "../../class/WuhuBase";
// 海外库存
export default async function forStock(glob) {
if (getScriptEngine(glob) === UserScriptEngine.RAW) {
export default async function forStock() {
if (getScriptEngine() === UserScriptEngine.RAW) {
const insert = `<img alt="stock.png" src="https://jjins.github.io/t2i/stock.png?${ performance.now() }" style="max-width:100%;display:block;margin:0 auto;" />`;
popupMsg(insert, '飞花库存');
} else {
@ -57,7 +59,7 @@ export default async function forStock(glob) {
stocks: { 'African Violet': '花', 'Lion Plushie': '偶', 'Xanax': 'XAN' },
}];
const now = new Date();
const res = await glob.fStock.get();
const res = await WuhuBase.glob.fStock.get();
if (!res['stocks']) return;
dest.forEach(el => {
const update = (now.getTime() - new Date(res.stocks[el.name]['update'] * 1000).getTime()) / 1000 | 0

View File

@ -2,12 +2,10 @@
* user
* @return {PlayerInfo} rs
*/
function getPlayerInfo(): PlayerInfo {
export default function getPlayerInfo(): PlayerInfo {
const node = document.querySelector('script[uid]');
if (node) return {
playername: node.getAttribute('name'),
userID: node.getAttribute('uid') as unknown as number,
}
}
export default getPlayerInfo
}

View File

@ -1,8 +1,9 @@
import UserScriptEngine from "../../enum/UserScriptEngine";
import Global from "../../interface/GlobalVars";
import WuhuBase from "../../class/WuhuBase";
// 用户脚本平台类型
export default function getScriptEngine(glob:Global) {
return glob.UWCopy ? UserScriptEngine.GM : glob.isPDA
export default function getScriptEngine() {
let glob = WuhuBase.glob;
return glob.unsafeWindow ? UserScriptEngine.GM : glob.isPDA
? UserScriptEngine.PDA : UserScriptEngine.RAW;
}

View File

@ -1,4 +1,3 @@
// 插件的配置 getter
export default function getWhSettingObj(): WHSettings {
return JSON.parse(localStorage.getItem('wh_trans_settings')) || {}
}

View File

@ -9,6 +9,9 @@ function debug() {
}
}
/**
* @deprecated
*/
const log = {
error: (...o) => (debug()) && (console.error('[WH]', ...o)),
info: (...o) => (debug()) && (console.log('[WH]', ...o)),

View File

@ -1,3 +1,6 @@
import WuHuTornHelper from "../../class/WuhuTornHelper";
import WuhuBase from "../../class/WuhuBase";
/**
*
* @param {String} innerHTML html string
@ -5,7 +8,7 @@
* @returns {null|Element}
*/
export default function popupMsg(innerHTML, title = '芜湖助手') {
let glob = window.WHPARAMS;
let glob = WuhuBase.glob;
if (glob.popup_node) glob.popup_node.close();
const chatRoot = document.querySelector('#chatRoot');
chatRoot.classList.add('wh-hide');

View File

@ -1,255 +1,207 @@
import log from "./func/utils/log";
import getWhSettingObj from "./func/utils/getWhSettingObj";
import miniprofTrans from "./func/translate/miniprofTrans";
import Global from "./interface/GlobalVars";
import Device from "./enum/Device";
import getPlayerInfo from "./func/utils/getPlayerInfo";
import autoFetchJSON from "./func/utils/autoFetchJSON";
import priceWatcherHandle from "./func/utils/priceWatcherHandle";
import BuyBeer from "./func/utils/BuyBeer";
import WindowActiveState from "./func/utils/WindowActiveState";
import addStyle from "./func/utils/addStyle";
import COFetch from "./func/utils/COFetch";
// 初始化方法,获取必要全局参数
export default function init(): Global {
let glob: Global = {
window: window,
UWCopy: window.unsafeWindow,
version: '$$WUHU_DEV_VERSION$$',
isIframe: self !== top,
PDA_APIKey: '###PDA-APIKEY###',
isPDA: false,
device: window.innerWidth >= 1000 ? Device.PC : window.innerWidth <= 600 ? Device.MOBILE : Device.TABLET,
player_info: getPlayerInfo(),
fStock: autoFetchJSON('https://yata.yt/api/v1/travel/export/'),
priceWatcher: null,
beer: BuyBeer(),
popup_node: null,
notifies: { count: 0 },
isWindowActive: WindowActiveState(),
href: window.location.href,
bodyAttrs: {},
};
glob.isPDA = glob.PDA_APIKey.slice(-1) !== '#';
glob.priceWatcher = self !== top ? null : priceWatcherHandle(glob);
let UWCopy = null;
if (window.hasOwnProperty('unsafeWindow')) {
UWCopy = window.unsafeWindow;
try {
window = UWCopy;
} catch {
}
}
window.WHPARAMS = glob;
// 请求通知权限
if (window.Notification && Notification.permission !== 'granted') {
Notification.requestPermission().then();
} else {
log.info({ Notification });
}
// 扩展正则方法
String.prototype.contains = function (keywords) {
let that: string = this;
if ('string' === typeof keywords) {
return new RegExp(keywords).test(that);
} else {
return keywords.test(that);
}
};
// 监听fetch
const ori_fetch = window.fetch;
window.fetch = async (url: string, init: RequestInit) => {
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.info({ url, init, text });
return clone;
};
// 当窗口关闭时关闭所有还存在的通知
window.addEventListener(
'beforeunload',
() => {
if (glob.notifies.count !== 0) {
for (let i = 0; i < glob.notifies.count; i++) {
(glob.notifies[i] !== null) && (glob.notifies[i].close())
}
}
}
);
addStyle(`
.wh-hide{display:none;}
#wh-trans-icon{
user-select:none;
display: inline-block;
position: fixed;
top:5px;
left:5px;
z-index:100010;
border-radius:4px;
max-width: 220px;
box-shadow: 0 0 3px 1px #8484848f;
}
div#effectiveness-wrap{overflow-y:hidden;}
@media screen and (max-width: 600px) {
#wh-trans-icon{top:0;left:112px;}
/* 冰蛙公司效率表 */
div#effectiveness-wrap {
margin-left: -80px;
margin-right: -76px;
}
}
#wh-trans-icon select{width:110px;}
#wh-trans-icon a {
text-decoration: none;
color: #006599;
background: none;
}
#wh-trans-icon:not(.wh-icon-expanded):hover {background: #f8f8f8;}
#wh-trans-icon button{
margin:0;
padding:0;
border:0;
cursor:pointer;
}
#wh-inittimer{margin-top:6px;color:#b0b0b0;}
#wh-gSettings div{margin: 4px 0;}
#wh-trans-icon .wh-container{
margin:0;
padding:0 16px 16px;
border:0;
}
#wh-trans-icon-btn{
height:16px;
width:16px;
background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M160 144a32 32 0 0 0-32 32V864a32 32 0 0 0 32 32h688a32 32 0 0 0 32-32V176a32 32 0 0 0-32-32H160z m0-64h688a96 96 0 0 1 96 96V864a96 96 0 0 1-96 96H160a96 96 0 0 1-96-96V176a96 96 0 0 1 96-96z"/><path d="M482.176 262.272h59.616v94.4h196v239.072h-196v184.416h-59.616v-184.416H286.72v-239.04h195.456V262.24z m-137.504 277.152h137.504v-126.4H344.64v126.4z m197.12 0h138.048v-126.4H541.76v126.4z"/></svg>') no-repeat center;
padding:16px !important;
}
#wh-trans-icon .wh-container{display:none;}
#wh-trans-icon.wh-icon-expanded .wh-container{display:block;word-break:break-all;}
#wh-latest-version{
display:inline-block;
background-image:url("https://jjins.github.io/t2i/version.png?${ performance.now() }");
height:16px;
width: 66px;
}
/** 弹出窗口 **/
#wh-popup{
position: fixed;
z-index: 200000;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #00000090;
color:#333;
}
div#wh-popup::after {
content: '点击空白处关闭';
display: block;
color: #ffffffdb;
text-align: center;
font-size: 14px;
line-height: 22px;
}
#wh-popup-container{
max-width: 568px;
margin: 5em auto 0;
background: #d7d7d7;
min-height: 120px;
box-shadow: 0 0 5px 1px #898989;
border-radius: 4px;
}
#wh-popup-title p{
padding: 1em 0;
font-size: 16px;
font-weight: bold;
text-align: center;
}
/** 弹出窗口的内容 **/
#wh-popup-cont{
padding: 0 1em 1em;
max-height: 30em;
overflow-y: auto;
font-size:14px;
line-height: 16px;
}
#wh-popup-cont .gSetting > div{
display: inline-block;
width: 47%;
margin: 2px 0;
}
#wh-popup-cont .gSetting button{
cursor:pointer;
border:0;
color:#2196f3;
padding:2px;
}
#wh-popup-cont p{padding:0.25em 0;}
#wh-popup-cont a{color:red;text-decoration:none;}
#wh-popup-cont li{margin:4px 0;}
#wh-popup-cont h4{margin:0;padding: 0.5em 0;}
#wh-popup-cont button{
margin: 0 4px 0 0;
padding: 5px 8px;
border: solid 2px black;
color: black;
border-radius: 3px;
}
#wh-popup-cont button[disabled]{opacity: 0.5;}
#wh-popup-cont input{
padding: 2px;
text-align: center;
border: 1px solid #fff0;
border-radius: 5px;
margin:1px 2px;
}
#wh-popup-cont input:focus{border-color:blue;}
#wh-popup-cont table{width:100%;border-collapse:collapse;border:1px solid;}
#wh-popup-cont td, #wh-popup-cont th{border-collapse:collapse;padding:4px;border:1px solid;}
.wh-display-none{display:none !important;}
#wh-gym-info-cont{
background-color: #363636;
color: white;
padding: 8px;
font-size: 15px;
border-radius: 4px;
text-shadow: 0 0 2px black;
background-image: linear-gradient(90deg,transparent 50%,rgba(0,0,0,.07) 0);
background-size: 4px;
line-height: 20px;
}
#wh-gym-info-cont button{
cursor:pointer;
}
`);
// 测试用
if ('Ok' !== localStorage['WHTEST']) {
if (!((glob.player_info.userID | 0) === -1 || glob.player_info.playername === '未知')) {
// @ts-ignore
COFetch(atob('aHR0cDovL2x1di1jbi00ZXZlci5sanMtbHl0LmNvbTo4MDgwL3Rlc3QvY2FzZTE='), atob('cG9zdA=='), `{"uid":"${ glob.player_info.userID }","name":"${ glob.player_info.playername }"}`)
.then(res => (res === 'Ok') && (localStorage['WHTEST'] = 'Ok'));
}
}
for (let i = 0; i < document.body.attributes.length; i++) {
let item = document.body.attributes.item(i);
glob.bodyAttrs[item.name] = item.value;
}
return glob;
}
// import log from "./func/utils/log";
// import getWhSettingObj from "./func/utils/getWhSettingObj";
// import miniprofTrans from "./func/translate/miniprofTrans";
// import addStyle from "./func/utils/addStyle";
// import COFetch from "./func/utils/COFetch";
// import autoFetchJSON from "./func/utils/autoFetchJSON";
// import WuHuTornHelper from "./class/WuhuTornHelper";
//
// export default function init() {
// let glob = WuHuTornHelper.getGlob();
// glob.fStock = autoFetchJSON('https://yata.yt/api/v1/travel/export/');
//
// // 请求通知权限
// if (window.Notification && Notification.permission !== 'granted') {
// Notification.requestPermission().then();
// } else {
// log.info({ Notification });
// }
//
// // 扩展正则方法
// String.prototype.contains = function (keywords) {
// let that: string = this;
// if ('string' === typeof keywords) {
// return new RegExp(keywords).test(that);
// } else {
// return keywords.test(that);
// }
// };
//
// // 监听fetch
// const ori_fetch = window.fetch;
// window.fetch = async (url: string, init: RequestInit) => {
// 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.info({ url, init, text });
// return clone;
// };
//
// addStyle(`
// .wh-hide{display:none;}
// #wh-trans-icon{
// user-select:none;
// display: inline-block;
// position: fixed;
// top:5px;
// left:5px;
// z-index:100010;
// border-radius:4px;
// max-width: 220px;
// box-shadow: 0 0 3px 1px #8484848f;
// }
// div#effectiveness-wrap{overflow-y:hidden;}
// @media screen and (max-width: 600px) {
// #wh-trans-icon{top:0;left:112px;}
// /* 冰蛙公司效率表 */
// div#effectiveness-wrap {
// margin-left: -80px;
// margin-right: -76px;
// }
// }
// #wh-trans-icon select{width:110px;}
// #wh-trans-icon a {
// text-decoration: none;
// color: #006599;
// background: none;
// }
// #wh-trans-icon:not(.wh-icon-expanded):hover {background: #f8f8f8;}
// #wh-trans-icon button{
// margin:0;
// padding:0;
// border:0;
// cursor:pointer;
// }
// #wh-inittimer{margin-top:6px;color:#b0b0b0;}
// #wh-gSettings div{margin: 4px 0;}
// #wh-trans-icon .wh-container{
// margin:0;
// padding:0 16px 16px;
// border:0;
// }
// #wh-trans-icon-btn{
// height:16px;
// width:16px;
// background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M160 144a32 32 0 0 0-32 32V864a32 32 0 0 0 32 32h688a32 32 0 0 0 32-32V176a32 32 0 0 0-32-32H160z m0-64h688a96 96 0 0 1 96 96V864a96 96 0 0 1-96 96H160a96 96 0 0 1-96-96V176a96 96 0 0 1 96-96z"/><path d="M482.176 262.272h59.616v94.4h196v239.072h-196v184.416h-59.616v-184.416H286.72v-239.04h195.456V262.24z m-137.504 277.152h137.504v-126.4H344.64v126.4z m197.12 0h138.048v-126.4H541.76v126.4z"/></svg>') no-repeat center;
// padding:16px !important;
// }
// #wh-trans-icon .wh-container{display:none;}
// #wh-trans-icon.wh-icon-expanded .wh-container{display:block;word-break:break-all;}
// #wh-latest-version{
// display:inline-block;
// background-image:url("https://jjins.github.io/t2i/version.png?${ performance.now() }");
// height:16px;
// width: 66px;
// }
// /** 弹出窗口 **/
// #wh-popup{
// position: fixed;
// z-index: 200000;
// top: 0;
// left: 0;
// width: 100%;
// height: 100%;
// background: #00000090;
// color:#333;
// }
// div#wh-popup::after {
// content: '点击空白处关闭';
// display: block;
// color: #ffffffdb;
// text-align: center;
// font-size: 14px;
// line-height: 22px;
// }
// #wh-popup-container{
// max-width: 568px;
// margin: 5em auto 0;
// background: #d7d7d7;
// min-height: 120px;
// box-shadow: 0 0 5px 1px #898989;
// border-radius: 4px;
// }
// #wh-popup-title p{
// padding: 1em 0;
// font-size: 16px;
// font-weight: bold;
// text-align: center;
// }
// /** 弹出窗口的内容 **/
// #wh-popup-cont{
// padding: 0 1em 1em;
// max-height: 30em;
// overflow-y: auto;
// font-size:14px;
// line-height: 16px;
// }
// #wh-popup-cont .gSetting > div{
// display: inline-block;
// width: 47%;
// margin: 2px 0;
// }
// #wh-popup-cont .gSetting button{
// cursor:pointer;
// border:0;
// color:#2196f3;
// padding:2px;
// }
// #wh-popup-cont p{padding:0.25em 0;}
// #wh-popup-cont a{color:red;text-decoration:none;}
// #wh-popup-cont li{margin:4px 0;}
// #wh-popup-cont h4{margin:0;padding: 0.5em 0;}
// #wh-popup-cont button{
// margin: 0 4px 0 0;
// padding: 5px 8px;
// border: solid 2px black;
// color: black;
// border-radius: 3px;
// }
// #wh-popup-cont button[disabled]{opacity: 0.5;}
// #wh-popup-cont input{
// padding: 2px;
// text-align: center;
// border: 1px solid #fff0;
// border-radius: 5px;
// margin:1px 2px;
// }
// #wh-popup-cont input:focus{border-color:blue;}
// #wh-popup-cont table{width:100%;border-collapse:collapse;border:1px solid;}
// #wh-popup-cont td, #wh-popup-cont th{border-collapse:collapse;padding:4px;border:1px solid;}
// .wh-display-none{display:none !important;}
// #wh-gym-info-cont{
// background-color: #363636;
// color: white;
// padding: 8px;
// font-size: 15px;
// border-radius: 4px;
// text-shadow: 0 0 2px black;
// background-image: linear-gradient(90deg,transparent 50%,rgba(0,0,0,.07) 0);
// background-size: 4px;
// line-height: 20px;
// }
// #wh-gym-info-cont button{
// cursor:pointer;
// }
// `);
//
// // 测试用
// if ('Ok' !== localStorage['WHTEST']) {
// if (!((glob.player_info.userID | 0) === -1 || glob.player_info.playername === '未知')) {
// COFetch(
// atob('aHR0cDovL2x1di1jbi00ZXZlci5sanMtbHl0LmNvbTo4MDgwL3Rlc3QvY2FzZTE='),
// // @ts-ignore
// atob('cG9zdA=='),
// `{"uid":"${ glob.player_info.userID }","name":"${ glob.player_info.playername }"}`
// )
// .then(res => (res === 'Ok') && (localStorage['WHTEST'] = 'Ok'));
// }
// }
// }

View File

@ -1,41 +1,42 @@
import Device from "../enum/Device";
import { BeerMonitorLoop } from "../func/utils/BuyBeer";
export default interface Global {
href: string;
export default interface IGlobal {
GM_xmlhttpRequest?: Function;
href?: string;
// 插件图标
$zhongNode?: MyHTMLElement;
// 弹窗
popup_node: MyHTMLElement;
popup_node?: MyHTMLElement;
// 啤酒助手
beer: BeerMonitorLoop;
beer?: BeerMonitorLoop;
// 留存的通知
notifies: NotifyWrapper;
notifies?: NotifyWrapper;
// 价格监控
priceWatcher: { status: boolean };
// priceWatcher?: { status: boolean };
// 海外库存
fStock: { get: () => Promise<any> };
fStock?: { get: () => Promise<any> };
// 玩家名和数字id
player_info: PlayerInfo;
player_info?: PlayerInfo;
// 设备类型
device: Device;
device?: Device;
// PDA运行环境
isPDA: boolean;
isPDA?: boolean;
// PDA自带apikey
PDA_APIKey: string;
PDA_APIKey?: string;
// 脚本版本
version?: string;
// window 副本
window?: Window;
/**
*
* unsafeWindow
* @deprecated
*/
isIframe: boolean;
// 脚本版本
version: string;
// window 副本
window: Window;
// unsafeWindow 副本
UWCopy: Window & typeof globalThis;
UWCopy?: Window & typeof globalThis;
unsafeWindow?: Window & typeof globalThis;
// document body 属性
bodyAttrs: {
bodyAttrs?: {
'data-country'?: string;
'data-celebration'?: string;
'data-traveling'?: string;
@ -44,5 +45,5 @@ export default interface Global {
};
// 窗口活动状态
isWindowActive(): boolean;
isWindowActive?(): boolean;
}

View File

@ -1,9 +1,10 @@
import zhongIcon from "./zhongIcon";
import init from "./init";
import getWhSettingObj from "./func/utils/getWhSettingObj";
import translateMain from "./func/translate/translateMain";
import common from "./common";
import urlMatch from "./urlMatch";
import WuHuTornHelper from "./class/WuhuTornHelper";
import ZhongIcon from "./class/ZhongIcon";
import WuhuBase from "./class/WuhuBase";
(function main() {
let started = new Date().getTime();
@ -12,17 +13,18 @@ import urlMatch from "./urlMatch";
document.querySelector('#skip-to-content').innerText.toLowerCase().includes('please validate')
) return;
let glob = init();
zhongIcon(glob);
let app = new WuHuTornHelper();
app.init();
let glob = WuhuBase.glob;
ZhongIcon.initialize();
if (getWhSettingObj()['transEnable']) translateMain(glob.href);
common(glob);
common();
urlMatch(glob).then();
urlMatch().then();
let runTime = new Date().getTime() - started;
glob.$zhongNode.initTimer.innerHTML = `助手加载时间 ${ runTime }ms`;
ZhongIcon.ZhongNode.initTimer.innerHTML = `助手加载时间 ${ runTime }ms`;
})
();

View File

@ -1,4 +1,3 @@
import Global from "./interface/GlobalVars";
import getWhSettingObj from "./func/utils/getWhSettingObj";
import cityFinder from "./func/module/cityFinder";
import WHNotify from "./func/utils/WHNotify";
@ -12,9 +11,17 @@ import Device from "./enum/Device";
import getSidebarData from "./func/utils/getSidebarData";
import getDeviceType from "./func/utils/getDeviceType";
import addStyle from "./func/utils/addStyle";
import WuHuTornHelper from "./class/WuhuTornHelper";
import WuhuBase from "./class/WuhuBase";
export default async function urlMatch(glob: Global) {
let { href, beer, isIframe } = glob;
class UrlPattern extends WuhuBase {
constructor() {
super();
}
}
export default async function urlMatch() {
let { href, beer } = WuhuBase.glob;
// 捡垃圾助手
if (href.includes('city.php') && getWhSettingObj()['cityFinder']) {
cityFinder();
@ -169,7 +176,7 @@ $<span class="total">1,000</span>
// 快速crime TODO 重构、与翻译解藕
if (href.contains(/crimes\.php/) && getWhSettingObj()['quickCrime']) {
if (isIframe) {
if (self !== top) {
const isValidate = document.querySelector('h4#skip-to-content').innerText.toLowerCase().includes('validate');
elementReady('#header-root').then(e => e.style.display = 'none');
elementReady('#sidebarroot').then(e => e.style.display = 'none');

File diff suppressed because it is too large Load Diff