KR/activity/jd_cfd_pearl.js

670 lines
79 KiB
JavaScript
Raw Normal View History

2022-02-11 16:56:14 +08:00
/*
京喜财富岛合成珍珠
更新时间2021-9-11
活动入口京喜APP-我的-京喜财富岛合成珍珠
已支持IOS双京东账号,Node.js支持N个京东账号
脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js
============Quantumultx===============
[task_local]
#京喜财富岛合成珍珠
30 0-23/2 * * * https://raw.githubusercontent.com/KingRan/JDJB/main/jd_cfd_pearl.js, tag=京喜财富岛合成珍珠, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jxcfd.png, enabled=true
================Loon==============
[Script]
cron "30 0-23/2 * * *" script-path=https://raw.githubusercontent.com/KingRan/JDJB/main/jd_cfd_pearl.js,tag=京喜财富岛合成珍珠
===============Surge=================
京喜财富岛合成珍珠 = type=cron,cronexp="30 0-23/2 * * *",wake-system=1,timeout=3600,script-path=https://raw.githubusercontent.com/KingRan/JDJB/main/jd_cfd_pearl.js
============小火箭=========
京喜财富岛合成珍珠 = type=cron,script-path=https://raw.githubusercontent.com/KingRan/JDJB/main/jd_cfd_pearl.js, cronexpr="30 0-23/2 * * *", timeout=3600, enable=true
*/
const $ = new Env('京喜财富岛合成珍珠');
const jdCookieNode = $.isNode() ? require('./jdCookie.js') : '';
// const notify = $.isNode() ? require('./sendNotify') : '';
CryptoScripts()
$.CryptoJS = $.isNode() ? require('crypto-js') : CryptoJS;
let UA = `jdpingou;iPhone;5.2.2;14.3;${randomString(40)};network/wifi;model/iPhone12,1;appBuild/100630;ADID/00000000-0000-0000-0000-000000000000;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/0;hasOCPay/0;supportBestPay/0;session/1;pap/JA2019_3111789;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148`
function randomString(e) {
e = e || 32;
let t = "abcdef0123456789", a = t.length, n = "";
for (i = 0; i < e; i++)
n += t.charAt(Math.floor(Math.random() * a));
return n
}
$.InviteList = []
$.innerInviteList = [];
const HelpAuthorFlag = true;//是否助力作者SH true 助力false 不助力
// 热气球接客 每次运行接客次数
let serviceNum = 10;// 每次运行接客次数
if ($.isNode() && process.env.jd_wealth_island_serviceNum) {
serviceNum = Number(process.env.jd_wealth_island_serviceNum);
}
let cookiesArr = [], cookie = '';
if ($.isNode()) {
Object.keys(jdCookieNode).forEach((item) => {
cookiesArr.push(jdCookieNode[item])
})
if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => { };
} else {
cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item);
}
$.appId = 10032;
!(async () => {
if (!cookiesArr[0]) {
$.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { "open-url": "https://bean.m.jd.com/bean/signIndex.action" });
return;
}
await requestAlgo();
for (let i = 0; i < cookiesArr.length; i++) {
if (cookiesArr[i]) {
$.cookie = cookiesArr[i] + '';
$.UserName = decodeURIComponent($.cookie.match(/pt_pin=([^; ]+)(?=;?)/) && $.cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1])
$.index = i + 1;
$.isLogin = true;
console.log(`\n*****开始【京东账号${$.index}${$.UserName}****\n`);
UA = `jdpingou;iPhone;5.2.2;14.3;${randomString(40)};network/wifi;model/iPhone12,1;appBuild/100630;ADID/00000000-0000-0000-0000-000000000000;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/0;hasOCPay/0;supportBestPay/0;session/1;pap/JA2019_3111789;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148`
await run();
}
}
})()
.catch((e) => {
$.log('', `${$.name}, 失败! 原因: ${e}!`, '')
}).finally(() => {
$.done();
})
async function run() {
try{
$.HomeInfo = ''
$.LeadInfo = ''
$.buildList = ''
$.Fund = ''
$.task = []
$.Biztask = []
$.Aggrtask = []
$.Employtask = []
await GetHomePageInfo()
if($.HomeInfo){
$.InviteList.push($.HomeInfo.strMyShareId)
console.log(`等级:${$.HomeInfo.dwLandLvl} 当前金币:${$.HomeInfo.ddwCoinBalance} 当前财富:${$.HomeInfo.ddwRichBalance} 助力码:${$.HomeInfo.strMyShareId}`)
}
if($.LeadInfo && $.LeadInfo.dwLeadType == 2){
await $.wait(2000)
console.log(`\n新手引导`)
await noviceTask()
await GetHomePageInfo()
await $.wait(1000)
}
// 撸珍珠
await Pearl()
}
catch (e) {
console.log(e);
}
}
async function GetHomePageInfo() {
let e = getJxAppToken()
let additional= `&strPgtimestamp=${e.strPgtimestamp}&strPhoneID=${e.strPhoneID}&strPgUUNum=${e.strPgUUNum}&ddwTaskId=&strShareId=&strMarkList=guider_step%2Ccollect_coin_auth%2Cguider_medal%2Cguider_over_flag%2Cbuild_food_full%2Cbuild_sea_full%2Cbuild_shop_full%2Cbuild_fun_full%2Cmedal_guider_show%2Cguide_guider_show%2Cguide_receive_vistor%2Cdaily_task%2Cguider_daily_task%2Ccfd_has_show_selef_point`
let stk= `_cfd_t,bizCode,ddwTaskId,dwEnv,ptag,source,strMarkList,strPgUUNum,strPgtimestamp,strPhoneID,strShareId,strVersion,strZone`
$.HomeInfo = await taskGet(`user/QueryUserInfo`, stk, additional)
if($.HomeInfo){
$.Fund = $.HomeInfo.Fund || ''
$.LeadInfo = $.HomeInfo.LeadInfo || ''
$.buildInfo = $.HomeInfo.buildInfo || ''
$.XbStatus = $.HomeInfo.XbStatus || []
if($.buildInfo.buildList){
$.buildList = $.buildInfo.buildList || ''
}
}
}
// 撸珍珠
async function Pearl(){
try{
await $.wait(1500)
$.ComposeGameState = await taskGet(`user/ComposePearlState`, '', '&dwGetType=0')
console.log(`\n当前有${$.ComposeGameState.dwCurProgress}个珍珠${$.ComposeGameState.ddwVirHb && ' '+$.ComposeGameState.ddwVirHb/100+"红包" || ''}`)
if($.ComposeGameState.dayDrawInfo.dwIsDraw == 0){
let res = ''
res = await taskGet(`user/GetPearlDailyReward`, '__t,strZone', ``)
if(res && res.iRet == 0 && res.strToken){
res = await taskGet(`user/PearlDailyDraw`, '__t,ddwSeaonStart,strToken,strZone', `&ddwSeaonStart=${$.ComposeGameState.ddwSeasonStartTm}&strToken=${res.strToken}`)
if(res && res.iRet == 0){
if(res.strPrizeName){
console.log(`抽奖获得:${res.strPrizeName || $.toObj(res,res)}`)
}else{
console.log(`抽奖获得:${$.toObj(res,res)}`)
}
}else{
console.log("抽奖失败\n"+$.toObj(res,res))
}
}else{
console.log($.toObj(res,res))
}
}
if (($.ComposeGameState.dwCurProgress < 8 || true) && $.ComposeGameState.strDT) {
let b = 1
console.log(`合珍珠${b}`)
// b = 8-$.ComposeGameState.dwCurProgress
for(i=1;b--;i++){
let n = Math.ceil(Math.random()*8+8)
console.log(`上报次数${n}`)
for(m=1;n--;m++){
console.log(`上报第${m}`)
await $.wait(3000)
await taskGet(`user/RealTmReport`, '', `&dwIdentityType=0&strBussKey=composegame&strMyShareId=${$.ComposeGameState.strMyShareId}&ddwCount=10`)
let s = Math.floor((Math.random()*3))
let n = 0
if(s == 1) n = 1
if(n === 1){
let res = await taskGet(`user/ComposePearlAward`, '__t,size,strBT,strZone,type', `__t=${Date.now()}&type=4&size=1&strBT=${$.ComposeGameState.strDT}`)
if(res && res.iRet == 0){
console.log(`上报得红包:${res.ddwAwardHb && '获得'+res.ddwAwardHb/100+"红包" || ''}${res.ddwVirHb && ' 当前有'+res.ddwVirHb/100+"红包" || ''}`)
}else{
console.log($.toObj(res,res))
}
}
}
console.log("合成珍珠")
let strLT = ($.ComposeGameState.oPT || [])[$.ComposeGameState.ddwCurTime % ($.ComposeGameState.oPT || []).length]
let res = await taskGet(`user/ComposePearlAddProcess`, '__t,strBT,strLT,strZone', `&strBT=${$.ComposeGameState.strDT}&strLT=${strLT}`)
if(res && res.iRet == 0){
console.log(`合成成功:${res.ddwAwardHb && '获得'+res.ddwAwardHb/100+"红包 " || ''}当前有${res.dwCurProgress}个珍珠${res.ddwVirHb && ' '+res.ddwVirHb/100+"红包" || ''}`)
}else{
console.log(JSON.stringify(res))
}
$.ComposeGameState = await taskGet(`user/ComposePearlState`, '', '&dwGetType=0')
}
}
for (let i of $.ComposeGameState.stagelist || []) {
if (i.dwIsAward == 0 && $.ComposeGameState.dwCurProgress >= i.dwCurStageEndCnt) {
await $.wait(2000)
let res = await taskGet(`user/ComposeGameAward`, '__t,dwCurStageEndCnt,strZone', `&dwCurStageEndCnt=${i.dwCurStageEndCnt}`)
await printRes(res,'珍珠领奖')
}
}
}catch (e) {
$.logErr(e);
}
}
function printRes(res, msg=''){
if(res.iRet == 0 && (res.Data || res.ddwCoin || res.ddwMoney || res.strPrizeName)){
let result = res
if(res.Data){
result = res.Data
}
if(result.ddwCoin || result.ddwMoney || result.strPrizeName || result.StagePrizeInfo && result.StagePrizeInfo.strPrizeName){
console.log(`${msg}获得:${result.ddwCoin && ' '+result.ddwCoin+'金币' || ''}${result.ddwMoney && ' '+result.ddwMoney+'财富' || ''}${result.strPrizeName && ' '+result.strPrizeName+'红包' || ''}${result.StagePrizeInfo && result.StagePrizeInfo.strPrizeName && ' '+result.StagePrizeInfo.strPrizeName || ''}`)
}else if(result.Prize){
console.log(`${msg}获得: ${result.Prize.strPrizeName && '优惠券 '+result.Prize.strPrizeName || ''}`)
}else if(res && res.sErrMsg){
console.log(res.sErrMsg)
}else{
console.log(`${msg}完成`, JSON.stringify(res))
// console.log(`完成`)
}
}else if(res && res.sErrMsg){
console.log(`${msg}失败:${res.sErrMsg}`)
}else{
console.log(`${msg}失败:${JSON.stringify(res)}`)
}
}
function getJxAppToken(){
function generateStr(e) {
e = e || 32;
let t = "abcdefghijklmnopqrstuvwxyz1234567890", a = t.length, n = "";
for (i = 0; i < e; i++)
n += t.charAt(Math.floor(Math.random() * a));
return n
}
let phoneId = generateStr(40);
let timestamp = Date.now().toString();
let pgUUNum = $.CryptoJS.MD5('' + decodeURIComponent($.UserName || '') + timestamp + phoneId + 'tPOamqCuk9NLgVPAljUyIHcPRmKlVxDy').toString($.CryptoJS.enc.MD5);
return {
'strPgtimestamp': timestamp,
'strPhoneID': phoneId,
'strPgUUNum': pgUUNum
}
}
async function noviceTask(){
let additional= ``
let stk= ``
additional= ``
stk= `_cfd_t,bizCode,dwEnv,ptag,source,strZone`
await taskGet(`user/guideuser`, stk, additional)
additional= `&strMark=guider_step&strValue=welcom&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
additional= `&strMark=guider_over_flag&strValue=999&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
additional= `&strMark=guider_step&strValue=999&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
additional= `&strMark=guider_step&strValue=999&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
additional= `&strMark=guider_over_flag&strValue=999&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
additional= `&strMark=guider_step&strValue=gift_redpack&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
additional= `&strMark=guider_step&strValue=none&dwType=2`
stk= `_cfd_t,bizCode,dwEnv,dwType,ptag,source,strMark,strValue,strZone`
await taskGet(`user/SetMark`, stk, additional)
}
function taskGet(type, stk, additional){
return new Promise(async (resolve) => {
let myRequest = getGetRequest(type, stk, additional)
$.get(myRequest, async (err, resp, _data) => {
let data = ''
try {
let contents = ''
// console.log(_data)
data = $.toObj(_data)
if(data && data.iRet == 0){
// console.log(_data)
}else{
// 1771|1771|5001|0|0,1771|75|1023|0|请刷新页面重试
// console.log(_data)
}
contents = `1771|${opId(type)}|${data && data.iRet || 0}|0|${data && data.sErrMsg || 0}`
await biz(contents)
}
catch (e) {
$.logErr(e, resp);
}
finally {
resolve(data);
}
});
});
}
function getGetRequest(type, stk='', additional='') {
let url = ``;
let dwEnv = 7;
let types = {
'GetUserTaskStatusList':['GetUserTaskStatusList','jxbfd'],
'Award':['Award','jxbfd'],
'Award1':['Award','jxbfddch'],
'Award2':['Award','jxbfdprop'],
'DoTask':['DoTask','jxbfd'],
'DoTask1':['DoTask','jxbfddch'],
'DoTask2':['DoTask','jxbfdprop'],
}
if(type == 'user/ComposeGameState'){
url = `https://m.jingxi.com/jxbfd/${type}?__t=${Date.now()}&strZone=jxbfd${additional}&_=${Date.now()}&sceneval=2`
}else if(type == 'user/RealTmReport'){
url = `https://m.jingxi.com/jxbfd/${type}?__t=${Date.now()}${additional}&_=${Date.now()}&sceneval=2`
}else{
let stks = ''
if(stk) stks = `&_stk=${stk}`
if(type == 'story/GetTakeAggrPages' || type == 'story/RewardSigns') dwEnv = 6
if(type == 'story/GetTakeAggrPages') type = 'story/GetTakeAggrPage'
if(type == 'story/RewardSigns') type = 'story/RewardSign'
if(types[type]){
url = `https://m.jingxi.com/newtasksys/newtasksys_front/${types[type][0]}?strZone=jxbfd&bizCode=${types[type][1]}&source=jxbfd&dwEnv=${dwEnv}&_cfd_t=${Date.now()}${additional}${stks}&_ste=1&_=${Date.now()}&sceneval=2&g_login_type=1`
}else if(type == 'user/ComposeGameAddProcess' || type == 'user/ComposeGameAward'){
url = `https://m.jingxi.com/jxbfd/${type}?strZone=jxbfd&__t=${Date.now()}${additional}${stks}&_=${Date.now()}&sceneval=2`;
}else{
url = `https://m.jingxi.com/jxbfd/${type}?strZone=jxbfd&bizCode=jxbfd&source=jxbfd&dwEnv=${dwEnv}&_cfd_t=${Date.now()}&ptag=${additional}${stks}&_=${Date.now()}&sceneval=2`;
}
url += `&h5st=${decrypt(Date.now(), stk, '', url)}`;
}
return {
url,
headers: {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Connection": "keep-alive",
'Cookie': $.cookie,
'Host': 'm.jingxi.com',
"Referer": "https://st.jingxi.com/",
"User-Agent": UA,
}
}
}
function biz(contents){
return new Promise(async (resolve) => {
let myRequest = {
url:`https://m.jingxi.com/webmonitor/collect/biz.json?contents=${contents}&t=${Math.random()}&sceneval=2`,
headers: {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Connection": "keep-alive",
'Cookie': $.cookie,
'Host': 'm.jingxi.com',
"Referer": "https://st.jingxi.com/",
"User-Agent": UA,
}
}
$.get(myRequest, async (err, resp, _data) => {
try {
// console.log(_data)
}
catch (e) {
$.logErr(e, resp);
}
finally {
resolve();
}
});
});
}
function opId(type){
let jsonMap = {
"user/QueryUserInfo": 1,
"user/GetMgrAllConf": 3,
"story/QueryUserStory": 5,
"user/GetJdToken": 11,
"story/CouponState": 13,
"story/WelfareDraw": 15,
"story/GetWelfarePage": 17,
"story/SendWelfareMoney": 19,
"user/SetMark": 23,
"user/GetMark": 25,
"user/guideuser": 27,
"user/createbuilding": 29,
"user/BuildLvlUp": 31,
"user/CollectCoin": 33,
"user/GetBuildInfo": 35,
"user/SpeedUp": 37,
"story/AddNoticeMsg": 39,
"user/breakgoldenegg": 41,
"user/closewindow": 43,
"user/drawpackprize": 45,
"user/GetMoneyDetail": 47,
"user/EmployTourGuide": 49,
"story/sellgoods": 51,
"story/querystorageroom": 53,
"user/queryuseraccount": 55,
"user/EmployTourGuideInfo": 57,
"consume/TreasureHunt": 59,
"story/QueryAppSignList": 61,
"story/AppRewardSign": 63,
"story/queryshell": 65,
"story/QueryRubbishInfo": 67,
"story/pickshell": 69,
"story/CollectorOper": 71,
"story/MermaidOper": 73,
"story/RubbishOper": 75,
"story/SpecialUserOper": 77,
"story/GetUserTaskStatusList": 79,
"user/ExchangeState": 87,
"user/ExchangePrize": 89,
"user/GetRebateGoods": 91,
"user/BuyGoods": 93,
"user/UserCashOutState": 95,
"user/CashOut": 97,
"user/GetCashRecord": 99,
"user/CashOutQuali": 101,
"user/GetAwardList": 103,
"story/QueryMailBox": 105,
"story/MailBoxOper": 107,
"story/UserMedal": 109,
"story/QueryMedalList": 111,
"story/GetTakeAggrPage": 113,
"story/GetTaskRedDot": 115,
"story/RewardSign": 117,
"story/helpdraw": 119,
"story/helpbystage": 121,
"task/addCartSkuNotEnough": 123,
"story/GetActTask": 125,
"story/ActTaskAward": 127,
"story/DelayBizReq": 131,
"story/AddSuggest": 133,
}
let opId = jsonMap[type]
if (opId!=undefined) return opId
return 5001
}
async function requestAlgo() {
$.fp = (getRandomIDPro({ size: 13 }) + Date.now()).slice(0, 16);
const options = {
"url": `https://cactus.jd.com/request_algo?g_ty=ajax`,
headers: {
'Authority': 'cactus.jd.com',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': 'https://st.jingxi.com',
'Sec-Fetch-Site': 'cross-site',
'User-Agent': UA,
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Referer': 'https://st.jingxi.com/',
'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7'
},
'body': JSON.stringify({
"version": "1.0",
"fp": $.fp,
"appId": $.appId,
"timestamp": Date.now(),
"platform": "web",
"expandParams": ""
})
}
return new Promise(async resolve => {
$.post(options, (err, resp, data) => {
try {
const { ret, msg, data: { result } = {} } = JSON.parse(data);
$.token = result.tk;
$.genKey = new Function(`return ${result.algo}`)();
} catch (e) {
$.logErr(e, resp);
} finally {
resolve();
}
})
})
}
function getRandomIDPro() {
var e,
t,
a = void 0 === (n = (t = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}).size) ? 10 : n,
n = void 0 === (n = t.dictType) ? 'number' : n,
i = '';
if ((t = t.customDict) && 'string' == typeof t) e = t;
else
switch (n) {
case 'alphabet':
e = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'max':
e = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';
break;
case 'number':
default:
e = '0123456789';
}
for (; a--;) i += e[(Math.random() * e.length) | 0];
return i;
}
function decrypt(time, stk, type, url) {
stk = stk || (url ? getUrlQueryParams(url, '_stk') : '')
if (stk) {
const timestamp = format("yyyyMMddhhmmssSSS", time);
const hash1 = $.genKey($.token, $.fp.toString(), timestamp.toString(), $.appId.toString(), $.CryptoJS).toString($.CryptoJS.enc.Hex);
let st = '';
stk.split(',').map((item, index) => {
st += `${item}:${getUrlQueryParams(url, item)}${index === stk.split(',').length - 1 ? '' : '&'}`;
})
const hash2 = $.CryptoJS.HmacSHA256(st, hash1.toString()).toString($.CryptoJS.enc.Hex);
return encodeURIComponent(["".concat(timestamp.toString()), "".concat($.fp.toString()), "".concat($.appId.toString()), "".concat($.token), "".concat(hash2)].join(";"))
} else {
return encodeURIComponent('20210713151140309;3329030085477162;10032;tk01we5431d52a8nbmxySnZya05SXBQSsarucS7aqQIUX98n+iAZjIzQFpu6+ZjRvOMzOaVvqHvQz9pOhDETNW7JmftM;3e219f9d420850cadd117e456d422e4ecd8ebfc34397273a5378a0edc70872b9')
}
}
function format(a, time) {
if (!a) a = 'yyyy-MM-dd';
var t;
if (!time) {
t = Date.now();
} else {
t = new Date(time);
}
var e,
n = new Date(t),
d = a,
l = {
'M+': n.getMonth() + 1,
'd+': n.getDate(),
'D+': n.getDate(),
'h+': n.getHours(),
'H+': n.getHours(),
'm+': n.getMinutes(),
's+': n.getSeconds(),
'w+': n.getDay(),
'q+': Math.floor((n.getMonth() + 3) / 3),
'S+': n.getMilliseconds(),
};
/(y+)/i.test(d) && (d = d.replace(RegExp.$1, ''.concat(n.getFullYear()).substr(4 - RegExp.$1.length)));
Object.keys(l).forEach(e => {
if (new RegExp('('.concat(e, ')')).test(d)) {
var t,
a = 'S+' === e ? '000' : '00';
d = d.replace(RegExp.$1, 1 == RegExp.$1.length ? l[e] : ''.concat(a).concat(l[e]).substr(''.concat(l[e]).length));
}
});
return d;
}
function getUrlQueryParams(url_string, param) {
let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)", "i");
let r = url_string.split('?')[1].substr(0).match(reg);
if (r != null) {
return decodeURIComponent(r[2]);
};
return '';
}
function getAuthorShareCode(url) {
return new Promise(async resolve => {
const options = {
"url": `${url}?${new Date()}`,
"timeout": 10000,
"headers": {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/87.0.4280.88"
}
};
if ($.isNode() && process.env.TG_PROXY_HOST && process.env.TG_PROXY_PORT) {
const tunnel = require("tunnel");
const agent = {
https: tunnel.httpsOverHttp({
proxy: {
host: process.env.TG_PROXY_HOST,
port: process.env.TG_PROXY_PORT * 1
}
})
}
Object.assign(options, { agent })
}
let res = []
$.get(options, async (err, resp, data) => {
try {
if (err) {
} else {
if (data) res = JSON.parse(data)
}
} catch (e) {
// $.logErr(e, resp)
} finally {
resolve(res || []);
}
})
await $.wait(10000)
resolve(res);
})
}
/**
* 随机从一数组里面取
* @param arr
* @param count
* @returns {Buffer}
*/
function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
// 计算时间
function timeFn(dateBegin) {
var hours = 0
var minutes = 0
var seconds = 0
if(dateBegin != 0){
//如果时间格式是正确的,那下面这一步转化时间格式就可以不用了
var dateEnd = new Date();//获取当前时间
var dateDiff = dateBegin - dateEnd.getTime();//时间差的毫秒数
var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
//计算相差分钟数
var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
//计算相差秒数
var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
seconds = Math.round(leave3 / 1000)
}
hours = hours < 10 ? '0'+ hours : hours
minutes = minutes < 10 ? '0'+ minutes : minutes
seconds = seconds < 10 ? '0'+ seconds : seconds
var timeFn = hours + ":" + minutes + ":" + seconds;
return timeFn;
}
function jsonParse(str) {
if (typeof str == "string") {
try {
return JSON.parse(str);
} catch (e) {
console.log(e);
$.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie')
return [];
}
}
}
function CryptoScripts() {
// prettier-ignore
!function(t,e){"object"==typeof exports?module.exports=exports=e():"function"==typeof define&&define.amd?define([],e):t.CryptoJS=e()}(this,function(){var t,e,r,i,n,o,s,c,a,h,l,f,d,u,p,_,v,y,g,B,w,k,S,m,x,b,H,z,A,C,D,E,R,M,F,P,W,O,I,U,K,X,L,j,N,T,q,Z,V,G,J,$,Q,Y,tt,et,rt,it,nt,ot,st,ct,at,ht,lt,ft,dt,ut,pt,_t,vt,yt,gt,Bt,wt,kt,St,mt=mt||function(t){var e;if("undefined"!=typeof window&&window.crypto&&(e=window.crypto),!e&&"undefined"!=typeof window&&window.msCrypto&&(e=window.msCrypto),!e&&"undefined"!=typeof global&&global.crypto&&(e=global.crypto),!e&&"function"==typeof require)try{e=require("crypto")}catch(e){}function r(){if(e){if("function"==typeof e.getRandomValues)try{return e.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof e.randomBytes)try{return e.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")}var i=Object.create||function(t){var e;return n.prototype=t,e=new n,n.prototype=null,e};function n(){}var o={},s=o.lib={},c=s.Base={extend:function(t){var e=i(this);return t&&e.mixIn(t),e.hasOwnProperty("init")&&this.init!==e.init||(e.init=function(){e.$super.init.apply(this,arguments)}),(e.init.prototype=e).$super=this,e},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}},a=s.WordArray=c.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=null!=e?e:4*t.length},toString:function(t){return(t||l).stringify(this)},concat:function(t){var e=this.words,r=t.words,i=this.sigBytes,n=t.sigBytes;if(this.clamp(),i%4)for(var o=0;o<n;o++){var s=r[o>>>2]>>>24-o%4*8&255;e[i+o>>>2]|=s<<24-(i+o)%4*8}else for(o=0;o<n;o+=4)e[i+o>>>2]=r[o>>>2];return this.sigBytes+=n,this},clamp:function(){var e=this.words,r=this.sigBytes;e[r>>>2]&=4294967295<<32-r%4*8,e.length=t.ceil(r/4)},clone:function(){var t=c.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],i=0;i<t;i+=4)e.push(r());return new a.init(e,t)}}),h=o.enc={},l=h.Hex={stringify:function(t){for(var e=t.words,r=t.sigBytes,i=[],n=0;n<r;n++){var o=e[n>>>2]>>>24-n%4*8&255;i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(t){for(var e=t.length,r=[],i=0;i<e;i+=2)r[i>>>3]|=parseInt(t.substr(i,2),16)<<24-i%8*4;return new a.init(r,e/2)}},f=h.Latin1={stringify:function(t){for(var e=t.words,r=t.sigBytes,i=[],n=0;n<r;n++){var o=e[n>>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(o))}return i.join("")},parse:function(t){for(var e=t.length,r=[],i=0;i<e;i++)r[i>>>2]|=(255&t.charCodeAt(i))<<24-i%4*8;return new a.init(r,e)}},d=h.Utf8={stringify:function(t){try{return decodeURIComponent(escape(f.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return f.parse(unescape(encodeURIComponent(t)))}},u=s.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=d.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var r,i=this._data,n=i.words,o=i.sigBytes,s=this.blockSize,c=o/(4*s),h=(c=e?t.ceil(c):t.max((0|c)-this._minBufferSize,0))*s,l=t.min(4*h,o);if(h){for(var f=0;f<h;f+=s)this._doProcessBlock(n,f);r=n.splice(0,h),i.sigBytes-=l}return new a.init(r,l)},clone:function(){var t=c.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0}),p=(s.Hasher=u.extend({cfg:c.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){u.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){return t&&this._append(t),this._doFinalize()},blockSize:16,_createHelper:function(t){return function(e,r){return new t.init(r).finalize(e)}},_createHmacHelper:function(t){return function(e,r){return new p.HMAC.init(t,r).finalize(e)}}}),o.algo={});return o}(Math);function xt(t,e,r){return t^e^r}fu
}
function Env(t,e){"undefined"!=typeof process&&JSON.stringify(process.env).indexOf("GITHUB")>-1&&process.exit(0);class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}isShadowrocket(){return"undefined"!=typeof $rocket}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(del