MagicJS3.js 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. function MagicJS(scriptName = "MagicJS", logLevel = "INFO") {
  2. const MagicEnvironment = () => {
  3. const isLoon = typeof $loon !== "undefined";
  4. const isQuanX = typeof $task !== "undefined";
  5. const isNode = typeof module !== "undefined";
  6. const isSurge = typeof $httpClient !== "undefined" && !isLoon;
  7. const isStorm = typeof $storm !== "undefined";
  8. const isStash = typeof $environment !== "undefined" && typeof $environment["stash-build"] !== "undefined";
  9. const isSurgeLike = isSurge || isLoon || isStorm || isStash;
  10. const isScriptable = typeof importModule !== "undefined";
  11. return {
  12. isLoon: isLoon,
  13. isQuanX: isQuanX,
  14. isNode: isNode,
  15. isSurge: isSurge,
  16. isStorm: isStorm,
  17. isStash: isStash,
  18. isSurgeLike: isSurgeLike,
  19. isScriptable: isScriptable,
  20. get name() {
  21. if (isLoon) {
  22. return "Loon";
  23. } else if (isQuanX) {
  24. return "QuantumultX";
  25. } else if (isNode) {
  26. return "NodeJS";
  27. } else if (isSurge) {
  28. return "Surge";
  29. } else if (isScriptable) {
  30. return "Scriptable";
  31. } else {
  32. return "unknown";
  33. }
  34. },
  35. get build() {
  36. if (isSurge) {
  37. return $environment["surge-build"];
  38. } else if (isStash) {
  39. return $environment["stash-build"];
  40. } else if (isStorm) {
  41. return $storm.buildVersion;
  42. }
  43. },
  44. get language() {
  45. if (isSurge || isStash) {
  46. return $environment["language"];
  47. }
  48. },
  49. get version() {
  50. if (isSurge) {
  51. return $environment["surge-version"];
  52. } else if (isStash) {
  53. return $environment["stash-version"];
  54. } else if (isStorm) {
  55. return $storm.appVersion;
  56. } else if (isNode) {
  57. return process.version;
  58. }
  59. },
  60. get system() {
  61. if (isSurge) {
  62. return $environment["system"];
  63. } else if (isNode) {
  64. return process.platform;
  65. }
  66. },
  67. get systemVersion() {
  68. if (isStorm) {
  69. return $storm.systemVersion;
  70. }
  71. },
  72. get deviceName() {
  73. if (isStorm) {
  74. return $storm.deviceName;
  75. }
  76. }
  77. };
  78. };
  79. const MagicLogger = (scriptName, logLevel = "INFO") => {
  80. let _level = logLevel;
  81. let logSeparator = '\n';
  82. const logLevels = {
  83. SNIFFER: 6,
  84. DEBUG: 5,
  85. INFO: 4,
  86. NOTIFY: 3,
  87. WARNING: 2,
  88. ERROR: 1,
  89. CRITICAL: 0,
  90. NONE: -1
  91. };
  92. const logEmoji = {
  93. SNIFFER: "",
  94. DEBUG: "",
  95. INFO: "",
  96. NOTIFY: "",
  97. WARNING: "❗ ",
  98. ERROR: "❌ ",
  99. CRITICAL: "❌ ",
  100. NONE: ""
  101. };
  102. const _log = (msg, level = "INFO") => {
  103. // let level = "INFO";
  104. // if (logs.length > 1) {
  105. // let lastParam = logs[logs.length-1];
  106. // let leveArr = ["SNIFFER","DEBUG","INFO","NOTIFY","WARNING","ERROR","RETRY"];
  107. // if(typeof(lastParam) == 'string' && leveArr.indexOf(lastParam) > 0){
  108. // level = lastParam;
  109. // logs.length = logs.length-1;
  110. // }
  111. // }
  112. // let msg = logs.join('\n');
  113. if (!(logLevels[_level] < logLevels[level.toUpperCase()])) console.log(`██[${scriptName}][${level}]` + '' + `${logEmoji[level.toUpperCase()]}${msg}` + '\n' + ``);
  114. };
  115. const setLevel = logLevel => {
  116. _level = logLevel;
  117. };
  118. return {
  119. getLevel: () => {
  120. return _level;
  121. },
  122. setLevel: setLevel,
  123. sniffer: (...logs) => {
  124. let msg = logs.join(logSeparator);
  125. _log(msg, "SNIFFER");
  126. },
  127. log: (...logs) => {
  128. let msg = logs.join(logSeparator);
  129. console.log(`██[${scriptName}]` + '' + `${msg}` + '\n' + ``);
  130. },
  131. debug: (...logs) => {
  132. let msg = logs.join(logSeparator);
  133. _log(msg, "DEBUG");
  134. },
  135. info: (...logs) => {
  136. let msg = logs.join(logSeparator);
  137. _log(msg, "INFO");
  138. },
  139. notify: (...logs) => {
  140. let msg = logs.join(logSeparator);
  141. _log(msg, "NOTIFY");
  142. },
  143. warning: (...logs) => {
  144. let msg = logs.join(logSeparator);
  145. _log(msg, "WARNING");
  146. },
  147. error: (...logs) => {
  148. let msg = logs.join(logSeparator);
  149. _log(msg, "ERROR");
  150. },
  151. retry: (...logs) => {
  152. let msg = logs.join(logSeparator);
  153. _log(msg, "RETRY");
  154. }
  155. };
  156. };
  157. return new class {
  158. constructor(scriptName, logLevel) {
  159. this._startTime = Date.now();
  160. this.version = "3.0.0";
  161. this.scriptName = scriptName;
  162. this.env = MagicEnvironment();
  163. this.logger = MagicLogger(scriptName, logLevel);
  164. this.http = typeof MagicHttp === "function" ? MagicHttp(this.env, this.logger) : undefined;
  165. this.data = typeof MagicData === "function" ? MagicData(this.env, this.logger) : undefined;
  166. this.notification = typeof MagicNotification === "function" ? MagicNotification(this.scriptName, this.env, this.logger, this.http) : undefined;
  167. this.utils = typeof MagicUtils === "function" ? MagicUtils(this.env, this.logger) : undefined;
  168. this.qinglong = typeof MagicQingLong === "function" ? MagicQingLong(this.env, this.data, this.logger) : undefined;
  169. if (typeof this.data !== "undefined") {
  170. let magicLoglevel = this.data.read("magic_loglevel");
  171. const barkUrl = this.data.read("magic_bark_url");
  172. if (magicLoglevel) {
  173. this.logger.setLevel(magicLoglevel.toUpperCase());
  174. }
  175. if (barkUrl) {
  176. this.notification.setBark(barkUrl);
  177. }
  178. }
  179. this.logger.info(`${scriptName}, 开始执行!`);
  180. // this.checkRecordRequestBody();
  181. }
  182. get isRequest() {
  183. return typeof $request !== "undefined";
  184. }
  185. get isStrictRequest() {
  186. return typeof $request !== "undefined" && typeof $response === "undefined";
  187. }
  188. get isResponse() {
  189. return typeof $response !== "undefined";
  190. }
  191. get isDebug() {
  192. return this.logger.level === "DEBUG";
  193. }
  194. get request() {
  195. return typeof $request !== "undefined" ? $request : undefined;
  196. }
  197. get response() {
  198. if (typeof $response !== "undefined") {
  199. if ($response.hasOwnProperty("status")) $response["statusCode"] = $response["status"];
  200. if ($response.hasOwnProperty("statusCode")) $response["status"] = $response["statusCode"];
  201. return $response;
  202. } else {
  203. return undefined;
  204. }
  205. }
  206. log(...logs) {
  207. this.logger.log(logs);
  208. }
  209. toStr(data, defVal = null) {
  210. try {
  211. return JSON.stringify(data);
  212. } catch {
  213. return defVal;
  214. }
  215. }
  216. toObj(str, defVal = null) {
  217. try {
  218. return JSON.parse(str);
  219. } catch {
  220. return defVal;
  221. }
  222. }
  223. checkRecordRequestBody() {
  224. if (!this.isRequest) {
  225. return;
  226. }
  227. const reqBody = $request.body;
  228. if (!reqBody) {
  229. return;
  230. }
  231. const env = this.env;
  232. const path = $request.path;
  233. let cacheKey = this.scriptName + "#" + path.replace("/", "_");
  234. cacheKey = cacheKey.replace("?", "#");
  235. if (env.isQuanX) $prefs.setValueForKey(reqBody, cacheKey);
  236. if (env.isLoon || env.isSurge) $persistentStore.write(reqBody, cacheKey);
  237. if (env.isNode) {
  238. const node_fs = require("fs");
  239. node_fs.writeFileSync(
  240. `${cacheKey}.json`,
  241. reqBody,
  242. {
  243. flag: "w"
  244. },
  245. (err) => console.log(err)
  246. );
  247. }
  248. }
  249. getRequestBody() {
  250. const env = this.env;
  251. const path = $request.path;
  252. let cacheKey = this.scriptName + "#" + path.replace("/", "_");
  253. cacheKey = cacheKey.replace("?", "#");
  254. if (env.isSurge || env.isLoon) {
  255. return $persistentStore.read(cacheKey);
  256. }
  257. if (env.isQuanX) {
  258. return $prefs.valueForKey(cacheKey);
  259. }
  260. if (env.isNode) {
  261. const fpath = `${cacheKey}.json`;
  262. const node_fs = require("fs");
  263. if (!node_fs.existsSync(fpath)) {
  264. return JSON.parse(
  265. node_fs.readFileSync(fpath)
  266. );
  267. }
  268. }
  269. }
  270. getResponseBody() {
  271. if ($response) {
  272. return $response.body;
  273. }
  274. }
  275. // 解析cookie字符串的函数
  276. parseCookies(cookieString) {
  277. let dict = {};
  278. cookieString && cookieString.split(';').forEach(function (cookie) {
  279. let parts = cookie.split('=');
  280. dict[parts.shift().trim()] = decodeURI(parts.join('='));
  281. });
  282. return dict;
  283. }
  284. // 系列化为cookie字符串
  285. serializeCookies(cookieData) {
  286. const parts = [];
  287. for (let key in cookieData) {
  288. let value = cookieData[key];
  289. let cookiePart = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
  290. parts.push(cookiePart);
  291. }
  292. return parts.join('; ');
  293. }
  294. parseSetCookies(cookieString) {
  295. const attribKeys = ['Expires', 'Max-Age', 'Domain', 'Path', 'HttpOnly', 'SameSite'];
  296. const parts = cookieString.split(';');
  297. let mainKey = null;
  298. const retDict = {};
  299. const retData = [];
  300. parts.forEach(part => {
  301. let pstr = part.trim();
  302. let aKey = null;
  303. let aValue = true;
  304. if (pstr.includes('=')) {
  305. let kvdata = pstr.split('=');
  306. aKey = kvdata[0].trim();
  307. aValue = kvdata[1].trim();
  308. } else {
  309. aKey = pstr;
  310. }
  311. if (attribKeys.includes(aKey)) {
  312. if (retDict[mainKey]) {
  313. retDict[mainKey][aKey] = aValue;
  314. let attribs = retDict[mainKey].attribs;
  315. attribs[aKey] = aValue;
  316. }
  317. } else {
  318. mainKey = aKey;
  319. let attribs = {};
  320. if (mainKey.includes(',')) {
  321. const keys = mainKey.split(',');
  322. keys.forEach(key => {
  323. const k = key.trim();
  324. if (attribKeys.includes(k)) {
  325. attribs[k] = true;
  326. } else {
  327. mainKey = k;
  328. }
  329. });
  330. }
  331. retDict[mainKey] = { name: mainKey, value: aValue, attribs: attribs };
  332. retData.push(retDict[mainKey]);
  333. }
  334. });
  335. return retData;
  336. }
  337. objToQueryStr(obj, encode) {
  338. let str = '';
  339. for (const key in obj) {
  340. let value = obj[key];
  341. if (value != null && value !== '') {
  342. if (typeof value === 'object') {
  343. value = JSON.stringify(value);
  344. } else if (encode) {
  345. value = encodeURIComponent(value);
  346. }
  347. str += `${key}=${value}&`;
  348. }
  349. }
  350. str = str.substring(0, str.length - 1);
  351. return str;
  352. }
  353. parseQueryStr(str) {
  354. let obj = {};
  355. if (str.indexOf("?") > -1) {
  356. str = str.split("?")[1];
  357. }
  358. let arr = str.split("&");
  359. for (let i = 0; i < arr.length; i++) {
  360. let kv = arr[i].split("=");
  361. obj[kv[0]] = kv[1];
  362. }
  363. return obj;
  364. }
  365. deepClone(obj, newObj) {
  366. newObj = newObj || {};
  367. for (let key in obj) {
  368. if (typeof obj[key] == 'object') {
  369. newObj[key] = (obj[key].constructor === Array) ? [] : {};
  370. this.deepClone(obj[key], newObj[key]);
  371. } else {
  372. newObj[key] = obj[key];
  373. }
  374. }
  375. return newObj;
  376. }
  377. /**
  378. * formatDate y:年 M:月 d:日 q:季 H:时 m:分 s:秒 S:毫秒
  379. */
  380. formatDate(date, format) {
  381. let o = {
  382. 'M+': date.getMonth() + 1,
  383. 'd+': date.getDate(),
  384. 'H+': date.getHours(),
  385. 'm+': date.getMinutes(),
  386. 's+': date.getSeconds(),
  387. 'q+': Math.floor((date.getMonth() + 3) / 3),
  388. 'S': date.getMilliseconds()
  389. }
  390. if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  391. for (let k in o)
  392. if (new RegExp('(' + k + ')').test(format))
  393. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  394. return format
  395. }
  396. /**
  397. * parseDate 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
  398. */
  399. parseDate(str, format) {
  400. format = format || 'yyyy-MM-dd';
  401. let obj = { y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0 };
  402. format.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function (m, $1, $2, $3, $4, idx, old) {
  403. str = str.replace(new RegExp($1 + '(\\d{' + $2.length + '})' + $4), function (_m, _$1) {
  404. obj[$3] = parseInt(_$1);
  405. return '';
  406. });
  407. return '';
  408. });
  409. obj.M--; // 月份是从0开始的,所以要减去1
  410. let date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
  411. if (obj.S !== 0) date.setMilliseconds(obj.S); // 如果设置了毫秒
  412. return date;
  413. }
  414. getBaseDoneHeaders(mixHeaders = {}) {
  415. return Object.assign(
  416. {
  417. 'Access-Control-Allow-Origin': '*',
  418. 'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PUT,DELETE',
  419. 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
  420. },
  421. mixHeaders
  422. )
  423. }
  424. getHtmlDoneHeaders() {
  425. return this.getBaseDoneHeaders({
  426. 'Content-Type': 'text/html;charset=UTF-8'
  427. })
  428. }
  429. getJsonDoneHeaders() {
  430. return this.getBaseDoneHeaders({
  431. 'Content-Type': 'text/json; charset=utf-8',
  432. 'Connection': 'keep-alive'
  433. })
  434. }
  435. /**
  436. * 推送微信消息
  437. * 管理后台 https://wxpusher.zjiecode.com/admin/
  438. * 通用助手 AT_7wDWqSoT8xpJCQqJtHpshKhw7kXc0XCW
  439. * 光予助手 AT_rTc93GQYIdMU8XLRnoJaSea8WkfhSzhX
  440. * i茅台助手 AT_6b8KjFF3bYqcr7Cv7woUUES7KadNFbvR
  441. * 个人uid UID_6P4B00X6Zv8U2oKC0I2R09emxtqq
  442. */
  443. doWxpusherSend(data) {
  444. // let data = {
  445. // appToken: "AT_rTc93GQYIdMU8XLRnoJaSea8WkfhSzhX",
  446. // content: content,// 这是主体内容
  447. // summary: summary,// 该参数可选,默认为 msg 的前10个字符
  448. // contentType: 1,
  449. // topicIds: [],
  450. // uids: [
  451. // "UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"
  452. // ],
  453. // url: "",
  454. // verifyPay: false
  455. // };
  456. // if (url) {
  457. // data.url = url;
  458. // }
  459. const headers = this.getJsonDoneHeaders();
  460. headers.Host = 'wxpusher.zjiecode.com';
  461. headers['Content-Type'] = 'application/json;charset=UTF-8';
  462. let options = {
  463. url: 'https://wxpusher.zjiecode.com/api/send/message',
  464. headers: headers,
  465. body: JSON.stringify(data),
  466. };
  467. return this.http.post(options);
  468. }
  469. fastWxpusherSend(content, summary = "", url = "") {
  470. let data = {
  471. appToken: "AT_7wDWqSoT8xpJCQqJtHpshKhw7kXc0XCW",
  472. content: content,// 这是主体内容
  473. summary: summary,// 该参数可选,默认为 msg 的前10个字符
  474. contentType: 1,
  475. topicIds: [82088],
  476. uids: [
  477. "UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"
  478. ],
  479. url: url,
  480. // verifyPay: false,
  481. verifyPayType: 0,
  482. };
  483. return this.doWxpusherSend(data);
  484. }
  485. isEmpty(obj) {
  486. return typeof obj == "undefined" || obj == null || obj == "" || obj == "null" || obj == "undefined" || obj.length === 0
  487. }
  488. base64Decode(input) {
  489. const base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  490. // 确保输入是一个正确的Base64编码字符串
  491. if (/([^\s]+[^0-9a-zA-Z\+\/\=]|[^0-9a-zA-Z\+\/\=]\s+)/.test(input)) {
  492. throw new Error('Invalid base64 input');
  493. }
  494. let str = input.replace(/\s/g, '');
  495. let output = '';
  496. let chr1, chr2, chr3;
  497. let enc1, enc2, enc3, enc4;
  498. let i = 0;
  499. while (i < str.length) {
  500. enc1 = base64_chars.indexOf(str.charAt(i++));
  501. enc2 = base64_chars.indexOf(str.charAt(i++));
  502. enc3 = base64_chars.indexOf(str.charAt(i++));
  503. enc4 = base64_chars.indexOf(str.charAt(i++));
  504. chr1 = (enc1 << 2) | (enc2 >> 4);
  505. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  506. chr3 = ((enc3 & 3) << 6) | enc4;
  507. output = output + String.fromCharCode(chr1);
  508. if (enc3 !== 64) {
  509. output = output + String.fromCharCode(chr2);
  510. }
  511. if (enc4 !== 64) {
  512. output = output + String.fromCharCode(chr3);
  513. }
  514. }
  515. output = this.utf8Decode(output);
  516. return output;
  517. }
  518. utf8Decode(str_data) {
  519. let tmp_arr = [],
  520. i = 0,
  521. c1 = 0,
  522. seqlen = 0;
  523. str_data = str_data.replace(/\r\n/g, "\n");
  524. while (i < str_data.length) {
  525. c1 = str_data.charCodeAt(i) & 0xFF;
  526. seqlen = 0;
  527. // Single byte sequence (0xxxxxxx)
  528. if (c1 <= 0xBF) {
  529. c1 = (c1 & 0x7F);
  530. seqlen = 1;
  531. } else if (c1 <= 0xDF) {
  532. c1 = (c1 & 0x1F);
  533. seqlen = 2;
  534. } else if (c1 <= 0xEF) {
  535. c1 = (c1 & 0x0F);
  536. seqlen = 3;
  537. } else {
  538. c1 = (c1 & 0x07);
  539. seqlen = 4;
  540. }
  541. for (let ai = 1; ai < seqlen; ++ai) {
  542. c1 = ((c1 << 0x06) | (str_data.charCodeAt(ai + i) & 0x3F));
  543. }
  544. if (seqlen === 4) {
  545. c1 -= 0x10000;
  546. tmp_arr.push(String.fromCharCode(0xD800 | ((c1 >> 10) & 0x3FF)));
  547. tmp_arr.push(String.fromCharCode(0xDC00 | (c1 & 0x3FF)));
  548. } else {
  549. tmp_arr.push(String.fromCharCode(c1));
  550. }
  551. i += seqlen;
  552. }
  553. return tmp_arr.join("");
  554. }
  555. parseJwt(token) {
  556. try {
  557. const segments = token.split('.');
  558. const base64HeaderUrl = segments[0];
  559. const base64Header = base64HeaderUrl.replace(/-/g, '+').replace(/_/g, '/');
  560. const jsonStrHeader = this.base64Decode(base64Header).replace(/\0/g, '');
  561. const headerData = JSON.parse(jsonStrHeader);
  562. const base64PayloadUrl = segments[1];
  563. const base64Payload = base64PayloadUrl.replace(/-/g, '+').replace(/_/g, '/');
  564. const jsonStrPayload = this.base64Decode(base64Payload).replace(/\0/g, '');
  565. const payloadData = JSON.parse(jsonStrPayload);
  566. return {
  567. header: headerData,
  568. payload: payloadData,
  569. signature: segments[2],
  570. };
  571. } catch (e) {
  572. this.log(e);
  573. return null;
  574. }
  575. }
  576. costTime() {
  577. let info = `${this.scriptName}执行完毕!`
  578. // if (this.isNode && this.isExecComm) {
  579. // info = `指令【${this.comm[1]}】执行完毕!`
  580. // }
  581. this._endTime = new Date().getTime();
  582. const ms = this._endTime - this._startTime;
  583. const costTime = ms / 1000;
  584. this.logger.info(`${info}耗时【${costTime}】秒`);
  585. }
  586. done = (value = {}) => {
  587. // this._endTime = Date.now();
  588. // let span = (this._endTime - this._startTime) / 1e3;
  589. // this.logger.info(`SCRIPT COMPLETED: ${span} S.`);
  590. this.costTime();
  591. if (typeof $done !== "undefined") {
  592. $done(value);
  593. }
  594. };
  595. }(scriptName, logLevel);
  596. }
  597. function MagicHttp(env, logger) {
  598. const phoneUA = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Mobile/15E148 Safari/604.1";
  599. const computerUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59";
  600. let axiosInstance;
  601. if (env.isNode) {
  602. const axios = require("axios");
  603. axiosInstance = axios.create();
  604. }
  605. class InterceptorManager {
  606. constructor(isRequest = true) {
  607. this.handlers = [];
  608. this.isRequest = isRequest;
  609. }
  610. use(fulfilled, rejected, options) {
  611. if (typeof fulfilled === "function") {
  612. logger.debug(`Register fulfilled ${fulfilled.name}`);
  613. }
  614. if (typeof rejected === "function") {
  615. logger.debug(`Register rejected ${rejected.name}`);
  616. }
  617. this.handlers.push({
  618. fulfilled: fulfilled,
  619. rejected: rejected,
  620. synchronous: options && typeof options.synchronous === "boolean" ? options.synchronous : false,
  621. runWhen: options ? options.runWhen : null
  622. });
  623. return this.handlers.length - 1;
  624. }
  625. eject(id) {
  626. if (this.handlers[id]) {
  627. this.handlers[id] = null;
  628. }
  629. }
  630. forEach(fn) {
  631. this.handlers.forEach(element => {
  632. if (element !== null) {
  633. fn(element);
  634. }
  635. });
  636. }
  637. }
  638. function paramsToQueryString(config) {
  639. let _config = {
  640. ...config
  641. };
  642. if (!!_config.params) {
  643. if (!env.isNode) {
  644. let qs = Object.keys(_config.params).map(key => {
  645. const encodeKey = encodeURIComponent(key);
  646. _config.url = _config.url.replace(new RegExp(`${key}=[^&]*`, "ig"), "");
  647. _config.url = _config.url.replace(new RegExp(`${encodeKey}=[^&]*`, "ig"), "");
  648. return `${encodeKey}=${encodeURIComponent(_config.params[key])}`;
  649. }).join("&");
  650. if (_config.url.indexOf("?") < 0) _config.url += "?";
  651. if (!/(&|\?)$/g.test(_config.url)) {
  652. _config.url += "&";
  653. }
  654. _config.url += qs;
  655. delete _config.params;
  656. logger.debug(`Params to QueryString: ${_config.url}`);
  657. }
  658. }
  659. return _config;
  660. }
  661. const mergeConfig = (method, configOrUrl) => {
  662. let config = typeof configOrUrl === "object" ? {
  663. headers: {},
  664. ...configOrUrl
  665. } : {
  666. url: configOrUrl,
  667. headers: {}
  668. };
  669. if (!config.method) {
  670. config["method"] = method;
  671. }
  672. config = paramsToQueryString(config);
  673. if (config["rewrite"] === true) {
  674. if (env.isSurge) {
  675. config.headers["X-Surge-Skip-Scripting"] = false;
  676. delete config["rewrite"];
  677. } else if (env.isQuanX) {
  678. config["hints"] = false;
  679. delete config["rewrite"];
  680. }
  681. }
  682. if (env.isSurgeLike) {
  683. const contentType = config.headers["content-type"] || config.headers["Content-Type"];
  684. if (config["method"] !== "GET" && contentType && contentType.indexOf("application/json") >= 0 && config.body instanceof Array) {
  685. config.body = JSON.stringify(config.body);
  686. logger.debug(`Convert Array object to String: ${config.body}`);
  687. }
  688. } else if (env.isQuanX) {
  689. if (config.hasOwnProperty("body") && typeof config["body"] !== "string") config["body"] = JSON.stringify(config["body"]);
  690. config["method"] = method;
  691. } else if (env.isNode) {
  692. if (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE") {
  693. config.data = config.data || config.body;
  694. } else if (method === "GET") {
  695. config.params = config.params || config.body;
  696. }
  697. delete config.body;
  698. }
  699. return config;
  700. };
  701. const modifyResponse = (resp, config = null) => {
  702. if (resp) {
  703. let _resp = {
  704. ...resp,
  705. config: resp.config || config,
  706. status: resp.statusCode || resp.status,
  707. body: resp.body || resp.data,
  708. headers: resp.headers || resp.header
  709. };
  710. if (typeof _resp.body === "string") {
  711. try {
  712. _resp.body = JSON.parse(_resp.body);
  713. } catch { }
  714. }
  715. delete _resp.data;
  716. return _resp;
  717. } else {
  718. return resp;
  719. }
  720. };
  721. const convertHeadersToLowerCase = headers => {
  722. return Object.keys(headers).reduce((acc, key) => {
  723. acc[key.toLowerCase()] = headers[key];
  724. return acc;
  725. }, {});
  726. };
  727. const convertHeadersToCamelCase = headers => {
  728. return Object.keys(headers).reduce((acc, key) => {
  729. const newKey = key.split("-").map(word => word[0].toUpperCase() + word.slice(1)).join("-");
  730. acc[newKey] = headers[key];
  731. return acc;
  732. }, {});
  733. };
  734. const raiseExceptionByStatusCode = (resp, config = null) => {
  735. if (!!resp && resp.status >= 400) {
  736. logger.debug(`Raise exception when status code is ${resp.status}`);
  737. return {
  738. name: "RequestException",
  739. message: `Request failed with status code ${resp.status}`,
  740. config: config || resp.config,
  741. response: resp
  742. };
  743. }
  744. };
  745. const interceptors = {
  746. request: new InterceptorManager(),
  747. response: new InterceptorManager(false)
  748. };
  749. let requestInterceptorChain = [];
  750. let responseInterceptorChain = [];
  751. let synchronousRequestInterceptors = true;
  752. function interceptConfig(config) {
  753. config = paramsToQueryString(config);
  754. logger.debug(`HTTP ${config["method"].toUpperCase()}:` + '\n' + `${JSON.stringify(config)}`);
  755. return config;
  756. }
  757. function interceptResponse(resp) {
  758. try {
  759. resp = !!resp ? modifyResponse(resp) : resp;
  760. logger.sniffer(`HTTP ${resp.config["method"].toUpperCase()}:` + '\n' + `${JSON.stringify(resp.config)}` + '\n' + `STATUS CODE:` + '\n' + `${resp.status}` + '\n' + `RESPONSE:` + '\n' + `${typeof resp.body === "object" ? JSON.stringify(resp.body) : resp.body}`);
  761. const err = raiseExceptionByStatusCode(resp);
  762. if (!!err) {
  763. return Promise.reject(err);
  764. }
  765. return resp;
  766. } catch (err) {
  767. logger.error(err);
  768. return resp;
  769. }
  770. }
  771. const registerInterceptors = config => {
  772. try {
  773. requestInterceptorChain = [];
  774. responseInterceptorChain = [];
  775. interceptors.request.forEach(interceptor => {
  776. if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
  777. return;
  778. }
  779. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  780. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  781. });
  782. interceptors.response.forEach(interceptor => {
  783. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  784. });
  785. } catch (err) {
  786. logger.error(`Failed to register interceptors: ${err}.`);
  787. }
  788. };
  789. const request = (method, config) => {
  790. let dispatchRequest;
  791. const _method = method.toUpperCase();
  792. config = mergeConfig(_method, config);
  793. if (env.isNode) {
  794. dispatchRequest = axiosInstance;
  795. } else {
  796. if (env.isSurgeLike) {
  797. dispatchRequest = config => {
  798. return new Promise((resolve, reject) => {
  799. $httpClient[method.toLowerCase()](config, (err, resp, body) => {
  800. if (err) {
  801. let newErr = {
  802. name: err.name || err,
  803. message: err.message || err,
  804. stack: err.stack || err,
  805. config: config,
  806. response: modifyResponse(resp)
  807. };
  808. reject(newErr);
  809. } else {
  810. resp.config = config;
  811. resp.body = body;
  812. resolve(resp);
  813. }
  814. });
  815. });
  816. };
  817. } else {
  818. dispatchRequest = config => {
  819. return new Promise((resolve, reject) => {
  820. $task.fetch(config).then(resp => {
  821. resp = modifyResponse(resp, config);
  822. const err = raiseExceptionByStatusCode(resp, config);
  823. if (err) {
  824. return Promise.reject(err);
  825. }
  826. resolve(resp);
  827. }).catch(err => {
  828. let newErr = {
  829. name: err.message || err.error,
  830. message: err.message || err.error,
  831. stack: err.error,
  832. config: config,
  833. response: !!err.response ? modifyResponse(err.response) : null
  834. };
  835. reject(newErr);
  836. });
  837. });
  838. };
  839. }
  840. }
  841. let promise;
  842. registerInterceptors(config);
  843. const defaultRequestInterceptors = [interceptConfig, undefined];
  844. const defaultResponseInterceptors = [interceptResponse, undefined];
  845. if (!synchronousRequestInterceptors) {
  846. logger.debug("Interceptors are executed in asynchronous mode");
  847. let chain = [dispatchRequest, undefined];
  848. Array.prototype.unshift.apply(chain, defaultRequestInterceptors);
  849. Array.prototype.unshift.apply(chain, requestInterceptorChain);
  850. chain = chain.concat(defaultResponseInterceptors);
  851. chain = chain.concat(responseInterceptorChain);
  852. promise = Promise.resolve(config);
  853. while (chain.length) {
  854. try {
  855. let onFulfilled = chain.shift();
  856. let onRejected = chain.shift();
  857. if (!env.isNode && config["timeout"] && onFulfilled === dispatchRequest) {
  858. onFulfilled = requestTimeout;
  859. }
  860. if (typeof onFulfilled === "function") {
  861. logger.debug(`Executing request fulfilled ${onFulfilled.name}`);
  862. }
  863. if (typeof onRejected === "function") {
  864. logger.debug(`Executing request rejected ${onRejected.name}`);
  865. }
  866. promise = promise.then(onFulfilled, onRejected);
  867. } catch (err) {
  868. logger.error(`request exception: ${err}`);
  869. }
  870. }
  871. return promise;
  872. } else {
  873. logger.debug("Interceptors are executed in synchronous mode");
  874. Array.prototype.unshift.apply(requestInterceptorChain, defaultRequestInterceptors);
  875. requestInterceptorChain = requestInterceptorChain.concat([interceptConfig, undefined]);
  876. while (requestInterceptorChain.length) {
  877. let onFulfilled = requestInterceptorChain.shift();
  878. let onRejected = requestInterceptorChain.shift();
  879. try {
  880. if (typeof onFulfilled === "function") {
  881. logger.debug(`Executing request fulfilled ${onFulfilled.name}`);
  882. }
  883. config = onFulfilled(config);
  884. } catch (error) {
  885. if (typeof onRejected === "function") {
  886. logger.debug(`Executing request rejected ${onRejected.name}`);
  887. }
  888. onRejected(error);
  889. break;
  890. }
  891. }
  892. try {
  893. if (!env.isNode && config["timeout"]) {
  894. promise = requestTimeout(config);
  895. } else {
  896. promise = dispatchRequest(config);
  897. }
  898. } catch (err) {
  899. return Promise.reject(err);
  900. }
  901. Array.prototype.unshift.apply(responseInterceptorChain, defaultResponseInterceptors);
  902. while (responseInterceptorChain.length) {
  903. promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
  904. }
  905. return promise;
  906. }
  907. function requestTimeout(config) {
  908. try {
  909. const timer = new Promise((_, reject) => {
  910. setTimeout(() => {
  911. let err = {
  912. message: `timeout of ${config["timeout"]}ms exceeded.`,
  913. config: config
  914. };
  915. reject(err);
  916. }, config["timeout"]);
  917. });
  918. return Promise.race([dispatchRequest(config), timer]);
  919. } catch (err) {
  920. logger.error(`Request Timeout exception: ${err}.`);
  921. }
  922. }
  923. };
  924. return {
  925. request: request,
  926. interceptors: interceptors,
  927. convertHeadersToLowerCase: convertHeadersToLowerCase,
  928. convertHeadersToCamelCase: convertHeadersToCamelCase,
  929. modifyResponse: modifyResponse,
  930. get: configOrUrl => {
  931. return request("GET", configOrUrl);
  932. },
  933. post: configOrUrl => {
  934. return request("POST", configOrUrl);
  935. },
  936. put: configOrUrl => {
  937. return request("PUT", configOrUrl);
  938. },
  939. patch: configOrUrl => {
  940. return request("PATCH", configOrUrl);
  941. },
  942. delete: configOrUrl => {
  943. return request("DELETE", configOrUrl);
  944. },
  945. head: configOrUrl => {
  946. return request("HEAD", configOrUrl);
  947. },
  948. options: configOrUrl => {
  949. return request("OPTIONS", configOrUrl);
  950. }
  951. };
  952. }
  953. function MagicData(env, logger) {
  954. let node = {
  955. fs: undefined,
  956. data: {}
  957. };
  958. if (env.isNode) {
  959. node.fs = require("fs");
  960. try {
  961. node.fs.accessSync("./magic.json", node.fs.constants.R_OK | node.fs.constants.W_OK);
  962. } catch (err) {
  963. node.fs.writeFileSync("./magic.json", "{}", {
  964. encoding: "utf8"
  965. });
  966. }
  967. node.data = require("./magic.json");
  968. }
  969. const defaultValueComparator = (oldVal, newVal) => {
  970. if (typeof newVal === "object") {
  971. return false;
  972. } else {
  973. return oldVal === newVal;
  974. }
  975. };
  976. const _typeConvertor = val => {
  977. if (val === "true") {
  978. return true;
  979. } else if (val === "false") {
  980. return false;
  981. } else if (typeof val === "undefined") {
  982. return null;
  983. } else {
  984. return val;
  985. }
  986. };
  987. const _valConvertor = (val, default_, session, read_no_session) => {
  988. if (session) {
  989. try {
  990. if (typeof val === "string") val = JSON.parse(val);
  991. if (val["magic_session"] === true) {
  992. val = val[session];
  993. } else {
  994. val = null;
  995. }
  996. } catch {
  997. val = null;
  998. }
  999. }
  1000. if (typeof val === "string" && val !== "null") {
  1001. try {
  1002. val = JSON.parse(val);
  1003. } catch { }
  1004. }
  1005. if (read_no_session === false && !!val && val["magic_session"] === true) {
  1006. val = null;
  1007. }
  1008. if ((val === null || typeof val === "undefined") && default_ !== null && typeof default_ !== "undefined") {
  1009. val = default_;
  1010. }
  1011. val = _typeConvertor(val);
  1012. return val;
  1013. };
  1014. const convertToObject = obj => {
  1015. if (typeof obj === "string") {
  1016. let data = {};
  1017. try {
  1018. data = JSON.parse(obj);
  1019. const type = typeof data;
  1020. if (type !== "object" || data instanceof Array || type === "bool" || data === null) {
  1021. data = {};
  1022. }
  1023. } catch { }
  1024. return data;
  1025. } else if (obj instanceof Array || obj === null || typeof obj === "undefined" || obj !== obj || typeof obj === "boolean") {
  1026. return {};
  1027. } else {
  1028. return obj;
  1029. }
  1030. };
  1031. const readForNode = (key, default_ = null, session = "", read_no_session = false, externalData = null) => {
  1032. let data = externalData || node.data;
  1033. if (!!data && typeof data[key] !== "undefined" && data[key] !== null) {
  1034. val = data[key];
  1035. } else {
  1036. val = !!session ? {} : null;
  1037. }
  1038. val = _valConvertor(val, default_, session, read_no_session);
  1039. return val;
  1040. };
  1041. const read = (key, default_ = null, session = "", read_no_session = false, externalData = null) => {
  1042. let val = "";
  1043. if (externalData || env.isNode) {
  1044. val = readForNode(key, default_, session, read_no_session, externalData);
  1045. } else {
  1046. if (env.isSurgeLike) {
  1047. val = $persistentStore.read(key);
  1048. } else if (env.isQuanX) {
  1049. val = $prefs.valueForKey(key);
  1050. }
  1051. val = _valConvertor(val, default_, session, read_no_session);
  1052. }
  1053. logger.debug(`READ DATA [${key}]${!!session ? `[${session}]` : ""} <${typeof val}>` + '\n' + `${JSON.stringify(val)}`);
  1054. return val;
  1055. };
  1056. const writeForNode = (key, val, session = "", externalData = null) => {
  1057. let data = externalData || node.data;
  1058. data = convertToObject(data);
  1059. if (!!session) {
  1060. let obj = convertToObject(data[key]);
  1061. obj["magic_session"] = true;
  1062. obj[session] = val;
  1063. data[key] = obj;
  1064. } else {
  1065. data[key] = val;
  1066. }
  1067. if (externalData !== null) {
  1068. externalData = data;
  1069. }
  1070. return data;
  1071. };
  1072. const write = (key, val, session = "", externalData = null) => {
  1073. if (typeof val === "undefined" || val !== val) {
  1074. return false;
  1075. }
  1076. if (!env.isNode && (typeof val === "boolean" || typeof val === "number")) {
  1077. val = String(val);
  1078. }
  1079. let data = "";
  1080. if (externalData || env.isNode) {
  1081. data = writeForNode(key, val, session, externalData);
  1082. } else {
  1083. if (!session) {
  1084. data = val;
  1085. } else {
  1086. if (env.isSurgeLike) {
  1087. data = !!$persistentStore.read(key) ? $persistentStore.read(key) : data;
  1088. } else if (env.isQuanX) {
  1089. data = !!$prefs.valueForKey(key) ? $prefs.valueForKey(key) : data;
  1090. }
  1091. data = convertToObject(data);
  1092. data["magic_session"] = true;
  1093. data[session] = val;
  1094. }
  1095. }
  1096. if (!!data && typeof data === "object") {
  1097. data = JSON.stringify(data, null, 4);
  1098. }
  1099. logger.debug(`WRITE DATA [${key}]${session ? `[${session}]` : ""} <${typeof val}>` + '\n' + `${JSON.stringify(val)}`);
  1100. if (!externalData) {
  1101. if (env.isSurgeLike) {
  1102. return $persistentStore.write(data, key);
  1103. } else if (env.isQuanX) {
  1104. return $prefs.setValueForKey(data, key);
  1105. } else if (env.isNode) {
  1106. try {
  1107. node.fs.writeFileSync("./magic.json", data);
  1108. return true;
  1109. } catch (err) {
  1110. logger.error(err);
  1111. return false;
  1112. }
  1113. }
  1114. }
  1115. return true;
  1116. };
  1117. const update = (key, val, session, comparator = defaultValueComparator, externalData = null) => {
  1118. val = _typeConvertor(val);
  1119. const oldValue = read(key, null, session, false, externalData);
  1120. if (comparator(oldValue, val) === true) {
  1121. return false;
  1122. } else {
  1123. const result = write(key, val, session, externalData);
  1124. let newVal = read(key, null, session, false, externalData);
  1125. if (comparator === defaultValueComparator && typeof newVal === "object") {
  1126. return result;
  1127. }
  1128. return comparator(val, newVal);
  1129. }
  1130. };
  1131. const delForNode = (key, session, externalData) => {
  1132. let data = externalData || node.data;
  1133. data = convertToObject(data);
  1134. if (!!session) {
  1135. obj = convertToObject(data[key]);
  1136. delete obj[session];
  1137. data[key] = obj;
  1138. } else {
  1139. delete data[key];
  1140. }
  1141. if (!!externalData) {
  1142. externalData = data;
  1143. }
  1144. return data;
  1145. };
  1146. const del = (key, session = "", externalData = null) => {
  1147. let data = {};
  1148. if (externalData || env.isNode) {
  1149. data = delForNode(key, session, externalData);
  1150. if (!externalData) {
  1151. node.fs.writeFileSync("./magic.json", JSON.stringify(data, null, 4));
  1152. } else {
  1153. externalData = data;
  1154. }
  1155. } else {
  1156. if (!session) {
  1157. if (env.isStorm) {
  1158. return $persistentStore.remove(key);
  1159. } else if (env.isSurgeLike) {
  1160. return $persistentStore.write(null, key);
  1161. } else if (env.isQuanX) {
  1162. return $prefs.removeValueForKey(key);
  1163. }
  1164. } else {
  1165. if (env.isSurgeLike) {
  1166. data = $persistentStore.read(key);
  1167. } else if (env.isQuanX) {
  1168. data = $prefs.valueForKey(key);
  1169. }
  1170. data = convertToObject(data);
  1171. delete data[session];
  1172. const json = JSON.stringify(data, null, 4);
  1173. write(key, json);
  1174. }
  1175. }
  1176. logger.debug(`DELETE KEY [${key}]${!!session ? `[${session}]` : ""}`);
  1177. };
  1178. const allSessionNames = (key, externalData = null) => {
  1179. let _sessions = [];
  1180. let data = read(key, null, null, true, externalData);
  1181. data = convertToObject(data);
  1182. if (data["magic_session"] !== true) {
  1183. _sessions = [];
  1184. } else {
  1185. _sessions = Object.keys(data).filter(key => key !== "magic_session");
  1186. }
  1187. logger.debug(`READ ALL SESSIONS [${key}] <${typeof _sessions}>` + '\n' + `${JSON.stringify(_sessions, null, 4)}`);
  1188. return _sessions;
  1189. };
  1190. const allSessions = (key, externalData = null) => {
  1191. let _sessions = {};
  1192. let data = read(key, null, null, true, externalData);
  1193. data = convertToObject(data);
  1194. if (data["magic_session"] === true) {
  1195. _sessions = {
  1196. ...data
  1197. };
  1198. delete _sessions["magic_session"];
  1199. }
  1200. logger.debug(`READ ALL SESSIONS [${key}] <${typeof _sessions}>` + '\n' + `${JSON.stringify(_sessions, null, 4)}`);
  1201. return _sessions;
  1202. };
  1203. return {
  1204. read: read,
  1205. write: write,
  1206. del: del,
  1207. update: update,
  1208. allSessions: allSessions,
  1209. allSessionNames: allSessionNames,
  1210. defaultValueComparator: defaultValueComparator,
  1211. convertToObject: convertToObject
  1212. };
  1213. }
  1214. function MagicNotification(scriptName, env, logger, http) {
  1215. let _barkUrl = null;
  1216. let _barkKey = null;
  1217. let notifyInfo = []
  1218. const setBark = url => {
  1219. try {
  1220. let _url = url.replace(/\/+$/g, "");
  1221. _barkUrl = `${/^https?:\/\/([^/]*)/.exec(_url)[0]}/push`;
  1222. _barkKey = /\/([^\/]+)\/?$/.exec(_url)[1];
  1223. } catch (ex) {
  1224. logger.error(`Bark url error: ${ex}.`);
  1225. }
  1226. };
  1227. function appendNotifyInfo(info, type) {
  1228. if (type == 1) {
  1229. notifyInfo = info
  1230. } else {
  1231. notifyInfo.push(info)
  1232. }
  1233. }
  1234. function prependNotifyInfo(info) {
  1235. notifyInfo.splice(0, 0, info)
  1236. }
  1237. function msg(subtitle, message, openUrl, mediaUrl) {
  1238. let opts = {};
  1239. if (openUrl) {
  1240. opts["open-url"] = openUrl;
  1241. }
  1242. if (mediaUrl) {
  1243. opts["media-url"] = mediaUrl;
  1244. }
  1245. if (!message || message.length == 0) {
  1246. if (Array.isArray(notifyInfo)) {
  1247. message = notifyInfo.join("\n");
  1248. } else {
  1249. message = notifyInfo;
  1250. }
  1251. }
  1252. if (message && message.length > 0) {
  1253. post(scriptName, "", message, opts);
  1254. }
  1255. }
  1256. function post(title = scriptName, subTitle = "", body = "", opts = "") {
  1257. const _adaptOpts = _opts => {
  1258. try {
  1259. let newOpts = {};
  1260. if (typeof _opts === "string") {
  1261. if (_opts.length > 0) {
  1262. if (env.isLoon) {
  1263. newOpts = {
  1264. openUrl: _opts
  1265. };
  1266. } else if (env.isQuanX) {
  1267. newOpts = {
  1268. "open-url": _opts
  1269. };
  1270. } else if (env.isSurge) {
  1271. newOpts = {
  1272. url: _opts
  1273. };
  1274. }
  1275. }
  1276. } else if (typeof _opts === "object") {
  1277. if (env.isLoon) {
  1278. newOpts["openUrl"] = !!_opts["open-url"] ? _opts["open-url"] : "";
  1279. newOpts["mediaUrl"] = !!_opts["media-url"] ? _opts["media-url"] : "";
  1280. } else if (env.isQuanX) {
  1281. newOpts = !!_opts["open-url"] || !!_opts["media-url"] ? _opts : {};
  1282. } else if (env.isSurge) {
  1283. let openUrl = _opts["open-url"] || _opts["openUrl"];
  1284. newOpts = openUrl ? {
  1285. url: openUrl
  1286. } : {};
  1287. }
  1288. }
  1289. return newOpts;
  1290. } catch (err) {
  1291. logger.error(`通知选项转换失败${err}`);
  1292. }
  1293. return _opts;
  1294. };
  1295. opts = _adaptOpts(opts);
  1296. if (arguments.length === 1) {
  1297. title = scriptName;
  1298. subTitle = "", body = arguments[0];
  1299. }
  1300. logger.notify('\n' + `title:${title}` + '\n' + `subTitle:${subTitle}` + '\n' + `body:${body}` + '\n' + `options:${typeof opts === "object" ? JSON.stringify(opts) : opts}`);
  1301. if (env.isSurge) {
  1302. $notification.post(title, subTitle, body, opts);
  1303. } else if (env.isLoon) {
  1304. if (!!opts) $notification.post(title, subTitle, body, opts); else $notification.post(title, subTitle, body);
  1305. } else if (env.isQuanX) {
  1306. $notify(title, subTitle, body, opts);
  1307. }
  1308. if (_barkUrl && _barkKey) {
  1309. bark(title, subTitle, body);
  1310. }
  1311. }
  1312. function debug(title = scriptName, subTitle = "", body = "", opts = "") {
  1313. if (logger.getLevel() === "DEBUG") {
  1314. if (arguments.length === 1) {
  1315. title = scriptName;
  1316. subTitle = "";
  1317. body = arguments[0];
  1318. }
  1319. this.post(title, subTitle, body, opts);
  1320. }
  1321. }
  1322. function bark(title = scriptName, subTitle = "", body = "", opts = "") {
  1323. if (typeof http === "undefined" || typeof http.post === "undefined") {
  1324. throw "Bark notification needs to import MagicHttp module.";
  1325. }
  1326. let options = {
  1327. url: _barkUrl,
  1328. headers: {
  1329. "content-type": "application/json; charset=utf-8"
  1330. },
  1331. body: {
  1332. title: title,
  1333. body: subTitle ? `${subTitle}` + '\n' + `${body}` : body,
  1334. device_key: _barkKey
  1335. }
  1336. };
  1337. http.post(options).catch(ex => {
  1338. logger.error(`Bark notify error: ${ex}`);
  1339. });
  1340. }
  1341. return {
  1342. post: post,
  1343. debug: debug,
  1344. bark: bark,
  1345. setBark: setBark,
  1346. appendNotifyInfo: appendNotifyInfo,
  1347. prependNotifyInfo: prependNotifyInfo,
  1348. msg: msg,
  1349. };
  1350. }
  1351. function MagicUtils(env, logger) {
  1352. const retry = (fn, retries = 5, interval = 0, callback = null) => {
  1353. return (...args) => {
  1354. return new Promise((resolve, reject) => {
  1355. function _retry(...args) {
  1356. Promise.resolve().then(() => fn.apply(this, args)).then(result => {
  1357. if (typeof callback === "function") {
  1358. Promise.resolve().then(() => callback(result)).then(() => {
  1359. resolve(result);
  1360. }).catch(ex => {
  1361. if (retries >= 1) {
  1362. if (interval > 0) setTimeout(() => _retry.apply(this, args), interval); else _retry.apply(this, args);
  1363. } else {
  1364. reject(ex);
  1365. }
  1366. retries--;
  1367. });
  1368. } else {
  1369. resolve(result);
  1370. }
  1371. }).catch(ex => {
  1372. logger.error(ex);
  1373. if (retries >= 1 && interval > 0) {
  1374. setTimeout(() => _retry.apply(this, args), interval);
  1375. } else if (retries >= 1) {
  1376. _retry.apply(this, args);
  1377. } else {
  1378. reject(ex);
  1379. }
  1380. retries--;
  1381. });
  1382. }
  1383. _retry.apply(this, args);
  1384. });
  1385. };
  1386. };
  1387. const formatTime = (time, fmt = "yyyy-MM-dd hh:mm:ss") => {
  1388. let o = {
  1389. "M+": time.getMonth() + 1,
  1390. "d+": time.getDate(),
  1391. "h+": time.getHours(),
  1392. "m+": time.getMinutes(),
  1393. "s+": time.getSeconds(),
  1394. "q+": Math.floor((time.getMonth() + 3) / 3),
  1395. S: time.getMilliseconds()
  1396. };
  1397. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
  1398. for (let k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  1399. return fmt;
  1400. };
  1401. const now = () => {
  1402. return formatTime(new Date(), "yyyy-MM-dd hh:mm:ss");
  1403. };
  1404. const today = () => {
  1405. return formatTime(new Date(), "yyyy-MM-dd");
  1406. };
  1407. const sleep = time => {
  1408. return new Promise(resolve => setTimeout(resolve, time));
  1409. };
  1410. const assert = (val, msg = null) => {
  1411. if (env.isNode) {
  1412. const _assert = require("assert");
  1413. if (msg) _assert(val, msg); else _assert(val);
  1414. } else {
  1415. if (val !== true) {
  1416. let err = `AssertionError: ${msg || "The expression evaluated to a falsy value."}`;
  1417. logger.error(err);
  1418. }
  1419. }
  1420. };
  1421. return {
  1422. retry: retry,
  1423. formatTime: formatTime,
  1424. now: now,
  1425. today: today,
  1426. sleep: sleep,
  1427. assert: assert
  1428. };
  1429. }
  1430. function MagicQingLong(env, data, logger) {
  1431. let qlUrl = "";
  1432. let qlName = "";
  1433. let qlClient = "";
  1434. let qlSecret = "";
  1435. let qlPwd = "";
  1436. let qlToken = "";
  1437. const magicJsonFileName = "magic.json";
  1438. const timeout = 3e3;
  1439. const http = (() => MagicHttp(env, logger))();
  1440. const init = (url, clientId, clientSecret, username, password) => {
  1441. qlUrl = url;
  1442. qlClient = clientId;
  1443. qlSecret = clientSecret;
  1444. qlName = username;
  1445. qlPwd = password;
  1446. };
  1447. function readQingLongConfig(config) {
  1448. qlUrl = qlUrl || data.read("magic_qlurl");
  1449. qlToken = qlToken || data.read("magic_qltoken");
  1450. logger.debug(`QingLong url: ${qlUrl}` + '\n' + `QingLong token: ${qlToken}`);
  1451. return config;
  1452. }
  1453. function setBaseUrlAndTimeout(config) {
  1454. if (!qlUrl) {
  1455. qlUrl = data.read("magic_qlurl");
  1456. }
  1457. if (config.url.indexOf(qlUrl) < 0) {
  1458. config.url = `${qlUrl}${config.url}`;
  1459. }
  1460. return {
  1461. ...config,
  1462. timeout: timeout
  1463. };
  1464. }
  1465. function setTimestamp(config) {
  1466. config.params = {
  1467. ...config.params,
  1468. t: Date.now()
  1469. };
  1470. return config;
  1471. }
  1472. async function setAuthorization(config) {
  1473. qlToken = qlToken || data.read("magic_qltoken", "");
  1474. if (!qlToken) {
  1475. await getToken();
  1476. }
  1477. config.headers["authorization"] = `Bearer ${qlToken}`;
  1478. return config;
  1479. }
  1480. function switchClientMode(config) {
  1481. qlClient = qlClient || data.read("magic_qlclient");
  1482. if (!!qlClient) {
  1483. config.url = config.url.replace("/api/", "/open/");
  1484. }
  1485. return config;
  1486. }
  1487. async function refreshToken(error) {
  1488. try {
  1489. const message = error.message || error.error || JSON.stringify(error);
  1490. if ((message.indexOf("NSURLErrorDomain") >= 0 && message.indexOf("-1012") >= 0 || !!error.response && error.response.status === 401) && !!error.config && error.config.refreshToken !== true) {
  1491. logger.warning(`QingLong Panel token has expired`);
  1492. logger.info("Refreshing the QingLong Panel token");
  1493. await getToken();
  1494. error.config["refreshToken"] = true;
  1495. logger.info("Call the previous method again");
  1496. return await http.request(error.config.method, error.config);
  1497. } else {
  1498. return Promise.reject(error);
  1499. }
  1500. } catch (ex) {
  1501. return Promise.reject(ex);
  1502. }
  1503. }
  1504. http.interceptors.request.use(setBaseUrlAndTimeout, undefined);
  1505. http.interceptors.request.use(switchClientMode, undefined, {
  1506. runWhen: config => {
  1507. return config.url.indexOf("api/user/login") < 0 && config.url.indexOf("open/auth/token") < 0;
  1508. }
  1509. });
  1510. http.interceptors.request.use(setAuthorization, undefined, {
  1511. runWhen: config => {
  1512. return config.url.indexOf("api/user/login") < 0 && config.url.indexOf("open/auth/token") < 0;
  1513. }
  1514. });
  1515. http.interceptors.request.use(setTimestamp, undefined, {
  1516. runWhen: config => {
  1517. return config.url.indexOf("open/auth/token") < 0;
  1518. }
  1519. });
  1520. http.interceptors.request.use(readQingLongConfig, undefined);
  1521. http.interceptors.response.use(undefined, refreshToken);
  1522. async function getToken() {
  1523. qlClient = qlClient || data.read("magic_qlclient");
  1524. qlSecret = qlSecret || data.read("magic_qlsecrt");
  1525. qlName = qlName || data.read("magic_qlname");
  1526. qlPwd = qlPwd || data.read("magic_qlpwd");
  1527. if (qlUrl && qlClient && qlSecret) {
  1528. logger.info("Get token from QingLong Panel");
  1529. await http.get({
  1530. url: `/open/auth/token`,
  1531. headers: {
  1532. "content-type": "application/json"
  1533. },
  1534. params: {
  1535. client_id: qlClient,
  1536. client_secret: qlSecret
  1537. }
  1538. }).then(resp => {
  1539. if (Object.keys(resp.body).length > 0 && resp.body.data && resp.body.data.token) {
  1540. logger.info("Successfully logged in to QingLong Panel");
  1541. qlToken = resp.body.data.token;
  1542. data.write("magic_qltoken", qlToken);
  1543. } else {
  1544. throw new Error("Get QingLong Panel token failed.");
  1545. }
  1546. }).catch(err => {
  1547. logger.error(`Error logging in to QingLong Panel.` + '\n' + `${err.message || err}`);
  1548. });
  1549. } else if (qlUrl && qlName && qlPwd) {
  1550. await http.post({
  1551. url: `/api/user/login`,
  1552. headers: {
  1553. "content-type": "application/json"
  1554. },
  1555. body: {
  1556. username: qlName,
  1557. password: qlPwd
  1558. }
  1559. }).then(resp => {
  1560. logger.info("Successfully logged in to QingLong Panel");
  1561. qlToken = resp.body.data.token;
  1562. data.write("magic_qltoken", qlToken);
  1563. }).catch(err => {
  1564. logger.error(`Error logging in to QingLong Panel.` + '\n' + `${err.message || err}`);
  1565. });
  1566. }
  1567. return qlToken;
  1568. }
  1569. async function setEnv(name, value, id = null) {
  1570. qlUrl = qlUrl || data.read("magic_qlurl");
  1571. if (id === null) {
  1572. let envIds = await setEnvs([{
  1573. name: name,
  1574. value: value
  1575. }]);
  1576. if (!!envIds && envIds.length === 1) {
  1577. return envIds[0];
  1578. }
  1579. } else {
  1580. await http.put({
  1581. url: `/api/envs`,
  1582. headers: {
  1583. "content-type": "application/json"
  1584. },
  1585. body: {
  1586. name: name,
  1587. value: value,
  1588. id: id
  1589. }
  1590. }).then(resp => {
  1591. if (resp.body.code === 200) {
  1592. logger.debug(`QINGLONG UPDATE ENV ${name} <${typeof value}> (${id})` + '\n' + `${JSON.stringify(value)}`);
  1593. return true;
  1594. } else {
  1595. logger.error(`Error adding environment variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1596. }
  1597. }).catch(err => {
  1598. logger.error(`Error adding environment variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1599. return false;
  1600. });
  1601. }
  1602. }
  1603. async function setEnvs(envs) {
  1604. let envIds = [];
  1605. await http.post({
  1606. url: `/api/envs`,
  1607. headers: {
  1608. "content-type": "application/json"
  1609. },
  1610. body: envs
  1611. }).then(resp => {
  1612. if (resp.body.code === 200) {
  1613. resp.body.data.forEach(element => {
  1614. logger.debug(`QINGLONG ADD ENV ${element.name} <${typeof element.value}> (${element.id})` + '\n' + `${JSON.stringify(element)}`);
  1615. envIds.push(element.id);
  1616. });
  1617. } else {
  1618. logger.error(`Error adding environments variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1619. }
  1620. }).catch(err => {
  1621. logger.error(`Error adding environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1622. });
  1623. return envIds;
  1624. }
  1625. async function delEnvs(ids) {
  1626. return await http.delete({
  1627. url: `/api/envs`,
  1628. headers: {
  1629. accept: "application/json",
  1630. "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  1631. connection: "keep-alive",
  1632. "content-type": "application/json;charset=UTF-8",
  1633. "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"
  1634. },
  1635. body: ids
  1636. }).then(resp => {
  1637. if (resp.body.code === 200) {
  1638. logger.debug(`QINGLONG DELETE ENV IDS: ${ids}`);
  1639. return true;
  1640. } else {
  1641. logger.error(`Error deleting environments variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1642. return false;
  1643. }
  1644. }).catch(err => {
  1645. logger.error(`Error deleting environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1646. });
  1647. }
  1648. async function getEnvs(name = null, searchValue = "", retired = 0) {
  1649. let envs = [];
  1650. await http.get({
  1651. url: `/api/envs`,
  1652. headers: {
  1653. "content-type": "application/json"
  1654. },
  1655. params: {
  1656. searchValue: searchValue
  1657. }
  1658. }).then(resp => {
  1659. if (resp.body.code === 200) {
  1660. const allEnvs = resp.body.data;
  1661. if (!!name) {
  1662. let _envs = [];
  1663. for (const env of allEnvs) {
  1664. if (env.name === name) {
  1665. envs.push(env);
  1666. }
  1667. }
  1668. envs = _envs;
  1669. }
  1670. envs = allEnvs;
  1671. } else {
  1672. throw new Error(`Error reading environment variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1673. }
  1674. }).catch(err => {
  1675. throw new Error(`Error reading environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1676. });
  1677. return envs;
  1678. }
  1679. async function getEnv(id) {
  1680. let env = null;
  1681. const allEnvs = await getEnvs();
  1682. for (const _env of allEnvs) {
  1683. if (_env.id === id) {
  1684. env = _env;
  1685. break;
  1686. }
  1687. }
  1688. return env;
  1689. }
  1690. async function disableEnvs(ids) {
  1691. let result = false;
  1692. await http.put({
  1693. url: `/api/envs/disable`,
  1694. headers: {
  1695. accept: "application/json",
  1696. "accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  1697. connection: "keep-alive",
  1698. "content-type": "application/json;charset=UTF-8",
  1699. "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"
  1700. },
  1701. body: ids
  1702. }).then(resp => {
  1703. if (resp.body.code === 200) {
  1704. logger.debug(`QINGLONG DISABLED ENV IDS: ${ids}`);
  1705. result = true;
  1706. } else {
  1707. logger.error(`Error disabling environments variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1708. }
  1709. }).catch(err => {
  1710. logger.error(`Error disabling environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1711. });
  1712. return result;
  1713. }
  1714. async function enableEnvs(ids) {
  1715. let result = false;
  1716. await http.put({
  1717. url: `/api/envs/enable`,
  1718. headers: {
  1719. accept: "application/json",
  1720. "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  1721. connection: "keep-alive",
  1722. "content-type": "application/json;charset=UTF-8",
  1723. "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"
  1724. },
  1725. body: ids
  1726. }).then(resp => {
  1727. if (resp.body.code === 200) {
  1728. logger.debug(`QINGLONG ENABLED ENV IDS: ${ids}`);
  1729. result = true;
  1730. } else {
  1731. logger.error(`Error enabling environments variable from Qilong panel.` + '\n' + `${JSON.stringify(resp)}`);
  1732. }
  1733. }).catch(err => {
  1734. logger.error(`Error enabling environments variable from Qilong panel.` + '\n' + `${err.message || err}`);
  1735. });
  1736. return result;
  1737. }
  1738. async function addScript(name, path = "", content = "") {
  1739. let result = false;
  1740. await http.post({
  1741. url: `/api/scripts`,
  1742. headers: {
  1743. "content-type": "application/json"
  1744. },
  1745. body: {
  1746. filename: name,
  1747. path: path,
  1748. content: content
  1749. }
  1750. }).then(resp => {
  1751. if (resp.body.code === 200) {
  1752. result = true;
  1753. } else {
  1754. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1755. }
  1756. }).catch(err => {
  1757. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1758. });
  1759. return result;
  1760. }
  1761. async function getScript(name, path = "") {
  1762. let content = "";
  1763. await http.get({
  1764. url: `/api/scripts/${name}`,
  1765. params: {
  1766. path: path
  1767. }
  1768. }).then(resp => {
  1769. if (resp.body.code === 200) {
  1770. content = resp.body.data;
  1771. } else {
  1772. throw new Error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1773. }
  1774. }).catch(err => {
  1775. throw new Error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1776. });
  1777. return content;
  1778. }
  1779. async function editScript(name, path = "", content = "") {
  1780. let result = false;
  1781. await http.put({
  1782. url: `/api/scripts`,
  1783. headers: {
  1784. "content-type": "application/json"
  1785. },
  1786. body: {
  1787. filename: name,
  1788. path: path,
  1789. content: content
  1790. }
  1791. }).then(resp => {
  1792. if (resp.body.code === 200) {
  1793. result = true;
  1794. } else {
  1795. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1796. }
  1797. }).catch(err => {
  1798. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1799. });
  1800. return result;
  1801. }
  1802. async function delScript(name, path = "") {
  1803. let result = false;
  1804. await http.delete({
  1805. url: `/api/scripts`,
  1806. headers: {
  1807. "content-type": "application/json"
  1808. },
  1809. body: {
  1810. filename: name,
  1811. path: path
  1812. }
  1813. }).then(resp => {
  1814. if (resp.body.code === 200) {
  1815. result = true;
  1816. } else {
  1817. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1818. }
  1819. }).catch(err => {
  1820. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1821. });
  1822. return result;
  1823. }
  1824. async function write(key, val, session = "") {
  1825. let qlContent = await getScript(magicJsonFileName, "");
  1826. let qlData = data.convertToObject(qlContent);
  1827. let writeResult = data.write(key, val, session, qlData);
  1828. qlContent = JSON.stringify(qlData, null, 4);
  1829. let editResult = await editScript(magicJsonFileName, "", qlContent);
  1830. return editResult && writeResult;
  1831. }
  1832. async function batchWrite(...args) {
  1833. let qlContent = await getScript(magicJsonFileName, "");
  1834. let qlData = data.convertToObject(qlContent);
  1835. for (let arg of args) {
  1836. data.write(arg[0], arg[1], typeof arg[2] !== "undefined" ? arg[2] : "", qlData);
  1837. }
  1838. qlContent = JSON.stringify(qlData, null, 4);
  1839. return await editScript(magicJsonFileName, "", qlContent);
  1840. }
  1841. async function update(key, val, session, comparator = data.defaultValueComparator) {
  1842. let qlContent = await getScript(magicJsonFileName, "");
  1843. let qlData = data.convertToObject(qlContent);
  1844. const updateResult = data.update(key, val, session, comparator, qlData);
  1845. let editScriptResult = false;
  1846. if (updateResult === true) {
  1847. qlContent = JSON.stringify(qlData, null, 4);
  1848. editScriptResult = await editScript(magicJsonFileName, "", qlContent);
  1849. }
  1850. return updateResult && editScriptResult;
  1851. }
  1852. async function batchUpdate(...args) {
  1853. let qlContent = await getScript(magicJsonFileName, "");
  1854. let qlData = data.convertToObject(qlContent);
  1855. for (let arg of args) {
  1856. data.update(arg[0], arg[1], typeof arg[2] !== "undefined" ? arg[2] : "", typeof arg[3] !== "undefined" ? arg["comparator"] : data.defaultValueComparator, qlData);
  1857. }
  1858. qlContent = JSON.stringify(qlData, null, 4);
  1859. return await editScript(magicJsonFileName, "", qlContent);
  1860. }
  1861. async function read(key, val, session = "", read_no_session = false) {
  1862. let qlContent = await getScript(magicJsonFileName, "");
  1863. let qlData = data.convertToObject(qlContent);
  1864. return data.read(key, val, session, read_no_session, qlData);
  1865. }
  1866. async function batchRead(...args) {
  1867. let qlContent = await getScript(magicJsonFileName, "");
  1868. let qlData = data.convertToObject(qlContent);
  1869. let results = [];
  1870. for (let arg of args) {
  1871. const result = data.read(arg[0], arg[1], typeof arg[2] !== "undefined" ? arg[2] : "", typeof arg[3] === "boolean" ? arg[3] : false, qlData);
  1872. results.push(result);
  1873. }
  1874. return results;
  1875. }
  1876. async function del(key, session = "") {
  1877. let qlContent = await getScript(magicJsonFileName, "");
  1878. let qlData = data.convertToObject(qlContent);
  1879. const delResult = data.del(key, session, qlData);
  1880. qlContent = JSON.stringify(qlData, null, 4);
  1881. const editResult = await editScript(magicJsonFileName, "", qlContent);
  1882. return delResult && editResult;
  1883. }
  1884. async function batchDel(...args) {
  1885. let qlContent = await getScript(magicJsonFileName, "");
  1886. let qlData = data.convertToObject(qlContent);
  1887. for (let arg of args) {
  1888. data.del(arg[0], typeof arg[1] !== "undefined" ? arg[1] : "", qlData);
  1889. }
  1890. qlContent = JSON.stringify(qlData, null, 4);
  1891. return await editScript(magicJsonFileName, "", qlContent);
  1892. }
  1893. async function allSessionNames(key) {
  1894. let qlContent = await getScript(magicJsonFileName, "");
  1895. let qlData = data.convertToObject(qlContent);
  1896. return data.allSessionNames(key, qlData);
  1897. }
  1898. async function allSessions(key) {
  1899. let qlContent = await getScript(magicJsonFileName, "");
  1900. let qlData = data.convertToObject(qlContent);
  1901. return data.allSessions(key, qlData);
  1902. }
  1903. return {
  1904. url: qlUrl || data.read("magic_qlurl"),
  1905. init: init,
  1906. getToken: getToken,
  1907. setEnv: setEnv,
  1908. setEnvs: setEnvs,
  1909. getEnv: getEnv,
  1910. getEnvs: getEnvs,
  1911. delEnvs: delEnvs,
  1912. disableEnvs: disableEnvs,
  1913. enableEnvs: enableEnvs,
  1914. addScript: addScript,
  1915. getScript: getScript,
  1916. editScript: editScript,
  1917. delScript: delScript,
  1918. write: write,
  1919. read: read,
  1920. del: del,
  1921. update: update,
  1922. batchWrite: batchWrite,
  1923. batchRead: batchRead,
  1924. batchUpdate: batchUpdate,
  1925. batchDel: batchDel,
  1926. allSessions: allSessions,
  1927. allSessionNames: allSessionNames
  1928. };
  1929. }