pinganIkea.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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. [Script]
  6. # > 平安银行宜家礼品卡优惠券
  7. ^https?:\/\/b\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js
  8. ^https?:\/\/b\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js
  9. ^https?:\/\/rsb\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js
  10. ^https?:\/\/rsb\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js
  11. ^https?:\/\/rmb\.pingan\.com\.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js
  12. ^https?:\/\/rmb\.pingan\.com\.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/pingan/pinganIkea.js
  13. [MITM]
  14. hostname = b.pingan.com.cn,rsb.pingan.com.cn,rmb.pingan.com.cn
  15. */
  16. const scriptName = `平安银行宜家礼品卡优惠券`;
  17. const magicJS = MagicJS(scriptName, "INFO");
  18. const PingAnConstKey = {
  19. // 基础数据
  20. Cookie: 'PingAnInnerWebCookie',
  21. DeviceId: 'PingAnInnerWebDeviceId',
  22. x_g_sid: 'PingAnInnerWeb#x_g_sid',
  23. x_g_vid: 'PingAnInnerWeb#x_g_vid',
  24. x_g_rid: 'PingAnInnerWeb#x_g_rid',
  25. PageData: 'PingAnInnerWeb#PageData',
  26. PageActionId: 'PingAnInnerWeb#PageActionId',
  27. };
  28. let gRetBody;
  29. let errCodeStrMap = {
  30. 900111: "notStart",
  31. 900112: "notStart",
  32. 900113: "finish",
  33. 900109: "exceed",
  34. 910179: "nonLottery",
  35. 910204: "nonBindCard",
  36. 701001: "limitFlow",
  37. 700116: "nonBindWechat",
  38. 700118: "nonInterestWechat",
  39. 960002: "nonDayStock",
  40. 900537: "nonStock",
  41. 900139: "nonWhiteList",
  42. 900320: "riskList",
  43. 900130: "nonRules",
  44. 900982: "mutex",
  45. 950010: "nonDayTimes",
  46. 950710: "nonWeekTimes",
  47. 700119: "nonMonthTimes",
  48. 900144: "nonTimes",
  49. 950008: "nonDayPrizeTimes",
  50. 900745: "nonWeekPrizeTimes",
  51. 950009: "nonMonthPrizeTimes",
  52. 900143: "nonPrizeTimes",
  53. 600056: "timesCutDown",
  54. 780001: "nonBindAliPay",
  55. 900203: "notSendAble",
  56. 999999: "stockValidateText"
  57. };
  58. const gTeamId = `5K2422`;
  59. const gActivityId = `PK084123`;
  60. const gPageUrlFirstPath = '/kuaizhan/v2';
  61. const gPageUrlSuffix = `5K2422/20230925/k84123`;
  62. const gHost = 'rsb.pingan.com.cn';
  63. const gReferer = `https://b.pingan.com.cn/kuaizhan/v2/${gPageUrlSuffix}/index.html`;
  64. const gHomePageUrl = `${gReferer}?paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D`;
  65. 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`;
  66. let gDeviceId = magicJS.data.read(PingAnConstKey.DeviceId, 'AUUID_918d439ffcef935c2fd84d3a3e593b6523c916fc');
  67. let gPageActionId = magicJS.data.read(PingAnConstKey.PageActionId, '1F908E50');
  68. 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}`;
  69. let gTmpRequsetTimeStamp = Date.now();
  70. let gTmpRequestSortId = 100 + Math.floor(Math.random() * 100);
  71. const gCommonHeaders = {
  72. 'osVersion': `16.6.1`,
  73. 'Accept-Encoding': `gzip, deflate, br`,
  74. 'Host': `${gHost}`,
  75. 'X-App-Version': `6.23.0`,
  76. 'phoneModel': `iPhone15,2`,
  77. 'Connection': `keep-alive`,
  78. 'bank-mobile-model': `iPhone15,2`,
  79. 'Accept-Language': `zh-Hans-CN;q=1`,
  80. 'nativeVersion': `6.23.0`,
  81. 'User-Agent': `${gAppUserAgent}`,
  82. 'Referer': `${gReferer}`,
  83. 'X-Aladdin-Version': `4.8.77`,
  84. 'bank-mobile-brand': `Apple`,
  85. 'x-o-spanid': `0`,
  86. 'Accept': `*/*`,
  87. 'x-g-sid': `iSb07mg4hmSUYbUg5izmW0`,
  88. 'x-g-vid': `53mWJHzK00401M5Vv+uR3w`,
  89. 'x-g-rid': `J3/I3jF+hI6xiREInsHZlg5dn320120r`,
  90. 'X-REQUEST-ID': `${gDeviceId}-${gTmpRequsetTimeStamp}-${gTmpRequestSortId}`,
  91. 'Cookie': ``
  92. };
  93. let gPageData = {};
  94. let gPageId = 'PK084123';
  95. // 忽略执行的本地领券状态
  96. let gIgnoreCouponGotStatus = false;
  97. // 忽略查询的领券状态
  98. let gIgnoreActivityStatus = false;;
  99. async function Main() {
  100. if (magicJS.isStrictRequest) {
  101. magicJS.checkRecordRequestBody();
  102. }
  103. if (magicJS.isRequest) {
  104. checkHandleRequest();
  105. } else {
  106. updateHeaders();
  107. await tryGrabCoupon();
  108. }
  109. magicJS.notification.msg('');
  110. if (gRetBody) {
  111. magicJS.done({
  112. body: JSON.stringify(gRetBody)
  113. });
  114. } else {
  115. magicJS.done();
  116. }
  117. }
  118. function checkHandleRequest() {
  119. const url = $request.url;
  120. const path = $request.path;
  121. magicJS.log(`请求url=${url}#${$request.method}`);
  122. if ($request && $request.method != 'OPTIONS') {
  123. switch (path) {
  124. case '/brop/cmp/cust/cmpsf/mgm/share/createTokenId.do':
  125. handleCreateTokenId();
  126. break;
  127. case '/brop/mop/cust/mopsf/nrp/uc/simple/rule/info/batchSatisfy':
  128. handleBatchSatisfy();
  129. break;
  130. case '/brop/cmp/cust/cmpsf/mgm/origin/queryPageConfig.do':
  131. handlePageConfig();
  132. break;
  133. case '/brcp/uc/cust/uc-login-web.qryLoginStatus.do':
  134. break;
  135. case '/brop/mop/cust/mopsf/lottery/getLeftOfferNum':
  136. break;
  137. case '/brop/mop/cust/mopsf/uc/auth/lottery/sendCustomerOffer':
  138. handleCustomerOffer();
  139. break;
  140. default:
  141. if (path.indexOf('/kuaizhan/v2/5K2422/20230925/k84123/index.html') > -1) {
  142. handleHomePage();
  143. } else if (path.indexOf('/rmb/brcp/uc/cust/uc-login-web.qryLoginStatus.do') > -1) {
  144. handleLoginStatus();
  145. } else if (path.indexOf('/brop/mop/cust/mopsf/personality/activity/status/query') > -1) {
  146. handlePublicActivityStatus();
  147. } else if (path.indexOf('/bron/coss/cust/app/getSupernatant') > -1) {
  148. } else if (path.indexOf('/brop/mop/cust/mopsf/uc/auth/lottery/queryCustomerActivityStatus') > -1) {
  149. handleCustomerActivityStatus();
  150. } else if (path.indexOf('/brop/stp/kafka/http/h5monitor_web/rest/ac/h5Monitor') > -1) {
  151. handleH5MonitorUploadInfo();
  152. }
  153. break;
  154. }
  155. }
  156. }
  157. function getResponsePlainData() {
  158. let data = magicJS.getResponseBody();
  159. if (!data) {
  160. return;
  161. }
  162. try {
  163. return JSON.parse(data);
  164. } catch (err) {
  165. magicJS.logger.error(err);
  166. }
  167. }
  168. function getRequestPlainData() {
  169. let data = magicJS.getRequestBody();
  170. let reqData = null;
  171. if (data) {
  172. reqData = magicJS.parseQueryStr(data);
  173. } else {
  174. reqData = magicJS.parseQueryStr($request.url);
  175. }
  176. return reqData;
  177. }
  178. function getQueryPlainData() {
  179. let params = magicJS.parseQueryStr($request.url);
  180. return params;
  181. }
  182. function getXRequestId() {
  183. gTmpRequestSortId++;
  184. return `${gDeviceId}-${gTmpRequsetTimeStamp}-${gTmpRequestSortId}`
  185. }
  186. function handleHeaders() {
  187. if ($request && $request.method != 'OPTIONS') {
  188. let headers = $request.headers;
  189. let x_g_sid = headers['x-g-sid'];
  190. if (x_g_sid) {
  191. magicJS.data.write(PingAnConstKey.x_g_sid, x_g_sid);
  192. }
  193. let x_g_vid = headers['x-g-vid'];
  194. if (x_g_vid) {
  195. magicJS.data.write(PingAnConstKey.x_g_vid, x_g_vid);
  196. }
  197. let x_g_rid = headers['x-g-rid'];
  198. if (x_g_rid) {
  199. magicJS.data.write(PingAnConstKey.x_g_rid, x_g_rid);
  200. }
  201. if (headers['X-REQUEST-ID']) {
  202. let tmpArr = headers['X-REQUEST-ID'].split('-');
  203. magicJS.data.write(PingAnConstKey.DeviceId, tmpArr[0]);
  204. }
  205. let newCookieStr = headers['Cookie'];
  206. if (newCookieStr) {
  207. let oldCookieStr = magicJS.data.read(PingAnConstKey.Cookie, null);
  208. magicJS.logger.info(`oldCookieStr=${oldCookieStr}`);
  209. magicJS.logger.info(`newCookieStr=${newCookieStr}`);
  210. if (compareCookieStr(newCookieStr, oldCookieStr) != 0) {
  211. magicJS.data.write(PingAnConstKey.Cookie, newCookieStr);
  212. magicJS.logger.info(`当前Cookie刷新到最新`);
  213. magicJS.notification.appendNotifyInfo(`🎉当前Cookie刷新到最新`);
  214. } else {
  215. magicJS.data.write(PingAnConstKey.Cookie, newCookieStr);
  216. magicJS.logger.info(`当前Cookie已经是最新无需更新`);
  217. }
  218. }
  219. let userAgent = headers['User-Agent'];
  220. let mRet = userAgent.match(/pageActionId\/([\S.]+)\s*/);
  221. let pageActionId = mRet && mRet[1] ? mRet[1] : "";
  222. if (pageActionId && pageActionId.length > 0) {
  223. magicJS.data.write(PingAnConstKey.PageActionId, pageActionId);
  224. }
  225. }
  226. }
  227. function compareCookieStr(cookieStr1, cookieStr2) {
  228. let cookieDict1 = magicJS.parseCookies(cookieStr1);
  229. let cookieDict2 = magicJS.parseCookies(cookieStr2);
  230. let skipKeys = ['NGWhitelist', 'PAEBANK_PARAM', 'PAEBANK_PARAM_N', 'PAEBANK_PARAM_W', 'WEBTRENDS_SESSIONID', 'brcpSessionTicket', 'sdc_PABankParam', 'shuntid'];
  231. skipKeys = ['PAEBANK_PARAM', 'WEBTRENDS_SESSIONID'];
  232. let retCode = 0;
  233. for (let key in cookieDict1) {
  234. if (!skipKeys.includes(key)) {
  235. if (cookieDict1[key] != void 0 && cookieDict2[key] != void 0 && cookieDict1[key] != cookieDict2[key]) {
  236. magicJS.logger.info(`${key}`);
  237. retCode = -1;
  238. break;
  239. }
  240. }
  241. }
  242. return retCode;
  243. }
  244. function handleHomePage() {
  245. handleHeaders();
  246. }
  247. function handleCreateTokenId() {
  248. }
  249. function handleBatchSatisfy() {
  250. }
  251. function handlePageConfig() {
  252. handleHeaders();
  253. let rspData = getResponsePlainData();
  254. if (!rspData) {
  255. return;
  256. }
  257. if (rspData.responseCode != "000000") {
  258. return;
  259. }
  260. let data = rspData.data;
  261. if (data.reShow) {
  262. }
  263. }
  264. function handlePublicActivityStatus() {
  265. handleHeaders();
  266. let rspData = getResponsePlainData();
  267. if (!rspData) {
  268. return;
  269. }
  270. if (rspData.responseCode != "000000") {
  271. return;
  272. }
  273. let queryParams = getQueryPlainData();
  274. let activityCode = queryParams.activityCode;
  275. let queryNextTime = queryParams.queryNextTime;
  276. let data = rspData.data;
  277. }
  278. function handleCustomerActivityStatus() {
  279. handleHeaders();
  280. let rspData = getResponsePlainData();
  281. if (!rspData) {
  282. return;
  283. }
  284. rspData = { pagination: null, data: null, responseCode: "000000", responseMsg: "成功" };
  285. gRetBody = rspData;
  286. if (rspData.responseCode != "000000") {
  287. return;
  288. }
  289. }
  290. function handleCustomerOffer() {
  291. let rspData = getResponsePlainData();
  292. if (!rspData) {
  293. return;
  294. }
  295. rspData.responseCode = "000000";
  296. gRetBody = rspData;
  297. if (rspData.responseCode != "000000") {
  298. return;
  299. }
  300. }
  301. function handleLoginStatus() {
  302. handleHeaders();
  303. let rspData = getResponsePlainData();
  304. if (!rspData) {
  305. return;
  306. }
  307. if (rspData.responseCode != "000000") {
  308. return;
  309. }
  310. }
  311. function handleH5MonitorUploadInfo() {
  312. let rspData = getResponsePlainData();
  313. if (!rspData) {
  314. return;
  315. }
  316. if (rspData.responseCode != "000000") {
  317. return;
  318. }
  319. let reqData = getRequestPlainData();
  320. if (!reqData || !reqData.uploadInfo) {
  321. return;
  322. }
  323. let uploadInfo = reqData.uploadInfo;
  324. let reqObject = null;
  325. // reqObject = {
  326. // "countType": 32,
  327. // "totalDelay": 464,
  328. // "h5monitor_sdk_version": "1.7.0",
  329. // "performanceTiming": {
  330. // "navigationStart": 1724052379766,
  331. // "unloadEventStart": 0,
  332. // "unloadEventEnd": 0,
  333. // "redirectStart": 0,
  334. // "redirectEnd": 0,
  335. // "fetchStart": 1724052379766,
  336. // "domainLookupStart": 1724052379766,
  337. // "domainLookupEnd": 1724052379766,
  338. // "connectStart": 1724052379766,
  339. // "connectEnd": 1724052379766,
  340. // "secureConnectionStart": 0,
  341. // "requestStart": 1724052379766,
  342. // "responseStart": 1724052379766,
  343. // "responseEnd": 1724052379766,
  344. // "domLoading": 1724052380035,
  345. // "domInteractive": 1724052380184,
  346. // "domContentLoadedEventStart": 1724052380184,
  347. // "domContentLoadedEventEnd": 1724052380189,
  348. // "domComplete": 1724052380230,
  349. // "loadEventStart": 1724052380230,
  350. // "loadEventEnd": 1724052380230
  351. // },
  352. // "navigation": {
  353. // "type": 0,
  354. // "redirectCount": 0
  355. // },
  356. // "ttfb": 0,
  357. // "domReady": 418,
  358. // "qs": "?traceid=fixed_innerid_KDAPP-96SS-HDY-1&innerid=KDAPP-96SS-HDY-1",
  359. // "firstScreen": 418,
  360. // "routelabel": 0,
  361. // "firstSource": "api",
  362. // "dt": 1724052381231,
  363. // "fbextension": "",
  364. // "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",
  365. // "webtrendsid": "AUUID_918d439ffcef935c2fd84d3a3e593b6523c916fc",
  366. // "appversion": "6.23.0",
  367. // "platform": "ios",
  368. // "pageID": "PK084123",
  369. // "h5_app_id": "A208848050024B1584C78C904A4900E4",
  370. // "pagetitle": "宜家礼品卡88折起",
  371. // "ymd": "2024-08-19 15:26:21",
  372. // "page": "https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html",
  373. // "requestId": "6ugxCquxgrG49lDeOVXSqw61OT00123s"
  374. // };
  375. try {
  376. reqObject = JSON.parse(decodeURIComponent(uploadInfo));
  377. } catch (error) {
  378. }
  379. }
  380. async function getPageData() {
  381. let url = `https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/pageData.js?v=${new Date().getTime()}`;
  382. let body = ``;
  383. let headers = {
  384. 'Cookie': magicJS.data.read(PingAnConstKey.Cookie, ''),
  385. 'Sec-Fetch-Mode': `navigate`,
  386. 'Connection': `keep-alive`,
  387. 'Accept': `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`,
  388. 'Accept-Encoding': `gzip, deflate, br`,
  389. 'Host': `b.pingan.com.cn`,
  390. 'User-Agent': `${gAppUserAgent}`,
  391. 'Sec-Fetch-Site': `none`,
  392. 'Accept-Language': `zh-CN,zh-Hans;q=0.9`,
  393. 'Sec-Fetch-Dest': `document`,
  394. // 'If-Modified-Since': `Thu, 18 Jul 2024 11:10:01 GMT`
  395. };;
  396. let options = {
  397. url: url,
  398. headers: headers,
  399. body: body,
  400. };
  401. let result = await magicJS.http.get(options).then(response => {
  402. try {
  403. const body = response.body;
  404. let rspData = null;
  405. let retMatch = body.match(/var pageData = ([\s\S]*)/); // 正则表达式匹配
  406. if (retMatch) {
  407. rspData = JSON.parse(retMatch[1]);
  408. }
  409. // magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`);
  410. return rspData;
  411. } catch (e) {
  412. magicJS.logger.error(e);
  413. }
  414. }).catch(err => {
  415. const msg = `请求页面配置数据异常\n${JSON.stringify(err)}`;
  416. magicJS.logger.error(msg);
  417. });
  418. return result;
  419. }
  420. async function checkGetPageData() {
  421. let strToday = magicJS.formatDate(new Date(), 'yyyy-MM-dd');
  422. let key = `${PingAnConstKey.PageData}`;
  423. let cacheData = magicJS.data.read(key, null);
  424. if (cacheData && cacheData.storeDate == strToday) {
  425. magicJS.logger.info(`今日已更新过活动页面数据`);
  426. gPageData = cacheData.data;
  427. } else {
  428. magicJS.logger.info(`今日首次更新活动页面数据`);
  429. gPageData = await getPageData();
  430. magicJS.data.write(key, { storeDate: strToday, data: gPageData });
  431. }
  432. if (gPageData) {
  433. let buildTime = gPageData.buildTime;
  434. magicJS.logger.info(`当前活动页面数据最新构建时间:${magicJS.formatDate(new Date(buildTime), 'yyyy-MM-dd')}`);
  435. }
  436. return gPageData;
  437. }
  438. async function getClientTag() {
  439. if (!gPageData) {
  440. gPageData = await checkGetPageData();
  441. }
  442. if (!gPageData) {
  443. return;
  444. }
  445. let clientTag = '';
  446. let widgets = gPageData.widgets;
  447. for (let i = 0; i < widgets.length; i++) {
  448. const widget = widgets[i];
  449. if (widget.label.indexOf('简易规则') > -1) {
  450. clientTag = widget.config.clientTag;
  451. }
  452. }
  453. return clientTag;
  454. }
  455. function getResponseErrorMsg(errCode, config, responseMsg) {
  456. let key = errCodeStrMap[errCode];
  457. if (key && config && config[key]) {
  458. return config[key].toastText || responseMsg;
  459. } else {
  460. return responseMsg;
  461. }
  462. }
  463. function setActCouponStatus(activityCode, status) {
  464. let day = magicJS.formatDate(new Date(), 'yyyy-MM-dd');
  465. let key = `PingAnIKEA#${activityCode}_${day}`;
  466. magicJS.data.write(key, status);
  467. if (status == 1 || status == 2) {// 已领取
  468. key = `PingAnIKEA#${activityCode}_CouponGotTime}`;
  469. magicJS.data.write(key, new Date().getTime());
  470. }
  471. }
  472. function getActCouponStatus(activityCode) {
  473. let day = magicJS.formatDate(new Date(), 'yyyy-MM-dd');
  474. let key = `PingAnIKEA#${activityCode}_${day}`;
  475. let status = magicJS.data.read(key, -1);
  476. return Number(status);
  477. }
  478. // 今日是否执行过获取优惠券任务
  479. function isCouponExecToday(activityCode) {
  480. if (gIgnoreCouponGotStatus) {
  481. return false;
  482. }
  483. let status = getActCouponStatus(activityCode);
  484. if (status == 1 || status == 2 || status == 3) {
  485. return true;
  486. } else if (status == -1) {
  487. return false;
  488. } else {
  489. return false;
  490. }
  491. }
  492. // 当月是否领取过优惠券
  493. function hasCouponGotMonth(activityCode) {
  494. if (gIgnoreCouponGotStatus) {
  495. return false;
  496. }
  497. let key = `PingAnIKEA#${activityCode}_CouponGotTime}`;
  498. let strNum = magicJS.data.read(key, null);
  499. if (strNum) {
  500. let now = new Date();
  501. let date = new Date(Number(strNum));
  502. if (now.getFullYear() == date.getFullYear() && now.getMonth() == date.getMonth()) {
  503. return true;
  504. }
  505. return false;
  506. }
  507. return false;
  508. }
  509. function hasCouponGotWeek(activityCode) {
  510. if (gIgnoreCouponGotStatus) {
  511. return false;
  512. }
  513. let key = `PingAnIKEA#${activityCode}_CouponGotTime}`;
  514. let strNum = magicJS.data.read(key, null);
  515. if (strNum) {
  516. let now = new Date();
  517. let date = new Date(Number(strNum));
  518. if (isSameWeek(now, date)) {
  519. return true;
  520. }
  521. return false;
  522. }
  523. return false;
  524. }
  525. function hasCouponGotDay(activityCode) {
  526. if (gIgnoreCouponGotStatus) {
  527. return false;
  528. }
  529. let key = `PingAnIKEA#${activityCode}_CouponGotTime}`;
  530. let strNum = magicJS.data.read(key, null);
  531. if (strNum) {
  532. let now = new Date();
  533. let date = new Date(Number(strNum));
  534. if (now.getFullYear() == date.getFullYear() && now.getMonth() == date.getMonth() && now.getDate() == date.getDate()) {
  535. return true;
  536. }
  537. return false;
  538. }
  539. return false;
  540. }
  541. function isSameWeek(date1, date2) {
  542. // 获取每个日期的星期几
  543. const day1 = date1.getDay(); // 返回值为 0(周日)到 6(周六)
  544. const day2 = date2.getDay();
  545. // 获取每个日期的时间戳
  546. const time1 = date1.getTime();
  547. const time2 = date2.getTime();
  548. // 根据星期几和时间戳判断是否属于同一个星期
  549. const weekDiff = Math.floor(Math.abs(time1 - time2) / (1000 * 60 * 60 * 24 * 7));
  550. if (day1 <= day2) {
  551. return weekDiff === 0;
  552. } else {
  553. return weekDiff === 1;
  554. }
  555. }
  556. function updateHeaders() {
  557. gCommonHeaders[`Cookie`] = magicJS.data.read(PingAnConstKey.Cookie, '');
  558. let x_g_sid = magicJS.data.read(PingAnConstKey.x_g_sid, null);
  559. if (x_g_sid) {
  560. gCommonHeaders[`x-g-sid`] = x_g_sid;
  561. }
  562. let x_g_vid = magicJS.data.read(PingAnConstKey.x_g_vid, null);
  563. if (x_g_vid) {
  564. gCommonHeaders['x-g-vid'] = x_g_vid;
  565. }
  566. let x_g_rid = magicJS.data.read(PingAnConstKey.x_g_rid, null);
  567. if (x_g_rid) {
  568. gCommonHeaders['x-g-rid'] = x_g_rid;
  569. }
  570. }
  571. async function tryGrabCoupon() {
  572. gPageData = await checkGetPageData();
  573. let widgets = gPageData.widgets;
  574. let sk88Names = ['【天天88】满100减12优惠券'];
  575. // 天天88
  576. let path88 = ['pwm-kuaizhan-section', 'pwm-mkt-offer'];
  577. // 五折限量购
  578. let sk55Names = ['【五折限量购】满100减50优惠券'];
  579. let path55 = ['pwm-kuaizhan-simple-rule', 'pwm-kuaizhan-section', 'pwm-mkt-offer'];
  580. // 9.25折限量购
  581. let sk925Names = [
  582. '【9.25折限量折扣】满100减7.5优惠券',
  583. '【9.25折限量折扣】满100减15优惠券',
  584. '【9.25折限量折扣】满100减37.5优惠券',
  585. '【9.25折限量折扣】满1000减75优惠券',
  586. ];
  587. let path925 = ['pwm-kuaizhan-section-split', 'pwm-kuaizhan-section', 'pwm-mkt-offer'];
  588. let items925 = seekWidgets(widgets, path925);
  589. let isLogin = true;
  590. let strLoginFailMsg = `登录失败,请点击通知栏打开APP下载页面`;
  591. magicJS.logger.info(`########9.25折限量购########`);
  592. for (let i = items925.length - 1; i >= 0; i--) {
  593. const item = items925[i];
  594. const config = item.config;
  595. if (isCouponExecToday(config.activityCode)) {
  596. magicJS.logger.info(`${sk925Names[i]}今天已经执行过了[${config.activityCode}]`);
  597. continue;
  598. }
  599. if (hasCouponGotMonth(config.activityCode)) {
  600. magicJS.logger.info(`${sk925Names[i]}本月已经领过了[${config.activityCode}]`);
  601. continue;
  602. }
  603. // magicJS.logger.info(`activityCode=${config.activityCode} activityValue=${config.activityValue}`);
  604. let ret = await doGrabCoupon(config.activityCode, config.activityValue);
  605. let tipsText = ``;
  606. if (ret) {
  607. if (ret.responseCode == '900100') {//未登录
  608. isLogin = false;
  609. strLoginFailMsg = ret.responseMsg;
  610. // magicJS.notification.appendNotifyInfo(ret.responseMsg);
  611. break;
  612. }
  613. if (ret.data) {
  614. let activityData = ret.data.activityData;
  615. if (activityData) {
  616. sk925Names[i] = activityData.activityName;
  617. }
  618. }
  619. if (ret.responseCode == '000000') {
  620. setActCouponStatus(config.activityCode, 1);
  621. } else if (ret.responseCode == '950008' || ret.responseCode == '900745' || ret.responseCode == '950009') {//领奖机会已经用完
  622. setActCouponStatus(config.activityCode, 2);
  623. } else if (ret.responseCode == '960002') {//今天奖励已经发完
  624. setActCouponStatus(config.activityCode, 3);
  625. } else if (ret.responseCode == '900130') {//不符合领取规则
  626. setActCouponStatus(config.activityCode, 3);
  627. }
  628. if (ret.responseCode == '000000') {
  629. tipsText = `${sk925Names[i]}-领取成功`;
  630. } else {
  631. tipsText = sk925Names[i] + '-' + getResponseErrorMsg(ret.responseCode, config, ret.responseMsg)
  632. }
  633. } else {
  634. tipsText = `${sk925Names[i]}-领取失败`;
  635. }
  636. magicJS.notification.appendNotifyInfo(tipsText);
  637. }
  638. if (!isLogin) {
  639. let params = {
  640. "td": {
  641. "id": "唤醒浮层",
  642. "label": "APP下载浮层立即打开-样式2",
  643. "param": { "dlink_id": "M0P5EnN0addUoXCs240814104407" },
  644. "pageId": gPageId
  645. },
  646. "url": "https://b.pingan.com.cn/kuaizhan/v2/5K2422/20230925/k84123/index.html? paesuperbank=%7B%22dLinkId%22%3A%22M0P5EnN0addUoXCs240814104407%22%7D"
  647. };
  648. let schemaUrl = `paesuperbank://?paesuperbank=${encodeURIComponent(JSON.stringify(params))}`;
  649. magicJS.notification.post(scriptName, '', strLoginFailMsg, schemaUrl);
  650. return;
  651. }
  652. magicJS.logger.info(`##########天天88##########`);
  653. let items88 = seekWidgets(widgets, path88);
  654. for (let i = 0; i < items88.length; i++) {
  655. const item = items88[i];
  656. const config = item.config;
  657. if (isCouponExecToday(config.activityCode)) {
  658. magicJS.logger.info(`${sk88Names[i]}今天已经执行过了[${config.activityCode}]`);
  659. continue;
  660. }
  661. if (hasCouponGotMonth(config.activityCode)) {
  662. magicJS.logger.info(`${sk88Names[i]}本月已经领过了[${config.activityCode}]`);
  663. continue;
  664. }
  665. // magicJS.logger.info(`activityCode=${config.activityCode} activityValue=${config.activityValue}`);
  666. let ret = await doGrabCoupon(config.activityCode, config.activityValue);
  667. let tipsText = ``;
  668. if (ret) {
  669. if (ret.responseCode == '900100') {//未登录
  670. magicJS.notification.appendNotifyInfo(ret.responseMsg);
  671. break;
  672. }
  673. if (ret.data) {
  674. let activityData = ret.data.activityData;
  675. if (activityData) {
  676. sk88Names[i] = activityData.activityName;
  677. }
  678. }
  679. if (ret.responseCode == '000000') {
  680. setActCouponStatus(config.activityCode, 1);
  681. } else if (ret.responseCode == '950008' || ret.responseCode == '900745' || ret.responseCode == '950009') {//领奖机会已经用完
  682. setActCouponStatus(config.activityCode, 2);
  683. } else if (ret.responseCode == '960002') {//今天奖励已经发完
  684. setActCouponStatus(config.activityCode, 3);
  685. } else if (ret.responseCode == '900130') {//不符合领取规则
  686. setActCouponStatus(config.activityCode, 3);
  687. }
  688. if (ret.responseCode == '000000') {
  689. tipsText = `${sk88Names[i]}-领取成功`;
  690. } else {
  691. tipsText = sk88Names[i] + '-' + getResponseErrorMsg(ret.responseCode, config, ret.responseMsg)
  692. }
  693. } else {
  694. tipsText = `${sk88Names[i]}-领取失败`;
  695. }
  696. magicJS.notification.appendNotifyInfo(tipsText);
  697. }
  698. magicJS.logger.info(`########五折限量购########`);
  699. let items55 = seekWidgets(widgets, path55);
  700. for (let i = 0; i < items55.length; i++) {
  701. const item = items55[i];
  702. const config = item.config;
  703. if (isCouponExecToday(config.activityCode)) {
  704. magicJS.logger.info(`${sk55Names[i]}今天已经执行过了[${config.activityCode}]`);
  705. continue;
  706. }
  707. if (hasCouponGotMonth(config.activityCode)) {
  708. magicJS.logger.info(`${sk55Names[i]}本月已经领过了[${config.activityCode}]`);
  709. continue;
  710. }
  711. // magicJS.logger.info(`activityCode=${config.activityCode} activityValue=${config.activityValue}`);
  712. let ret = await doGrabCoupon(config.activityCode, config.activityValue);
  713. let tipsText = ``;
  714. if (ret) {
  715. if (ret.responseCode == '900100') {//未登录
  716. magicJS.notification.appendNotifyInfo(ret.responseMsg);
  717. break;
  718. }
  719. if (ret.data) {
  720. let activityData = ret.data.activityData;
  721. if (activityData) {
  722. sk55Names[i] = activityData.activityName;
  723. }
  724. }
  725. if (ret.responseCode == '000000') {
  726. setActCouponStatus(config.activityCode, 1);
  727. } else if (ret.responseCode == '950008' || ret.responseCode == '900745' || ret.responseCode == '950009') {//领奖机会已经用完
  728. setActCouponStatus(config.activityCode, 2);
  729. } else if (ret.responseCode == '960002') {//今天奖励已经发完
  730. setActCouponStatus(config.activityCode, 3);
  731. } else if (ret.responseCode == '900130') {//不符合领取规则
  732. setActCouponStatus(config.activityCode, 3);
  733. }
  734. if (ret.responseCode == '000000') {
  735. tipsText = `${sk55Names[i]}-领取成功`;
  736. } else {
  737. tipsText = sk55Names[i] + '-' + getResponseErrorMsg(ret.responseCode, config, ret.responseMsg)
  738. }
  739. } else {
  740. tipsText = `${sk55Names[i]}-领取失败`;
  741. }
  742. magicJS.notification.appendNotifyInfo(tipsText);
  743. }
  744. }
  745. function seekWidgets(widgets, namePaths, layer = 0) {
  746. let retLst = [];
  747. let name = namePaths[layer];
  748. if (namePaths.length == layer + 1) {
  749. for (let i = 0; i < widgets.length; i++) {
  750. const widget = widgets[i];
  751. if (widget.name == name) {
  752. retLst.push(widget);
  753. }
  754. }
  755. } else {
  756. for (let i = 0; i < widgets.length; i++) {
  757. const widget = widgets[i];
  758. if (widget.name == name) {
  759. retLst = retLst.concat(seekWidgets(widget.widgets, namePaths, layer + 1));
  760. }
  761. }
  762. }
  763. return retLst;
  764. }
  765. async function doGrabCoupon(activityCode, activityValue) {
  766. let result = await queryCustomerActivityStatus(activityCode, activityValue);
  767. if (result && gIgnoreActivityStatus) {
  768. result.responseCode = '000000';
  769. }
  770. if (result && result.responseCode == '000000') {
  771. result = await sendCustomerOffer(activityCode, activityValue);
  772. }
  773. return result;
  774. }
  775. async function queryCustomerActivityStatus(activityCode, activityValue, channelSource = 'KOUDAI', taskProVal = '') {
  776. let reqData = {
  777. activityCode: activityCode,
  778. activityValue: activityValue,
  779. channelSource: channelSource,
  780. taskProVal: taskProVal || '',
  781. };
  782. let url = `https://rsb.pingan.com.cn/brop/mop/cust/mopsf/uc/auth/lottery/queryCustomerActivityStatus?${magicJS.objToQueryStr(reqData)}`;
  783. let headers = gCommonHeaders;
  784. let options = {
  785. url: url,
  786. headers: headers,
  787. body: ``,
  788. };
  789. let result = await magicJS.http.get(options).then(response => {
  790. try {
  791. let rspData = response.body;
  792. magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`);
  793. return rspData;
  794. } catch (e) {
  795. magicJS.logger.error(e);
  796. }
  797. }).catch(err => {
  798. const msg = `请求用户活动状态异常\n${JSON.stringify(err)}`;
  799. magicJS.logger.error(msg);
  800. });
  801. return result;
  802. }
  803. async function sendCustomerOffer(activityCode, activityValue, channelSource = 'KOUDAI', taskProVal = '') {
  804. let url = `https://rsb.pingan.com.cn/brop/mop/cust/mopsf/uc/auth/lottery/sendCustomerOffer`;
  805. let info = {
  806. MGM: {
  807. activity_flowid: undefined,
  808. activity_id: undefined,
  809. },
  810. N: {
  811. campaignid: undefined,
  812. channel_source: undefined,
  813. source: 'all',
  814. innerid: 'KDAPP-96SS-HDY-1',
  815. outersource: undefined,
  816. },
  817. W: {
  818. outerid: undefined,
  819. },
  820. };
  821. let orderNo = '';
  822. let traceid = 'fixed_innerid_KDAPP-96SS-HDY-1';
  823. let offerAppid = '';
  824. let buryData = {
  825. "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}`,
  826. "idfa": "00000000-0000-0000-0000-000000000000",
  827. "osVersion": "16.6.1",
  828. "memoryStatus": { "totalMemory": 5644, "usedMemory": 3700 + Math.ceil(160 * Math.random()) },
  829. "language": "zh-Hans-CN",
  830. "deviceId": gDeviceId,
  831. "deviceType": "1",
  832. "sourceIP": "10.4.175.51",
  833. "deviceName": "iPhone",
  834. "vpn": "1",
  835. "isJailBroken": false,
  836. "deviceToken": "524be0e96038a72223cfe66c8c9044c65227c9c818225a28159100bbd9729ba4",
  837. "wifiMac": "Not Found",
  838. "appVersion": "6.23.0",
  839. "wifiSid": "Not Found",
  840. "appName": "平安口袋银行App",
  841. "idfv": "07A9900D-FBD5-4EB4-B16D-830E090913CF",
  842. "deviceModel": "iphone 14 pro",
  843. "aldDeviceId": "8A093177-C77E-49B6-B096-63F736D4B9F5",
  844. "osName": "iOS",
  845. "sourceIPType": "04",
  846. "subContracting": "AppStore"
  847. };
  848. let modifyNoVpn = true;
  849. if (modifyNoVpn) {
  850. buryData.vpn = '0';
  851. buryData.sourceIP = '14.145.199.18';
  852. }
  853. let reqData = {
  854. activityCode: activityCode,
  855. activityValue: activityValue,
  856. activityFlowId: String(info.MGM.activity_flowid),
  857. activityId: String(info.MGM.activity_id),
  858. buryData: encodeURIComponent(JSON.stringify(buryData)),
  859. campaignId: String(info.N.campaignid),
  860. channelsource: String(info.N.channel_source),
  861. channelSource: channelSource,
  862. drawTimesQueryFLag: "1",
  863. innerid: info.N.innerid,
  864. orderNo: orderNo,
  865. outerid: String(info.W.outerid),
  866. outersource: String(info.N.outersource),
  867. source: info.N.source,
  868. taskProVal: taskProVal,
  869. offerAppid: offerAppid,
  870. traceId: traceid
  871. }
  872. let headers = gCommonHeaders;
  873. let options = {
  874. url: url,
  875. headers: headers,
  876. body: magicJS.objToQueryStr(reqData),
  877. };
  878. let result = await magicJS.http.post(options).then(response => {
  879. try {
  880. let rspData = response.body;
  881. magicJS.logger.info(`rspData=${JSON.stringify(rspData)}`);
  882. return rspData;
  883. } catch (e) {
  884. magicJS.logger.error(e);
  885. }
  886. }).catch(err => {
  887. const msg = `请求用户报单异常\n${JSON.stringify(err)}`;
  888. magicJS.logger.error(msg);
  889. });
  890. return result;
  891. }
  892. Main().catch((e) => magicJS.logger.log(`-\n ${e}`)).finally(() => magicJS.done());
  893. //---SyncByPyScript---MagicJS3-start
  894. 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 } 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, g) { var e; let p; d.isNode && (e = require("axios"), p = e.create()); class t { constructor(e = !0) { this.handlers = [], this.isRequest = e } use(e, t, n) { return "function" == typeof e && g.debug("Register fulfilled " + e.name), "function" == typeof t && g.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, g.debug("Params to QueryString: " + n.url)), n } const y = (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 h = (e, t = null) => { if (e && 400 <= e.status) return g.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), g.debug(`HTTP ${e.method.toUpperCase()}:` + "\n" + JSON.stringify(e)), e } function E(t) { try { t = t && y(t), g.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 = h(t); return e ? Promise.reject(e) : t } catch (e) { return g.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), g.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 ? p : 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: y(t) }, o(e)) : (t.config = i, t.body = n, r(t)) }) }) : r => new Promise((n, t) => { $task.fetch(r).then(e => { e = y(e, r); var t = h(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 ? y(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) { g.error(`Failed to register interceptors: ${e}.`) } var i = [N, void 0], s = [E, void 0]; if (S) { for (g.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 && g.debug("Executing request fulfilled " + a.name), n = a(n) } catch (e) { "function" == typeof l && g.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 } { g.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) && g.debug("Executing request fulfilled " + e.name), "function" == typeof u && g.debug("Executing request rejected " + u.name), o = o.then(e, u) } catch (e) { g.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) { g.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: y, 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, g) { let p = { fs: void 0, data: {} }; if (d.isNode) { p.fs = require("fs"); try { p.fs.accessSync("./magic.json", p.fs.constants.R_OK | p.fs.constants.W_OK) } catch (e) { p.fs.writeFileSync("./magic.json", "{}", { encoding: "utf8" }) } p.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 || p.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)), g.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 || p.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)), g.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 { p.fs.writeFileSync("./magic.json", o) } catch (e) { return g.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 || p.data, s = f(s), i ? (delete (obj = f(s[o]))[i], s[o] = obj) : delete s[o], s), n ? n = r : p.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; g.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, g.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), g.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 && g(e, t, n) } function g(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: g, 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", g = 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 g.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 g.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 p(e) { let t = []; return await g.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 g.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 g.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 y(e, t = "", n = "") { let r = !1; return await g.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 g.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), g.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 }), g.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 }), g.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 }), g.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), g.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 g.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 p([{ name: t, value: n }]); if (e && 1 === e.length) return e[0] } else await g.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: p, 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 g.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 g.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 g.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 g.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: y, delScript: async function (e, t = "") { let n = !1; return await g.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 y(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 y(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 y(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), y(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), y(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), y(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) } } }
  895. //---SyncByPyScript---MagicJS3-end