imaotaiHelper.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. /******************************
  2. > i茅台
  3. *******************************
  4. [rewrite_local]
  5. ^http[s]?:\/\/app.moutai519.com.cn url script-request-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/imaotai/imaotaiHelper.js
  6. ^http[s]?:\/\/app.moutai519.com.cn url script-response-body https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/imaotai/imaotaiHelper.js
  7. [MITM]
  8. hostname=app.moutai519.com.cn
  9. ********************************/
  10. const lk = new ToolKit(`i茅台`, `IMaiTaiHelper`);
  11. let G_P_C_MAP = {};
  12. let G_MT_VERSION = '1.5.9'; // MT版本
  13. let G_MT_R = 'clips_OlU6TmFRag5rCXwbNAQ/Tz1SKlN8THcecBp/';
  14. let G_USER_AGENT = 'iOS;16.6.1;Apple;?unrecognized?';
  15. const G_AES_KEY = "qbhajinldepmucsonaaaccgypwuvcjaa";
  16. const G_AES_IV = "2018534749963515";
  17. const iMT_Products = {
  18. "10941": "53%vol 500ml贵州茅台酒(甲辰龙年)",
  19. "10942": "53%vol 375ml×2贵州茅台酒(甲辰龙年)",
  20. "10056": "53%vol 500ml茅台1935",
  21. "2478": "53%vol 500ml贵州茅台酒(珍品)",
  22. };
  23. const iMT_Location = {
  24. "province": "广东省",
  25. "city": "广州市",
  26. "lat": "23.121952",
  27. "lng": "113.392636",
  28. };
  29. const iMT_BuyItemCodes = ["10941", "10942"];
  30. let retBody;
  31. if (!lk.isExecComm) {
  32. if (lk.isRequest()) {
  33. checkHandleRequest();
  34. lk.msg('');
  35. if (retBody) {
  36. lk.done({ body: JSON.stringify(retBody) });
  37. } else {
  38. lk.done();
  39. }
  40. } else {
  41. main();
  42. }
  43. }
  44. async function main() {
  45. let userData = getUserData();
  46. if (lk.isEmpty(userData.userId) || lk.isEmpty(userData.token)) {
  47. lk.msg(`请登录i茅台APP获取用户信息`);
  48. lk.done();
  49. return;
  50. }
  51. G_MT_R = userData.mtR;
  52. G_USER_AGENT = userData.userAgent;
  53. let mapDataRet = await getProvinceCityMapData();
  54. G_P_C_MAP = mapDataRet[0];
  55. let sourceData = mapDataRet[1];
  56. let sessionId = await getSessionId(userData.userId, token, Date.now());
  57. let itemCodes = iMT_BuyItemCodes;
  58. let province = iMT_Location.province;
  59. let city = iMT_Location.city;
  60. let msgItems = [
  61. {
  62. name: '手机号',
  63. value: `${userData.mobile}`,
  64. },
  65. {
  66. name: '省份城市',
  67. value: `${province}${city}`,
  68. },
  69. ];
  70. for(let i=0; i < itemCodes.length;i++){
  71. const itemId = itemCodes[i];
  72. let maxShopId = await getShopItem(sessionId,itemId,userData.token,userData.deviceId,province,city,Date.now());
  73. if(maxShopId == '0'){
  74. continue;
  75. }
  76. let retMsg = await mtAdd(sessionId,itemId,maxShopId,userData.userId,userData.token,userData.deviceId);
  77. if (retMsg) {
  78. msgItems.push({
  79. name: '申购结果',
  80. value: retMsg,
  81. });
  82. } else {
  83. msgItems.push({
  84. name: '申购结果',
  85. value: '申购异常',
  86. });
  87. }
  88. }
  89. let msg = '';
  90. for(let i=0; i < msgItems.length; i++){
  91. msg += `${msgItems[i].name}:${msgItems[i].value}\n`;
  92. }
  93. lk.msg(msg);
  94. lk.done();
  95. }
  96. function checkHandleRequest() {
  97. const url = $request.url;
  98. const path = $request.path;
  99. lk.log(`请求url=${url}#${$request.method}`);
  100. lk.log(`请求body=${lk.getRequestBody()}`);
  101. if ($request && $request.method != 'OPTIONS') {
  102. if (path.match(/\/xhr\/front\/user\/register\/login/)) {
  103. handleLogin();
  104. } else if (path.match(/\/xhr\/front\/user\/info/)) {
  105. handleUserInfo();
  106. }
  107. }
  108. }
  109. function handleLogin() {
  110. let rspBody = lk.getResponseBody();
  111. if (!rspBody) {
  112. return;
  113. }
  114. let rspParams = JSON.parse(rspBody);
  115. if (rspParams.code != 2000) {
  116. return;
  117. }
  118. let rspData = rspParams.data;
  119. let userId = rspData.userId;
  120. let userName = rspData.userName;
  121. let idCode = rspData.idCode;
  122. let mobile = rspData.mobile;
  123. let mtToken = rspData.token;
  124. let userAgent = headers['user-agent'];
  125. let mtDeviceId = headers['mt-device-id'];
  126. let mtR = headers['mt-r'];
  127. let userTag = headers['mt-user-tag'];
  128. lk.setVal('lkMTUserId', userId);
  129. lk.setVal('lkMTUserName', userName);
  130. lk.setVal('lkMTIdCode', idCode);
  131. lk.setVal('lkMTMobile', mobile);
  132. lk.setVal('lkMTToken', mtToken);
  133. lk.setVal('lkMTUserAgent', userAgent);
  134. lk.setVal('lkMTDeviceId', mtDeviceId);
  135. lk.setVal('lkMT-R', mtR);
  136. lk.setVal('lkMTUserTag', userTag);
  137. let jwtData = lk.parseJwt(mtToken);
  138. if (jwtData) {
  139. let payload = jwtData.payload;
  140. let expDate = new Date(payload.exp * 1000);
  141. let expTimeStr = lk.formatDate(expDate, 'yyyy-MM-dd HH:mm:ss');
  142. k.setVal('lkMTTokenExpireTime', expTimeStr);
  143. }
  144. }
  145. function handleUserInfo() {
  146. let rspBody = lk.getResponseBody();
  147. if (!rspBody) {
  148. return;
  149. }
  150. let rspParams = JSON.parse(rspBody);
  151. if (rspParams.code != 2000) {
  152. return;
  153. }
  154. let rspData = rspParams.data;
  155. let userId = rspData.userId;
  156. let userName = rspData.userName;
  157. let idCode = rspData.idCode;
  158. let mobile = rspData.mobile;
  159. let headers = $request.headers;
  160. let mtToken = headers['mt-token'];
  161. let userAgent = headers['user-agent'];
  162. let mtDeviceId = headers['mt-device-id'];
  163. let mtR = headers['mt-r'];
  164. let userTag = headers['mt-user-tag'];
  165. let cookie = headers['cookie'];
  166. lk.setVal('lkMTUserId', userId);
  167. lk.setVal('lkMTUserName', userName);
  168. lk.setVal('lkMTIdCode', idCode);
  169. lk.setVal('lkMTMobile', mobile);
  170. lk.setVal('lkMTToken', mtToken);
  171. lk.setVal('lkMTUserAgent', userAgent);
  172. lk.setVal('lkMTDeviceId', mtDeviceId);
  173. lk.setVal('lkMT-R', mtR);
  174. lk.setVal('lkMTUserTag', userTag);
  175. lk.setVal('lkMTCookie', cookie);
  176. let jwtData = lk.parseJwt(mtToken);
  177. if (jwtData) {
  178. let payload = jwtData.payload;
  179. let expDate = new Date(payload.exp * 1000);
  180. let expTimeStr = lk.formatDate(expDate, 'yyyy-MM-dd HH:mm:ss');
  181. k.setVal('lkMTTokenExpireTime', expTimeStr);
  182. }
  183. }
  184. function getUserData() {
  185. let data = {
  186. userId: lk.getVal('lkMTUserId'),
  187. userName: lk.getVal('lkMTUserName'),
  188. idCode: lk.getVal('lkMTIdCode'),
  189. mobile: lk.getVal('lkMTMobile'),
  190. token: lk.getVal('lkMTToken'),
  191. userAgent: lk.getVal('lkMTUserAgent'),
  192. deviceId: lk.getVal('lkMTDeviceId'),
  193. mtR: lk.getVal('lkMT-R'),
  194. userTag: lk.getVal('lkMTUserTag'),
  195. cookie: lk.getVal('lkMTCookie'),
  196. };
  197. return data;
  198. }
  199. async function getMtv(deviceId, mtVersion) {
  200. return new Promise((resolve, _reject) => {
  201. try {
  202. const headers = {};
  203. const body = ``;
  204. const mtK = `${Date.now()}`;
  205. const url = `http://82.157.10.108:8086/get_mtv?DeviceID=${deviceId}&MTk=${mtK}&version=${mtVersion}&key=yaohuo`;
  206. let options = {
  207. url: url,
  208. headers: headers,
  209. body: body
  210. };
  211. lk.get(options, async (error, _response, data) => {
  212. let ret;
  213. try {
  214. if (error) {
  215. lk.execFail();
  216. } else {
  217. ret = data;
  218. }
  219. } catch (e) {
  220. lk.logErr(e);
  221. lk.execFail();
  222. } finally {
  223. resolve(ret);
  224. }
  225. });
  226. } catch (e) {
  227. lk.logErr(e);
  228. resolve();
  229. }
  230. });
  231. }
  232. async function getActParam(data) {
  233. return new Promise((resolve, _reject) => {
  234. try {
  235. const headers = {};
  236. const body = ``;
  237. const mtK = `${Date.now()}`;
  238. const url = `http://82.157.10.108:8086/get_actParam?key=yaohuo&actParam=${encodeURIComponent(JSON.stringify(data).replace(/\s/g, ''))}`;
  239. let options = {
  240. url: url,
  241. headers: headers,
  242. body: body
  243. };
  244. lk.get(options, async (error, _response, data) => {
  245. let ret;
  246. try {
  247. if (error) {
  248. lk.execFail();
  249. } else {
  250. ret = data;
  251. }
  252. } catch (e) {
  253. lk.logErr(e);
  254. lk.execFail();
  255. } finally {
  256. resolve(ret);
  257. }
  258. });
  259. } catch (e) {
  260. lk.logErr(e);
  261. resolve();
  262. }
  263. });
  264. }
  265. async function mtAdd(sessionId, itemId, shopId, userId, token, deviceId) {
  266. const mtK = `${new Date().getTime()}`;
  267. const mtV = await getMtv(deviceId, G_MT_VERSION);
  268. let headers = {
  269. "mt-network-type": "WIFI",
  270. "user-agent": G_USER_AGENT,
  271. "mt-token": token,
  272. "mt-user-tag": "0",
  273. "mt-r": G_MT_R,
  274. "mt-lat": "23.122443",
  275. "mt-k": mtK,
  276. "mt-lng": "113.380126",
  277. "content-length": "257",
  278. "mt-info": "028e7f96f6369cafe1d105579c5b9377",
  279. "mt-team-id": "",
  280. "mt-app-version": G_MT_VERSION,
  281. "mt-request-id": getMTRequestId(),
  282. "accept-language": "zh-Hans-CN;q=1",
  283. "mt-device-id": deviceId,
  284. "accept": "*/*",
  285. "content-type": "application/json",
  286. "accept-encoding": "gzip, deflate, br",
  287. "mt-bundle-id": "com.moutai.mall",
  288. "mt-v": mtV,
  289. };
  290. const d = {
  291. "itemInfoList": [{ "count": 1, "itemId": String(itemId) }],
  292. "sessionId": sessionId,
  293. "userId": String(userId),
  294. "shopId": String(shopId),
  295. };
  296. const actParam = await getActParam(d);
  297. d['actParam'] = actParam;
  298. return new Promise((resolve, _reject) => {
  299. try {
  300. const body = JSON.stringify(d);
  301. const url = `https://app.moutai519.com.cn/xhr/front/mall/reservation/add`;
  302. let options = {
  303. url: url,
  304. headers: headers,
  305. body: body
  306. };
  307. lk.post(options, async (error, _response, data) => {
  308. let ret;
  309. try {
  310. if (error) {
  311. lk.execFail();
  312. } else {
  313. const jsonRetObj = JSON.parse(data);
  314. if (jsonRetObj.code == 2000) {
  315. ret = jsonRetObj.data?.successDesc || "未知";
  316. } else {
  317. ret = '申购失败:' + (data.message || "未知原因");
  318. }
  319. }
  320. } catch (e) {
  321. lk.logErr(e);
  322. lk.execFail();
  323. } finally {
  324. resolve(ret);
  325. }
  326. });
  327. } catch (e) {
  328. lk.logErr(e);
  329. resolve();
  330. }
  331. });
  332. }
  333. async function getSessionId(deviceId, token, timeKeys) {
  334. return new Promise((resolve, _reject) => {
  335. try {
  336. const headers = {
  337. "mt-device-id": deviceId,
  338. "mt-user-tag": "0",
  339. "mt-lat": "23.122443",
  340. "accept": "*/*",
  341. "mt-network-type": "WIFI",
  342. "mt-token": token,
  343. "mt-team-id": "",
  344. "mt-bundle-id": "com.moutai.mall",
  345. "accept-language": "zh-Hans-CN;q=1",
  346. "mt-app-version": G_MT_VERSION,
  347. "user-agent": G_USER_AGENT,
  348. "mt-request-id": getMTRequestId(),
  349. "mt-r": G_MT_R,
  350. "mt-lng": "113.380126",
  351. "accept-encoding": "gzip, deflate, br"
  352. };
  353. const body = '';
  354. const url = `https://static.moutai519.com.cn/mt-backend/xhr/front/mall/index/session/get/${timeKeys}`;
  355. let options = {
  356. url: url,
  357. headers: headers,
  358. body: body
  359. };
  360. lk.get(options, async (error, _response, data) => {
  361. let ret;
  362. try {
  363. if (error) {
  364. lk.execFail();
  365. } else {
  366. const jsonRetObj = JSON.parse(data);
  367. if (jsonRetObj.code == 2000) {
  368. const sessionId = jsonRetObj.data?.sessionId;
  369. const itemList = jsonRetObj.data?.itemList || [];
  370. const itemCodes = itemList.map(item => item.itemCode);
  371. ret = { sessionId: sessionId, itemCodes: itemCodes, itemList: itemList };
  372. }
  373. }
  374. } catch (e) {
  375. lk.logErr(e);
  376. lk.execFail();
  377. } finally {
  378. resolve(ret);
  379. }
  380. });
  381. } catch (e) {
  382. lk.logErr(e);
  383. resolve();
  384. }
  385. });
  386. }
  387. function getMTRequestId() {
  388. return `${new Date().getTime()}${getRandomNumber(11111, 99999)}`;
  389. }
  390. async function getShopItem(sessionId, itemId, token, deviceId, province, city, timeKeys) {
  391. return new Promise((resolve, _reject) => {
  392. try {
  393. const headers = {
  394. "mt-device-id": deviceId,
  395. "mt-user-tag": "0",
  396. "mt-lat": "23.122443",
  397. "accept": "*/*",
  398. "mt-network-type": "WIFI",
  399. "mt-token": token,
  400. "mt-team-id": "",
  401. "mt-bundle-id": "com.moutai.mall",
  402. "accept-language": "zh-Hans-CN;q=1",
  403. "mt-app-version": G_MT_VERSION,
  404. "user-agent": G_USER_AGENT,
  405. "mt-request-id": getMTRequestId(),
  406. "mt-r": G_MT_R,
  407. "mt-lng": "113.380126",
  408. "accept-encoding": "gzip, deflate, br"
  409. };
  410. const body = '';
  411. const url = `https://static.moutai519.com.cn/mt-backend/xhr/front/mall/shop/list/slim/v3/${sessionId}/${province}/${city}/${timeKeys}`;
  412. let options = {
  413. url: url,
  414. headers: headers,
  415. body: body
  416. };
  417. lk.get(options, async (error, _response, data) => {
  418. let ret;
  419. try {
  420. if (error) {
  421. lk.execFail();
  422. } else {
  423. const jsonRetObj = JSON.parse(data);
  424. if (jsonRetObj.code == 2000) {
  425. const rspData = jsonRetObj.data || {};
  426. const shops = rspData.shops || [];
  427. const shopId = G_P_C_MAP[province][city];
  428. for (let i = 0; i < shops.lenght; i++) {
  429. const shopObj = shops[i];
  430. if (shopObj.shopId && shopId.indexOf(shopObj.shopId) > -1) {
  431. ret = shopObj.shopId;
  432. break;
  433. }
  434. }
  435. }
  436. }
  437. } catch (e) {
  438. lk.logErr(e);
  439. lk.execFail();
  440. } finally {
  441. resolve(ret);
  442. }
  443. });
  444. } catch (e) {
  445. lk.logErr(e);
  446. resolve();
  447. }
  448. });
  449. }
  450. async function getUserId(token, deviceId) {
  451. return new Promise((resolve, _reject) => {
  452. try {
  453. const headers = {
  454. "mt-device-id": deviceId,
  455. "mt-user-tag": "0",
  456. "accept": "*/*",
  457. "mt-network-type": "WIFI",
  458. "mt-token": token,
  459. "mt-team-id": "",
  460. "mt-bundle-id": "com.moutai.mall",
  461. "accept-language": "zh-Hans-CN;q=1",
  462. "mt-app-version": G_MT_VERSION,
  463. "user-agent": G_USER_AGENT,
  464. "mt-r": G_MT_R,
  465. "mt-request-id": getMTRequestId(),
  466. "accept-encoding": "gzip, deflate, br"
  467. };
  468. const body = '';
  469. const url = `https://app.moutai519.com.cn/xhr/front/user/info`;
  470. let options = {
  471. url: url,
  472. headers: headers,
  473. body: body
  474. };
  475. lk.get(options, async (error, _response, data) => {
  476. let ret;
  477. try {
  478. if (error) {
  479. lk.execFail();
  480. } else {
  481. const jsonRetObj = JSON.parse(data);
  482. const rspData = jsonRetObj.data || {};
  483. ret = rspData;
  484. }
  485. } catch (e) {
  486. lk.logErr(e);
  487. lk.execFail();
  488. } finally {
  489. resolve(ret);
  490. }
  491. });
  492. } catch (e) {
  493. lk.logErr(e);
  494. resolve();
  495. }
  496. });
  497. }
  498. async function getUserEnergyAward(deviceId, ck) {
  499. return new Promise((resolve, _reject) => {
  500. try {
  501. const cookies = {
  502. 'MT-Device-id-Wap': deviceId,
  503. 'MT-Token-Wap': ck,
  504. 'YX_SUPPORT_WEBP': '1',
  505. };
  506. const headers = {
  507. 'X-Requested-With': 'XMLHttpRequest',
  508. 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_2_1 like Mac OS X)',
  509. 'Client-User-Agent': 'iOS;15.0.1;Apple;iPhone 12 ProMax',
  510. 'MT-Device-id': deviceId,
  511. 'mt-user-tag': '0',
  512. 'Accept': 'application/json, text/javascript, */*; q=0.01',
  513. 'mt-network-type': 'WIFI',
  514. 'mt-bundle-id': 'com.moutai.mall',
  515. 'accept-language': 'zh-Hans-CN;q=1',
  516. 'MT-Request-ID': `${new Date().getTime()}`,
  517. 'MT-APP-Version': G_MT_VERSION,
  518. 'user-agent': 'iPhone 14',
  519. 'MT-R': G_MT_R,
  520. 'mt-lng': lng,
  521. 'mt-lat': lat,
  522. 'Cookie': lk.serializeCookies(cookies),
  523. 'Origin': 'https://h5.moutai519.com.cn',
  524. 'Referer': 'https://h5.moutai519.com.cn/gux/game/main?appConfig=2_1_2',
  525. };
  526. const body = '';
  527. const url = `https://app.moutai519.com.cn/xhr/front/user/info`;
  528. let options = {
  529. url: url,
  530. headers: headers,
  531. body: body
  532. };
  533. lk.get(options, async (error, _response, data) => {
  534. let ret;
  535. try {
  536. if (error) {
  537. lk.execFail();
  538. } else {
  539. const jsonRetObj = JSON.parse(data);
  540. const rspData = jsonRetObj.data || {};
  541. ret = rspData;
  542. }
  543. } catch (e) {
  544. lk.logErr(e);
  545. lk.execFail();
  546. } finally {
  547. resolve(ret);
  548. }
  549. });
  550. } catch (e) {
  551. lk.logErr(e);
  552. resolve();
  553. }
  554. });
  555. }
  556. function getRandomNumber(min, max) {
  557. return Math.floor(Math.random() * (max - min + 1)) + min;
  558. }
  559. async function getProvinceCityMapUrl() {
  560. return new Promise((resolve, _reject) => {
  561. try {
  562. const cookies = {
  563. 'MT-Device-id-Wap': deviceId,
  564. 'MT-Token-Wap': ck,
  565. 'YX_SUPPORT_WEBP': '1',
  566. };
  567. const mSecondsStr = `${new Date().getTime()}`;
  568. const headers = {
  569. 'X-Requested-With': 'XMLHttpRequest',
  570. 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0_1 like Mac OS X)',
  571. 'Referer': 'https://h5.moutai519.com.cn/gux/game/main?appConfig=2_1_2',
  572. 'Client-User-Agent': 'iOS;16.0.1;Apple;iPhone 14 ProMax',
  573. 'MT-R': G_MT_R,
  574. 'Origin': 'https://h5.moutai519.com.cn',
  575. 'MT-APP-Version': G_MT_VERSION,
  576. 'MT-Request-ID': `${mSecondsStr}${getRandomNumber(1111111, 999999999)}${mSecondsStr}`,
  577. 'Accept-Language': 'zh-CN,zh-Hans;q=1',
  578. 'MT-Device-id': `${mSecondsStr}${getRandomNumber(1111111, 999999999)}${mSecondsStr}`,
  579. 'Accept': 'application/json, text/javascript, */*; q=0.01',
  580. 'mt-lng': lng,
  581. 'mt-lat': lat
  582. };
  583. const body = '';
  584. const url = `https://static.moutai519.com.cn/mt-backend/xhr/front/mall/resource/get`;
  585. let options = {
  586. url: url,
  587. headers: headers,
  588. body: body
  589. };
  590. lk.get(options, async (error, _response, data) => {
  591. let ret;
  592. try {
  593. if (error) {
  594. lk.execFail();
  595. } else {
  596. const jsonRetObj = JSON.parse(data);
  597. const rspData = jsonRetObj.data;
  598. ret = rspData?.mtshops_pc?.url;
  599. }
  600. } catch (e) {
  601. lk.logErr(e);
  602. lk.execFail();
  603. } finally {
  604. resolve(ret);
  605. }
  606. });
  607. } catch (e) {
  608. lk.logErr(e);
  609. resolve();
  610. }
  611. });
  612. }
  613. async function getProvinceCityMapData() {
  614. return new Promise((resolve, _reject) => {
  615. try {
  616. let url = await getProvinceCityMapUrl();
  617. const headers = {};
  618. const body = '';
  619. let options = {
  620. url: url,
  621. headers: headers,
  622. body: body
  623. };
  624. lk.get(options, async (error, _response, data) => {
  625. let ret;
  626. try {
  627. if (error) {
  628. lk.execFail();
  629. } else {
  630. let pcMap = {};
  631. const jsonRetObj = JSON.parse(data);
  632. for (let k in jsonRetObj) {
  633. const provinceName = jsonRetObj[k].provinceName;
  634. const cityName = jsonRetObj[k].cityName;
  635. if (!pcMap[provinceName]) {
  636. pcMap[provinceName] = {};
  637. }
  638. if (!pcMap[provinceName][cityName]) {
  639. pcMap[provinceName][cityName] = [k];
  640. } else {
  641. pcMap[provinceName][cityName].push(k);
  642. }
  643. }
  644. ret = [pcMap, jsonRetObj];
  645. }
  646. } catch (e) {
  647. lk.logErr(e);
  648. lk.execFail();
  649. } finally {
  650. resolve(ret);
  651. }
  652. });
  653. } catch (e) {
  654. lk.logErr(e);
  655. resolve();
  656. }
  657. });
  658. }
  659. async function login(phone, vCode, deviceId) {
  660. const mtK = `${new Date().getTime()}`;
  661. const mtV = await getMtv(deviceId, G_MT_VERSION);
  662. const headers = {
  663. 'mt-device-id': deviceId,
  664. 'mt-user-tag': '0',
  665. 'accept': '*/*',
  666. 'mt-network-type': 'WIFI',
  667. 'mt-token': '',
  668. "mt-team-id": "",
  669. 'mt-k': mtK,
  670. 'mt-bundle-id': 'com.moutai.mall',
  671. 'mt-v': mtV,
  672. 'user-agent': 'iOS;16.0.1;Apple;iPhone 14 ProMax',
  673. 'accept-language': 'zh-Hans-CN;q=1',
  674. 'mt-request-id': `${new Date().getTime()}18342`,
  675. 'mt-r': G_MT_R,
  676. 'mt-app-version': G_MT_VERSION,
  677. };
  678. return new Promise((resolve, _reject) => {
  679. try {
  680. const data = {
  681. 'ydToken': '',
  682. 'mobile': phone,
  683. 'vCode': vCode,
  684. 'ydLogId': '',
  685. };
  686. const body = JSON.stringify(data);
  687. const url = `https://app.moutai519.com.cn/xhr/front/user/register/login`;
  688. let options = {
  689. url: url,
  690. headers: headers,
  691. body: body
  692. };
  693. lk.post(options, async (error, _response, data) => {
  694. let ret;
  695. try {
  696. if (error) {
  697. lk.execFail();
  698. } else {
  699. const jsonRetObj = JSON.parse(data);
  700. ret = jsonRetObj.data || {};
  701. }
  702. } catch (e) {
  703. lk.logErr(e);
  704. lk.execFail();
  705. } finally {
  706. resolve(ret);
  707. }
  708. });
  709. } catch (e) {
  710. lk.logErr(e);
  711. resolve();
  712. }
  713. });
  714. }
  715. async function getLoginVCode(mobile, deviceId) {
  716. const headers = {
  717. "content-type": "application/json",
  718. "mt-device-id": deviceId,
  719. "mt-user-tag": "0",
  720. "accept": "*/*",
  721. "mt-network-type": "WIFI",
  722. "mt-token": "",
  723. "mt-team-id": "",
  724. "accept-language": "zh-Hans-CN;q=1",
  725. "bs-dvid": "2Sm2hFjywxztKDX9gqT1T5dL3COGJA-L2cWr5_E8aLjndr7-Sy0gx8JuiwLa6uPC-RPQY1azn6-c8vVloGoZ57g",
  726. "mt-request-id": `${new Date().getTime()}40625`,
  727. "mt-app-version": "1.5.9",
  728. "user-agent": "iOS;16.6.1;Apple;?unrecognized?",
  729. "mt-r": G_MT_R,
  730. "mt-bundle-id": "com.moutai.mall",
  731. "accept-encoding": "gzip, deflate, br"
  732. };
  733. return new Promise((resolve, _reject) => {
  734. try {
  735. let timestamp = `${new Date().getTime()}`;
  736. let md5Str = '2af72f100c356273d46284f6fd1dfc08' + mobile + timestamp;
  737. let CryptoJS = createCryptoJS();
  738. let hash = CryptoJS.MD5(md5Str);
  739. md5Str = hash.toString(CryptoJS.enc.Hex);
  740. const data = {
  741. "md5": md5Str,
  742. "mobile": mobile,
  743. "timestamp": timestamp,
  744. };
  745. const body = JSON.stringify(data);
  746. const url = `https://app.moutai519.com.cn/xhr/front/user/register/vcode`;
  747. let options = {
  748. url: url,
  749. headers: headers,
  750. body: body
  751. };
  752. lk.post(options, async (error, _response, data) => {
  753. let ret;
  754. try {
  755. if (error) {
  756. lk.execFail();
  757. } else {
  758. const jsonRetObj = JSON.parse(data);
  759. if (jsonRetObj.code == 2000) {
  760. ret = true;
  761. } else {
  762. ret = false;
  763. }
  764. }
  765. } catch (e) {
  766. lk.logErr(e);
  767. lk.execFail();
  768. } finally {
  769. resolve(ret);
  770. }
  771. });
  772. } catch (e) {
  773. lk.logErr(e);
  774. resolve();
  775. }
  776. });
  777. }
  778. class Encrypt {
  779. constructor(key, iv) {
  780. this.key = CryptoJS.enc.Utf8.parse(key);
  781. this.iv = CryptoJS.enc.Utf8.parse(iv);
  782. }
  783. // AES加密
  784. aesEncrypt(content) {
  785. let srcs = CryptoJS.enc.Utf8.parse(content);
  786. let encrypted = CryptoJS.AES.encrypt(srcs, this.key, {
  787. iv: this.iv,
  788. mode: CryptoJS.mode.CBC,
  789. padding: CryptoJS.pad.Pkcs7
  790. });
  791. return encrypted.toString(); // 返回的是base64格式的加密字符串
  792. }
  793. // AES解密
  794. aesDecrypt(encrypted) {
  795. let decrypted = CryptoJS.AES.decrypt(encrypted, this.key, {
  796. iv: this.iv,
  797. mode: CryptoJS.mode.CBC,
  798. padding: CryptoJS.pad.Pkcs7
  799. });
  800. return CryptoJS.enc.Utf8.stringify(decrypted).toString(); // 返回Utf8格式的字符串
  801. }
  802. }
  803. //---SyncByPyScript---ToolKit-start
  804. function ToolKit(t,s,e){return new class{constructor(t,s,e){this.tgEscapeCharMapping={"&":"&","#":"#"},this.userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15",this.prefix="lk",this.name=t,this.id=s,this.data=null,this.dataFile=this.getRealPath(""+this.prefix+this.id+".dat"),this.boxJsJsonFile=this.getRealPath(""+this.prefix+this.id+".boxjs.json"),this.options=e,this.isExecComm=!1,this.isEnableLog=this.getVal(this.prefix+"IsEnableLog"+this.id),this.isEnableLog=!!this.isEmpty(this.isEnableLog)||JSON.parse(this.isEnableLog),this.isNotifyOnlyFail=this.getVal(this.prefix+"NotifyOnlyFail"+this.id),this.isNotifyOnlyFail=!this.isEmpty(this.isNotifyOnlyFail)&&JSON.parse(this.isNotifyOnlyFail),this.isEnableTgNotify=this.getVal(this.prefix+"IsEnableTgNotify"+this.id),this.isEnableTgNotify=!this.isEmpty(this.isEnableTgNotify)&&JSON.parse(this.isEnableTgNotify),this.tgNotifyUrl=this.getVal(this.prefix+"TgNotifyUrl"+this.id),this.isEnableTgNotify=this.isEnableTgNotify&&!this.isEmpty(this.tgNotifyUrl),this.costTotalStringKey=this.prefix+"CostTotalString"+this.id,this.costTotalString=this.getVal(this.costTotalStringKey),this.costTotalString=this.isEmpty(this.costTotalString)?"0,0":this.costTotalString.replace('"',""),this.costTotalMs=this.costTotalString.split(",")[0],this.execCount=this.costTotalString.split(",")[1],this.costTotalMs=this.isEmpty(this.costTotalMs)?0:parseInt(this.costTotalMs),this.execCount=this.isEmpty(this.execCount)?0:parseInt(this.execCount),this.logSeparator="\n██",this.now=new Date,this.startTime=this.now.getTime(),this.node=this.isNode()?{request:require("request")}:null,this.execStatus=!0,this.notifyInfo=[],this.log(this.name+", 开始执行!"),this.initCache(),this.checkRecordRequestBody(),this.execComm()}checkRecordRequestBody(){if(this.isRequest()){var s=$request.body;if(s){var e=$request.path;let t=this.id+"#"+e.replace("/","_");t=t.replace("?","#"),this.isQuanX()&&$prefs.setValueForKey(s,t),(this.isLoon()||this.isSurge())&&$persistentStore.write(s,t),this.isNode()&&this.node.fs.writeFileSync(t+".json",s,{flag:"w"},t=>console.log(t))}}}getRequestBody(){var t=$request.path;let s=this.id+"#"+t.replace("/","_");if(s=s.replace("?","#"),this.isSurge()||this.isLoon())return $persistentStore.read(s);if(this.isQuanX())return $prefs.valueForKey(s);if(this.isNode()){t=s+".json";if(!this.node.fs.existsSync(t))return JSON.parse(this.node.fs.readFileSync(t))}}initCache(){var t,s=this.getPersistKey();this.isQuanX()&&(this.cache=JSON.parse($prefs.valueForKey(s)||"{}")),(this.isLoon()||this.isSurge())&&(this.cache=JSON.parse($persistentStore.read(s)||"{}")),this.isNode()&&(this.node.fs.existsSync(t="root.json")||this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:"wx"},t=>console.log(t)),this.root={},this.node.fs.existsSync(t=s+".json")?this.cache=JSON.parse(this.node.fs.readFileSync(s+".json")):(this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:"wx"},t=>console.log(t)),this.cache={}))}getPersistKey(){return this.id+"#privateCache"}persistCache(){var t=this.getPersistKey(),s=JSON.stringify(this.cache,null,2);this.isQuanX()&&$prefs.setValueForKey(s,t),(this.isLoon()||this.isSurge())&&$persistentStore.write(s,t),this.isNode()&&(this.node.fs.writeFileSync(t+".json",s,{flag:"w"},t=>console.log(t)),this.node.fs.writeFileSync("root.json",JSON.stringify(this.root,null,2),{flag:"w"},t=>console.log(t)))}write(t,s){if(this.log("SET "+s),-1!==s.indexOf("#")){if(s=s.substr(1),isSurge||this.isLoon())return $persistentStore.write(t,s);if(this.isQuanX())return $prefs.setValueForKey(t,s);this.isNode()&&(this.root[s]=t)}else this.cache[s]=t;this.persistCache()}read(t){return this.log("READ "+t),-1!==t.indexOf("#")?(t=t.substr(1),this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?this.root[t]:void 0):this.cache[t]}delete(t){if(this.log("DELETE "+t),-1!==t.indexOf("#")){if(t=t.substr(1),this.isSurge()||this.isLoon())return $persistentStore.write(null,t);if(this.isQuanX())return $prefs.removeValueForKey(t);this.isNode()&&delete this.root[t]}else delete this.cache[t];this.persistCache()}getRealPath(t){var s;return this.isNode()?((s=process.argv.slice(1,2)[0].split("/"))[s.length-1]=t,s.join("/")):t}getUrlHost(t){return t.slice(0,t.indexOf("/",8))}getUrlPath(t){var s=t.lastIndexOf("/")===t.length-1?-1:void 0;return t.slice(t.indexOf("/",8),s)}async execComm(){if(this.isNode()){this.comm=process.argv.slice(1);let t=!1;"p"==this.comm[1]&&(this.isExecComm=!0,this.log(`开始执行指令【${this.comm[1]}】=> 发送到手机测试脚本!`),this.isEmpty(this.options)||this.isEmpty(this.options.httpApi)?(this.log("未设置options,使用默认值"),this.isEmpty(this.options)&&(this.options={}),this.options.httpApi="[email protected]:6166"):/.*?@.*?:[0-9]+/.test(this.options.httpApi)||(t=!0,this.log("❌httpApi格式错误!格式:[email protected]:6166"),this.done()),t||this.callApi(this.comm[2]))}}callApi(t){let i=this.comm[0],s=(this.log(`获取【${i}】内容传给手机`),"");this.fs=this.fs||require("fs"),this.path=this.path||require("path");var e=this.path.resolve(i),r=this.path.resolve(process.cwd(),i),o=this.fs.existsSync(e),n=!o&&this.fs.existsSync(r);if(o||n){n=o?e:r;try{s=this.fs.readFileSync(n)}catch(t){s=""}}else s="";o={url:`http://${this.options.httpApi.split("@")[1]}/v1/scripting/evaluate`,headers:{"X-Key":""+this.options.httpApi.split("@")[0]},body:{script_text:""+s,mock_type:"cron",timeout:!this.isEmpty(t)&&5<t?t:5},json:!0};this.post(o,(t,s,e)=>{this.log(`已将脚本【${i}】发给手机!`),this.done()})}getCallerFileNameAndLine(){let s;try{throw Error("")}catch(t){s=t}var t=s.stack.split("\n")[1];return this.path=this.path||require("path"),`[${t.substring(t.lastIndexOf(this.path.sep)+1,t.lastIndexOf(":"))}]`}getFunName(t){t=t.toString();return t=(t=t.substr("function ".length)).substr(0,t.indexOf("("))}boxJsJsonBuilder(s,r){if(this.isNode()){let i="/Users/lowking/Desktop/Scripts/lowking.boxjs.json";if(r&&r.hasOwnProperty("target_boxjs_json_path")&&(i=r.target_boxjs_json_path),this.fs.existsSync(i))if(this.isJsonObject(s)&&this.isJsonObject(r)){this.log("using node");var o=["settings","keys"],n="https://raw.githubusercontent.com/Orz-3";let e={},t="#lk{script_url}";if(r&&r.hasOwnProperty("script_url")&&(t=this.isEmpty(r.script_url)?"#lk{script_url}":r.script_url),e.id=""+this.prefix+this.id,e.name=this.name,e.desc_html=`⚠️使用说明</br>详情【<a href='${t}?raw=true'><font class='red--text'>点我查看</font></a>】`,e.icons=[n+`/mini/master/Alpha/${this.id.toLocaleLowerCase()}.png`,n+`/mini/master/Color/${this.id.toLocaleLowerCase()}.png`],e.keys=[],e.settings=[{id:this.prefix+"IsEnableLog"+this.id,name:"开启/关闭日志",val:!0,type:"boolean",desc:"默认开启"},{id:this.prefix+"NotifyOnlyFail"+this.id,name:"只当执行失败才通知",val:!1,type:"boolean",desc:"默认关闭"},{id:this.prefix+"IsEnableTgNotify"+this.id,name:"开启/关闭Telegram通知",val:!1,type:"boolean",desc:"默认关闭"},{id:this.prefix+"TgNotifyUrl"+this.id,name:"Telegram通知地址",val:"",type:"text",desc:"Tg的通知地址,如:https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="}],e.author="#lk{author}",e.repo="#lk{repo}",e.script=t+"?raw=true",!this.isEmpty(s))for(var h in o){var a=o[h];if(!this.isEmpty(s[a])){if("settings"===a)for(let t=0;t<s[a].length;t++){var l=s[a][t];for(let t=0;t<e.settings.length;t++){var p=e.settings[t];l.id===p.id&&e.settings.splice(t,1)}}e[a]=e[a].concat(s[a])}delete s[a]}if(Object.assign(e,s),this.isNode()){this.fs=this.fs||require("fs"),this.path=this.path||require("path");var n=this.path.resolve(this.boxJsJsonFile),c=this.path.resolve(process.cwd(),this.boxJsJsonFile),u=this.fs.existsSync(n),d=!u&&this.fs.existsSync(c),f=JSON.stringify(e,null,"\t"),u=(!u&&d?this.fs.writeFileSync(c,f):this.fs.writeFileSync(n,f),JSON.parse(this.fs.readFileSync(i)));if(u.hasOwnProperty("apps")&&Array.isArray(u.apps)&&0<u.apps.length){d=u.apps,c=d.indexOf(d.filter(t=>t.id==e.id)[0]);0<=c?u.apps[c]=e:u.apps.push(e);let s=JSON.stringify(u,null,2);if(!this.isEmpty(r))for(const m in r){let t="";r.hasOwnProperty(m)?t=r[m]:"author"===m?t="@lowking":"repo"===m&&(t="https://github.com/lowking/Scripts"),s=s.replace(`#lk{${m}}`,t)}for(var g,y=/(?:#lk\{)(.+?)(?=\})/,S=(null!==y.exec(s)&&this.log("生成BoxJs还有未配置的参数,请参考https://github.com/lowking/Scripts/blob/master/util/example/ToolKitDemo.js#L17-L18传入参数:\n"),new Set);null!==(g=y.exec(s));)S.add(g[1]),s=s.replace(`#lk{${g[1]}}`,"");S.forEach(t=>{console.log(t+" ")}),this.fs.writeFileSync(i,s)}}}else this.log("构建BoxJsJson传入参数格式错误,请传入json对象")}}isJsonObject(t){return"object"==typeof t&&"[object object]"==Object.prototype.toString.call(t).toLowerCase()&&!t.length}appendNotifyInfo(t,s){1==s?this.notifyInfo=t:this.notifyInfo.push(t)}prependNotifyInfo(t){this.notifyInfo.splice(0,0,t)}execFail(){this.execStatus=!1}isRequest(){return"undefined"!=typeof $request}isSurge(){return"undefined"!=typeof $httpClient}isQuanX(){return"undefined"!=typeof $task}isLoon(){return"undefined"!=typeof $loon}isJSBox(){return"undefined"!=typeof $app&&"undefined"!=typeof $http}isStash(){return"undefined"!=typeof $environment&&$environment["stash-version"]}isNode(){return"function"==typeof require&&!this.isJSBox()}async sleep(s){return new Promise(t=>setTimeout(t,s))}async wait(s){return new Promise(t=>setTimeout(t,s))}async delay(s){return new Promise(t=>setTimeout(t,s))}log(t){this.isEnableLog&&console.log(""+this.logSeparator+t)}logErr(t){this.execStatus=!0,this.isEnableLog&&(console.log(""+this.logSeparator+this.name+"执行异常:"),console.log(t),console.log("\n"+t.message))}msg(t,s,e,i){if((this.isRequest()||!this.isNotifyOnlyFail||!this.execStatus)&&(this.isEmpty(s)&&(s=Array.isArray(this.notifyInfo)?this.notifyInfo.join("\n"):this.notifyInfo),!this.isEmpty(s)))if(this.isEnableTgNotify){for(var r in this.log(this.name+"Tg通知开始"),this.tgEscapeCharMapping)this.tgEscapeCharMapping.hasOwnProperty(r)&&(s=s.replace(r,this.tgEscapeCharMapping[r]));this.get({url:encodeURI(this.tgNotifyUrl+"📌"+this.name+"\n"+s)},(t,s,e)=>{this.log("Tg通知完毕")})}else{var o={},n=!this.isEmpty(e),h=!this.isEmpty(i);this.isQuanX()&&(n&&(o["open-url"]=e),h&&(o["media-url"]=i),$notify(this.name,t,s,o)),(this.isSurge()||this.isStash())&&(n&&(o.url=e),$notification.post(this.name,t,s,o)),this.isNode()&&this.log("⭐️"+this.name+"\n"+t+"\n"+s),this.isJSBox()&&$push.schedule({title:this.name,body:t?t+"\n"+s:s})}}pushWxMsg(t,s,e,i=()=>{}){s={appToken:"AT_rTc93GQYIdMU8XLRnoJaSea8WkfhSzhX",content:s,summary:t,contentType:1,topicIds:[],uids:["UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"],url:"",verifyPay:!1},e&&(s.url=e),t=this.getJsonDoneHeaders(),t.Host="wxpusher.zjiecode.com",t["Content-Type"]="application/json;charset=UTF-8",e={url:"https://wxpusher.zjiecode.com/api/send/message",headers:t,body:JSON.stringify(s)};this.post(e,i)}getVal(t,s=""){let e;return(e=this.isSurge()||this.isLoon()||this.isStash()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loadData(),process.env[t]||this.data[t]):this.data&&this.data[t]||null)||s}setVal(t,s){return this.isSurge()||this.isLoon()||this.isStash()?$persistentStore.write(s,t):this.isQuanX()?$prefs.setValueForKey(s,t):this.isNode()?(this.data=this.loadData(),this.data[t]=s,this.writeData(),!0):this.data&&this.data[t]||null}loadData(){if(!this.isNode())return{};this.fs=this.fs||require("fs"),this.path=this.path||require("path");var t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s);if(!e&&!i)return{};i=e?t:s;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}writeData(){var t,s,e,i,r;this.isNode()&&(this.fs=this.fs||require("fs"),this.path=this.path||require("path"),t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),i=!(e=this.fs.existsSync(t))&&this.fs.existsSync(s),r=JSON.stringify(this.data),!e&&i?this.fs.writeFileSync(s,r):this.fs.writeFileSync(t,r))}adapterStatus(t){return t&&(t.status?t.statusCode=t.status:t.statusCode&&(t.status=t.statusCode)),t}get(t,i=()=>{}){this.isQuanX()&&((t="string"==typeof t?{url:t}:t).method="GET",$task.fetch(t).then(t=>{i(null,this.adapterStatus(t),t.body)},t=>i(t.error,null,null))),(this.isSurge()||this.isLoon()||this.isStash())&&$httpClient.get(t,(t,s,e)=>{i(t,this.adapterStatus(s),e)}),this.isNode()&&this.node.request(t,(t,s,e)=>{i(t,this.adapterStatus(s),e)}),this.isJSBox()&&((t="string"==typeof t?{url:t}:t).header=t.headers,t.handler=function(t){let s=t.error,e=(s=s&&JSON.stringify(t.error),t.data);"object"==typeof e&&(e=JSON.stringify(t.data)),i(s,this.adapterStatus(t.response),e)},$http.get(t))}post(t,i=()=>{}){this.isQuanX()&&((t="string"==typeof t?{url:t}:t).method="POST",$task.fetch(t).then(t=>{i(null,this.adapterStatus(t),t.body)},t=>i(t.error,null,null))),(this.isSurge()||this.isLoon()||this.isStash())&&$httpClient.post(t,(t,s,e)=>{i(t,this.adapterStatus(s),e)}),this.isNode()&&this.node.request.post(t,(t,s,e)=>{i(t,this.adapterStatus(s),e)}),this.isJSBox()&&((t="string"==typeof t?{url:t}:t).header=t.headers,t.handler=function(t){let s=t.error,e=(s=s&&JSON.stringify(t.error),t.data);"object"==typeof e&&(e=JSON.stringify(t.data)),i(s,this.adapterStatus(t.response),e)},$http.post(t))}put(t,i=()=>{}){this.isQuanX()&&((t="string"==typeof t?{url:t}:t).method="PUT",$task.fetch(t).then(t=>{i(null,this.adapterStatus(t),t.body)},t=>i(t.error,null,null))),(this.isSurge()||this.isLoon()||this.isStash())&&(t.method="PUT",$httpClient.put(t,(t,s,e)=>{i(t,this.adapterStatus(s),e)})),this.isNode()&&(t.method="PUT",this.node.request.put(t,(t,s,e)=>{i(t,this.adapterStatus(s),e)})),this.isJSBox()&&((t="string"==typeof t?{url:t}:t).header=t.headers,t.handler=function(t){let s=t.error,e=(s=s&&JSON.stringify(t.error),t.data);"object"==typeof e&&(e=JSON.stringify(t.data)),i(s,this.adapterStatus(t.response),e)},$http.post(t))}costTime(){let t=this.name+"执行完毕!";this.isNode()&&this.isExecComm&&(t=`指令【${this.comm[1]}】执行完毕!`);var s=(new Date).getTime()-this.startTime,e=s/1e3;this.execCount++,this.costTotalMs+=s,this.log(`${t}耗时【${e}】秒\n总共执行【${this.execCount}】次,平均耗时【${(this.costTotalMs/this.execCount/1e3).toFixed(4)}】秒`),this.setVal(this.costTotalStringKey,JSON.stringify(this.costTotalMs+","+this.execCount))}done(t={}){this.costTime(),(this.isSurge()||this.isQuanX()||this.isLoon()||this.isStash())&&$done(t)}getRequestUrl(){return $request.url}getResponseBody(){if($response)return $response.body}isGetCookie(t){return!("OPTIONS"==$request.method||!this.getRequestUrl().match(t))}isEmpty(t){return void 0===t||null==t||""==t||"null"==t||"undefined"==t||0===t.length}randomString(s){s=s||32;var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890",i=e.length,r="";for(let t=0;t<s;t++)r+=e.charAt(Math.floor(Math.random()*i));return r}autoComplete(s,t,e,i,r,o,n,h,a,l){if((s+="").length<r)for(;s.length<r;)0==o?s+=i:s=i+s;if(n){let t="";for(var p=0;p<h;p++)t+=l;s=s.substring(0,a)+t+s.substring(h+a)}return this.toDBC(s=t+s+e)}customReplace(t,s,e,i){try{for(var r in this.isEmpty(e)&&(e="#{"),this.isEmpty(i)&&(i="}"),s)t=t.replace(""+e+r+i,s[r])}catch(t){this.logErr(t)}return t}toDBC(t){for(var s="",e=0;e<t.length;e++)32==t.charCodeAt(e)?s+=String.fromCharCode(12288):t.charCodeAt(e)<127&&(s+=String.fromCharCode(t.charCodeAt(e)+65248));return s}hash(t){let s=0,e,i;for(e=0;e<t.length;e++)i=t.charCodeAt(e),s=(s<<5)-s+i,s|=0;return String(s)}formatDate(t,s){var e,i={"M+":t.getMonth()+1,"d+":t.getDate(),"H+":t.getHours(),"m+":t.getMinutes(),"s+":t.getSeconds(),"q+":Math.floor((t.getMonth()+3)/3),S:t.getMilliseconds()};for(e in/(y+)/.test(s)&&(s=s.replace(RegExp.$1,(t.getFullYear()+"").substr(4-RegExp.$1.length))),i)new RegExp("("+e+")").test(s)&&(s=s.replace(RegExp.$1,1==RegExp.$1.length?i[e]:("00"+i[e]).substr((""+i[e]).length)));return s}parseDate(h,t){let a={y:0,M:1,d:0,H:0,h:0,m:0,s:0,S:0};(t=t||"yyyy-MM-dd").replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g,function(t,s,e,i,r,o,n){return h=h.replace(new RegExp(s+"(\\d{"+e.length+"})"+r),function(t,s){return a[i]=parseInt(s),""}),""}),a.M--;t=new Date(a.y,a.M,a.d,a.H,a.m,a.s);return 0!==a.S&&t.setMilliseconds(a.S),t}objToQueryStr(s,e){let i="";for(const r in s){let t=s[r];null!=t&&""!==t&&("object"==typeof t?t=JSON.stringify(t):e&&(t=encodeURIComponent(t)),i+=`${r}=${t}&`)}return i=i.substring(0,i.length-1)}parseQueryStr(t){var s={},e=(t=-1<t.indexOf("?")?t.split("?")[1]:t).split("&");for(let t=0;t<e.length;t++){var i=e[t].split("=");s[i[0]]=i[1]}return s}deepClone(t,s){for(var e in s=s||{},t)"object"==typeof t[e]?(s[e]=t[e].constructor===Array?[]:{},this.deepClone(t[e],s[e])):s[e]=t[e];return s}getBaseDoneHeaders(t={}){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"},t)}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"})}shallowClone(t){var s,e={};for(s in t)t.hasOwnProperty(s)&&(e[s]=t[s]);return e}parseCookies(t){let s={};return t&&t.split(";").forEach(function(t){t=t.split("=");s[t.shift().trim()]=decodeURI(t.join("="))}),s}serializeCookies(t){var s,e=[];for(s in t){var i=t[s],i=encodeURIComponent(s)+"="+encodeURIComponent(i);e.push(i)}return e.join("; ")}parseSetCookies(t){const r=["Expires","Max-Age","Domain","Path","HttpOnly","SameSite"];t=t.split(";");let o=null;const n={},h=[];return t.forEach(t=>{t=t.trim();let e=null,i=!0;if(t.includes("=")?(kvdata=t.split("="),e=kvdata[0].trim(),i=kvdata[1].trim()):e=t,r.includes(e))n[o]&&(n[o][e]=i,(attribs=n[o].attribs)[e]=i);else{o=e;let s={};o.includes(",")&&o.split(",").forEach(t=>{t=t.trim();r.includes(t)?s[t]=!0:o=t}),n[o]={name:o,value:i,attribs:s},h.push(n[o])}}),h}base64Decode(t){var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";if(/([^\s]+[^0-9a-zA-Z\+\/\=]|[^0-9a-zA-Z\+\/\=]\s+)/.test(t))throw new Error("Invalid base64 input");var e,i,r,o,n,h,a=t.replace(/\s/g,"");let l="",p=0;for(;p<a.length;)r=s.indexOf(a.charAt(p++)),e=(15&(o=s.indexOf(a.charAt(p++))))<<4|(n=s.indexOf(a.charAt(p++)))>>2,i=(3&n)<<6|(h=s.indexOf(a.charAt(p++))),l+=String.fromCharCode(r<<2|o>>4),64!==n&&(l+=String.fromCharCode(e)),64!==h&&(l+=String.fromCharCode(i));return l=this.utf8Decode(l)}utf8Decode(s){let t=[],e=0,i=0,r=0;for(s=s.replace(/\r\n/g,"\n");e<s.length;){i=255&s.charCodeAt(e),r=0,r=i<=191?(i&=127,1):i<=223?(i&=31,2):i<=239?(i&=15,3):(i&=7,4);for(let t=1;t<r;++t)i=i<<6|63&s.charCodeAt(t+e);4===r?(i-=65536,t.push(String.fromCharCode(55296|i>>10&1023)),t.push(String.fromCharCode(56320|1023&i))):t.push(String.fromCharCode(i)),e+=r}return t.join("")}parseJwt(t){try{var s=t.split("."),e=s[0].replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(this.base64Decode(e)),r=s[1].replace(/-/g,"+").replace(/_/g,"/");return{header:i,payload:JSON.parse(this.base64Decode(r)),signature:s[2]}}catch(t){return this.log(t),null}}}(t,s,e)}
  805. //---SyncByPyScript---ToolKit-end