gandartComposite.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. const config = {
  2. "PATH_IMG_V2_PRO": "https://cdn-image.gandart.com/",
  3. "RUN_TYPE": 1,
  4. "BOTTOM_LOAD_MORE_THROTTLE": 100,
  5. "BASE_API": "https://api.gandart.com/base",
  6. "RESALE_API": "https://api.gandart.com/market",
  7. "RESALE_API_V2": "https://api2.gandart.com/market/api/v2",
  8. "RESALE_API_V3": "https://api2.gandart.com/market/api/v3",
  9. "SALE_API": "https://api.gandart.com/read/api",
  10. "ORDER_API": "https://api.gandart.com",
  11. "WALLET_API": "https://api.gandart.com/api",
  12. "HXT_API": "https://api.gandart.com/wallet",
  13. "PATH_IMG_V2": "https://cdn-image.gandart.com/",
  14. "SAND_RECHARGE_ACTION": "https://cap.sandpay.com.cn/v4/front-electrans/ceas.elec.trans.quick.deposit.apply",
  15. "GAME_ElF_API": "https://elf.pentajam.cn/api",
  16. "GAME_ELF_URL": "https://elf.pentajam.cn",
  17. "CORECENTER_URL": "https://api.gandart.com/corecenter"
  18. };
  19. const lk = new ToolKit(`光予合成手`, `GandartCompostier`, `gandartComposite.js`);
  20. const GandartConstKey = {
  21. Token: 'lkGandartToken',
  22. CollectionName: 'lkGandartCollectionName',
  23. CastingId: 'lkGandartCastingId',
  24. LimitPrice: 'lkGandartLimitPrice',
  25. TransactionRecordId: 'lkGandartTransactionRecordId',
  26. CollectionCateLst: 'lkGandartCollectionCateLst',
  27. FloatPriceIntaval: 'lkGandartFloatPriceIntaval',
  28. IsCollectionWatchLocked: 'lkIsGandartCollectionWatchLocked',
  29. CompositeFuncEnalbleList: 'lkGandartCompositeFuncEnalbleList',
  30. CompositeTaskList0: 'lkGandartCompositeTaskList0',
  31. CompositeTaskList1: 'lkGandartCompositeTaskList1',
  32. CompositeTaskList2: 'lkGandartCompositeTaskList2',
  33. CompositeTaskId: 'lkGandartCompositeTaskId',
  34. CompositeTaskName: 'lkGandartCompositeTaskName',
  35. CompositeCountArray: 'lkGandartCompositeCountArray',
  36. CompositeTaskMateList: 'lkGandartCompositeTaskMateList',
  37. CompositeTaskListStatus: 'lkGandartCompositeTaskListStatus',
  38. CompositeTaskListCache: 'lkIsCompositeTaskListCache',
  39. CompositeMaterialCache: 'lkIsCompositeMaterialCache',
  40. CompositeTaskMode: 'lkGandartCompositeTaskMode',
  41. };
  42. let gandartToken = lk.getVal(GandartConstKey.Token, '');
  43. const GCommonGandartHeads = {
  44. 'Accept': `application/json, text/plain, */*`,
  45. 'Origin': `https://www.gandart.com`,
  46. 'Accept-Encoding': `gzip, deflate, br`,
  47. 'Content-Type': `application/x-www-form-urlencoded;charset=UTF-8`,
  48. 'Connection': `keep-alive`,
  49. 'Host': `api2.gandart.com`,
  50. 'User-Agent': `Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Mobile/15E148 Safari/604.1`,
  51. 'Referer': `https://www.gandart.com/`,
  52. 'Accept-Language': `zh-CN,zh-Hans;q=0.9`,
  53. 'token': gandartToken
  54. };
  55. const gMaterialDetails = {};
  56. const gFuncEnables = lk.getVal(GandartConstKey.CompositeFuncEnalbleList);
  57. if (lk.isEmpty(gFuncEnables)) {
  58. gFuncEnables = gFuncEnables.split(',');
  59. } else {
  60. gFuncEnables = [];
  61. }
  62. if (!lk.isExecComm) {
  63. if (!lk.isRequest()) {
  64. all();
  65. }
  66. }
  67. async function all() {
  68. let taskLst = [];
  69. if (isGetTaskListEnable()) {
  70. let status = getCompositeTaskListStatus();
  71. let tmpLst = [];
  72. switch (status) {
  73. case 0:
  74. tmpLst = await checkGetCompositeTaskList(status);
  75. if (tmpLst) {
  76. taskLst = taskLst.concat(tmpLst);
  77. }
  78. break;
  79. case 1:
  80. tmpLst = await checkGetCompositeTaskList(status);
  81. if (tmpLst) {
  82. taskLst = taskLst.concat(tmpLst);
  83. }
  84. break;
  85. case 2:
  86. tmpLst = await checkGetCompositeTaskList(status);
  87. if (tmpLst) {
  88. taskLst = taskLst.concat(tmpLst);
  89. }
  90. break;
  91. case 3:
  92. tmpLst = await checkGetCompositeTaskList(1);
  93. if (tmpLst) {
  94. taskLst = taskLst.concat(tmpLst);
  95. }
  96. tmpLst = await checkGetCompositeTaskList(0);
  97. if (tmpLst) {
  98. taskLst = taskLst.concat(tmpLst);
  99. }
  100. break;
  101. default:
  102. break;
  103. }
  104. }
  105. if (isCaclMateListEnable()) {
  106. let taskId = getWillCompositeTaskId();
  107. if (taskId > 0) {
  108. for (let i = 0; i < taskLst.length; i++) {
  109. let taskInfo = taskLst[i];
  110. if (taskInfo.id == taskId) {
  111. lk.setVal(GandartConstKey.CompositeTaskName, taskInfo.compositeTaskName);
  112. tryToExecCompositeTask(taskInfo.id, taskInfo);
  113. break;
  114. }
  115. }
  116. }
  117. }
  118. lk.msg('');
  119. }
  120. function getCompositeTaskListStatus() {
  121. let val = lk.getVal(GandartConstKey.CompositeTaskListStatus);
  122. if (lk.isEmpty(val)) {
  123. val = 1;
  124. } else {
  125. val = Number(val);
  126. }
  127. return val;
  128. }
  129. function getCompositeTaskMode() {
  130. let val = lk.getVal(GandartConstKey.CompositeTaskMode);
  131. if (lk.isEmpty(val)) {
  132. val = 1;
  133. } else {
  134. val = Number(val);
  135. }
  136. return val;
  137. }
  138. function isGetTaskListEnable() {
  139. if (gFuncEnables.indexOf('TaskList') > -1) {
  140. return true;
  141. }
  142. return false;
  143. }
  144. function isCaclMateListEnable() {
  145. if (gFuncEnables.indexOf('MateList') > -1) {
  146. return true;
  147. }
  148. return false;
  149. }
  150. function isGenFinalLisstEnable() {
  151. if (gFuncEnables.indexOf('DecidedList') > -1) {
  152. return true;
  153. }
  154. return false;
  155. }
  156. function isExecFinalComposite() {
  157. if (gFuncEnables.indexOf('ExecComposite') > -1) {
  158. return true;
  159. }
  160. return false;
  161. }
  162. function getWillCompositeTaskId() {
  163. let val = lk.getVal(GandartConstKey.CompositeTaskId);
  164. if (lk.isEmpty(val)) {
  165. val = 0;
  166. } else {
  167. val = Number(val);
  168. }
  169. return val;
  170. }
  171. async function tryToExecCompositeTask(taskId, taskInfo = {}) {
  172. if (getCompositeTaskMode() == 0) {
  173. let jsonStr = lk.getVal(GandartConstKey.CompositeTaskMateList);
  174. if (!lk.isEmpty(jsonStr)) {
  175. let data = JSON.parse(jsonStr);
  176. let taskInfo = data.taskInfo;
  177. let finalGroups = data.finalGroups;
  178. let retOrderLst = [];
  179. for (let i = 0; i < finalGroups.length; i++) {
  180. let ret = await confirmCompositeV2(taskInfo.id, taskInfo, finalGroups[i]);
  181. if (ret) {
  182. retOrderLst.push(retOrderLst);
  183. }
  184. }
  185. lk.log(`合成成功${retOrderLst.length},订单为${retOrderLst.join(",")}`);
  186. for (let i = 0; i < retOrderLst.length; i++) {
  187. let ret = await checkCompositeResult(retOrderLst[i]);
  188. }
  189. }
  190. return;
  191. }
  192. let materialSelLst = await getCompositeMaterial(taskId);
  193. if (materialSelLst && materialSelLst.length > 0) {
  194. let ret = calcCompositeGroups(materialSelLst);
  195. let materialGroups = ret[0];
  196. // 获取用户材料拥有详情
  197. let materialDict = ret[1];
  198. for (let k in materialDict) {
  199. let mInfo = materialDict[k];
  200. gMaterialDetails[k] = await getDetailByCasting(mInfo.castingId, mInfo.collectionName);
  201. }
  202. // 找出可行的合成搭配
  203. let validCompositeGroups = findValidGroupMaterialGroups(materialGroups, gMaterialDetails);
  204. lk.setVal(GandartConstKey.CompositeTaskMateList, JSON.stringify(validCompositeGroups));
  205. if (isGenFinalLisstEnable()) {
  206. let compositeCountDict = getCompositeCountDict();
  207. let finalGroups = [];
  208. for (let k in compositeCountDict) {
  209. let mGroup = validCompositeGroups[k];
  210. if (mGroup) {
  211. let arr = checkPickMaterialForComposite(mGroup, gMaterialDetails, compositeCountDict[k]);
  212. finalGroups = finalGroups.concat(arr);
  213. }
  214. }
  215. if (isExecFinalComposite()) {
  216. let retOrderLst = [];
  217. for (let i = 0; i < finalGroups.length; i++) {
  218. let ret = await confirmCompositeV2(taskId, taskInfo, finalGroups[i]);
  219. if (ret) {
  220. retOrderLst.push(retOrderLst);
  221. }
  222. }
  223. lk.log(`合成成功${retOrderLst.length},订单为${retOrderLst.join(",")}`);
  224. for (let i = 0; i < retOrderLst.length; i++) {
  225. let ret = await checkCompositeResult(retOrderLst[i]);
  226. }
  227. lk.setVal(GandartConstKey.CompositeTaskMateList, '{}');
  228. } else {
  229. let finalCacheData = {
  230. taskInfo: taskInfo,
  231. finalGroups: finalGroups,
  232. };
  233. lk.setVal(GandartConstKey.CompositeTaskMateList, JSON.stringify(finalCacheData));
  234. }
  235. } else {
  236. lk.execFail();
  237. lk.appendNotifyInfo('⚠️请设置光予合成任务ID');
  238. }
  239. }
  240. }
  241. function getCompositeCountDict() {
  242. let str = lk.getVal(GandartConstKey.CompositeCountArray, '0#1');
  243. let arr1 = str.split(',');
  244. let ret = {};
  245. for (let i = 0; i < arr1.length; i++) {
  246. let arr2 = arr1[i].split('#');
  247. let key = arr2[0];
  248. ret[key] = Number(arr2[1] || 1);
  249. }
  250. return ret;
  251. }
  252. function findValidGroupMaterialGroups(materialGroups, materialDetails) {
  253. let validGroups = [];
  254. for (let i = 0; i < materialGroups.length; i++) {
  255. let canCount = checkMaterialEnough(materialGroups[i], materialDetails);
  256. if (canCount > 0) {
  257. validGroups.push(materialGroups[i]);
  258. }
  259. }
  260. return validGroups;
  261. }
  262. function checkMaterialEnough(materialGroup, materialDetails) {
  263. let minCount = 99999;
  264. for (let i = 0; i < materialGroup.length; i++) {
  265. const materialObj = materialGroup[i];
  266. const castingId = materialObj.castingId;
  267. const ownLst = materialDetails[castingId];
  268. if (!ownLst) {
  269. break;
  270. }
  271. if (ownLst.length < materialObj.number) {
  272. let maxCount = Math.floor(ownLst.length / materialObj.number);
  273. if (maxCount < minCount) {
  274. minCount = maxCount;
  275. }
  276. } else {
  277. break;
  278. }
  279. }
  280. if (minCount == 99999) {
  281. minCount = 0;
  282. }
  283. return minCount
  284. }
  285. function checkPickMaterialForComposite(materialGroup, materialDetails, wantCount) {
  286. let minCount = 99999;
  287. for (let i = 0; i < materialGroup.length; i++) {
  288. const materialObj = materialGroup[i];
  289. const castingId = materialObj.castingId;
  290. const ownLst = materialDetails[castingId] || [];
  291. const maxCount = Math.floor(ownLst.length / materialObj.number);
  292. if (maxCount < minCount) {
  293. minCount = maxCount;
  294. }
  295. }
  296. minCount = Math.min(minCount, wantCount);
  297. let nCompositeGroup = [];
  298. for (let n = 0; n < minCount; n++) {
  299. let resultMaterialLst = [];
  300. for (let i = 0; i < materialGroup.length; i++) {
  301. const materialObj = materialGroup[i];
  302. const castingId = materialObj.castingId;
  303. const ownLst = materialDetails[castingId];
  304. const num = materialGroup.number;
  305. let oneMaterial = {
  306. castingId: castingId,
  307. orderList: [],
  308. };
  309. for (let j = ownLst.length - 1; j >= 0; j--) {
  310. num -= 1;
  311. let info = ownLst[j];
  312. oneMaterial.orderList.push(info.id);
  313. ownLst.splice(j, 1);
  314. if (num == 0) {
  315. break;
  316. }
  317. }
  318. resultMaterialLst.push(oneMaterial);
  319. }
  320. nCompositeGroup.push(resultMaterialLst);
  321. }
  322. return nCompositeGroup;
  323. }
  324. function calcCompositeGroups(materialSelLst) {
  325. let materialDict = {};
  326. let materialGroups = [];
  327. function arrange(transArr, index, resultArr, resultTmp) {
  328. for (let i = 0; i < transArr[index].length; i++) {
  329. const materialInfo = transArr[index][i];
  330. resultTmp[index] = materialInfo;
  331. const castingId = materialInfo.castingId;
  332. materiaDict[castingId] = materialInfo;
  333. if (index != transArr.length - 1) {
  334. arrage(transArr, index + 1, resultArr, resultTmp);
  335. } else {
  336. resultArr.push([].concat(resultTmp));
  337. }
  338. }
  339. return resultArr;
  340. }
  341. arrange(materialSelLst, 0, materialGroups, []);
  342. return [materialGroups, materialDict];
  343. }
  344. async function checkGetCompositeTaskList(status) {
  345. let taskLst;
  346. let useCache = lk.getVal(GandartConstKey.CompositeTaskListCache);
  347. if (lk.isEmpty(useCache)) {
  348. useCache = JSON.parse(useCache);
  349. } else {
  350. useCache = false;
  351. }
  352. if (useCache) {
  353. taskLst = getCompositeTaskListByCache(status);
  354. } else {
  355. taskLst = await getCompositeTaskListByServer(status);
  356. cacheCompositeTaskList(status, taskLst);
  357. }
  358. return taskLst;
  359. }
  360. function getCompositeTaskListByCache(status, pageSize = 10, page = 1) {
  361. try {
  362. let jsonStr = '';
  363. if (status == 0) {
  364. jsonStr = lk.getVal(GandartConstKey.CompositeTaskList0);
  365. } else if (status == 1) {
  366. jsonStr = lk.getVal(GandartConstKey.CompositeTaskList1);
  367. } else if (status == 2) {
  368. jsonStr = lk.getVal(GandartConstKey.CompositeTaskList2);
  369. }
  370. if (!lk.isEmpty(jsonStr)) {
  371. return JSON.parse(jsonStr);
  372. }
  373. } catch (error) {
  374. lk.logErr(error);
  375. }
  376. }
  377. function cacheCompositeTaskList(status, taskLst) {
  378. let jsonStr = JSON.stringify(taskLst);
  379. if (status == 0) {
  380. lk.setVal(GandartConstKey.CompositeTaskList0, jsonStr);
  381. } else if (status == 1) {
  382. lk.setVal(GandartConstKey.CompositeTaskList1, jsonStr);
  383. } else if (status == 2) {
  384. lk.setVal(GandartConstKey.CompositeTaskList2, jsonStr);
  385. }
  386. }
  387. async function getCompositeTaskListByServer(status, pageSize = 10, page = 1) {
  388. return new Promise((resolve, _reject) => {
  389. try {
  390. const headers = GCommonGandartHeads;
  391. headers['Host'] = 'api.gandart.com';
  392. headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  393. let body = `page=${page}&pageSize=${pageSize}&total=0&status=${status}&labelName=`;
  394. let url = {
  395. url: `${config.BASE_API}/v2/composite/v3/compositeMaterial`,
  396. headers: headers,
  397. body: body
  398. };
  399. let tagNames = [
  400. '待开始',
  401. '合成中',
  402. '已结束',
  403. ];
  404. lk.log(`获取合成任务[${tagNames[status]}]列表:${body}`);
  405. lk.post(url, async (error, _response, data) => {
  406. let retTaskLst = [];
  407. try {
  408. if (error) {
  409. lk.log(`获取合成任务材料详情发生错误`);
  410. lk.execFail();
  411. lk.appendNotifyInfo(`❌获取合成任务材料详情失败,请稍后再试`);
  412. } else {
  413. let ret = JSON.parse(data);
  414. if (ret.rows && ret.rows.length > 0) {
  415. retTaskLst = ret.rows;
  416. }
  417. }
  418. } catch (e) {
  419. lk.log(`获取合成任务材料详情发生错误`);
  420. lk.logErr(e);
  421. lk.execFail();
  422. } finally {
  423. resolve(retTaskLst);
  424. }
  425. });
  426. } catch (e) {
  427. lk.log(`获取合成任务材料详情发生错误`);
  428. lk.logErr(e);
  429. resolve();
  430. }
  431. });
  432. }
  433. async function getCompositeMaterial(taskId) {
  434. return new Promise((resolve, _reject) => {
  435. try {
  436. const headers = GCommonGandartHeads;
  437. headers['Host'] = 'api.gandart.com';
  438. headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  439. let body = `taskId=${taskId}`;
  440. let url = {
  441. url: `${config.BASE_API}/v2/composite/v3/compositeMaterial`,
  442. headers: headers,
  443. body: body
  444. };
  445. let taskTitleName = ''; //合成标题
  446. lk.log(`获取合成任务[${taskTitleName}#${taskId}]材料详情:${body}`);
  447. lk.post(url, async (error, _response, data) => {
  448. let retItemLst = [];
  449. try {
  450. if (error) {
  451. lk.log(`获取合成任务材料详情发生错误`);
  452. lk.execFail();
  453. lk.appendNotifyInfo(`❌获取合成任务材料详情失败,请稍后再试`);
  454. } else {
  455. let ret = JSON.parse(data);
  456. if (ret.success) {
  457. let obj = ret.obj;
  458. retItemLst = obj;
  459. } else {
  460. }
  461. }
  462. } catch (e) {
  463. lk.log(`获取合成任务材料详情发生错误`);
  464. lk.logErr(e);
  465. lk.execFail();
  466. } finally {
  467. resolve(retItemLst);
  468. }
  469. });
  470. } catch (e) {
  471. lk.log(`获取合成任务材料详情发生错误`);
  472. lk.logErr(e);
  473. resolve();
  474. }
  475. });
  476. }
  477. async function getDetailByCasting(castingId, collectionName, pageSize = 50, page = 1) {
  478. return new Promise((resolve, _reject) => {
  479. try {
  480. const headers = GCommonGandartHeads;
  481. headers['Host'] = 'api.gandart.com';
  482. headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  483. let params = {
  484. castingId: castingId,
  485. page: page,
  486. pageSize: pageSize,
  487. };
  488. let signData = getSign();
  489. signData = Object.assign(signData, params);
  490. let body = lk.objToQueryStr(signData);
  491. let url = {
  492. url: `${config.SALE_API}/composite/getDetailByCasting?${lk.objToQueryStr(params)}`,
  493. headers: headers,
  494. body: body
  495. };
  496. collectionName = collectionName || getCollectionNameById(castingId);
  497. lk.log(`请求产品[${collectionName}(${castingId})]拥有详情:${body}`);
  498. lk.post(url, async (error, _response, data) => {
  499. let retItemLst = [];
  500. try {
  501. if (error) {
  502. lk.log(`获取产品拥有详情发生错误`);
  503. lk.execFail();
  504. lk.appendNotifyInfo(`❌获取产品拥有详情失败,请稍后再试`);
  505. } else {
  506. let ret = JSON.parse(data);
  507. if (ret.success) {
  508. let obj = ret.obj;
  509. retItemLst = obj.list;
  510. } else {
  511. }
  512. }
  513. } catch (e) {
  514. lk.log(`获取产品拥有详情发生错误`);
  515. lk.logErr(e);
  516. lk.execFail();
  517. } finally {
  518. resolve(retItemLst);
  519. }
  520. });
  521. } catch (e) {
  522. lk.log(`获取产品拥有详情发生错误`);
  523. lk.logErr(e);
  524. resolve();
  525. }
  526. });
  527. }
  528. async function confirmCompositeV2(taskId, taskInfo, materialDetailList) {
  529. return new Promise((resolve, _reject) => {
  530. try {
  531. const headers = GCommonGandartHeads;
  532. headers['Host'] = 'api.gandart.com';
  533. headers['Content-Type'] = 'application/json';
  534. let data = {
  535. taskId: Number(taskId),
  536. compositeList: [
  537. {
  538. materialDetailList: materialDetailList
  539. }
  540. ],
  541. };
  542. let body = JSON.stringify(data);
  543. let url = {
  544. url: `${config.BASE_API}/v2/composite/v3/confirmCompositeV2`,
  545. headers: headers,
  546. body: body
  547. };
  548. lk.log(`请求合成任务[${taskId}]:${body}`);
  549. lk.post(url, async (error, _response, data) => {
  550. let retOrder;
  551. try {
  552. if (error) {
  553. lk.log(`合成发生错误`);
  554. lk.execFail();
  555. lk.appendNotifyInfo(`❌合成失败,请稍后再试`);
  556. } else {
  557. let ret = JSON.parse(data);
  558. if (ret.success) {
  559. retOrder = ret.obj;
  560. lk.appendNotifyInfo(`🎉合成任务[${taskId}]成功,订单号:${obj}`);
  561. } else {
  562. lk.log(`合成失败,msg=${ret.msg}`);
  563. }
  564. }
  565. } catch (e) {
  566. lk.log(`合成发生错误`);
  567. lk.logErr(e);
  568. lk.execFail();
  569. } finally {
  570. resolve(retOrder);
  571. }
  572. });
  573. } catch (e) {
  574. lk.log(`合成发生错误`);
  575. lk.logErr(e);
  576. resolve();
  577. }
  578. });
  579. }
  580. async function checkCompositeResult(orderNum) {
  581. return new Promise((resolve, _reject) => {
  582. try {
  583. const headers = GCommonGandartHeads;
  584. headers['Host'] = 'api.gandart.com';
  585. headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  586. let body = `orderNum=${orderNum}`;
  587. let url = {
  588. url: `${config.RESALE_API}/v2/composite/v3/compositeResult`,
  589. headers: headers,
  590. body: body
  591. };
  592. lk.log(`获取合成结果[${orderNum}]:${body}`);
  593. lk.post(url, async (error, _response, data) => {
  594. let retItemLst;
  595. try {
  596. if (error) {
  597. lk.log(`获取合成结果发生错误`);
  598. lk.execFail();
  599. lk.appendNotifyInfo(`❌获取合成结果失败,请稍后再试`);
  600. } else {
  601. let ret = JSON.parse(data);
  602. if (ret.success) {
  603. retItemLst = ret.obj;
  604. let cName = '';
  605. for (let i = 0; i < retItemLst.length; i++) {
  606. cName += retItemLst[i].collectionName + ",";
  607. }
  608. cName = cName.substring(0, cName.length - 1);
  609. lk.appendNotifyInfo(`🎉合成产品:${cName}`);
  610. } else {
  611. lk.log(`获取合成结果失败,msg=${ret.msg}`);
  612. }
  613. }
  614. } catch (e) {
  615. lk.log(`获取合成结果发生错误`);
  616. lk.logErr(e);
  617. lk.execFail();
  618. } finally {
  619. resolve(retItemLst);
  620. }
  621. });
  622. } catch (e) {
  623. lk.log(`获取合成结果发生错误`);
  624. lk.logErr(e);
  625. resolve();
  626. }
  627. });
  628. }
  629. function getCollectionMInfoById(castingId) {
  630. let ret;
  631. try {
  632. let clst = JSON.parse(lk.getVal(GandartConstKey.CollectionCateLst, "[]"));
  633. for (const d of clst) {
  634. if (d.castingId == castingId) {
  635. ret = d;
  636. break;
  637. }
  638. }
  639. } catch (error) {
  640. lk.log(JSON.stringify(error));
  641. }
  642. return ret;
  643. }
  644. function getCollectionNameById(castingId) {
  645. let name = '未获取';
  646. let info = getCollectionMInfoById(castingId);
  647. if (info) {
  648. name = info.collectionName;
  649. }
  650. return name;
  651. }
  652. function getSign() {
  653. const now = new Date().getTime();
  654. const s1 = now - 20000;
  655. const s2 = now;
  656. const s3 = now + 20000;
  657. const s4 = now + 40000;
  658. const sssfffeee = 'e9'; //localStorage.getItem('sssfffeee');
  659. const aggaaa = '9'; //localStorage.getItem('aggaaa');
  660. const yyhhhasdww = '0a';
  661. let arr = [sssfffeee, yyhhhasdww, aggaaa, '29', 'e', 'c', 3];
  662. let crypto = Crypto();
  663. let s5 = crypto.md5(s3 + arr.join(''));
  664. return {
  665. 's1': s1,
  666. 's2': s2,
  667. 's3': s3,
  668. 's4': s4,
  669. 's5': s5
  670. };
  671. }
  672. //ToolKit-start
  673. function ToolKit(t,s,i){return new class{constructor(t,s,i){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=i,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(){var t,s;this.isRequest()&&(t=$request.body)&&(s=$request.path,s=this.id+"#"+s.replace("/","_"),this.isQuanX()&&$prefs.setValueForKey(t,s),(this.isLoon()||this.isSurge())&&$persistentStore.write(t,s),this.isNode())&&this.node.fs.writeFileSync(s+".json",t,{flag:"w"},t=>console.log(t))}getRequestBody(){var t=$request.path,t=this.id+"#"+t.replace("/","_");if(this.isSurge()||this.isLoon())return $persistentStore.read(t);if(this.isQuanX())return $prefs.valueForKey(t);if(this.isNode()){t=t+".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 e=this.comm[0],s=(this.log(`获取【${e}】内容传给手机`),"");this.fs=this.fs||require("fs"),this.path=this.path||require("path");var i=this.path.resolve(e),r=this.path.resolve(process.cwd(),e),o=this.fs.existsSync(i),h=!o&&this.fs.existsSync(r);if(o||h){h=o?i:r;try{s=this.fs.readFileSync(h)}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,i)=>{this.log(`已将脚本【${e}】发给手机!`),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 e="/Users/lowking/Desktop/Scripts/lowking.boxjs.json";if(r&&r.hasOwnProperty("target_boxjs_json_path")&&(e=r.target_boxjs_json_path),this.fs.existsSync(e))if(this.isJsonObject(s)&&this.isJsonObject(r)){this.log("using node");var o=["settings","keys"],h="https://raw.githubusercontent.com/Orz-3";let i={},t="#lk{script_url}";if(r&&r.hasOwnProperty("script_url")&&(t=this.isEmpty(r.script_url)?"#lk{script_url}":r.script_url),i.id=""+this.prefix+this.id,i.name=this.name,i.desc_html=`⚠️使用说明</br>详情【<a href='${t}?raw=true'><font class='red--text'>点我查看</font></a>】`,i.icons=[h+`/mini/master/Alpha/${this.id.toLocaleLowerCase()}.png`,h+`/mini/master/Color/${this.id.toLocaleLowerCase()}.png`],i.keys=[],i.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="}],i.author="#lk{author}",i.repo="#lk{repo}",i.script=t+"?raw=true",!this.isEmpty(s))for(var n in o){var a=o[n];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<i.settings.length;t++){var p=i.settings[t];l.id===p.id&&i.settings.splice(t,1)}}i[a]=i[a].concat(s[a])}delete s[a]}if(Object.assign(i,s),this.isNode()){this.fs=this.fs||require("fs"),this.path=this.path||require("path");var h=this.path.resolve(this.boxJsJsonFile),u=this.path.resolve(process.cwd(),this.boxJsJsonFile),f=this.fs.existsSync(h),c=!f&&this.fs.existsSync(u),d=JSON.stringify(i,null,"\t"),f=(!f&&c?this.fs.writeFileSync(u,d):this.fs.writeFileSync(h,d),JSON.parse(this.fs.readFileSync(e)));if(f.hasOwnProperty("apps")&&Array.isArray(f.apps)&&0<f.apps.length){c=f.apps,u=c.indexOf(c.filter(t=>t.id==i.id)[0]);0<=u?f.apps[u]=i:f.apps.push(i);let s=JSON.stringify(f,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(e,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()}sleep(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,i,e){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,i)=>{this.log("Tg通知完毕")})}else{var o={},h=!this.isEmpty(i),n=!this.isEmpty(e);this.isQuanX()&&(h&&(o["open-url"]=i),n&&(o["media-url"]=e),$notify(this.name,t,s,o)),(this.isSurge()||this.isStash())&&(h&&(o.url=i),$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})}}getVal(t,s=""){let i;return(i=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),i=this.fs.existsSync(t),e=!i&&this.fs.existsSync(s);if(!i&&!e)return{};e=i?t:s;try{return JSON.parse(this.fs.readFileSync(e))}catch(t){return{}}}writeData(){var t,s,i,e,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),e=!(i=this.fs.existsSync(t))&&this.fs.existsSync(s),r=JSON.stringify(this.data),!i&&e?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,e=()=>{}){this.isQuanX()&&((t="string"==typeof t?{url:t}:t).method="GET",$task.fetch(t).then(t=>{e(null,this.adapterStatus(t),t.body)},t=>e(t.error,null,null))),(this.isSurge()||this.isLoon()||this.isStash())&&$httpClient.get(t,(t,s,i)=>{e(t,this.adapterStatus(s),i)}),this.isNode()&&this.node.request(t,(t,s,i)=>{e(t,this.adapterStatus(s),i)}),this.isJSBox()&&((t="string"==typeof t?{url:t}:t).header=t.headers,t.handler=function(t){let s=t.error,i=(s=s&&JSON.stringify(t.error),t.data);"object"==typeof i&&(i=JSON.stringify(t.data)),e(s,this.adapterStatus(t.response),i)},$http.get(t))}post(t,e=()=>{}){this.isQuanX()&&((t="string"==typeof t?{url:t}:t).method="POST",$task.fetch(t).then(t=>{e(null,this.adapterStatus(t),t.body)},t=>e(t.error,null,null))),(this.isSurge()||this.isLoon()||this.isStash())&&$httpClient.post(t,(t,s,i)=>{e(t,this.adapterStatus(s),i)}),this.isNode()&&this.node.request.post(t,(t,s,i)=>{e(t,this.adapterStatus(s),i)}),this.isJSBox()&&((t="string"==typeof t?{url:t}:t).header=t.headers,t.handler=function(t){let s=t.error,i=(s=s&&JSON.stringify(t.error),t.data);"object"==typeof i&&(i=JSON.stringify(t.data)),e(s,this.adapterStatus(t.response),i)},$http.post(t))}put(t,e=()=>{}){this.isQuanX()&&((t="string"==typeof t?{url:t}:t).method="PUT",$task.fetch(t).then(t=>{e(null,this.adapterStatus(t),t.body)},t=>e(t.error,null,null))),(this.isSurge()||this.isLoon()||this.isStash())&&(t.method="PUT",$httpClient.put(t,(t,s,i)=>{e(t,this.adapterStatus(s),i)})),this.isNode()&&(t.method="PUT",this.node.request.put(t,(t,s,i)=>{e(t,this.adapterStatus(s),i)})),this.isJSBox()&&((t="string"==typeof t?{url:t}:t).header=t.headers,t.handler=function(t){let s=t.error,i=(s=s&&JSON.stringify(t.error),t.data);"object"==typeof i&&(i=JSON.stringify(t.data)),e(s,this.adapterStatus(t.response),i)},$http.post(t))}costTime(){let t=this.name+"执行完毕!";this.isNode()&&this.isExecComm&&(t=`指令【${this.comm[1]}】执行完毕!`);var s=(new Date).getTime()-this.startTime,i=s/1e3;this.execCount++,this.costTotalMs+=s,this.log(`${t}耗时【${i}】秒\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 i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890",e=i.length,r="";for(let t=0;t<s;t++)r+=i.charAt(Math.floor(Math.random()*e));return r}autoComplete(s,t,i,e,r,o,h,n,a,l){if((s+="").length<r)for(;s.length<r;)0==o?s+=e:s=e+s;if(h){let t="";for(var p=0;p<n;p++)t+=l;s=s.substring(0,a)+t+s.substring(n+a)}return this.toDBC(s=t+s+i)}customReplace(t,s,i,e){try{for(var r in this.isEmpty(i)&&(i="#{"),this.isEmpty(e)&&(e="}"),s)t=t.replace(""+i+r+e,s[r])}catch(t){this.logErr(t)}return t}toDBC(t){for(var s="",i=0;i<t.length;i++)32==t.charCodeAt(i)?s+=String.fromCharCode(12288):t.charCodeAt(i)<127&&(s+=String.fromCharCode(t.charCodeAt(i)+65248));return s}hash(t){let s=0,i,e;for(i=0;i<t.length;i++)e=t.charCodeAt(i),s=(s<<5)-s+e,s|=0;return String(s)}formatDate(t,s){var i,e={"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(i in/(y+)/.test(s)&&(s=s.replace(RegExp.$1,(t.getFullYear()+"").substr(4-RegExp.$1.length))),e)new RegExp("("+i+")").test(s)&&(s=s.replace(RegExp.$1,1==RegExp.$1.length?e[i]:("00"+e[i]).substr((""+e[i]).length)));return s}objToQueryStr(s,i){let e="";for(const r in s){let t=s[r];null!=t&&""!==t&&("object"==typeof t?t=JSON.stringify(t):i&&(t=encodeURIComponent(t)),e+=`${r}=${t}&`)}return e=e.substring(0,e.length-1)}parseQueryStr(t){var s={},i=(t=-1<t.indexOf("?")?t.split("?")[1]:t).split("&");for(let t=0;t<i.length;t++){var e=i[t].split("=");s[e[0]]=e[1]}return s}deepClone(t,s){for(var i in s=s||{},t)"object"==typeof t[i]?(s[i]=t[i].constructor===Array?[]:{},this.deepClone(t[i],s[i])):s[i]=t[i];return s}}(t,s,i)}
  674. //ToolKit-end