pinganHelper.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*
  2. 平安银行助手
  3. https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html?paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D
  4. pahkebank://
  5. rmb.pingan.com.cn 202.69.23.211 124.196.28.130
  6. rsb.pingan.com.cn 202.69.23.214 124.196.28.135
  7. [Script]
  8. # > 平安银行助手
  9. ^https?:\/\/b\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  10. ^https?:\/\/b\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  11. ^https?:\/\/rsb\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  12. ^https?:\/\/rsb\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  13. ^https?:\/\/rmb\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  14. ^https?:\/\/rmb\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  15. ^https?:\/\/202\.69\.23\.214 url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  16. ^https?:\/\/202\.69\.23\.214 url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  17. ^https?:\/\/124\.196\.28\.135 url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  18. ^https?:\/\/124\.196\.28\.135 url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  19. ^https?:\/\/202\.69\.23\.211 url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  20. ^https?:\/\/202\.69\.23\.211 url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  21. ^https?:\/\/124\.196\.28\.130 url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  22. ^https?:\/\/124\.196\.28\.130 url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganHelper.js
  23. [MITM]
  24. hostname = b.pingan.com.cn,rsb.pingan.com.cn,rmb.pingan.com.cn,202.69.23.211,124.196.28.130,202.69.23.214,124.196.28.135
  25. */
  26. const scriptName = `平安银行助手`;
  27. const magicJS = MagicJS(scriptName, "INFO");
  28. const PingAnConstKey = {
  29. // 基础数据
  30. Cookie: 'PingAnInnerWebCookie',
  31. DeviceId: 'PingAnInnerWebDeviceId',
  32. x_g_sid: 'PingAnInnerWeb#x_g_sid',
  33. x_g_vid: 'PingAnInnerWeb#x_g_vid',
  34. x_g_rid: 'PingAnInnerWeb#x_g_rid',
  35. PageData: 'PingAnInnerWeb#PageData',
  36. PageActionId: 'PingAnInnerWeb#PageActionId',
  37. };
  38. let gRetBody;
  39. let errCodeStrMap = {
  40. 900111: "notStart",
  41. 900112: "notStart",
  42. 900113: "finish",
  43. 900109: "exceed",
  44. 910179: "nonLottery",
  45. 910204: "nonBindCard",
  46. 701001: "limitFlow",
  47. 700116: "nonBindWechat",
  48. 700118: "nonInterestWechat",
  49. 960002: "nonDayStock",
  50. 900537: "nonStock",
  51. 900139: "nonWhiteList",
  52. 900320: "riskList",
  53. 900130: "nonRules",
  54. 900982: "mutex",
  55. 950010: "nonDayTimes",
  56. 950710: "nonWeekTimes",
  57. 700119: "nonMonthTimes",
  58. 900144: "nonTimes",
  59. 950008: "nonDayPrizeTimes",
  60. 900745: "nonWeekPrizeTimes",
  61. 950009: "nonMonthPrizeTimes",
  62. 900143: "nonPrizeTimes",
  63. 600056: "timesCutDown",
  64. 780001: "nonBindAliPay",
  65. 900203: "notSendAble",
  66. 999999: "stockValidateText"
  67. };
  68. const gHost = 'b.pingan.com.cn';
  69. const gTeamId = `5K2422`;
  70. const gActivityId = `PK084123`;
  71. const gPageUrlFirstPath = '/kuaizhan/v2';
  72. const gPageUrlSuffix = `5K2422/20230925/k84123`;
  73. const gHomePageUrl = `https://b.pingan.com.cn/kuaizhan/v2/${gPageUrlSuffix}/index.html?paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D`;
  74. 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`;
  75. let gDeviceId = magicJS.data.read(PingAnConstKey.DeviceId, 'AUUID_918d439ffcef935c2fd84d3a3e593b6523c916fc');
  76. let gPageActionId = magicJS.data.read(PingAnConstKey.PageActionId, '1F908E50');
  77. 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}`;
  78. let gTmpRequsetTimeStamp = Date.now();
  79. let gTmpRequestSortId = 100 + Math.floor(Math.random() * 100);
  80. const gCommonHeaders = {
  81. 'osVersion': `16.6.1`,
  82. 'Accept-Encoding': `gzip, deflate, br`,
  83. 'Host': `rsb.pingan.com.cn`,
  84. 'X-App-Version': `6.23.0`,
  85. 'phoneModel': `iPhone15,2`,
  86. 'Connection': `keep-alive`,
  87. 'bank-mobile-model': `iPhone15,2`,
  88. 'Accept-Language': `zh-Hans-CN;q=1`,
  89. 'nativeVersion': `6.23.0`,
  90. 'User-Agent': `${gAppUserAgent}`,
  91. 'Referer': `https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html`,
  92. 'X-Aladdin-Version': `4.8.77`,
  93. 'bank-mobile-brand': `Apple`,
  94. 'x-o-spanid': `0`,
  95. 'Accept': `*/*`,
  96. 'x-g-sid': `iSb07mg4hmSUYbUg5izmW0`,
  97. 'x-g-vid': `53mWJHzK00401M5Vv+uR3w`,
  98. 'x-g-rid': `J3/I3jF+hI6xiREInsHZlg5dn320120r`,
  99. 'X-REQUEST-ID': `${gDeviceId}-${gTmpRequsetTimeStamp}-${gTmpRequestSortId}`,
  100. 'Cookie': ``
  101. };
  102. let gPageData = {};
  103. // 忽略执行的本地领券状态
  104. let gIgnoreCouponGotStatus = false;
  105. // 忽略查询的领券状态
  106. let gIgnoreActivityStatus = false;;
  107. async function Main() {
  108. if (magicJS.isStrictRequest) {
  109. magicJS.checkRecordRequestBody();
  110. }
  111. if (magicJS.isRequest) {
  112. checkHandleRequest();
  113. }
  114. magicJS.notification.msg('');
  115. if (gRetBody) {
  116. magicJS.done({
  117. body: JSON.stringify(gRetBody)
  118. });
  119. } else {
  120. magicJS.done();
  121. }
  122. }
  123. function checkHandleRequest() {
  124. const url = $request.url;
  125. const path = $request.path;
  126. magicJS.log(`请求url=${url}#${$request.method}`);
  127. if ($request && $request.method != 'OPTIONS') {
  128. switch (path) {
  129. case '/brop/cmp/cust/cmpsf/mgm/share/createTokenId.do':
  130. handleCreateTokenId();
  131. break;
  132. case '/brop/mop/cust/mopsf/nrp/uc/simple/rule/info/batchSatisfy':
  133. handleBatchSatisfy();
  134. break;
  135. case '/brop/cmp/cust/cmpsf/mgm/origin/queryPageConfig.do':
  136. handlePageConfig();
  137. break;
  138. case '/brcp/uc/cust/uc-login-web.qryLoginStatus.do':
  139. break;
  140. case '/brop/mop/cust/mopsf/lottery/getLeftOfferNum':
  141. break;
  142. case '/brop/mop/cust/mopsf/uc/auth/lottery/sendCustomerOffer':
  143. handleCustomerOffer();
  144. break;
  145. case '/credit/core/cust/ma/pabank/getSessionStatus':
  146. handleSessionStatus();
  147. break;
  148. case '/core/cust/ma/online/pabank/ma/pm/others/eightPoint8/getMallGoods':
  149. break;
  150. case '/credit/core/cust/ma/online/pabank/ma/pm/others/seckill/show':
  151. handleSecKillData();
  152. break;
  153. case '/credit/core/cust/ma/online/pabank/ma/pm/others/eightPoint8/getPageInfo':
  154. break;
  155. default:
  156. if (path.indexOf('/kuaizhan/v2/5K2422/20230925/k84123/index.html') > -1) {
  157. handleIkeaPage();
  158. } else if (path.indexOf('/rmb/brcp/uc/cust/uc-login-web.qryLoginStatus.do') > -1) {
  159. handleLoginStatus();
  160. } else if (path.indexOf('/brop/mop/cust/mopsf/personality/activity/status/query') > -1) {
  161. handlePublicActivityStatus();
  162. } else if (path.indexOf('/bron/coss/cust/app/getSupernatant') > -1) {
  163. } else if (path.indexOf('/brop/mop/cust/mopsf/uc/auth/lottery/queryCustomerActivityStatus') > -1) {
  164. handleCustomerActivityStatus();
  165. } else if (path.indexOf('/brop/stp/kafka/http/h5monitor_web/rest/ac/h5Monitor') > -1) {
  166. handleH5MonitorUploadInfo();
  167. } else if (path.indexOf('/creditcard/mk8point8/8point8.html') > -1) {
  168. handleSeckillPage();
  169. } else {
  170. }
  171. break;
  172. }
  173. }
  174. }
  175. function getResponsePlainData() {
  176. let data = magicJS.getResponseBody();
  177. if (!data) {
  178. return;
  179. }
  180. try {
  181. return JSON.parse(data);
  182. } catch (err) {
  183. magicJS.logger.error(err);
  184. }
  185. }
  186. function getRequestPlainData() {
  187. let data = magicJS.getRequestBody();
  188. let reqData = null;
  189. if (data) {
  190. reqData = magicJS.parseQueryStr(data);
  191. } else {
  192. reqData = magicJS.parseQueryStr($request.url);
  193. }
  194. return reqData;
  195. }
  196. function getQueryPlainData() {
  197. let params = magicJS.parseQueryStr($request.url);
  198. return params;
  199. }
  200. function getXRequestId() {
  201. gTmpRequestSortId++;
  202. return `${gDeviceId}-${gTmpRequsetTimeStamp}-${gTmpRequestSortId}`
  203. }
  204. function handleHeaders() {
  205. if ($request && $request.method != 'OPTIONS') {
  206. let headers = $request.headers;
  207. let x_g_sid = headers['x-g-sid'];
  208. if (x_g_sid) {
  209. magicJS.data.write(PingAnConstKey.x_g_sid, x_g_sid);
  210. }
  211. let x_g_vid = headers['x-g-vid'];
  212. if (x_g_sid) {
  213. magicJS.data.write(PingAnConstKey.x_g_vid, x_g_vid);
  214. }
  215. let x_g_rid = headers['x-g-rid'];
  216. if (x_g_sid) {
  217. magicJS.data.write(PingAnConstKey.x_g_rid, x_g_rid);
  218. }
  219. if (headers['X-REQUEST-ID']) {
  220. let tmpArr = headers['X-REQUEST-ID'].split('-');
  221. magicJS.data.write(PingAnConstKey.DeviceId, tmpArr[0]);
  222. }
  223. let newCookieStr = headers['Cookie'];
  224. if (newCookieStr) {
  225. let oldCookieStr = magicJS.data.read(PingAnConstKey.Cookie, null);
  226. magicJS.logger.info(`oldCookieStr=${oldCookieStr}`);
  227. magicJS.logger.info(`newCookieStr=${newCookieStr}`);
  228. if (compareCookieStr(newCookieStr, oldCookieStr) != 0) {
  229. magicJS.data.write(PingAnConstKey.Cookie, newCookieStr);
  230. magicJS.logger.info(`当前Cookie刷新到最新`);
  231. magicJS.notification.appendNotifyInfo(`🎉当前Cookie刷新到最新`);
  232. } else {
  233. magicJS.data.write(PingAnConstKey.Cookie, newCookieStr);
  234. magicJS.logger.info(`当前Cookie已经是最新无需更新`);
  235. }
  236. }
  237. let userAgent = headers['User-Agent'];
  238. let mRet = userAgent.match(/pageActionId\/([\S.]+)\s*/);
  239. let pageActionId = mRet && mRet[1] ? mRet[1] : "";
  240. if (pageActionId && pageActionId.length > 0) {
  241. magicJS.data.write(PingAnConstKey.PageActionId, pageActionId);
  242. }
  243. }
  244. }
  245. function compareCookieStr(cookieStr1, cookieStr2) {
  246. let cookieDict1 = magicJS.parseCookies(cookieStr1);
  247. let cookieDict2 = magicJS.parseCookies(cookieStr2);
  248. let skipKeys = ['NGWhitelist', 'PAEBANK_PARAM', 'PAEBANK_PARAM_N', 'PAEBANK_PARAM_W', 'WEBTRENDS_SESSIONID', 'brcpSessionTicket', 'sdc_PABankParam', 'shuntid'];
  249. skipKeys = ['PAEBANK_PARAM', 'WEBTRENDS_SESSIONID'];
  250. let retCode = 0;
  251. for (let key in cookieDict1) {
  252. if (!skipKeys.includes(key)) {
  253. if (cookieDict1[key] != void 0 && cookieDict2[key] != void 0 && cookieDict1[key] != cookieDict2[key]) {
  254. magicJS.logger.info(`${key}`);
  255. retCode = -1;
  256. break;
  257. }
  258. }
  259. }
  260. return retCode;
  261. }
  262. function handleIkeaPage() {
  263. handleHeaders();
  264. }
  265. function handleSeckillPage() {
  266. handleHeaders();
  267. }
  268. function handleCreateTokenId() {
  269. }
  270. function handleBatchSatisfy() {
  271. }
  272. function handlePageConfig() {
  273. handleHeaders();
  274. let rspData = getResponsePlainData();
  275. if (!rspData) {
  276. return;
  277. }
  278. if (rspData.responseCode != "000000") {
  279. return;
  280. }
  281. let data = rspData.data;
  282. let reqData = getRequestPlainData();
  283. let partnerId = reqData.partnerId;
  284. let pageId = reqData.pageId;
  285. let tokenId = reqData.tokenId;
  286. let innerId = reqData.innerId;
  287. if (data.reShow) {
  288. }
  289. }
  290. function handlePublicActivityStatus() {
  291. handleHeaders();
  292. let rspData = getResponsePlainData();
  293. if (!rspData) {
  294. return;
  295. }
  296. if (rspData.responseCode != "000000") {
  297. return;
  298. }
  299. let queryParams = getQueryPlainData();
  300. let activityCode = queryParams.activityCode;
  301. let queryNextTime = queryParams.queryNextTime;
  302. let data = rspData.data;
  303. }
  304. function handleCustomerActivityStatus() {
  305. handleHeaders();
  306. let rspData = getResponsePlainData();
  307. if (!rspData) {
  308. return;
  309. }
  310. // rspData = { pagination: null, data: null, responseCode: "000000", responseMsg: "成功" };
  311. // gRetBody = rspData;
  312. if (rspData.responseCode != "000000") {
  313. return;
  314. }
  315. }
  316. function handleCustomerOffer() {
  317. let rspData = getResponsePlainData();
  318. if (!rspData) {
  319. return;
  320. }
  321. // rspData.responseCode = "000000";
  322. // gRetBody = rspData;
  323. if (rspData.responseCode != "000000") {
  324. return;
  325. }
  326. }
  327. function handleLoginStatus() {
  328. handleHeaders();
  329. let rspData = getResponsePlainData();
  330. if (!rspData) {
  331. return;
  332. }
  333. if (rspData.responseCode != "000000") {
  334. return;
  335. }
  336. }
  337. function handleH5MonitorUploadInfo() {
  338. let rspData = getResponsePlainData();
  339. if (!rspData) {
  340. return;
  341. }
  342. if (rspData.responseCode != "000000") {
  343. return;
  344. }
  345. let reqData = getRequestPlainData();
  346. if (!reqData || !reqData.uploadInfo) {
  347. return;
  348. }
  349. let uploadInfo = reqData.uploadInfo;
  350. let reqObject = null;
  351. // reqObject = {
  352. // "countType": 32,
  353. // "totalDelay": 464,
  354. // "h5monitor_sdk_version": "1.7.0",
  355. // "performanceTiming": {
  356. // "navigationStart": 1724052379766,
  357. // "unloadEventStart": 0,
  358. // "unloadEventEnd": 0,
  359. // "redirectStart": 0,
  360. // "redirectEnd": 0,
  361. // "fetchStart": 1724052379766,
  362. // "domainLookupStart": 1724052379766,
  363. // "domainLookupEnd": 1724052379766,
  364. // "connectStart": 1724052379766,
  365. // "connectEnd": 1724052379766,
  366. // "secureConnectionStart": 0,
  367. // "requestStart": 1724052379766,
  368. // "responseStart": 1724052379766,
  369. // "responseEnd": 1724052379766,
  370. // "domLoading": 1724052380035,
  371. // "domInteractive": 1724052380184,
  372. // "domContentLoadedEventStart": 1724052380184,
  373. // "domContentLoadedEventEnd": 1724052380189,
  374. // "domComplete": 1724052380230,
  375. // "loadEventStart": 1724052380230,
  376. // "loadEventEnd": 1724052380230
  377. // },
  378. // "navigation": {
  379. // "type": 0,
  380. // "redirectCount": 0
  381. // },
  382. // "ttfb": 0,
  383. // "domReady": 418,
  384. // "qs": "?traceid=fixed_innerid_KDAPP-96SS-HDY-1&innerid=KDAPP-96SS-HDY-1",
  385. // "firstScreen": 418,
  386. // "routelabel": 0,
  387. // "firstSource": "api",
  388. // "dt": 1724052381231,
  389. // "fbextension": "",
  390. // "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",
  391. // "webtrendsid": "AUUID_918d439ffcef935c2fd84d3a3e593b6523c916fc",
  392. // "appversion": "6.23.0",
  393. // "platform": "ios",
  394. // "pageID": "PK084123",
  395. // "h5_app_id": "A208848050024B1584C78C904A4900E4",
  396. // "pagetitle": "宜家礼品卡88折起",
  397. // "ymd": "2024-08-19 15:26:21",
  398. // "page": "https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html",
  399. // "requestId": "6ugxCquxgrG49lDeOVXSqw61OT00123s"
  400. // };
  401. try {
  402. reqObject = JSON.parse(decodeURIComponent(uploadInfo));
  403. } catch (error) {
  404. }
  405. }
  406. function handleSessionStatus() {
  407. let rspData = getResponsePlainData();
  408. if (!rspData) {
  409. return;
  410. }
  411. if (rspData.code != "000000") {
  412. return;
  413. }
  414. if (rspData.body && rspData.body.userStatus != "0") {
  415. handleHeaders();
  416. }
  417. }
  418. function handleSecKillData() {
  419. let rspData = getResponsePlainData();
  420. if (!rspData) {
  421. return;
  422. }
  423. if (rspData.code != "000000") {
  424. return;
  425. }
  426. handleHeaders();
  427. let data = rspData.body;
  428. let actStatus = data.actStatus;
  429. let dictInfo = data.dictInfo;
  430. let stockInfo = data.stockInfo;
  431. // 更改系统时间
  432. let nowDateStr = magicJS.formatDate(new Date(), 'yyyy-MM-dd');
  433. actStatus.systemTime = actStatus.systemTime.replace(nowDateStr, actStatus.seckillDate);
  434. // 更改抢购结束时间
  435. let actInfoList = dictInfo.actInfoList;
  436. for (let i = 0; i < actInfoList.length; ++i) {
  437. let item = actInfoList[i];
  438. item.endTime = '23:59:59';
  439. }
  440. // 更改库存是否抢光
  441. for (let i = 0; i < stockInfo.length; ++i) {
  442. let item = stockInfo[i];
  443. item.remain = true;
  444. }
  445. gRetBody = rspData;
  446. }
  447. async function getPageData() {
  448. let url = `https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/pageData.js?v=${new Date().getTime()}`;
  449. let body = ``;
  450. let headers = {
  451. 'Cookie': magicJS.data.read(PingAnConstKey.Cookie, ''),
  452. 'Sec-Fetch-Mode': `navigate`,
  453. 'Connection': `keep-alive`,
  454. 'Accept': `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`,
  455. 'Accept-Encoding': `gzip, deflate, br`,
  456. 'Host': `b.pingan.com.cn`,
  457. 'User-Agent': `${gAppUserAgent}`,
  458. 'Sec-Fetch-Site': `none`,
  459. 'Accept-Language': `zh-CN,zh-Hans;q=0.9`,
  460. 'Sec-Fetch-Dest': `document`,
  461. // 'If-Modified-Since': `Thu, 18 Jul 2024 11:10:01 GMT`
  462. };;
  463. let options = {
  464. url: url,
  465. headers: headers,
  466. body: body,
  467. };
  468. let result = await magicJS.http.get(options).then(response => {
  469. try {
  470. const body = response.body;
  471. let rspData = null;
  472. let retMatch = body.match(/var pageData = ([\s\S]*)/); // 正则表达式匹配
  473. if (retMatch) {
  474. rspData = JSON.parse(retMatch[1]);
  475. }
  476. // magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`);
  477. return rspData;
  478. } catch (e) {
  479. magicJS.logger.error(e);
  480. }
  481. }).catch(err => {
  482. const msg = `请求页面配置数据异常\n${JSON.stringify(err)}`;
  483. magicJS.logger.error(msg);
  484. });
  485. return result;
  486. }
  487. async function checkGetPageData() {
  488. let strToday = magicJS.formatDate(new Date(), 'yyyy-MM-dd');
  489. let key = `${PingAnConstKey.PageData}`;
  490. let cacheData = magicJS.data.read(key, null);
  491. if (cacheData && cacheData.storeDate == strToday) {
  492. magicJS.logger.info(`今日已更新过活动页面数据`);
  493. gPageData = cacheData.data;
  494. } else {
  495. magicJS.logger.info(`今日首次更新活动页面数据`);
  496. gPageData = await getPageData();
  497. magicJS.data.write(key, { storeDate: strToday, data: gPageData });
  498. }
  499. if (gPageData) {
  500. let buildTime = gPageData.buildTime;
  501. magicJS.logger.info(`当前活动页面数据最新构建时间:${magicJS.formatDate(new Date(buildTime), 'yyyy-MM-dd')}`);
  502. }
  503. return gPageData;
  504. }
  505. async function getClientTag() {
  506. if (!gPageData) {
  507. gPageData = await checkGetPageData();
  508. }
  509. if (!gPageData) {
  510. return;
  511. }
  512. let clientTag = '';
  513. let widgets = gPageData.widgets;
  514. for (let i = 0; i < widgets.length; i++) {
  515. const widget = widgets[i];
  516. if (widget.label.indexOf('简易规则') > -1) {
  517. clientTag = widget.config.clientTag;
  518. }
  519. }
  520. return clientTag;
  521. }
  522. function getResponseErrorMsg(errCode, config, responseMsg) {
  523. let key = errCodeStrMap[errCode];
  524. if (key && config && config[key]) {
  525. return config[key].toastText || responseMsg;
  526. } else {
  527. return responseMsg;
  528. }
  529. }
  530. Main().catch((e) => magicJS.logger.log(`-\n ${e}`)).finally(() => magicJS.done());
  531. //---SyncByPyScript---MagicJS3-start
  532. function MagicJS(e="MagicJS",t="INFO"){const r=()=>{const e="undefined"!=typeof $loon,t="undefined"!=typeof $task,n="undefined"!=typeof module,r="undefined"!=typeof $httpClient&&!e,o="undefined"!=typeof $storm,i="undefined"!=typeof $environment&&void 0!==$environment["stash-build"];var s=r||e||o||i;const a="undefined"!=typeof importModule;return{isLoon:e,isQuanX:t,isNode:n,isSurge:r,isStorm:o,isStash:i,isSurgeLike:s,isScriptable:a,get name(){return e?"Loon":t?"QuantumultX":n?"NodeJS":r?"Surge":a?"Scriptable":"unknown"},get build(){return r?$environment["surge-build"]:i?$environment["stash-build"]:o?$storm.buildVersion:void 0},get language(){if(r||i)return $environment.language},get version(){return r?$environment["surge-version"]:i?$environment["stash-version"]:o?$storm.appVersion:n?process.version:void 0},get system(){return r?$environment.system:n?process.platform:void 0},get systemVersion(){if(o)return $storm.systemVersion},get deviceName(){if(o)return $storm.deviceName}}},o=(n,e="INFO")=>{let r=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[r]<o[t.toUpperCase()]||console.log(`██[${n}][${t}]`+i[t.toUpperCase()]+e+"\n")};return{getLevel:()=>r,setLevel:e=>{r=e},sniffer:(...e)=>{e=e.join(t);s(e,"SNIFFER")},log:(...e)=>{e=e.join(t);console.log(`██[${n}]`+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 n;this._startTime=Date.now(),this.version="3.0.0",this.scriptName=e,this.env=r(),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"),n=this.data.read("magic_bark_url"),t&&this.logger.setLevel(t.toUpperCase()),n)&&this.notification.setBark(n),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 n=this.env,r=$request.path;let e=this.scriptName+"#"+r.replace("/","_");e=e.replace("?","#"),n.isQuanX&&$prefs.setValueForKey(t,e),(n.isLoon||n.isSurge)&&$persistentStore.write(t,e),n.isNode&&require("fs").writeFileSync(e+".json",t,{flag:"w"},e=>console.log(e))}}}getRequestBody(){var e=this.env,t=$request.path;let n=this.scriptName+"#"+t.replace("/","_");if(n=n.replace("?","#"),e.isSurge||e.isLoon)return $persistentStore.read(n);if(e.isQuanX)return $prefs.valueForKey(n);if(e.isNode){t=n+".json",e=require("fs");if(!e.existsSync(t))return JSON.parse(e.readFileSync(t))}}getResponseBody(){if($response)return $response.body}parseCookies(e){let t={};return e&&e.split(";").forEach(function(e){e=e.split("=");t[e.shift().trim()]=decodeURI(e.join("="))}),t}serializeCookies(e){var t,n=[];for(t in e){var r=e[t],r=encodeURIComponent(t)+"="+encodeURIComponent(r);n.push(r)}return n.join("; ")}parseSetCookies(e){const o=["Expires","Max-Age","Domain","Path","HttpOnly","SameSite"];e=e.split(";");let i=null;const s={},a=[];return e.forEach(e=>{var t,e=e.trim();let n=null,r=!0;if(e.includes("=")?(t=e.split("="),n=t[0].trim(),r=t[1].trim()):n=e,o.includes(n))s[i]&&(s[i][n]=r,s[i].attribs[n]=r);else{i=n;let t={};i.includes(",")&&i.split(",").forEach(e=>{e=e.trim();o.includes(e)?t[e]=!0:i=e}),s[i]={name:i,value:r,attribs:t},a.push(s[i])}}),a}objToQueryStr(t,n){let r="";for(const o in t){let e=t[o];null!=e&&""!==e&&("object"==typeof e?e=JSON.stringify(e):n&&(e=encodeURIComponent(e)),r+=`${o}=${e}&`)}return r=r.substring(0,r.length-1)}parseQueryStr(e){var t={},n=(e=-1<e.indexOf("?")?e.split("?")[1]:e).split("&");for(let e=0;e<n.length;e++){var r=n[e].split("=");t[r[0]]=r[1]}return t}deepClone(e,t){for(var n in t=t||{},e)"object"==typeof e[n]?(t[n]=e[n].constructor===Array?[]:{},this.deepClone(e[n],t[n])):t[n]=e[n];return t}formatDate(e,t){var n,r={"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(n in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),r)new RegExp("("+n+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?r[n]:("00"+r[n]).substr((""+r[n]).length)));return t}parseDate(a,e){let l={y:0,M:1,d:0,H:0,h:0,m:0,s:0,S:0};(e=e||"yyyy-MM-dd").replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g,function(e,t,n,r,o,i,s){return a=a.replace(new RegExp(t+"(\\d{"+n.length+"})"+o),function(e,t){return l[r]=parseInt(t),""}),""}),l.M--;e=new Date(l.y,l.M,l.d,l.H,l.m,l.s);return 0!==l.S&&e.setMilliseconds(l.S),e}getBaseDoneHeaders(e={}){return Object.assign({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"POST,GET,OPTIONS,PUT,DELETE","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept"},e)}getHtmlDoneHeaders(){return this.getBaseDoneHeaders({"Content-Type":"text/html;charset=UTF-8"})}getJsonDoneHeaders(){return this.getBaseDoneHeaders({"Content-Type":"text/json; charset=utf-8",Connection:"keep-alive"})}doWxpusherSend(e){var t=this.getJsonDoneHeaders(),t=(t.Host="wxpusher.zjiecode.com",t["Content-Type"]="application/json;charset=UTF-8",{url:"https://wxpusher.zjiecode.com/api/send/message",headers:t,body:JSON.stringify(e)});return this.http.post(t)}fastWxpusherSend(e,t="",n=""){return this.doWxpusherSend({appToken:"AT_7wDWqSoT8xpJCQqJtHpshKhw7kXc0XCW",content:e,summary:t,contentType:1,topicIds:[],uids:["UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"],url:n,verifyPay:!1,verifyPayType:0})}isEmpty(e){return void 0===e||null==e||""==e||"null"==e||"undefined"==e||0===e.length}base64Encode(e){var t,n,r,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,s,a;for(a=e.length,s=0,i="";s<a;){if(t=255&e.charCodeAt(s++),s==a){i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4)+"==";break}if(n=e.charCodeAt(s++),s==a){i=(i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4|(240&n)>>4))+o.charAt((15&n)<<2)+"=";break}r=e.charCodeAt(s++),i=(i=(i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4|(240&n)>>4))+o.charAt((15&n)<<2|(192&r)>>6))+o.charAt(63&r)}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 n,r,o,i,s,a,l=e.replace(/\s/g,"");let u="",c=0;for(;c<l.length;)o=t.indexOf(l.charAt(c++)),n=(15&(i=t.indexOf(l.charAt(c++))))<<4|(s=t.indexOf(l.charAt(c++)))>>2,r=(3&s)<<6|(a=t.indexOf(l.charAt(c++))),u+=String.fromCharCode(o<<2|i>>4),64!==s&&(u+=String.fromCharCode(n)),64!==a&&(u+=String.fromCharCode(r));return u=this.utf8Decode(u)}utf8Decode(t){let e=[],n=0,r=0,o=0;for(t=t.replace(/\r\n/g,"\n");n<t.length;){r=255&t.charCodeAt(n),o=0,o=r<=191?(r&=127,1):r<=223?(r&=31,2):r<=239?(r&=15,3):(r&=7,4);for(let e=1;e<o;++e)r=r<<6|63&t.charCodeAt(e+n);4===o?(r-=65536,e.push(String.fromCharCode(55296|r>>10&1023)),e.push(String.fromCharCode(56320|1023&r))):e.push(String.fromCharCode(r)),n+=o}return e.join("")}parseJwt(e){try{var t=e.split("."),n=t[0].replace(/-/g,"+").replace(/_/g,"/"),r=this.base64Decode(n).replace(/\0/g,""),o=JSON.parse(r),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,n){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:!(!n||"boolean"!=typeof n.synchronous)&&n.synchronous,runWhen:n?n.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 n={...e};return n.params&&!d.isNode&&(e=Object.keys(n.params).map(e=>{var t=encodeURIComponent(e);return n.url=n.url.replace(new RegExp(e+"=[^&]*","ig"),""),n.url=n.url.replace(new RegExp(t+"=[^&]*","ig"),""),t+"="+encodeURIComponent(n.params[e])}).join("&"),n.url.indexOf("?")<0&&(n.url+="?"),/(&|\?)$/g.test(n.url)||(n.url+="&"),n.url+=e,delete n.params,p.debug("Params to QueryString: "+n.url)),n}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 n=(e,n)=>{let r;n=((e,t)=>{let n="object"==typeof t?{headers:{},...t}:{url:t,headers:{}};return n.method||(n.method=e),!0===(n=f(n)).rewrite&&(d.isSurge?(n.headers["X-Surge-Skip-Scripting"]=!1,delete n.rewrite):d.isQuanX&&(n.hints=!1,delete n.rewrite)),d.isSurgeLike?(t=n.headers["content-type"]||n.headers["Content-Type"],"GET"!==n.method&&t&&0<=t.indexOf("application/json")&&n.body instanceof Array&&(n.body=JSON.stringify(n.body),p.debug("Convert Array object to String: "+n.body))):d.isQuanX?(n.hasOwnProperty("body")&&"string"!=typeof n.body&&(n.body=JSON.stringify(n.body)),n.method=e):d.isNode&&("POST"===e||"PUT"===e||"PATCH"===e||"DELETE"===e?n.data=n.data||n.body:"GET"===e&&(n.params=n.params||n.body),delete n.body),n})(e.toUpperCase(),n),r=d.isNode?g:d.isSurgeLike?i=>new Promise((r,o)=>{$httpClient[e.toLowerCase()](i,(e,t,n)=>{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=n,r(t))})}):r=>new Promise((n,t)=>{$task.fetch(r).then(e=>{e=h(e,r);var t=y(e,r);if(t)return Promise.reject(t);n(e)}).catch(e=>{e={name:e.message||e.error,message:e.message||e.error,stack:e.error,config:r,response:e.response?h(e.response):null};t(e)})});let o;var t=n;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),n=a(n)}catch(e){"function"==typeof l&&p.debug("Executing request rejected "+l.name),l(e);break}}try{o=(!d.isNode&&n.timeout?c:r)(n)}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=[r,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(n);t.length;)try{let e=t.shift();var u=t.shift();"function"==typeof(e=!d.isNode&&n.timeout&&e===r?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(n){try{var e=new Promise((e,t)=>{setTimeout(()=>{var e={message:`timeout of ${n.timeout}ms exceeded.`,config:n};t(e)},n.timeout)});return Promise.race([r(n),e])}catch(e){p.error(`Request Timeout exception: ${e}.`)}}};return{request:n,interceptors:m,convertHeadersToLowerCase:n=>Object.keys(n).reduce((e,t)=>(e[t.toLowerCase()]=n[t],e),{}),convertHeadersToCamelCase:n=>Object.keys(n).reduce((e,t)=>{return e[t.split("-").map(e=>e[0].toUpperCase()+e.slice(1)).join("-")]=n[t],e},{}),modifyResponse:h,get:e=>n("GET",e),post:e=>n("POST",e),put:e=>n("PUT",e),patch:e=>n("PATCH",e),delete:e=>n("DELETE",e),head:e=>n("HEAD",e),options:e=>n("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,n,r)=>{if(n)try{e=!0===(e="string"==typeof e?JSON.parse(e):e).magic_session?e[n]:null}catch{e=null}if("string"==typeof e&&"null"!==e)try{e=JSON.parse(e)}catch{}return null==(e=!1===r&&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 n=typeof(e=JSON.parse(t));("object"!=n||e instanceof Array||"bool"==n||null===e)&&(e={})}catch{}return e}},u=(e,t=null,n="",r=!1,o=null)=>{let i="";return i=o||d.isNode?((e,t=null,n="",r=!1,o=null)=>{o=o||g.data;return val=o&&void 0!==o[e]&&null!==o[e]?o[e]:n?{}:null,val=l(val,t,n,r)})(e,t,n,r,o):(d.isSurgeLike?i=$persistentStore.read(e):d.isQuanX&&(i=$prefs.valueForKey(e)),l(i,t,n,r)),p.debug(`READ DATA [${e}]${n?`[${n}]`:""} <${typeof i}>`+"\n"+JSON.stringify(i)),i},c=(e,t,n="",r=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(r||d.isNode?o=([i,s,a="",l=null]=[e,t,n,r],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):n?(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[n]=t):o=t,o&&"object"==typeof o&&(o=JSON.stringify(o,null,4)),p.debug(`WRITE DATA [${e}]${n?`[${n}]`:""} <${typeof t}>`+"\n"+JSON.stringify(t)),!r){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="",n=null)=>{let r={};if(n||d.isNode)r=(o=e,i=t,s=n||g.data,s=f(s),i?(delete(obj=f(s[o]))[i],s[o]=obj):delete s[o],s),n?n=r:g.fs.writeFileSync("./magic.json",JSON.stringify(r,null,4));else if(t){d.isSurgeLike?r=$persistentStore.read(e):d.isQuanX&&(r=$prefs.valueForKey(e)),delete(r=f(r))[t];i=JSON.stringify(r,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,n,r=s,o=null)=>{var i;return t=a(t),!0!==r(u(e,null,n,!1,o),t)&&(i=c(e,t,n,o),e=u(e,null,n,!1,o),r===s&&"object"==typeof e?i:r(t,e))},allSessions:(e,t=null)=>{let n={};t=u(e,null,null,!0,t);return!0===(t=f(t)).magic_session&&delete(n={...t}).magic_session,p.debug(`READ ALL SESSIONS [${e}] <${typeof n}>`+"\n"+JSON.stringify(n,null,4)),n},allSessionNames:(e,t=null)=>{let n=[];t=u(e,null,null,!0,t),t=f(t);return n=!0!==t.magic_session?[]:Object.keys(t).filter(e=>"magic_session"!==e),p.debug(`READ ALL SESSIONS [${e}] <${typeof n}>`+"\n"+JSON.stringify(n,null,4)),n},defaultValueComparator:s,convertToObject:f}}function MagicNotification(i,o,s,a){let l=null,u=null,c=[];function d(e=i,t="",n="",r=""){r=(t=>{try{let e={};var n;return"string"==typeof t?0<t.length&&(o.isLoon?e={openUrl:t}:o.isQuanX?e={"open-url":t}:o.isSurge&&(e={url:t})):"object"==typeof t&&(o.isLoon?(e.openUrl=t["open-url"]||"",e.mediaUrl=t["media-url"]||""):o.isQuanX?e=t["open-url"]||t["media-url"]?t:{}:o.isSurge&&(n=t["open-url"]||t.openUrl,e=n?{url:n}:{})),e}catch(e){s.error("通知选项转换失败"+e)}return t})(r),1===arguments.length&&(e=i,t="",n=arguments[0]),s.notify("\ntitle:"+e+"\nsubTitle:"+t+"\nbody:"+n+"\noptions:"+("object"==typeof r?JSON.stringify(r):r)),o.isSurge?$notification.post(e,t,n,r):o.isLoon?r?$notification.post(e,t,n,r):$notification.post(e,t,n):o.isQuanX&&$notify(e,t,n,r),l&&u&&p(e,t,n)}function p(e=i,t="",n="",r){if(void 0===a||void 0===a.post)throw"Bark notification needs to import MagicHttp module.";e={url:l,headers:{"content-type":"application/json; charset=utf-8"},body:{title:e,body:t?t+"\n"+n:n,device_key:u}};a.post(e).catch(e=>{s.error("Bark notify error: "+e)})}return{post:d,debug:function(e=i,t="",n="",r=""){"DEBUG"===s.getLevel()&&(1===arguments.length&&(e=i,t="",n=arguments[0]),this.post(e,t,n,r))},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,n,r){var o={};n&&(o["open-url"]=n),r&&(o["media-url"]=r),(t=t&&0!=t.length?t:Array.isArray(c)?c.join("\n"):c)&&0<t.length&&d(i,"",t,o)}}}function MagicUtils(r,u){const e=(e,t="yyyy-MM-dd hh:mm:ss")=>{var n,r={"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(n in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),r)new RegExp("("+n+")").test(t)&&(t=t.replace(RegExp.$1,1===RegExp.$1.length?r[n]:("00"+r[n]).substr((""+r[n]).length)));return t};return{retry:(i,s=5,a=0,l=null)=>(...e)=>new Promise((n,r)=>{function o(...t){Promise.resolve().then(()=>i.apply(this,t)).then(e=>{"function"==typeof l?Promise.resolve().then(()=>l(e)).then(()=>{n(e)}).catch(e=>{1<=s?0<a?setTimeout(()=>o.apply(this,t),a):o.apply(this,t):r(e),s--}):n(e)}).catch(e=>{u.error(e),1<=s&&0<a?setTimeout(()=>o.apply(this,t),a):1<=s?o.apply(this,t):r(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 n;r.isNode?(n=require("assert"),t?n(e,t):n(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 n(){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<Object.keys(e.body).length&&e.body.data&&e.body.data.token))throw new Error("Get QingLong Panel token failed.");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))})):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 r(r=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(r){var t=[];for(const n of e)n.name===r&&o.push(n);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 n="";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));n=e.body.data}).catch(e=>{throw new Error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n}async function h(e,t="",n=""){let r=!1;return await p.put({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:n}}).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}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 n(),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 n(),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,n,r,o)=>{i=e,l=t,u=n,s=r,c=o},getToken:n,setEnv:async function(t,n,r=null){if(i=i||a.read("magic_qlurl"),null===r){var e=await g([{name:t,value:n}]);if(e&&1===e.length)return e[0]}else await p.put({url:"/api/envs",headers:{"content-type":"application/json"},body:{name:t,value:n,id:r}}).then(e=>{if(200===e.body.code)return o.debug(`QINGLONG UPDATE ENV ${t} <${typeof n}> (${r})`+"\n"+JSON.stringify(n)),!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 n of await r())if(n.id===e){t=n;break}return t},getEnvs:r,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 n=!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),n=!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))}),n},enableEnvs:async function(t){let n=!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),n=!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))}),n},addScript:async function(e,t="",n=""){let r=!1;return await p.post({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:n}}).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},getScript:f,editScript:h,delScript:async function(e,t=""){let n=!1;return await p.delete({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t}}).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},write:async function(e,t,n=""){var r=await f(d,""),o=a.convertToObject(r),e=a.write(e,t,n,o),r=JSON.stringify(o,null,4);return await h(d,"",r)&&e},read:async function(e,t,n="",r=!1){var o=await f(d,""),o=a.convertToObject(o);return a.read(e,t,n,r,o)},del:async function(e,t=""){var n=await f(d,""),r=a.convertToObject(n),e=a.del(e,t,r),n=JSON.stringify(r,null,4),t=await h(d,"",n);return e&&t},update:async function(e,t,n,r=a.defaultValueComparator){var o=await f(d,""),i=a.convertToObject(o),e=a.update(e,t,n,r,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,n=await f(d,""),r=a.convertToObject(n);for(t of e)a.write(t[0],t[1],void 0!==t[2]?t[2]:"",r);return n=JSON.stringify(r,null,4),h(d,"",n)},batchRead:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n),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],r);o.push(i)}return o},batchUpdate:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n);for(t of e)a.update(t[0],t[1],void 0!==t[2]?t[2]:"",void 0!==t[3]?t.comparator:a.defaultValueComparator,r);return n=JSON.stringify(r,null,4),h(d,"",n)},batchDel:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n);for(t of e)a.del(t[0],void 0!==t[1]?t[1]:"",r);return n=JSON.stringify(r,null,4),h(d,"",n)},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)}}}
  533. //---SyncByPyScript---MagicJS3-end