/* 平安银行宜家礼品卡优惠券 https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html?paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D pahkebank:// [Script] # > 平安银行宜家礼品卡优惠券 ^https?:\/\/b\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js ^https?:\/\/b\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js ^https?:\/\/rsb\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js ^https?:\/\/rsb\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js ^https?:\/\/rmb\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js ^https?:\/\/rmb\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js [MITM] hostname = b.pingan.com.cn,rsb.pingan.com.cn,rmb.pingan.com.cn */ const scriptName = `平安银行宜家礼品卡优惠券`; const magicJS = MagicJS(scriptName, "INFO"); const PingAnConstKey = { // 基础数据 Cookie: 'PingAnInnerWebCookie', DeviceId: 'PingAnInnerWebDeviceId', x_g_sid: 'PingAnInnerWeb#x_g_sid', x_g_vid: 'PingAnInnerWeb#x_g_vid', x_g_rid: 'PingAnInnerWeb#x_g_rid', PageData: 'PingAnInnerWeb#PageData', PageActionId: 'PingAnInnerWeb#PageActionId', }; let gRetBody; let errCodeStrMap = { 900111: "notStart", 900112: "notStart", 900113: "finish", 900109: "exceed", 910179: "nonLottery", 910204: "nonBindCard", 701001: "limitFlow", 700116: "nonBindWechat", 700118: "nonInterestWechat", 960002: "nonDayStock", 900537: "nonStock", 900139: "nonWhiteList", 900320: "riskList", 900130: "nonRules", 900982: "mutex", 950010: "nonDayTimes", 950710: "nonWeekTimes", 700119: "nonMonthTimes", 900144: "nonTimes", 950008: "nonDayPrizeTimes", 900745: "nonWeekPrizeTimes", 950009: "nonMonthPrizeTimes", 900143: "nonPrizeTimes", 600056: "timesCutDown", 780001: "nonBindAliPay", 900203: "notSendAble", 999999: "stockValidateText" }; const gTeamId = `5K2422`; const gActivityId = `PK084123`; const gPageUrlFirstPath = '/kuaizhan/v2'; const gPageUrlSuffix = `5K2422/20230925/k84123`; const gHost = 'rsb.pingan.com.cn'; const gReferer = `https://b.pingan.com.cn/kuaizhan/v2/${gPageUrlSuffix}/index.html`; const gHomePageUrl = `${gReferer}?paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D`; const gWebUserAgent = `Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.50(0x18003237) NetType/WIFI Language/zh_CN`; let gDeviceId = magicJS.data.read(PingAnConstKey.DeviceId, 'AUUID_918d439ffcef935c2fd84d3a3e593b6523c916fc'); let gPageActionId = magicJS.data.read(PingAnConstKey.PageActionId, '1F908E50'); let gAppUserAgent = `Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 iphone 14 pro AladdinHybrid/4.8.77 (PAEBank 6.23.0) AladdinBridge/3.0.0 subContracting/AppStore deviceId/${gDeviceId} UnionPay/1.0 PABANK deviceType/1 networkState/WIFI KiwiBridge/1.0.0 device-dpr/3 device-dr/852*393 AppStyle/BZ bz-navbarHeight/309 dzTab-navbarHeight/327 pageActionId/${gPageActionId}`; let gTmpRequsetTimeStamp = Date.now(); let gTmpRequestSortId = 100 + Math.floor(Math.random() * 100); const gCommonHeaders = { 'osVersion': `16.6.1`, 'Accept-Encoding': `gzip, deflate, br`, 'Host': `${gHost}`, 'X-App-Version': `6.23.0`, 'phoneModel': `iPhone15,2`, 'Connection': `keep-alive`, 'bank-mobile-model': `iPhone15,2`, 'Accept-Language': `zh-Hans-CN;q=1`, 'nativeVersion': `6.23.0`, 'User-Agent': `${gAppUserAgent}`, 'Referer': `${gReferer}`, 'X-Aladdin-Version': `4.8.77`, 'bank-mobile-brand': `Apple`, 'x-o-spanid': `0`, 'Accept': `*/*`, 'x-g-sid': `iSb07mg4hmSUYbUg5izmW0`, 'x-g-vid': `53mWJHzK00401M5Vv+uR3w`, 'x-g-rid': `J3/I3jF+hI6xiREInsHZlg5dn320120r`, 'X-REQUEST-ID': `${gDeviceId}-${gTmpRequsetTimeStamp}-${gTmpRequestSortId}`, 'Cookie': `` }; let gPageData = {}; let gPageId = 'PK084123'; // 忽略执行的本地领券状态 let gIgnoreCouponGotStatus = false; // 忽略查询的领券状态 let gIgnoreActivityStatus = false;; async function Main() { if (magicJS.isStrictRequest) { magicJS.checkRecordRequestBody(); } if (magicJS.isRequest) { checkHandleRequest(); } else { updateHeaders(); await tryGrabCoupon(); } magicJS.notification.msg(''); if (gRetBody) { magicJS.done({ body: JSON.stringify(gRetBody) }); } else { magicJS.done(); } } function checkHandleRequest() { const url = $request.url; const path = $request.path; magicJS.log(`请求url=${url}#${$request.method}`); if ($request && $request.method != 'OPTIONS') { switch (path) { case '/brop/cmp/cust/cmpsf/mgm/share/createTokenId.do': handleCreateTokenId(); break; case '/brop/mop/cust/mopsf/nrp/uc/simple/rule/info/batchSatisfy': handleBatchSatisfy(); break; case '/brop/cmp/cust/cmpsf/mgm/origin/queryPageConfig.do': handlePageConfig(); break; case '/brcp/uc/cust/uc-login-web.qryLoginStatus.do': break; case '/brop/mop/cust/mopsf/lottery/getLeftOfferNum': break; case '/brop/mop/cust/mopsf/uc/auth/lottery/sendCustomerOffer': handleCustomerOffer(); break; default: if (path.indexOf('/kuaizhan/v2/5K2422/20230925/k84123/index.html') > -1) { handleHomePage(); } else if (path.indexOf('/rmb/brcp/uc/cust/uc-login-web.qryLoginStatus.do') > -1) { handleLoginStatus(); } else if (path.indexOf('/brop/mop/cust/mopsf/personality/activity/status/query') > -1) { handlePublicActivityStatus(); } else if (path.indexOf('/bron/coss/cust/app/getSupernatant') > -1) { } else if (path.indexOf('/brop/mop/cust/mopsf/uc/auth/lottery/queryCustomerActivityStatus') > -1) { handleCustomerActivityStatus(); } else if (path.indexOf('/brop/stp/kafka/http/h5monitor_web/rest/ac/h5Monitor') > -1) { handleH5MonitorUploadInfo(); } break; } } } function getResponsePlainData() { let data = magicJS.getResponseBody(); if (!data) { return; } try { return JSON.parse(data); } catch (err) { magicJS.logger.error(err); } } function getRequestPlainData() { let data = magicJS.getRequestBody(); let reqData = null; if (data) { reqData = magicJS.parseQueryStr(data); } else { reqData = magicJS.parseQueryStr($request.url); } return reqData; } function getQueryPlainData() { let params = magicJS.parseQueryStr($request.url); return params; } function getXRequestId() { gTmpRequestSortId++; return `${gDeviceId}-${gTmpRequsetTimeStamp}-${gTmpRequestSortId}` } function getWillRequestHeaders() { let headers = gCommonHeaders; headers['X-REQUEST-ID'] = getXRequestId(); return headers; } function handleHeaders() { if ($request && $request.method != 'OPTIONS') { let headers = $request.headers; let x_g_sid = headers['x-g-sid']; if (x_g_sid) { magicJS.data.write(PingAnConstKey.x_g_sid, x_g_sid); } let x_g_vid = headers['x-g-vid']; if (x_g_vid) { magicJS.data.write(PingAnConstKey.x_g_vid, x_g_vid); } let x_g_rid = headers['x-g-rid']; if (x_g_rid) { magicJS.data.write(PingAnConstKey.x_g_rid, x_g_rid); } if (headers['X-REQUEST-ID']) { let tmpArr = headers['X-REQUEST-ID'].split('-'); magicJS.data.write(PingAnConstKey.DeviceId, tmpArr[0]); } let newCookieStr = headers['Cookie']; if (newCookieStr) { let oldCookieStr = magicJS.data.read(PingAnConstKey.Cookie, null); magicJS.logger.info(`oldCookieStr=${oldCookieStr}`); magicJS.logger.info(`newCookieStr=${newCookieStr}`); if (compareCookieStr(newCookieStr, oldCookieStr) != 0) { magicJS.data.write(PingAnConstKey.Cookie, newCookieStr); magicJS.logger.info(`当前Cookie刷新到最新`); magicJS.notification.appendNotifyInfo(`🎉当前Cookie刷新到最新`); } else { magicJS.data.write(PingAnConstKey.Cookie, newCookieStr); magicJS.logger.info(`当前Cookie已经是最新无需更新`); } } let userAgent = headers['User-Agent']; let mRet = userAgent.match(/pageActionId\/([\S.]+)\s*/); let pageActionId = mRet && mRet[1] ? mRet[1] : ""; if (pageActionId && pageActionId.length > 0) { magicJS.data.write(PingAnConstKey.PageActionId, pageActionId); } } } function compareCookieStr(cookieStr1, cookieStr2) { let cookieDict1 = magicJS.parseCookies(cookieStr1); let cookieDict2 = magicJS.parseCookies(cookieStr2); let skipKeys = ['NGWhitelist', 'PAEBANK_PARAM', 'PAEBANK_PARAM_N', 'PAEBANK_PARAM_W', 'WEBTRENDS_SESSIONID', 'brcpSessionTicket', 'sdc_PABankParam', 'shuntid']; skipKeys = ['PAEBANK_PARAM', 'WEBTRENDS_SESSIONID']; let retCode = 0; for (let key in cookieDict1) { if (!skipKeys.includes(key)) { if (cookieDict1[key] != void 0 && cookieDict2[key] != void 0 && cookieDict1[key] != cookieDict2[key]) { magicJS.logger.info(`${key}`); retCode = -1; break; } } } return retCode; } function handleHomePage() { handleHeaders(); } function handleCreateTokenId() { } function handleBatchSatisfy() { } function handlePageConfig() { handleHeaders(); let rspData = getResponsePlainData(); if (!rspData) { return; } if (rspData.responseCode != "000000") { return; } let data = rspData.data; if (data.reShow) { } } function handlePublicActivityStatus() { handleHeaders(); let rspData = getResponsePlainData(); if (!rspData) { return; } if (rspData.responseCode != "000000") { return; } let queryParams = getQueryPlainData(); let activityCode = queryParams.activityCode; let queryNextTime = queryParams.queryNextTime; let data = rspData.data; } function handleCustomerActivityStatus() { handleHeaders(); let rspData = getResponsePlainData(); if (!rspData) { return; } rspData = { pagination: null, data: null, responseCode: "000000", responseMsg: "成功" }; gRetBody = rspData; if (rspData.responseCode != "000000") { return; } } function handleCustomerOffer() { let rspData = getResponsePlainData(); if (!rspData) { return; } rspData.responseCode = "000000"; gRetBody = rspData; if (rspData.responseCode != "000000") { return; } } function handleLoginStatus() { handleHeaders(); let rspData = getResponsePlainData(); if (!rspData) { return; } if (rspData.responseCode != "000000") { return; } } function handleH5MonitorUploadInfo() { let rspData = getResponsePlainData(); if (!rspData) { return; } if (rspData.responseCode != "000000") { return; } let reqData = getRequestPlainData(); if (!reqData || !reqData.uploadInfo) { return; } let uploadInfo = reqData.uploadInfo; let reqObject = null; // reqObject = { // "countType": 32, // "totalDelay": 464, // "h5monitor_sdk_version": "1.7.0", // "performanceTiming": { // "navigationStart": 1724052379766, // "unloadEventStart": 0, // "unloadEventEnd": 0, // "redirectStart": 0, // "redirectEnd": 0, // "fetchStart": 1724052379766, // "domainLookupStart": 1724052379766, // "domainLookupEnd": 1724052379766, // "connectStart": 1724052379766, // "connectEnd": 1724052379766, // "secureConnectionStart": 0, // "requestStart": 1724052379766, // "responseStart": 1724052379766, // "responseEnd": 1724052379766, // "domLoading": 1724052380035, // "domInteractive": 1724052380184, // "domContentLoadedEventStart": 1724052380184, // "domContentLoadedEventEnd": 1724052380189, // "domComplete": 1724052380230, // "loadEventStart": 1724052380230, // "loadEventEnd": 1724052380230 // }, // "navigation": { // "type": 0, // "redirectCount": 0 // }, // "ttfb": 0, // "domReady": 418, // "qs": "?traceid=fixed_innerid_KDAPP-96SS-HDY-1&innerid=KDAPP-96SS-HDY-1", // "firstScreen": 418, // "routelabel": 0, // "firstSource": "api", // "dt": 1724052381231, // "fbextension": "", // "source": "mozilla/5.0 (iphone; cpu iphone os 16_6_1 like mac os x) applewebkit/605.1.15 (khtml, like gecko) mobile/15e148 iphone 14 pro aladdinhybrid/4.8.77 (paebank 6.23.0) aladdinbridge/3.0.0 subcontracting/appstore deviceid/auuid_918d439ffcef935c2fd84d3a3e593b6523c916fc unionpay/1.0 pabank devicetype/1 networkstate/wifi kiwibridge/1.0.0 device-dpr/3 device-dr/852*393 appstyle/bz bz-navbarheight/309 dztab-navbarheight/327 pageactionid/662fc3b8", // "webtrendsid": "AUUID_918d439ffcef935c2fd84d3a3e593b6523c916fc", // "appversion": "6.23.0", // "platform": "ios", // "pageID": "PK084123", // "h5_app_id": "A208848050024B1584C78C904A4900E4", // "pagetitle": "宜家礼品卡88折起", // "ymd": "2024-08-19 15:26:21", // "page": "https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html", // "requestId": "6ugxCquxgrG49lDeOVXSqw61OT00123s" // }; try { reqObject = JSON.parse(decodeURIComponent(uploadInfo)); } catch (error) { } } async function getPageData() { let url = `https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/pageData.js?v=${new Date().getTime()}`; let body = ``; let headers = { 'Cookie': magicJS.data.read(PingAnConstKey.Cookie, ''), 'Sec-Fetch-Mode': `navigate`, 'Connection': `keep-alive`, 'Accept': `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`, 'Accept-Encoding': `gzip, deflate, br`, 'Host': `b.pingan.com.cn`, 'User-Agent': `${gAppUserAgent}`, 'Sec-Fetch-Site': `none`, 'Accept-Language': `zh-CN,zh-Hans;q=0.9`, 'Sec-Fetch-Dest': `document`, // 'If-Modified-Since': `Thu, 18 Jul 2024 11:10:01 GMT` };; let options = { url: url, headers: headers, body: body, }; let result = await magicJS.http.get(options).then(response => { try { const body = response.body; let rspData = null; let retMatch = body.match(/var pageData = ([\s\S]*)/); // 正则表达式匹配 if (retMatch) { rspData = JSON.parse(retMatch[1]); } // magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`); return rspData; } catch (e) { magicJS.logger.error(e); } }).catch(err => { const msg = `请求页面配置数据异常\n${JSON.stringify(err)}`; magicJS.logger.error(msg); }); return result; } async function checkGetPageData() { let strToday = magicJS.formatDate(new Date(), 'yyyy-MM-dd'); let key = `${PingAnConstKey.PageData}`; let cacheData = magicJS.data.read(key, null); if (cacheData && cacheData.storeDate == strToday) { magicJS.logger.info(`今日已更新过活动页面数据`); gPageData = cacheData.data; } else { magicJS.logger.info(`今日首次更新活动页面数据`); gPageData = await getPageData(); magicJS.data.write(key, { storeDate: strToday, data: gPageData }); } if (gPageData) { let buildTime = gPageData.buildTime; magicJS.logger.info(`当前活动页面数据最新构建时间:${magicJS.formatDate(new Date(buildTime), 'yyyy-MM-dd')}`); } return gPageData; } async function getClientTag() { if (!gPageData) { gPageData = await checkGetPageData(); } if (!gPageData) { return; } let clientTag = ''; let widgets = gPageData.widgets; for (let i = 0; i < widgets.length; i++) { const widget = widgets[i]; if (widget.label.indexOf('简易规则') > -1) { clientTag = widget.config.clientTag; } } return clientTag; } function getResponseErrorMsg(errCode, config, responseMsg) { let key = errCodeStrMap[errCode]; if (key && config && config[key]) { return config[key].toastText || responseMsg; } else { return responseMsg; } } function setActCouponStatus(activityCode, status) { let day = magicJS.formatDate(new Date(), 'yyyy-MM-dd'); let key = `PingAnIKEA#${activityCode}_${day}`; magicJS.data.write(key, status); if (status == 1 || status == 2) {// 已领取 key = `PingAnIKEA#${activityCode}_CouponGotTime}`; magicJS.data.write(key, new Date().getTime()); } } function getActCouponStatus(activityCode) { let day = magicJS.formatDate(new Date(), 'yyyy-MM-dd'); let key = `PingAnIKEA#${activityCode}_${day}`; let status = magicJS.data.read(key, -1); return Number(status); } // 今日是否执行过获取优惠券任务 function isCouponExecToday(activityCode) { if (gIgnoreCouponGotStatus) { return false; } let status = getActCouponStatus(activityCode); if (status == 1 || status == 2 || status == 3) { return true; } else if (status == -1) { return false; } else { return false; } } // 当月是否领取过优惠券 function hasCouponGotMonth(activityCode) { if (gIgnoreCouponGotStatus) { return false; } let key = `PingAnIKEA#${activityCode}_CouponGotTime}`; let strNum = magicJS.data.read(key, null); if (strNum) { let now = new Date(); let date = new Date(Number(strNum)); if (now.getFullYear() == date.getFullYear() && now.getMonth() == date.getMonth()) { return true; } return false; } return false; } function hasCouponGotWeek(activityCode) { if (gIgnoreCouponGotStatus) { return false; } let key = `PingAnIKEA#${activityCode}_CouponGotTime}`; let strNum = magicJS.data.read(key, null); if (strNum) { let now = new Date(); let date = new Date(Number(strNum)); if (isSameWeek(now, date)) { return true; } return false; } return false; } function hasCouponGotDay(activityCode) { if (gIgnoreCouponGotStatus) { return false; } let key = `PingAnIKEA#${activityCode}_CouponGotTime}`; let strNum = magicJS.data.read(key, null); if (strNum) { let now = new Date(); let date = new Date(Number(strNum)); if (now.getFullYear() == date.getFullYear() && now.getMonth() == date.getMonth() && now.getDate() == date.getDate()) { return true; } return false; } return false; } function isSameWeek(date1, date2) { // 获取每个日期的星期几 const day1 = date1.getDay(); // 返回值为 0(周日)到 6(周六) const day2 = date2.getDay(); // 获取每个日期的时间戳 const time1 = date1.getTime(); const time2 = date2.getTime(); // 根据星期几和时间戳判断是否属于同一个星期 const weekDiff = Math.floor(Math.abs(time1 - time2) / (1000 * 60 * 60 * 24 * 7)); if (day1 <= day2) { return weekDiff === 0; } else { return weekDiff === 1; } } function updateHeaders() { gCommonHeaders[`Cookie`] = magicJS.data.read(PingAnConstKey.Cookie, ''); let x_g_sid = magicJS.data.read(PingAnConstKey.x_g_sid, null); if (x_g_sid) { gCommonHeaders[`x-g-sid`] = x_g_sid; } let x_g_vid = magicJS.data.read(PingAnConstKey.x_g_vid, null); if (x_g_vid) { gCommonHeaders['x-g-vid'] = x_g_vid; } let x_g_rid = magicJS.data.read(PingAnConstKey.x_g_rid, null); if (x_g_rid) { gCommonHeaders['x-g-rid'] = x_g_rid; } } async function tryGrabCoupon() { gPageData = await checkGetPageData(); let widgets = gPageData.widgets; let sk88Names = ['【天天88】满100减12优惠券']; // 天天88 let path88 = ['pwm-kuaizhan-section', 'pwm-mkt-offer']; // 五折限量购 let sk55Names = ['【五折限量购】满100减50优惠券']; let path55 = ['pwm-kuaizhan-simple-rule', 'pwm-kuaizhan-section', 'pwm-mkt-offer']; // 9.25折限量购 let sk925Names = [ '【9.25折限量折扣】满100减7.5优惠券', '【9.25折限量折扣】满100减15优惠券', '【9.25折限量折扣】满100减37.5优惠券', '【9.25折限量折扣】满1000减75优惠券', ]; let path925 = ['pwm-kuaizhan-section-split', 'pwm-kuaizhan-section', 'pwm-mkt-offer']; let items925 = seekWidgets(widgets, path925); let isLogin = true; let strLoginFailMsg = `登录失败,请点击通知栏打开APP下载页面`; magicJS.logger.info(`########9.25折限量购########`); for (let i = items925.length - 1; i >= 0; i--) { const item = items925[i]; const config = item.config; if (isCouponExecToday(config.activityCode)) { magicJS.logger.info(`${sk925Names[i]}今天已经执行过了[${config.activityCode}]`); continue; } if (hasCouponGotMonth(config.activityCode)) { magicJS.logger.info(`${sk925Names[i]}本月已经领过了[${config.activityCode}]`); continue; } // magicJS.logger.info(`activityCode=${config.activityCode} activityValue=${config.activityValue}`); let ret = await doGrabCoupon(config.activityCode, config.activityValue); let tipsText = ``; if (ret) { if (ret.responseCode == '900100') {//未登录 isLogin = false; strLoginFailMsg = ret.responseMsg; // magicJS.notification.appendNotifyInfo(ret.responseMsg); break; } if (ret.data) { let activityData = ret.data.activityData; if (activityData) { sk925Names[i] = activityData.activityName; } } if (ret.responseCode == '000000') { setActCouponStatus(config.activityCode, 1); } else if (ret.responseCode == '950008' || ret.responseCode == '900745' || ret.responseCode == '950009') {//领奖机会已经用完 setActCouponStatus(config.activityCode, 2); } else if (ret.responseCode == '960002') {//今天奖励已经发完 setActCouponStatus(config.activityCode, 3); } else if (ret.responseCode == '900130') {//不符合领取规则 setActCouponStatus(config.activityCode, 3); } if (ret.responseCode == '000000') { tipsText = `${sk925Names[i]}-领取成功`; } else { tipsText = sk925Names[i] + '-' + getResponseErrorMsg(ret.responseCode, config, ret.responseMsg) } } else { tipsText = `${sk925Names[i]}-领取失败`; } magicJS.notification.appendNotifyInfo(tipsText); } if (!isLogin) { let params = { "td": { "id": "唤醒浮层", "label": "APP下载浮层立即打开-样式2", "param": { "dlink_id": "M0P5EnN0addUoXCs240814104407" }, "pageId": gPageId }, "url": "https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html? paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D" }; let schemaUrl = `paesuperbank://?paesuperbank=${encodeURIComponent(JSON.stringify(params))}`; magicJS.notification.post(scriptName, '', strLoginFailMsg, schemaUrl); return; } magicJS.logger.info(`##########天天88##########`); let items88 = seekWidgets(widgets, path88); for (let i = 0; i < items88.length; i++) { const item = items88[i]; const config = item.config; if (isCouponExecToday(config.activityCode)) { magicJS.logger.info(`${sk88Names[i]}今天已经执行过了[${config.activityCode}]`); continue; } if (hasCouponGotMonth(config.activityCode)) { magicJS.logger.info(`${sk88Names[i]}本月已经领过了[${config.activityCode}]`); continue; } // magicJS.logger.info(`activityCode=${config.activityCode} activityValue=${config.activityValue}`); let ret = await doGrabCoupon(config.activityCode, config.activityValue); let tipsText = ``; if (ret) { if (ret.responseCode == '900100') {//未登录 magicJS.notification.appendNotifyInfo(ret.responseMsg); break; } if (ret.data) { let activityData = ret.data.activityData; if (activityData) { sk88Names[i] = activityData.activityName; } } if (ret.responseCode == '000000') { setActCouponStatus(config.activityCode, 1); } else if (ret.responseCode == '950008' || ret.responseCode == '900745' || ret.responseCode == '950009') {//领奖机会已经用完 setActCouponStatus(config.activityCode, 2); } else if (ret.responseCode == '960002') {//今天奖励已经发完 setActCouponStatus(config.activityCode, 3); } else if (ret.responseCode == '900130') {//不符合领取规则 setActCouponStatus(config.activityCode, 3); } if (ret.responseCode == '000000') { tipsText = `${sk88Names[i]}-领取成功`; } else { tipsText = sk88Names[i] + '-' + getResponseErrorMsg(ret.responseCode, config, ret.responseMsg) } } else { tipsText = `${sk88Names[i]}-领取失败`; } magicJS.notification.appendNotifyInfo(tipsText); } magicJS.logger.info(`########五折限量购########`); let items55 = seekWidgets(widgets, path55); for (let i = 0; i < items55.length; i++) { const item = items55[i]; const config = item.config; if (isCouponExecToday(config.activityCode)) { magicJS.logger.info(`${sk55Names[i]}今天已经执行过了[${config.activityCode}]`); continue; } if (hasCouponGotMonth(config.activityCode)) { magicJS.logger.info(`${sk55Names[i]}本月已经领过了[${config.activityCode}]`); continue; } // magicJS.logger.info(`activityCode=${config.activityCode} activityValue=${config.activityValue}`); let ret = await doGrabCoupon(config.activityCode, config.activityValue); let tipsText = ``; if (ret) { if (ret.responseCode == '900100') {//未登录 magicJS.notification.appendNotifyInfo(ret.responseMsg); break; } if (ret.data) { let activityData = ret.data.activityData; if (activityData) { sk55Names[i] = activityData.activityName; } } if (ret.responseCode == '000000') { setActCouponStatus(config.activityCode, 1); } else if (ret.responseCode == '950008' || ret.responseCode == '900745' || ret.responseCode == '950009') {//领奖机会已经用完 setActCouponStatus(config.activityCode, 2); } else if (ret.responseCode == '960002') {//今天奖励已经发完 setActCouponStatus(config.activityCode, 3); } else if (ret.responseCode == '900130') {//不符合领取规则 setActCouponStatus(config.activityCode, 3); } if (ret.responseCode == '000000') { tipsText = `${sk55Names[i]}-领取成功`; } else { tipsText = sk55Names[i] + '-' + getResponseErrorMsg(ret.responseCode, config, ret.responseMsg) } } else { tipsText = `${sk55Names[i]}-领取失败`; } magicJS.notification.appendNotifyInfo(tipsText); } } function seekWidgets(widgets, namePaths, layer = 0) { let retLst = []; let name = namePaths[layer]; if (namePaths.length == layer + 1) { for (let i = 0; i < widgets.length; i++) { const widget = widgets[i]; if (widget.name == name) { retLst.push(widget); } } } else { for (let i = 0; i < widgets.length; i++) { const widget = widgets[i]; if (widget.name == name) { retLst = retLst.concat(seekWidgets(widget.widgets, namePaths, layer + 1)); } } } return retLst; } async function doGrabCoupon(activityCode, activityValue) { let result = await queryCustomerActivityStatus(activityCode, activityValue); if (result && gIgnoreActivityStatus) { result.responseCode = '000000'; } if (result && result.responseCode == '000000') { result = await sendCustomerOffer(activityCode, activityValue); } return result; } async function queryCustomerActivityStatus(activityCode, activityValue, channelSource = 'KOUDAI', taskProVal = '') { let reqData = { activityCode: activityCode, activityValue: activityValue, channelSource: channelSource, taskProVal: taskProVal || '', }; let url = `https://rsb.pingan.com.cn/brop/mop/cust/mopsf/uc/auth/lottery/queryCustomerActivityStatus?${magicJS.objToQueryStr(reqData)}`; let headers = getWillRequestHeaders(); let options = { url: url, headers: headers, body: ``, }; let result = await magicJS.http.get(options).then(response => { try { let rspData = response.body; magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`); return rspData; } catch (e) { magicJS.logger.error(e); } }).catch(err => { const msg = `请求用户活动状态异常\n${JSON.stringify(err)}`; magicJS.logger.error(msg); }); return result; } async function sendCustomerOffer(activityCode, activityValue, channelSource = 'KOUDAI', taskProVal = '') { let url = `https://rsb.pingan.com.cn/brop/mop/cust/mopsf/uc/auth/lottery/sendCustomerOffer`; let info = { MGM: { activity_flowid: undefined, activity_id: undefined, }, N: { campaignid: undefined, channel_source: undefined, source: 'all', innerid: 'KDAPP-96SS-HDY-1', outersource: undefined, }, W: { outerid: undefined, }, }; let orderNo = ''; let traceid = 'fixed_innerid_KDAPP-96SS-HDY-1'; let offerAppid = ''; let buryData = { "login_type": `Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 iphone 14 pro AladdinHybrid/4.8.77 (PAEBank 6.23.0) AladdinBridge/3.0.0 subContracting/AppStore deviceId/${gDeviceId} UnionPay/1.0 PABANK deviceType/1 networkState/WIFI KiwiBridge/1.0.0 device-dpr/3 device-dr/852*393 AppStyle/BZ bz-navbarHeight/309 dzTab-navbarHeight/327 pageActionId/${gPageActionId}`, "idfa": "00000000-0000-0000-0000-000000000000", "osVersion": "16.6.1", "memoryStatus": { "totalMemory": 5644, "usedMemory": 3700 + Math.ceil(160 * Math.random()) }, "language": "zh-Hans-CN", "deviceId": gDeviceId, "deviceType": "1", "sourceIP": "10.4.175.51", "deviceName": "iPhone", "vpn": "1", "isJailBroken": false, "deviceToken": "524be0e96038a72223cfe66c8c9044c65227c9c818225a28159100bbd9729ba4", "wifiMac": "Not Found", "appVersion": "6.23.0", "wifiSid": "Not Found", "appName": "平安口袋银行App", "idfv": "07A9900D-FBD5-4EB4-B16D-830E090913CF", "deviceModel": "iphone 14 pro", "aldDeviceId": "8A093177-C77E-49B6-B096-63F736D4B9F5", "osName": "iOS", "sourceIPType": "04", "subContracting": "AppStore" }; let modifyNoVpn = true; if (modifyNoVpn) { buryData.vpn = '0'; buryData.sourceIP = '14.145.199.18'; } let reqData = { activityCode: activityCode, activityValue: activityValue, activityFlowId: String(info.MGM.activity_flowid), activityId: String(info.MGM.activity_id), buryData: encodeURIComponent(JSON.stringify(buryData)), campaignId: String(info.N.campaignid), channelsource: String(info.N.channel_source), channelSource: channelSource, drawTimesQueryFLag: "1", innerid: info.N.innerid, orderNo: orderNo, outerid: String(info.W.outerid), outersource: String(info.N.outersource), source: info.N.source, taskProVal: taskProVal, offerAppid: offerAppid, traceId: traceid } let headers = getWillRequestHeaders(); let options = { url: url, headers: headers, body: magicJS.objToQueryStr(reqData), }; let result = await magicJS.http.post(options).then(response => { try { let rspData = response.body; magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`); return rspData; } catch (e) { magicJS.logger.error(e); } }).catch(err => { const msg = `请求用户报单异常\n${JSON.stringify(err)}`; magicJS.logger.error(msg); }); return result; } Main().catch((e) => magicJS.logger.log(`-\n ${e}`)).finally(() => magicJS.done()); //---SyncByPyScript---MagicJS3-start function MagicJS(e="MagicJS",t="INFO"){const n=()=>{const e="undefined"!=typeof $loon,t="undefined"!=typeof $task,r="undefined"!=typeof module,n="undefined"!=typeof $httpClient&&!e,o="undefined"!=typeof $storm,i="undefined"!=typeof $environment&&void 0!==$environment["stash-build"];var s=n||e||o||i;const a="undefined"!=typeof importModule;return{isLoon:e,isQuanX:t,isNode:r,isSurge:n,isStorm:o,isStash:i,isSurgeLike:s,isScriptable:a,get name(){return e?"Loon":t?"QuantumultX":r?"NodeJS":n?"Surge":a?"Scriptable":"unknown"},get build(){return n?$environment["surge-build"]:i?$environment["stash-build"]:o?$storm.buildVersion:void 0},get language(){if(n||i)return $environment.language},get version(){return n?$environment["surge-version"]:i?$environment["stash-version"]:o?$storm.appVersion:r?process.version:void 0},get system(){return n?$environment.system:r?process.platform:void 0},get systemVersion(){if(o)return $storm.systemVersion},get deviceName(){if(o)return $storm.deviceName}}},o=(r,e="INFO")=>{let n=e,t="\n";const o={SNIFFER:6,DEBUG:5,INFO:4,NOTIFY:3,WARNING:2,ERROR:1,CRITICAL:0,NONE:-1},i={SNIFFER:"",DEBUG:"",INFO:"",NOTIFY:"",WARNING:"❗ ",ERROR:"❌ ",CRITICAL:"❌ ",NONE:""},s=(e,t="INFO")=>{o[n]n,setLevel:e=>{n=e},sniffer:(...e)=>{e=e.join(t);s(e,"SNIFFER")},log:(...e)=>{e=e.join(t);console.log(`██[${r}]`+e+"\n")},debug:(...e)=>{e=e.join(t);s(e,"DEBUG")},info:(...e)=>{e=e.join(t);s(e,"INFO")},notify:(...e)=>{e=e.join(t);s(e,"NOTIFY")},warning:(...e)=>{e=e.join(t);s(e,"WARNING")},error:(...e)=>{e=e.join(t);s(e,"ERROR")},retry:(...e)=>{e=e.join(t);s(e,"RETRY")}}};return new class{constructor(e,t){var r;this._startTime=Date.now(),this.version="3.0.0",this.scriptName=e,this.env=n(),this.logger=o(e,t),this.http="function"==typeof MagicHttp?MagicHttp(this.env,this.logger):void 0,this.data="function"==typeof MagicData?MagicData(this.env,this.logger):void 0,this.notification="function"==typeof MagicNotification?MagicNotification(this.scriptName,this.env,this.logger,this.http):void 0,this.utils="function"==typeof MagicUtils?MagicUtils(this.env,this.logger):void 0,this.qinglong="function"==typeof MagicQingLong?MagicQingLong(this.env,this.data,this.logger):void 0,void 0!==this.data&&(t=this.data.read("magic_loglevel"),r=this.data.read("magic_bark_url"),t&&this.logger.setLevel(t.toUpperCase()),r)&&this.notification.setBark(r),this.logger.info(e+", 开始执行!")}get isRequest(){return"undefined"!=typeof $request}get isStrictRequest(){return"undefined"!=typeof $request&&"undefined"==typeof $response}get isResponse(){return"undefined"!=typeof $response}get isDebug(){return"DEBUG"===this.logger.level}get request(){return"undefined"!=typeof $request?$request:void 0}get response(){if("undefined"!=typeof $response)return $response.hasOwnProperty("status")&&($response.statusCode=$response.status),$response.hasOwnProperty("statusCode")&&($response.status=$response.statusCode),$response}log(...e){this.logger.log(e)}toStr(e,t=null){try{return JSON.stringify(e)}catch{return t}}toObj(e,t=null){try{return JSON.parse(e)}catch{return t}}checkRecordRequestBody(){if(this.isRequest){var t=$request.body;if(t){var r=this.env,n=$request.path;let e=this.scriptName+"#"+n.replace("/","_");e=e.replace("?","#"),r.isQuanX&&$prefs.setValueForKey(t,e),(r.isLoon||r.isSurge)&&$persistentStore.write(t,e),r.isNode&&require("fs").writeFileSync(e+".json",t,{flag:"w"},e=>console.log(e))}}}getRequestBody(){var e=this.env,t=$request.path;let r=this.scriptName+"#"+t.replace("/","_");if(r=r.replace("?","#"),e.isSurge||e.isLoon)return $persistentStore.read(r);if(e.isQuanX)return $prefs.valueForKey(r);if(e.isNode){t=r+".json",e=require("fs");if(!e.existsSync(t))return JSON.parse(e.readFileSync(t))}}getResponseBody(){if($response)return $response.body}parseCookies(e,t=!1){let r={};return t?e&&e.split(";").forEach(function(e){e=e.split("=");r[e.shift().trim()]=decodeURIComponent(e.join("="))}):e&&e.split(";").forEach(function(e){e=e.split("=");r[e.shift().trim()]=e.join("=")}),r}serializeCookies(e,t=!1){var r=[];if(t)for(var n in e){var o=e[n],n=n+"="+encodeURIComponent(o);r.push(n)}else for(var i in e){var s=e[i],i=i+"="+s;r.push(i)}return r.join("; ")}parseSetCookies(e){var t=e.split(/,\s*/).map(e=>{var e=e.trim().split(/;\s*(?=[^=]+=[^;]*)/),t=e[0].split("=").map(e=>e.trim());const r={name:t[0],value:t[1]};return e.slice(1).forEach(e=>{var[e,t]=e.split("=").map(e=>e.trim());r[e]=t||!0}),r}),r=[];let n=0;for(;n>2))+o.charAt((3&t)<<4)+"==";break}if(r=e.charCodeAt(s++),s==a){i=(i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4|(240&r)>>4))+o.charAt((15&r)<<2)+"=";break}n=e.charCodeAt(s++),i=(i=(i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4|(240&r)>>4))+o.charAt((15&r)<<2|(192&n)>>6))+o.charAt(63&n)}return i}base64Decode(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";if(/([^\s]+[^0-9a-zA-Z\+\/\=]|[^0-9a-zA-Z\+\/\=]\s+)/.test(e))throw new Error("Invalid base64 input");var r,n,o,i,s,a,l=e.replace(/\s/g,"");let u="",c=0;for(;c>2,n=(3&s)<<6|(a=t.indexOf(l.charAt(c++))),u+=String.fromCharCode(o<<2|i>>4),64!==s&&(u+=String.fromCharCode(r)),64!==a&&(u+=String.fromCharCode(n));return u=this.utf8Decode(u)}utf8Decode(t){let e=[],r=0,n=0,o=0;for(t=t.replace(/\r\n/g,"\n");r>10&1023)),e.push(String.fromCharCode(56320|1023&n))):e.push(String.fromCharCode(n)),r+=o}return e.join("")}parseJwt(e){try{var t=e.split("."),r=t[0].replace(/-/g,"+").replace(/_/g,"/"),n=this.base64Decode(r).replace(/\0/g,""),o=JSON.parse(n),i=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=this.base64Decode(i).replace(/\0/g,"");return{header:o,payload:JSON.parse(s),signature:t[2]}}catch(e){return this.log(e),null}}costTime(){var e=this.scriptName+"执行完毕!",t=(this._endTime=(new Date).getTime(),this._endTime-this._startTime);this.logger.info(e+`耗时【${t/1e3}】秒`)}done=(e={})=>{this.costTime(),"undefined"!=typeof $done&&$done(e)}}(e,t)}function MagicHttp(d,p){var e;let g;d.isNode&&(e=require("axios"),g=e.create());class t{constructor(e=!0){this.handlers=[],this.isRequest=e}use(e,t,r){return"function"==typeof e&&p.debug("Register fulfilled "+e.name),"function"==typeof t&&p.debug("Register rejected "+t.name),this.handlers.push({fulfilled:e,rejected:t,synchronous:!(!r||"boolean"!=typeof r.synchronous)&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}forEach(t){this.handlers.forEach(e=>{null!==e&&t(e)})}}function f(e){let r={...e};return r.params&&!d.isNode&&(e=Object.keys(r.params).map(e=>{var t=encodeURIComponent(e);return r.url=r.url.replace(new RegExp(e+"=[^&]*","ig"),""),r.url=r.url.replace(new RegExp(t+"=[^&]*","ig"),""),t+"="+encodeURIComponent(r.params[e])}).join("&"),r.url.indexOf("?")<0&&(r.url+="?"),/(&|\?)$/g.test(r.url)||(r.url+="&"),r.url+=e,delete r.params,p.debug("Params to QueryString: "+r.url)),r}const h=(e,t=null)=>{if(e){t={...e,config:e.config||t,status:e.statusCode||e.status,body:e.body||e.data,headers:e.headers||e.header};if("string"==typeof t.body)try{t.body=JSON.parse(t.body)}catch{}return delete t.data,t}return e};const y=(e,t=null)=>{if(e&&400<=e.status)return p.debug("Raise exception when status code is "+e.status),{name:"RequestException",message:"Request failed with status code "+e.status,config:t||e.config,response:e}},m={request:new t,response:new t(!1)};let v=[],b=[],S=!0;function N(e){return e=f(e),p.debug(`HTTP ${e.method.toUpperCase()}:`+"\n"+JSON.stringify(e)),e}function E(t){try{t=t&&h(t),p.sniffer(`HTTP ${t.config.method.toUpperCase()}:`+"\n"+JSON.stringify(t.config)+"\nSTATUS CODE:\n"+t.status+"\nRESPONSE:\n"+("object"==typeof t.body?JSON.stringify(t.body):t.body));var e=y(t);return e?Promise.reject(e):t}catch(e){return p.error(e),t}}const r=(e,r)=>{let n;r=((e,t)=>{let r="object"==typeof t?{headers:{},...t}:{url:t,headers:{}};return r.method||(r.method=e),!0===(r=f(r)).rewrite&&(d.isSurge?(r.headers["X-Surge-Skip-Scripting"]=!1,delete r.rewrite):d.isQuanX&&(r.hints=!1,delete r.rewrite)),d.isSurgeLike?(t=r.headers["content-type"]||r.headers["Content-Type"],"GET"!==r.method&&t&&0<=t.indexOf("application/json")&&r.body instanceof Array&&(r.body=JSON.stringify(r.body),p.debug("Convert Array object to String: "+r.body))):d.isQuanX?(r.hasOwnProperty("body")&&"string"!=typeof r.body&&(r.body=JSON.stringify(r.body)),r.method=e):d.isNode&&("POST"===e||"PUT"===e||"PATCH"===e||"DELETE"===e?r.data=r.data||r.body:"GET"===e&&(r.params=r.params||r.body),delete r.body),r})(e.toUpperCase(),r),n=d.isNode?g:d.isSurgeLike?i=>new Promise((n,o)=>{$httpClient[e.toLowerCase()](i,(e,t,r)=>{e?(e={name:e.name||e,message:e.message||e,stack:e.stack||e,config:i,response:h(t)},o(e)):(t.config=i,t.body=r,n(t))})}):n=>new Promise((r,t)=>{$task.fetch(n).then(e=>{e=h(e,n);var t=y(e,n);if(t)return Promise.reject(t);r(e)}).catch(e=>{e={name:e.message||e.error,message:e.message||e.error,stack:e.error,config:n,response:e.response?h(e.response):null};t(e)})});let o;var t=r;try{v=[],b=[],m.request.forEach(e=>{"function"==typeof e.runWhen&&!1===e.runWhen(t)||(S=S&&e.synchronous,v.unshift(e.fulfilled,e.rejected))}),m.response.forEach(e=>{b.push(e.fulfilled,e.rejected)})}catch(e){p.error(`Failed to register interceptors: ${e}.`)}var i=[N,void 0],s=[E,void 0];if(S){for(p.debug("Interceptors are executed in synchronous mode"),Array.prototype.unshift.apply(v,i),v=v.concat([N,void 0]);v.length;){var a=v.shift(),l=v.shift();try{"function"==typeof a&&p.debug("Executing request fulfilled "+a.name),r=a(r)}catch(e){"function"==typeof l&&p.debug("Executing request rejected "+l.name),l(e);break}}try{o=(!d.isNode&&r.timeout?c:n)(r)}catch(e){return Promise.reject(e)}for(Array.prototype.unshift.apply(b,s);b.length;)o=o.then(b.shift(),b.shift());return o}{p.debug("Interceptors are executed in asynchronous mode");let t=[n,void 0];for(Array.prototype.unshift.apply(t,i),Array.prototype.unshift.apply(t,v),t=(t=t.concat(s)).concat(b),o=Promise.resolve(r);t.length;)try{let e=t.shift();var u=t.shift();"function"==typeof(e=!d.isNode&&r.timeout&&e===n?c:e)&&p.debug("Executing request fulfilled "+e.name),"function"==typeof u&&p.debug("Executing request rejected "+u.name),o=o.then(e,u)}catch(e){p.error("request exception: "+e)}return o}function c(r){try{var e=new Promise((e,t)=>{setTimeout(()=>{var e={message:`timeout of ${r.timeout}ms exceeded.`,config:r};t(e)},r.timeout)});return Promise.race([n(r),e])}catch(e){p.error(`Request Timeout exception: ${e}.`)}}};return{request:r,interceptors:m,convertHeadersToLowerCase:r=>Object.keys(r).reduce((e,t)=>(e[t.toLowerCase()]=r[t],e),{}),convertHeadersToCamelCase:r=>Object.keys(r).reduce((e,t)=>{return e[t.split("-").map(e=>e[0].toUpperCase()+e.slice(1)).join("-")]=r[t],e},{}),modifyResponse:h,get:e=>r("GET",e),post:e=>r("POST",e),put:e=>r("PUT",e),patch:e=>r("PATCH",e),delete:e=>r("DELETE",e),head:e=>r("HEAD",e),options:e=>r("OPTIONS",e)}}function MagicData(d,p){let g={fs:void 0,data:{}};if(d.isNode){g.fs=require("fs");try{g.fs.accessSync("./magic.json",g.fs.constants.R_OK|g.fs.constants.W_OK)}catch(e){g.fs.writeFileSync("./magic.json","{}",{encoding:"utf8"})}g.data=require("./magic.json")}const s=(e,t)=>"object"!=typeof t&&e===t,a=e=>"true"===e||"false"!==e&&(void 0===e?null:e),l=(e,t,r,n)=>{if(r)try{e=!0===(e="string"==typeof e?JSON.parse(e):e).magic_session?e[r]:null}catch{e=null}if("string"==typeof e&&"null"!==e)try{e=JSON.parse(e)}catch{}return null==(e=!1===n&&e&&!0===e.magic_session?null:e)&&null!=t&&(e=t),e=a(e)},f=t=>{if("string"!=typeof t)return t instanceof Array||null==t||t!=t||"boolean"==typeof t?{}:t;{let e={};try{var r=typeof(e=JSON.parse(t));("object"!=r||e instanceof Array||"bool"==r||null===e)&&(e={})}catch{}return e}},u=(e,t=null,r="",n=!1,o=null)=>{let i="";return i=o||d.isNode?((e,t=null,r="",n=!1,o=null)=>{o=o||g.data;return val=o&&void 0!==o[e]&&null!==o[e]?o[e]:r?{}:null,val=l(val,t,r,n)})(e,t,r,n,o):(d.isSurgeLike?i=$persistentStore.read(e):d.isQuanX&&(i=$prefs.valueForKey(e)),l(i,t,r,n)),p.debug(`READ DATA [${e}]${r?`[${r}]`:""} <${typeof i}>`+"\n"+JSON.stringify(i)),i},c=(e,t,r="",n=null)=>{if(void 0===t||t!=t)return!1;d.isNode||"boolean"!=typeof t&&"number"!=typeof t||(t=String(t));let o="";var i,s,a,l,u,c;if(n||d.isNode?o=([i,s,a="",l=null]=[e,t,r,n],c=l||g.data,c=f(c),a?((u=f(c[i])).magic_session=!0,u[a]=s,c[i]=u):c[i]=s,null!==l&&(l=c),c):r?(d.isSurgeLike?o=$persistentStore.read(e)?$persistentStore.read(e):o:d.isQuanX&&(o=$prefs.valueForKey(e)?$prefs.valueForKey(e):o),(o=f(o)).magic_session=!0,o[r]=t):o=t,o&&"object"==typeof o&&(o=JSON.stringify(o,null,4)),p.debug(`WRITE DATA [${e}]${r?`[${r}]`:""} <${typeof t}>`+"\n"+JSON.stringify(t)),!n){if(d.isSurgeLike)return $persistentStore.write(o,e);if(d.isQuanX)return $prefs.setValueForKey(o,e);if(d.isNode)try{g.fs.writeFileSync("./magic.json",o)}catch(e){return p.error(e),!1}}return!0};return{read:u,write:c,del:(e,t="",r=null)=>{let n={};if(r||d.isNode)n=(o=e,i=t,s=r||g.data,s=f(s),i?(delete(obj=f(s[o]))[i],s[o]=obj):delete s[o],s),r?r=n:g.fs.writeFileSync("./magic.json",JSON.stringify(n,null,4));else if(t){d.isSurgeLike?n=$persistentStore.read(e):d.isQuanX&&(n=$prefs.valueForKey(e)),delete(n=f(n))[t];i=JSON.stringify(n,null,4);c(e,i)}else{if(d.isStorm)return $persistentStore.remove(e);if(d.isSurgeLike)return $persistentStore.write(null,e);if(d.isQuanX)return $prefs.removeValueForKey(e)}var o,i,s;p.debug(`DELETE KEY [${e}]`+(t?`[${t}]`:""))},update:(e,t,r,n=s,o=null)=>{var i;return t=a(t),!0!==n(u(e,null,r,!1,o),t)&&(i=c(e,t,r,o),e=u(e,null,r,!1,o),n===s&&"object"==typeof e?i:n(t,e))},allSessions:(e,t=null)=>{let r={};t=u(e,null,null,!0,t);return!0===(t=f(t)).magic_session&&delete(r={...t}).magic_session,p.debug(`READ ALL SESSIONS [${e}] <${typeof r}>`+"\n"+JSON.stringify(r,null,4)),r},allSessionNames:(e,t=null)=>{let r=[];t=u(e,null,null,!0,t),t=f(t);return r=!0!==t.magic_session?[]:Object.keys(t).filter(e=>"magic_session"!==e),p.debug(`READ ALL SESSIONS [${e}] <${typeof r}>`+"\n"+JSON.stringify(r,null,4)),r},defaultValueComparator:s,convertToObject:f}}function MagicNotification(i,o,s,a){let l=null,u=null,c=[];function d(e=i,t="",r="",n=""){n=(t=>{try{let e={};var r;return"string"==typeof t?0{s.error("Bark notify error: "+e)})}return{post:d,debug:function(e=i,t="",r="",n=""){"DEBUG"===s.getLevel()&&(1===arguments.length&&(e=i,t="",r=arguments[0]),this.post(e,t,r,n))},bark:p,setBark:e=>{try{var t=e.replace(/\/+$/g,"");l=/^https?:\/\/([^/]*)/.exec(t)[0]+"/push",u=/\/([^\/]+)\/?$/.exec(t)[1]}catch(e){s.error(`Bark url error: ${e}.`)}},appendNotifyInfo:function(e,t){1==t?c=e:c.push(e)},prependNotifyInfo:function(e){c.splice(0,0,e)},msg:function(e,t,r,n){var o={};r&&(o["open-url"]=r),n&&(o["media-url"]=n),(t=t&&0!=t.length?t:Array.isArray(c)?c.join("\n"):c)&&0{var r,n={"M+":e.getMonth()+1,"d+":e.getDate(),"h+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};for(r in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),n)new RegExp("("+r+")").test(t)&&(t=t.replace(RegExp.$1,1===RegExp.$1.length?n[r]:("00"+n[r]).substr((""+n[r]).length)));return t};return{retry:(i,s=5,a=0,l=null)=>(...e)=>new Promise((r,n)=>{function o(...t){Promise.resolve().then(()=>i.apply(this,t)).then(e=>{"function"==typeof l?Promise.resolve().then(()=>l(e)).then(()=>{r(e)}).catch(e=>{1<=s?0o.apply(this,t),a):o.apply(this,t):n(e),s--}):r(e)}).catch(e=>{u.error(e),1<=s&&0o.apply(this,t),a):1<=s?o.apply(this,t):n(e),s--})}o.apply(this,e)}),formatTime:e,now:()=>e(new Date,"yyyy-MM-dd hh:mm:ss"),today:()=>e(new Date,"yyyy-MM-dd"),sleep:t=>new Promise(e=>setTimeout(e,t)),assert:(e,t=null)=>{var r;n.isNode?(r=require("assert"),t?r(e,t):r(e)):!0!==e&&u.error("AssertionError: "+(t||"The expression evaluated to a falsy value."))}}}function MagicQingLong(e,a,o){let i="",s="",l="",u="",c="",t="";const d="magic.json",p=MagicHttp(e,o);async function r(){return l=l||a.read("magic_qlclient"),u=u||a.read("magic_qlsecrt"),s=s||a.read("magic_qlname"),c=c||a.read("magic_qlpwd"),i&&l&&u?(o.info("Get token from QingLong Panel"),await p.get({url:"/open/auth/token",headers:{"content-type":"application/json"},params:{client_id:l,client_secret:u}}).then(e=>{if(!(0{o.error("Error logging in to QingLong Panel.\n"+(e.message||e))})):i&&s&&c&&await p.post({url:"/api/user/login",headers:{"content-type":"application/json"},body:{username:s,password:c}}).then(e=>{o.info("Successfully logged in to QingLong Panel"),t=e.body.data.token,a.write("magic_qltoken",t)}).catch(e=>{o.error("Error logging in to QingLong Panel.\n"+(e.message||e))}),t}async function g(e){let t=[];return await p.post({url:"/api/envs",headers:{"content-type":"application/json"},body:e}).then(e=>{200===e.body.code?e.body.data.forEach(e=>{o.debug(`QINGLONG ADD ENV ${e.name} <${typeof e.value}> (${e.id})`+"\n"+JSON.stringify(e)),t.push(e.id)}):o.error("Error adding environments variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error adding environments variable from QingLong Panel.\n"+(e.message||e))}),t}async function n(n=null,e="",t){let o=[];return await p.get({url:"/api/envs",headers:{"content-type":"application/json"},params:{searchValue:e}}).then(e=>{if(200!==e.body.code)throw new Error("Error reading environment variable from QingLong Panel.\n"+JSON.stringify(e));e=e.body.data;if(n){var t=[];for(const r of e)r.name===n&&o.push(r);o=t}o=e}).catch(e=>{throw new Error("Error reading environments variable from QingLong Panel.\n"+(e.message||e))}),o}async function f(e,t=""){let r="";return await p.get({url:"/api/scripts/"+e,params:{path:t}}).then(e=>{if(200!==e.body.code)throw new Error("Error reading data from QingLong Panel.\n"+JSON.stringify(e));r=e.body.data}).catch(e=>{throw new Error("Error reading data from QingLong Panel.\n"+(e.message||e))}),r}async function h(e,t="",r=""){let n=!1;return await p.put({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:r}}).then(e=>{200===e.body.code?n=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n}return p.interceptors.request.use(function(e){return i=i||a.read("magic_qlurl"),e.url.indexOf(i)<0&&(e.url=""+i+e.url),{...e,timeout:3e3}},void 0),p.interceptors.request.use(function(e){return(l=l||a.read("magic_qlclient"))&&(e.url=e.url.replace("/api/","/open/")),e},void 0,{runWhen:e=>e.url.indexOf("api/user/login")<0&&e.url.indexOf("open/auth/token")<0}),p.interceptors.request.use(async function(e){return(t=t||a.read("magic_qltoken",""))||await r(),e.headers.authorization="Bearer "+t,e},void 0,{runWhen:e=>e.url.indexOf("api/user/login")<0&&e.url.indexOf("open/auth/token")<0}),p.interceptors.request.use(function(e){return e.params={...e.params,t:Date.now()},e},void 0,{runWhen:e=>e.url.indexOf("open/auth/token")<0}),p.interceptors.request.use(function(e){return i=i||a.read("magic_qlurl"),t=t||a.read("magic_qltoken"),o.debug("QingLong url: "+i+"\nQingLong token: "+t),e},void 0),p.interceptors.response.use(void 0,async function(e){try{var t=e.message||e.error||JSON.stringify(e);return(0<=t.indexOf("NSURLErrorDomain")&&0<=t.indexOf("-1012")||e.response&&401===e.response.status)&&e.config&&!0!==e.config.refreshToken?(o.warning("QingLong Panel token has expired"),o.info("Refreshing the QingLong Panel token"),await r(),e.config.refreshToken=!0,o.info("Call the previous method again"),await p.request(e.config.method,e.config)):Promise.reject(e)}catch(e){return Promise.reject(e)}}),{url:i||a.read("magic_qlurl"),init:(e,t,r,n,o)=>{i=e,l=t,u=r,s=n,c=o},getToken:r,setEnv:async function(t,r,n=null){if(i=i||a.read("magic_qlurl"),null===n){var e=await g([{name:t,value:r}]);if(e&&1===e.length)return e[0]}else await p.put({url:"/api/envs",headers:{"content-type":"application/json"},body:{name:t,value:r,id:n}}).then(e=>{if(200===e.body.code)return o.debug(`QINGLONG UPDATE ENV ${t} <${typeof r}> (${n})`+"\n"+JSON.stringify(r)),!0;o.error("Error adding environment variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>(o.error("Error adding environment variable from QingLong Panel.\n"+(e.message||e)),!1))},setEnvs:g,getEnv:async function(e){let t=null;for(const r of await n())if(r.id===e){t=r;break}return t},getEnvs:n,delEnvs:async function(t){return p.delete({url:"/api/envs",headers:{accept:"application/json","accept-language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>200===e.body.code?(o.debug("QINGLONG DELETE ENV IDS: "+t),!0):(o.error("Error deleting environments variable from QingLong Panel.\n"+JSON.stringify(e)),!1)).catch(e=>{o.error("Error deleting environments variable from QingLong Panel.\n"+(e.message||e))})},disableEnvs:async function(t){let r=!1;return await p.put({url:"/api/envs/disable",headers:{accept:"application/json","accept-Language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>{200===e.body.code?(o.debug("QINGLONG DISABLED ENV IDS: "+t),r=!0):o.error("Error disabling environments variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error disabling environments variable from QingLong Panel.\n"+(e.message||e))}),r},enableEnvs:async function(t){let r=!1;return await p.put({url:"/api/envs/enable",headers:{accept:"application/json","accept-language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>{200===e.body.code?(o.debug("QINGLONG ENABLED ENV IDS: "+t),r=!0):o.error("Error enabling environments variable from Qilong panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error enabling environments variable from Qilong panel.\n"+(e.message||e))}),r},addScript:async function(e,t="",r=""){let n=!1;return await p.post({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:r}}).then(e=>{200===e.body.code?n=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n},getScript:f,editScript:h,delScript:async function(e,t=""){let r=!1;return await p.delete({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t}}).then(e=>{200===e.body.code?r=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),r},write:async function(e,t,r=""){var n=await f(d,""),o=a.convertToObject(n),e=a.write(e,t,r,o),n=JSON.stringify(o,null,4);return await h(d,"",n)&&e},read:async function(e,t,r="",n=!1){var o=await f(d,""),o=a.convertToObject(o);return a.read(e,t,r,n,o)},del:async function(e,t=""){var r=await f(d,""),n=a.convertToObject(r),e=a.del(e,t,n),r=JSON.stringify(n,null,4),t=await h(d,"",r);return e&&t},update:async function(e,t,r,n=a.defaultValueComparator){var o=await f(d,""),i=a.convertToObject(o),e=a.update(e,t,r,n,i);let s=!1;return!0===e&&(o=JSON.stringify(i,null,4),s=await h(d,"",o)),e&&s},batchWrite:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r);for(t of e)a.write(t[0],t[1],void 0!==t[2]?t[2]:"",n);return r=JSON.stringify(n,null,4),h(d,"",r)},batchRead:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r),o=[];for(t of e){var i=a.read(t[0],t[1],void 0!==t[2]?t[2]:"","boolean"==typeof t[3]&&t[3],n);o.push(i)}return o},batchUpdate:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r);for(t of e)a.update(t[0],t[1],void 0!==t[2]?t[2]:"",void 0!==t[3]?t.comparator:a.defaultValueComparator,n);return r=JSON.stringify(n,null,4),h(d,"",r)},batchDel:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r);for(t of e)a.del(t[0],void 0!==t[1]?t[1]:"",n);return r=JSON.stringify(n,null,4),h(d,"",r)},allSessions:async function(e){var t=await f(d,""),t=a.convertToObject(t);return a.allSessions(e,t)},allSessionNames:async function(e){var t=await f(d,""),t=a.convertToObject(t);return a.allSessionNames(e,t)}}} //---SyncByPyScript---MagicJS3-end