MagicJS3.js 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  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: [32852],
  476. topicIds: [],
  477. uids: [
  478. "UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"
  479. ],
  480. url: url,
  481. verifyPay: false,
  482. verifyPayType: 0,
  483. };
  484. return this.doWxpusherSend(data);
  485. }
  486. isEmpty(obj) {
  487. return typeof obj == "undefined" || obj == null || obj == "" || obj == "null" || obj == "undefined" || obj.length === 0
  488. }
  489. base64Encode(str) {
  490. let base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  491. let out, i, len;
  492. let c1, c2, c3;
  493. len = str.length;
  494. i = 0;
  495. out = "";
  496. while (i < len) {
  497. c1 = str.charCodeAt(i++) & 0xff;
  498. if (i == len) {
  499. out += base64EncodeChars.charAt(c1 >> 2);
  500. out += base64EncodeChars.charAt((c1 & 0x3) << 4);
  501. out += "==";
  502. break;
  503. }
  504. c2 = str.charCodeAt(i++);
  505. if (i == len) {
  506. out += base64EncodeChars.charAt(c1 >> 2);
  507. out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  508. out += base64EncodeChars.charAt((c2 & 0xF) << 2);
  509. out += "=";
  510. break;
  511. }
  512. c3 = str.charCodeAt(i++);
  513. out += base64EncodeChars.charAt(c1 >> 2);
  514. out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  515. out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  516. out += base64EncodeChars.charAt(c3 & 0x3F);
  517. }
  518. return out;
  519. }
  520. base64Decode(input) {
  521. const base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  522. // 确保输入是一个正确的Base64编码字符串
  523. if (/([^\s]+[^0-9a-zA-Z\+\/\=]|[^0-9a-zA-Z\+\/\=]\s+)/.test(input)) {
  524. throw new Error('Invalid base64 input');
  525. }
  526. let str = input.replace(/\s/g, '');
  527. let output = '';
  528. let chr1, chr2, chr3;
  529. let enc1, enc2, enc3, enc4;
  530. let i = 0;
  531. while (i < str.length) {
  532. enc1 = base64_chars.indexOf(str.charAt(i++));
  533. enc2 = base64_chars.indexOf(str.charAt(i++));
  534. enc3 = base64_chars.indexOf(str.charAt(i++));
  535. enc4 = base64_chars.indexOf(str.charAt(i++));
  536. chr1 = (enc1 << 2) | (enc2 >> 4);
  537. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  538. chr3 = ((enc3 & 3) << 6) | enc4;
  539. output = output + String.fromCharCode(chr1);
  540. if (enc3 !== 64) {
  541. output = output + String.fromCharCode(chr2);
  542. }
  543. if (enc4 !== 64) {
  544. output = output + String.fromCharCode(chr3);
  545. }
  546. }
  547. output = this.utf8Decode(output);
  548. return output;
  549. }
  550. utf8Decode(str_data) {
  551. let tmp_arr = [],
  552. i = 0,
  553. c1 = 0,
  554. seqlen = 0;
  555. str_data = str_data.replace(/\r\n/g, "\n");
  556. while (i < str_data.length) {
  557. c1 = str_data.charCodeAt(i) & 0xFF;
  558. seqlen = 0;
  559. // Single byte sequence (0xxxxxxx)
  560. if (c1 <= 0xBF) {
  561. c1 = (c1 & 0x7F);
  562. seqlen = 1;
  563. } else if (c1 <= 0xDF) {
  564. c1 = (c1 & 0x1F);
  565. seqlen = 2;
  566. } else if (c1 <= 0xEF) {
  567. c1 = (c1 & 0x0F);
  568. seqlen = 3;
  569. } else {
  570. c1 = (c1 & 0x07);
  571. seqlen = 4;
  572. }
  573. for (let ai = 1; ai < seqlen; ++ai) {
  574. c1 = ((c1 << 0x06) | (str_data.charCodeAt(ai + i) & 0x3F));
  575. }
  576. if (seqlen === 4) {
  577. c1 -= 0x10000;
  578. tmp_arr.push(String.fromCharCode(0xD800 | ((c1 >> 10) & 0x3FF)));
  579. tmp_arr.push(String.fromCharCode(0xDC00 | (c1 & 0x3FF)));
  580. } else {
  581. tmp_arr.push(String.fromCharCode(c1));
  582. }
  583. i += seqlen;
  584. }
  585. return tmp_arr.join("");
  586. }
  587. parseJwt(token) {
  588. try {
  589. const segments = token.split('.');
  590. const base64HeaderUrl = segments[0];
  591. const base64Header = base64HeaderUrl.replace(/-/g, '+').replace(/_/g, '/');
  592. const jsonStrHeader = this.base64Decode(base64Header).replace(/\0/g, '');
  593. const headerData = JSON.parse(jsonStrHeader);
  594. const base64PayloadUrl = segments[1];
  595. const base64Payload = base64PayloadUrl.replace(/-/g, '+').replace(/_/g, '/');
  596. const jsonStrPayload = this.base64Decode(base64Payload).replace(/\0/g, '');
  597. const payloadData = JSON.parse(jsonStrPayload);
  598. return {
  599. header: headerData,
  600. payload: payloadData,
  601. signature: segments[2],
  602. };
  603. } catch (e) {
  604. this.log(e);
  605. return null;
  606. }
  607. }
  608. costTime() {
  609. let info = `${this.scriptName}执行完毕!`
  610. // if (this.isNode && this.isExecComm) {
  611. // info = `指令【${this.comm[1]}】执行完毕!`
  612. // }
  613. this._endTime = new Date().getTime();
  614. const ms = this._endTime - this._startTime;
  615. const costTime = ms / 1000;
  616. this.logger.info(`${info}耗时【${costTime}】秒`);
  617. }
  618. done = (value = {}) => {
  619. // this._endTime = Date.now();
  620. // let span = (this._endTime - this._startTime) / 1e3;
  621. // this.logger.info(`SCRIPT COMPLETED: ${span} S.`);
  622. this.costTime();
  623. if (typeof $done !== "undefined") {
  624. $done(value);
  625. }
  626. };
  627. }(scriptName, logLevel);
  628. }
  629. function MagicHttp(env, logger) {
  630. 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";
  631. 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";
  632. let axiosInstance;
  633. if (env.isNode) {
  634. const axios = require("axios");
  635. axiosInstance = axios.create();
  636. }
  637. class InterceptorManager {
  638. constructor(isRequest = true) {
  639. this.handlers = [];
  640. this.isRequest = isRequest;
  641. }
  642. use(fulfilled, rejected, options) {
  643. if (typeof fulfilled === "function") {
  644. logger.debug(`Register fulfilled ${fulfilled.name}`);
  645. }
  646. if (typeof rejected === "function") {
  647. logger.debug(`Register rejected ${rejected.name}`);
  648. }
  649. this.handlers.push({
  650. fulfilled: fulfilled,
  651. rejected: rejected,
  652. synchronous: options && typeof options.synchronous === "boolean" ? options.synchronous : false,
  653. runWhen: options ? options.runWhen : null
  654. });
  655. return this.handlers.length - 1;
  656. }
  657. eject(id) {
  658. if (this.handlers[id]) {
  659. this.handlers[id] = null;
  660. }
  661. }
  662. forEach(fn) {
  663. this.handlers.forEach(element => {
  664. if (element !== null) {
  665. fn(element);
  666. }
  667. });
  668. }
  669. }
  670. function paramsToQueryString(config) {
  671. let _config = {
  672. ...config
  673. };
  674. if (!!_config.params) {
  675. if (!env.isNode) {
  676. let qs = Object.keys(_config.params).map(key => {
  677. const encodeKey = encodeURIComponent(key);
  678. _config.url = _config.url.replace(new RegExp(`${key}=[^&]*`, "ig"), "");
  679. _config.url = _config.url.replace(new RegExp(`${encodeKey}=[^&]*`, "ig"), "");
  680. return `${encodeKey}=${encodeURIComponent(_config.params[key])}`;
  681. }).join("&");
  682. if (_config.url.indexOf("?") < 0) _config.url += "?";
  683. if (!/(&|\?)$/g.test(_config.url)) {
  684. _config.url += "&";
  685. }
  686. _config.url += qs;
  687. delete _config.params;
  688. logger.debug(`Params to QueryString: ${_config.url}`);
  689. }
  690. }
  691. return _config;
  692. }
  693. const mergeConfig = (method, configOrUrl) => {
  694. let config = typeof configOrUrl === "object" ? {
  695. headers: {},
  696. ...configOrUrl
  697. } : {
  698. url: configOrUrl,
  699. headers: {}
  700. };
  701. if (!config.method) {
  702. config["method"] = method;
  703. }
  704. config = paramsToQueryString(config);
  705. if (config["rewrite"] === true) {
  706. if (env.isSurge) {
  707. config.headers["X-Surge-Skip-Scripting"] = false;
  708. delete config["rewrite"];
  709. } else if (env.isQuanX) {
  710. config["hints"] = false;
  711. delete config["rewrite"];
  712. }
  713. }
  714. if (env.isSurgeLike) {
  715. const contentType = config.headers["content-type"] || config.headers["Content-Type"];
  716. if (config["method"] !== "GET" && contentType && contentType.indexOf("application/json") >= 0 && config.body instanceof Array) {
  717. config.body = JSON.stringify(config.body);
  718. logger.debug(`Convert Array object to String: ${config.body}`);
  719. }
  720. } else if (env.isQuanX) {
  721. if (config.hasOwnProperty("body") && typeof config["body"] !== "string") config["body"] = JSON.stringify(config["body"]);
  722. config["method"] = method;
  723. } else if (env.isNode) {
  724. if (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE") {
  725. config.data = config.data || config.body;
  726. } else if (method === "GET") {
  727. config.params = config.params || config.body;
  728. }
  729. delete config.body;
  730. }
  731. return config;
  732. };
  733. const modifyResponse = (resp, config = null) => {
  734. if (resp) {
  735. let _resp = {
  736. ...resp,
  737. config: resp.config || config,
  738. status: resp.statusCode || resp.status,
  739. body: resp.body || resp.data,
  740. headers: resp.headers || resp.header
  741. };
  742. if (typeof _resp.body === "string") {
  743. try {
  744. _resp.body = JSON.parse(_resp.body);
  745. } catch { }
  746. }
  747. delete _resp.data;
  748. return _resp;
  749. } else {
  750. return resp;
  751. }
  752. };
  753. const convertHeadersToLowerCase = headers => {
  754. return Object.keys(headers).reduce((acc, key) => {
  755. acc[key.toLowerCase()] = headers[key];
  756. return acc;
  757. }, {});
  758. };
  759. const convertHeadersToCamelCase = headers => {
  760. return Object.keys(headers).reduce((acc, key) => {
  761. const newKey = key.split("-").map(word => word[0].toUpperCase() + word.slice(1)).join("-");
  762. acc[newKey] = headers[key];
  763. return acc;
  764. }, {});
  765. };
  766. const raiseExceptionByStatusCode = (resp, config = null) => {
  767. if (!!resp && resp.status >= 400) {
  768. logger.debug(`Raise exception when status code is ${resp.status}`);
  769. return {
  770. name: "RequestException",
  771. message: `Request failed with status code ${resp.status}`,
  772. config: config || resp.config,
  773. response: resp
  774. };
  775. }
  776. };
  777. const interceptors = {
  778. request: new InterceptorManager(),
  779. response: new InterceptorManager(false)
  780. };
  781. let requestInterceptorChain = [];
  782. let responseInterceptorChain = [];
  783. let synchronousRequestInterceptors = true;
  784. function interceptConfig(config) {
  785. config = paramsToQueryString(config);
  786. logger.debug(`HTTP ${config["method"].toUpperCase()}:` + '\n' + `${JSON.stringify(config)}`);
  787. return config;
  788. }
  789. function interceptResponse(resp) {
  790. try {
  791. resp = !!resp ? modifyResponse(resp) : resp;
  792. 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}`);
  793. const err = raiseExceptionByStatusCode(resp);
  794. if (!!err) {
  795. return Promise.reject(err);
  796. }
  797. return resp;
  798. } catch (err) {
  799. logger.error(err);
  800. return resp;
  801. }
  802. }
  803. const registerInterceptors = config => {
  804. try {
  805. requestInterceptorChain = [];
  806. responseInterceptorChain = [];
  807. interceptors.request.forEach(interceptor => {
  808. if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
  809. return;
  810. }
  811. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  812. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  813. });
  814. interceptors.response.forEach(interceptor => {
  815. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  816. });
  817. } catch (err) {
  818. logger.error(`Failed to register interceptors: ${err}.`);
  819. }
  820. };
  821. const request = (method, config) => {
  822. let dispatchRequest;
  823. const _method = method.toUpperCase();
  824. config = mergeConfig(_method, config);
  825. if (env.isNode) {
  826. dispatchRequest = axiosInstance;
  827. } else {
  828. if (env.isSurgeLike) {
  829. dispatchRequest = config => {
  830. return new Promise((resolve, reject) => {
  831. $httpClient[method.toLowerCase()](config, (err, resp, body) => {
  832. if (err) {
  833. let newErr = {
  834. name: err.name || err,
  835. message: err.message || err,
  836. stack: err.stack || err,
  837. config: config,
  838. response: modifyResponse(resp)
  839. };
  840. reject(newErr);
  841. } else {
  842. resp.config = config;
  843. resp.body = body;
  844. resolve(resp);
  845. }
  846. });
  847. });
  848. };
  849. } else {
  850. dispatchRequest = config => {
  851. return new Promise((resolve, reject) => {
  852. $task.fetch(config).then(resp => {
  853. resp = modifyResponse(resp, config);
  854. const err = raiseExceptionByStatusCode(resp, config);
  855. if (err) {
  856. return Promise.reject(err);
  857. }
  858. resolve(resp);
  859. }).catch(err => {
  860. let newErr = {
  861. name: err.message || err.error,
  862. message: err.message || err.error,
  863. stack: err.error,
  864. config: config,
  865. response: !!err.response ? modifyResponse(err.response) : null
  866. };
  867. reject(newErr);
  868. });
  869. });
  870. };
  871. }
  872. }
  873. let promise;
  874. registerInterceptors(config);
  875. const defaultRequestInterceptors = [interceptConfig, undefined];
  876. const defaultResponseInterceptors = [interceptResponse, undefined];
  877. if (!synchronousRequestInterceptors) {
  878. logger.debug("Interceptors are executed in asynchronous mode");
  879. let chain = [dispatchRequest, undefined];
  880. Array.prototype.unshift.apply(chain, defaultRequestInterceptors);
  881. Array.prototype.unshift.apply(chain, requestInterceptorChain);
  882. chain = chain.concat(defaultResponseInterceptors);
  883. chain = chain.concat(responseInterceptorChain);
  884. promise = Promise.resolve(config);
  885. while (chain.length) {
  886. try {
  887. let onFulfilled = chain.shift();
  888. let onRejected = chain.shift();
  889. if (!env.isNode && config["timeout"] && onFulfilled === dispatchRequest) {
  890. onFulfilled = requestTimeout;
  891. }
  892. if (typeof onFulfilled === "function") {
  893. logger.debug(`Executing request fulfilled ${onFulfilled.name}`);
  894. }
  895. if (typeof onRejected === "function") {
  896. logger.debug(`Executing request rejected ${onRejected.name}`);
  897. }
  898. promise = promise.then(onFulfilled, onRejected);
  899. } catch (err) {
  900. logger.error(`request exception: ${err}`);
  901. }
  902. }
  903. return promise;
  904. } else {
  905. logger.debug("Interceptors are executed in synchronous mode");
  906. Array.prototype.unshift.apply(requestInterceptorChain, defaultRequestInterceptors);
  907. requestInterceptorChain = requestInterceptorChain.concat([interceptConfig, undefined]);
  908. while (requestInterceptorChain.length) {
  909. let onFulfilled = requestInterceptorChain.shift();
  910. let onRejected = requestInterceptorChain.shift();
  911. try {
  912. if (typeof onFulfilled === "function") {
  913. logger.debug(`Executing request fulfilled ${onFulfilled.name}`);
  914. }
  915. config = onFulfilled(config);
  916. } catch (error) {
  917. if (typeof onRejected === "function") {
  918. logger.debug(`Executing request rejected ${onRejected.name}`);
  919. }
  920. onRejected(error);
  921. break;
  922. }
  923. }
  924. try {
  925. if (!env.isNode && config["timeout"]) {
  926. promise = requestTimeout(config);
  927. } else {
  928. promise = dispatchRequest(config);
  929. }
  930. } catch (err) {
  931. return Promise.reject(err);
  932. }
  933. Array.prototype.unshift.apply(responseInterceptorChain, defaultResponseInterceptors);
  934. while (responseInterceptorChain.length) {
  935. promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
  936. }
  937. return promise;
  938. }
  939. function requestTimeout(config) {
  940. try {
  941. const timer = new Promise((_, reject) => {
  942. setTimeout(() => {
  943. let err = {
  944. message: `timeout of ${config["timeout"]}ms exceeded.`,
  945. config: config
  946. };
  947. reject(err);
  948. }, config["timeout"]);
  949. });
  950. return Promise.race([dispatchRequest(config), timer]);
  951. } catch (err) {
  952. logger.error(`Request Timeout exception: ${err}.`);
  953. }
  954. }
  955. };
  956. return {
  957. request: request,
  958. interceptors: interceptors,
  959. convertHeadersToLowerCase: convertHeadersToLowerCase,
  960. convertHeadersToCamelCase: convertHeadersToCamelCase,
  961. modifyResponse: modifyResponse,
  962. get: configOrUrl => {
  963. return request("GET", configOrUrl);
  964. },
  965. post: configOrUrl => {
  966. return request("POST", configOrUrl);
  967. },
  968. put: configOrUrl => {
  969. return request("PUT", configOrUrl);
  970. },
  971. patch: configOrUrl => {
  972. return request("PATCH", configOrUrl);
  973. },
  974. delete: configOrUrl => {
  975. return request("DELETE", configOrUrl);
  976. },
  977. head: configOrUrl => {
  978. return request("HEAD", configOrUrl);
  979. },
  980. options: configOrUrl => {
  981. return request("OPTIONS", configOrUrl);
  982. }
  983. };
  984. }
  985. function MagicData(env, logger) {
  986. let node = {
  987. fs: undefined,
  988. data: {}
  989. };
  990. if (env.isNode) {
  991. node.fs = require("fs");
  992. try {
  993. node.fs.accessSync("./magic.json", node.fs.constants.R_OK | node.fs.constants.W_OK);
  994. } catch (err) {
  995. node.fs.writeFileSync("./magic.json", "{}", {
  996. encoding: "utf8"
  997. });
  998. }
  999. node.data = require("./magic.json");
  1000. }
  1001. const defaultValueComparator = (oldVal, newVal) => {
  1002. if (typeof newVal === "object") {
  1003. return false;
  1004. } else {
  1005. return oldVal === newVal;
  1006. }
  1007. };
  1008. const _typeConvertor = val => {
  1009. if (val === "true") {
  1010. return true;
  1011. } else if (val === "false") {
  1012. return false;
  1013. } else if (typeof val === "undefined") {
  1014. return null;
  1015. } else {
  1016. return val;
  1017. }
  1018. };
  1019. const _valConvertor = (val, default_, session, read_no_session) => {
  1020. if (session) {
  1021. try {
  1022. if (typeof val === "string") val = JSON.parse(val);
  1023. if (val["magic_session"] === true) {
  1024. val = val[session];
  1025. } else {
  1026. val = null;
  1027. }
  1028. } catch {
  1029. val = null;
  1030. }
  1031. }
  1032. if (typeof val === "string" && val !== "null") {
  1033. try {
  1034. val = JSON.parse(val);
  1035. } catch { }
  1036. }
  1037. if (read_no_session === false && !!val && val["magic_session"] === true) {
  1038. val = null;
  1039. }
  1040. if ((val === null || typeof val === "undefined") && default_ !== null && typeof default_ !== "undefined") {
  1041. val = default_;
  1042. }
  1043. val = _typeConvertor(val);
  1044. return val;
  1045. };
  1046. const convertToObject = obj => {
  1047. if (typeof obj === "string") {
  1048. let data = {};
  1049. try {
  1050. data = JSON.parse(obj);
  1051. const type = typeof data;
  1052. if (type !== "object" || data instanceof Array || type === "bool" || data === null) {
  1053. data = {};
  1054. }
  1055. } catch { }
  1056. return data;
  1057. } else if (obj instanceof Array || obj === null || typeof obj === "undefined" || obj !== obj || typeof obj === "boolean") {
  1058. return {};
  1059. } else {
  1060. return obj;
  1061. }
  1062. };
  1063. const readForNode = (key, default_ = null, session = "", read_no_session = false, externalData = null) => {
  1064. let data = externalData || node.data;
  1065. if (!!data && typeof data[key] !== "undefined" && data[key] !== null) {
  1066. val = data[key];
  1067. } else {
  1068. val = !!session ? {} : null;
  1069. }
  1070. val = _valConvertor(val, default_, session, read_no_session);
  1071. return val;
  1072. };
  1073. const read = (key, default_ = null, session = "", read_no_session = false, externalData = null) => {
  1074. let val = "";
  1075. if (externalData || env.isNode) {
  1076. val = readForNode(key, default_, session, read_no_session, externalData);
  1077. } else {
  1078. if (env.isSurgeLike) {
  1079. val = $persistentStore.read(key);
  1080. } else if (env.isQuanX) {
  1081. val = $prefs.valueForKey(key);
  1082. }
  1083. val = _valConvertor(val, default_, session, read_no_session);
  1084. }
  1085. logger.debug(`READ DATA [${key}]${!!session ? `[${session}]` : ""} <${typeof val}>` + '\n' + `${JSON.stringify(val)}`);
  1086. return val;
  1087. };
  1088. const writeForNode = (key, val, session = "", externalData = null) => {
  1089. let data = externalData || node.data;
  1090. data = convertToObject(data);
  1091. if (!!session) {
  1092. let obj = convertToObject(data[key]);
  1093. obj["magic_session"] = true;
  1094. obj[session] = val;
  1095. data[key] = obj;
  1096. } else {
  1097. data[key] = val;
  1098. }
  1099. if (externalData !== null) {
  1100. externalData = data;
  1101. }
  1102. return data;
  1103. };
  1104. const write = (key, val, session = "", externalData = null) => {
  1105. if (typeof val === "undefined" || val !== val) {
  1106. return false;
  1107. }
  1108. if (!env.isNode && (typeof val === "boolean" || typeof val === "number")) {
  1109. val = String(val);
  1110. }
  1111. let data = "";
  1112. if (externalData || env.isNode) {
  1113. data = writeForNode(key, val, session, externalData);
  1114. } else {
  1115. if (!session) {
  1116. data = val;
  1117. } else {
  1118. if (env.isSurgeLike) {
  1119. data = !!$persistentStore.read(key) ? $persistentStore.read(key) : data;
  1120. } else if (env.isQuanX) {
  1121. data = !!$prefs.valueForKey(key) ? $prefs.valueForKey(key) : data;
  1122. }
  1123. data = convertToObject(data);
  1124. data["magic_session"] = true;
  1125. data[session] = val;
  1126. }
  1127. }
  1128. if (!!data && typeof data === "object") {
  1129. data = JSON.stringify(data, null, 4);
  1130. }
  1131. logger.debug(`WRITE DATA [${key}]${session ? `[${session}]` : ""} <${typeof val}>` + '\n' + `${JSON.stringify(val)}`);
  1132. if (!externalData) {
  1133. if (env.isSurgeLike) {
  1134. return $persistentStore.write(data, key);
  1135. } else if (env.isQuanX) {
  1136. return $prefs.setValueForKey(data, key);
  1137. } else if (env.isNode) {
  1138. try {
  1139. node.fs.writeFileSync("./magic.json", data);
  1140. return true;
  1141. } catch (err) {
  1142. logger.error(err);
  1143. return false;
  1144. }
  1145. }
  1146. }
  1147. return true;
  1148. };
  1149. const update = (key, val, session, comparator = defaultValueComparator, externalData = null) => {
  1150. val = _typeConvertor(val);
  1151. const oldValue = read(key, null, session, false, externalData);
  1152. if (comparator(oldValue, val) === true) {
  1153. return false;
  1154. } else {
  1155. const result = write(key, val, session, externalData);
  1156. let newVal = read(key, null, session, false, externalData);
  1157. if (comparator === defaultValueComparator && typeof newVal === "object") {
  1158. return result;
  1159. }
  1160. return comparator(val, newVal);
  1161. }
  1162. };
  1163. const delForNode = (key, session, externalData) => {
  1164. let data = externalData || node.data;
  1165. data = convertToObject(data);
  1166. if (!!session) {
  1167. obj = convertToObject(data[key]);
  1168. delete obj[session];
  1169. data[key] = obj;
  1170. } else {
  1171. delete data[key];
  1172. }
  1173. if (!!externalData) {
  1174. externalData = data;
  1175. }
  1176. return data;
  1177. };
  1178. const del = (key, session = "", externalData = null) => {
  1179. let data = {};
  1180. if (externalData || env.isNode) {
  1181. data = delForNode(key, session, externalData);
  1182. if (!externalData) {
  1183. node.fs.writeFileSync("./magic.json", JSON.stringify(data, null, 4));
  1184. } else {
  1185. externalData = data;
  1186. }
  1187. } else {
  1188. if (!session) {
  1189. if (env.isStorm) {
  1190. return $persistentStore.remove(key);
  1191. } else if (env.isSurgeLike) {
  1192. return $persistentStore.write(null, key);
  1193. } else if (env.isQuanX) {
  1194. return $prefs.removeValueForKey(key);
  1195. }
  1196. } else {
  1197. if (env.isSurgeLike) {
  1198. data = $persistentStore.read(key);
  1199. } else if (env.isQuanX) {
  1200. data = $prefs.valueForKey(key);
  1201. }
  1202. data = convertToObject(data);
  1203. delete data[session];
  1204. const json = JSON.stringify(data, null, 4);
  1205. write(key, json);
  1206. }
  1207. }
  1208. logger.debug(`DELETE KEY [${key}]${!!session ? `[${session}]` : ""}`);
  1209. };
  1210. const allSessionNames = (key, externalData = null) => {
  1211. let _sessions = [];
  1212. let data = read(key, null, null, true, externalData);
  1213. data = convertToObject(data);
  1214. if (data["magic_session"] !== true) {
  1215. _sessions = [];
  1216. } else {
  1217. _sessions = Object.keys(data).filter(key => key !== "magic_session");
  1218. }
  1219. logger.debug(`READ ALL SESSIONS [${key}] <${typeof _sessions}>` + '\n' + `${JSON.stringify(_sessions, null, 4)}`);
  1220. return _sessions;
  1221. };
  1222. const allSessions = (key, externalData = null) => {
  1223. let _sessions = {};
  1224. let data = read(key, null, null, true, externalData);
  1225. data = convertToObject(data);
  1226. if (data["magic_session"] === true) {
  1227. _sessions = {
  1228. ...data
  1229. };
  1230. delete _sessions["magic_session"];
  1231. }
  1232. logger.debug(`READ ALL SESSIONS [${key}] <${typeof _sessions}>` + '\n' + `${JSON.stringify(_sessions, null, 4)}`);
  1233. return _sessions;
  1234. };
  1235. return {
  1236. read: read,
  1237. write: write,
  1238. del: del,
  1239. update: update,
  1240. allSessions: allSessions,
  1241. allSessionNames: allSessionNames,
  1242. defaultValueComparator: defaultValueComparator,
  1243. convertToObject: convertToObject
  1244. };
  1245. }
  1246. function MagicNotification(scriptName, env, logger, http) {
  1247. let _barkUrl = null;
  1248. let _barkKey = null;
  1249. let notifyInfo = []
  1250. const setBark = url => {
  1251. try {
  1252. let _url = url.replace(/\/+$/g, "");
  1253. _barkUrl = `${/^https?:\/\/([^/]*)/.exec(_url)[0]}/push`;
  1254. _barkKey = /\/([^\/]+)\/?$/.exec(_url)[1];
  1255. } catch (ex) {
  1256. logger.error(`Bark url error: ${ex}.`);
  1257. }
  1258. };
  1259. function appendNotifyInfo(info, type) {
  1260. if (type == 1) {
  1261. notifyInfo = info
  1262. } else {
  1263. notifyInfo.push(info)
  1264. }
  1265. }
  1266. function prependNotifyInfo(info) {
  1267. notifyInfo.splice(0, 0, info)
  1268. }
  1269. function msg(subtitle, message, openUrl, mediaUrl) {
  1270. let opts = {};
  1271. if (openUrl) {
  1272. opts["open-url"] = openUrl;
  1273. }
  1274. if (mediaUrl) {
  1275. opts["media-url"] = mediaUrl;
  1276. }
  1277. if (!message || message.length == 0) {
  1278. if (Array.isArray(notifyInfo)) {
  1279. message = notifyInfo.join("\n");
  1280. } else {
  1281. message = notifyInfo;
  1282. }
  1283. }
  1284. if (message && message.length > 0) {
  1285. post(scriptName, "", message, opts);
  1286. }
  1287. }
  1288. function post(title = scriptName, subTitle = "", body = "", opts = "") {
  1289. const _adaptOpts = _opts => {
  1290. try {
  1291. let newOpts = {};
  1292. if (typeof _opts === "string") {
  1293. if (_opts.length > 0) {
  1294. if (env.isLoon) {
  1295. newOpts = {
  1296. openUrl: _opts
  1297. };
  1298. } else if (env.isQuanX) {
  1299. newOpts = {
  1300. "open-url": _opts
  1301. };
  1302. } else if (env.isSurge) {
  1303. newOpts = {
  1304. url: _opts
  1305. };
  1306. }
  1307. }
  1308. } else if (typeof _opts === "object") {
  1309. if (env.isLoon) {
  1310. newOpts["openUrl"] = !!_opts["open-url"] ? _opts["open-url"] : "";
  1311. newOpts["mediaUrl"] = !!_opts["media-url"] ? _opts["media-url"] : "";
  1312. } else if (env.isQuanX) {
  1313. newOpts = !!_opts["open-url"] || !!_opts["media-url"] ? _opts : {};
  1314. } else if (env.isSurge) {
  1315. let openUrl = _opts["open-url"] || _opts["openUrl"];
  1316. newOpts = openUrl ? {
  1317. url: openUrl
  1318. } : {};
  1319. }
  1320. }
  1321. return newOpts;
  1322. } catch (err) {
  1323. logger.error(`通知选项转换失败${err}`);
  1324. }
  1325. return _opts;
  1326. };
  1327. opts = _adaptOpts(opts);
  1328. if (arguments.length === 1) {
  1329. title = scriptName;
  1330. subTitle = "", body = arguments[0];
  1331. }
  1332. logger.notify('\n' + `title:${title}` + '\n' + `subTitle:${subTitle}` + '\n' + `body:${body}` + '\n' + `options:${typeof opts === "object" ? JSON.stringify(opts) : opts}`);
  1333. if (env.isSurge) {
  1334. $notification.post(title, subTitle, body, opts);
  1335. } else if (env.isLoon) {
  1336. if (!!opts) $notification.post(title, subTitle, body, opts); else $notification.post(title, subTitle, body);
  1337. } else if (env.isQuanX) {
  1338. $notify(title, subTitle, body, opts);
  1339. }
  1340. if (_barkUrl && _barkKey) {
  1341. bark(title, subTitle, body);
  1342. }
  1343. }
  1344. function debug(title = scriptName, subTitle = "", body = "", opts = "") {
  1345. if (logger.getLevel() === "DEBUG") {
  1346. if (arguments.length === 1) {
  1347. title = scriptName;
  1348. subTitle = "";
  1349. body = arguments[0];
  1350. }
  1351. this.post(title, subTitle, body, opts);
  1352. }
  1353. }
  1354. function bark(title = scriptName, subTitle = "", body = "", opts = "") {
  1355. if (typeof http === "undefined" || typeof http.post === "undefined") {
  1356. throw "Bark notification needs to import MagicHttp module.";
  1357. }
  1358. let options = {
  1359. url: _barkUrl,
  1360. headers: {
  1361. "content-type": "application/json; charset=utf-8"
  1362. },
  1363. body: {
  1364. title: title,
  1365. body: subTitle ? `${subTitle}` + '\n' + `${body}` : body,
  1366. device_key: _barkKey
  1367. }
  1368. };
  1369. http.post(options).catch(ex => {
  1370. logger.error(`Bark notify error: ${ex}`);
  1371. });
  1372. }
  1373. return {
  1374. post: post,
  1375. debug: debug,
  1376. bark: bark,
  1377. setBark: setBark,
  1378. appendNotifyInfo: appendNotifyInfo,
  1379. prependNotifyInfo: prependNotifyInfo,
  1380. msg: msg,
  1381. };
  1382. }
  1383. function MagicUtils(env, logger) {
  1384. const retry = (fn, retries = 5, interval = 0, callback = null) => {
  1385. return (...args) => {
  1386. return new Promise((resolve, reject) => {
  1387. function _retry(...args) {
  1388. Promise.resolve().then(() => fn.apply(this, args)).then(result => {
  1389. if (typeof callback === "function") {
  1390. Promise.resolve().then(() => callback(result)).then(() => {
  1391. resolve(result);
  1392. }).catch(ex => {
  1393. if (retries >= 1) {
  1394. if (interval > 0) setTimeout(() => _retry.apply(this, args), interval); else _retry.apply(this, args);
  1395. } else {
  1396. reject(ex);
  1397. }
  1398. retries--;
  1399. });
  1400. } else {
  1401. resolve(result);
  1402. }
  1403. }).catch(ex => {
  1404. logger.error(ex);
  1405. if (retries >= 1 && interval > 0) {
  1406. setTimeout(() => _retry.apply(this, args), interval);
  1407. } else if (retries >= 1) {
  1408. _retry.apply(this, args);
  1409. } else {
  1410. reject(ex);
  1411. }
  1412. retries--;
  1413. });
  1414. }
  1415. _retry.apply(this, args);
  1416. });
  1417. };
  1418. };
  1419. const formatTime = (time, fmt = "yyyy-MM-dd hh:mm:ss") => {
  1420. let o = {
  1421. "M+": time.getMonth() + 1,
  1422. "d+": time.getDate(),
  1423. "h+": time.getHours(),
  1424. "m+": time.getMinutes(),
  1425. "s+": time.getSeconds(),
  1426. "q+": Math.floor((time.getMonth() + 3) / 3),
  1427. S: time.getMilliseconds()
  1428. };
  1429. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
  1430. 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));
  1431. return fmt;
  1432. };
  1433. const now = () => {
  1434. return formatTime(new Date(), "yyyy-MM-dd hh:mm:ss");
  1435. };
  1436. const today = () => {
  1437. return formatTime(new Date(), "yyyy-MM-dd");
  1438. };
  1439. const sleep = time => {
  1440. return new Promise(resolve => setTimeout(resolve, time));
  1441. };
  1442. const assert = (val, msg = null) => {
  1443. if (env.isNode) {
  1444. const _assert = require("assert");
  1445. if (msg) _assert(val, msg); else _assert(val);
  1446. } else {
  1447. if (val !== true) {
  1448. let err = `AssertionError: ${msg || "The expression evaluated to a falsy value."}`;
  1449. logger.error(err);
  1450. }
  1451. }
  1452. };
  1453. return {
  1454. retry: retry,
  1455. formatTime: formatTime,
  1456. now: now,
  1457. today: today,
  1458. sleep: sleep,
  1459. assert: assert
  1460. };
  1461. }
  1462. function MagicQingLong(env, data, logger) {
  1463. let qlUrl = "";
  1464. let qlName = "";
  1465. let qlClient = "";
  1466. let qlSecret = "";
  1467. let qlPwd = "";
  1468. let qlToken = "";
  1469. const magicJsonFileName = "magic.json";
  1470. const timeout = 3e3;
  1471. const http = (() => MagicHttp(env, logger))();
  1472. const init = (url, clientId, clientSecret, username, password) => {
  1473. qlUrl = url;
  1474. qlClient = clientId;
  1475. qlSecret = clientSecret;
  1476. qlName = username;
  1477. qlPwd = password;
  1478. };
  1479. function readQingLongConfig(config) {
  1480. qlUrl = qlUrl || data.read("magic_qlurl");
  1481. qlToken = qlToken || data.read("magic_qltoken");
  1482. logger.debug(`QingLong url: ${qlUrl}` + '\n' + `QingLong token: ${qlToken}`);
  1483. return config;
  1484. }
  1485. function setBaseUrlAndTimeout(config) {
  1486. if (!qlUrl) {
  1487. qlUrl = data.read("magic_qlurl");
  1488. }
  1489. if (config.url.indexOf(qlUrl) < 0) {
  1490. config.url = `${qlUrl}${config.url}`;
  1491. }
  1492. return {
  1493. ...config,
  1494. timeout: timeout
  1495. };
  1496. }
  1497. function setTimestamp(config) {
  1498. config.params = {
  1499. ...config.params,
  1500. t: Date.now()
  1501. };
  1502. return config;
  1503. }
  1504. async function setAuthorization(config) {
  1505. qlToken = qlToken || data.read("magic_qltoken", "");
  1506. if (!qlToken) {
  1507. await getToken();
  1508. }
  1509. config.headers["authorization"] = `Bearer ${qlToken}`;
  1510. return config;
  1511. }
  1512. function switchClientMode(config) {
  1513. qlClient = qlClient || data.read("magic_qlclient");
  1514. if (!!qlClient) {
  1515. config.url = config.url.replace("/api/", "/open/");
  1516. }
  1517. return config;
  1518. }
  1519. async function refreshToken(error) {
  1520. try {
  1521. const message = error.message || error.error || JSON.stringify(error);
  1522. if ((message.indexOf("NSURLErrorDomain") >= 0 && message.indexOf("-1012") >= 0 || !!error.response && error.response.status === 401) && !!error.config && error.config.refreshToken !== true) {
  1523. logger.warning(`QingLong Panel token has expired`);
  1524. logger.info("Refreshing the QingLong Panel token");
  1525. await getToken();
  1526. error.config["refreshToken"] = true;
  1527. logger.info("Call the previous method again");
  1528. return await http.request(error.config.method, error.config);
  1529. } else {
  1530. return Promise.reject(error);
  1531. }
  1532. } catch (ex) {
  1533. return Promise.reject(ex);
  1534. }
  1535. }
  1536. http.interceptors.request.use(setBaseUrlAndTimeout, undefined);
  1537. http.interceptors.request.use(switchClientMode, undefined, {
  1538. runWhen: config => {
  1539. return config.url.indexOf("api/user/login") < 0 && config.url.indexOf("open/auth/token") < 0;
  1540. }
  1541. });
  1542. http.interceptors.request.use(setAuthorization, undefined, {
  1543. runWhen: config => {
  1544. return config.url.indexOf("api/user/login") < 0 && config.url.indexOf("open/auth/token") < 0;
  1545. }
  1546. });
  1547. http.interceptors.request.use(setTimestamp, undefined, {
  1548. runWhen: config => {
  1549. return config.url.indexOf("open/auth/token") < 0;
  1550. }
  1551. });
  1552. http.interceptors.request.use(readQingLongConfig, undefined);
  1553. http.interceptors.response.use(undefined, refreshToken);
  1554. async function getToken() {
  1555. qlClient = qlClient || data.read("magic_qlclient");
  1556. qlSecret = qlSecret || data.read("magic_qlsecrt");
  1557. qlName = qlName || data.read("magic_qlname");
  1558. qlPwd = qlPwd || data.read("magic_qlpwd");
  1559. if (qlUrl && qlClient && qlSecret) {
  1560. logger.info("Get token from QingLong Panel");
  1561. await http.get({
  1562. url: `/open/auth/token`,
  1563. headers: {
  1564. "content-type": "application/json"
  1565. },
  1566. params: {
  1567. client_id: qlClient,
  1568. client_secret: qlSecret
  1569. }
  1570. }).then(resp => {
  1571. if (Object.keys(resp.body).length > 0 && resp.body.data && resp.body.data.token) {
  1572. logger.info("Successfully logged in to QingLong Panel");
  1573. qlToken = resp.body.data.token;
  1574. data.write("magic_qltoken", qlToken);
  1575. } else {
  1576. throw new Error("Get QingLong Panel token failed.");
  1577. }
  1578. }).catch(err => {
  1579. logger.error(`Error logging in to QingLong Panel.` + '\n' + `${err.message || err}`);
  1580. });
  1581. } else if (qlUrl && qlName && qlPwd) {
  1582. await http.post({
  1583. url: `/api/user/login`,
  1584. headers: {
  1585. "content-type": "application/json"
  1586. },
  1587. body: {
  1588. username: qlName,
  1589. password: qlPwd
  1590. }
  1591. }).then(resp => {
  1592. logger.info("Successfully logged in to QingLong Panel");
  1593. qlToken = resp.body.data.token;
  1594. data.write("magic_qltoken", qlToken);
  1595. }).catch(err => {
  1596. logger.error(`Error logging in to QingLong Panel.` + '\n' + `${err.message || err}`);
  1597. });
  1598. }
  1599. return qlToken;
  1600. }
  1601. async function setEnv(name, value, id = null) {
  1602. qlUrl = qlUrl || data.read("magic_qlurl");
  1603. if (id === null) {
  1604. let envIds = await setEnvs([{
  1605. name: name,
  1606. value: value
  1607. }]);
  1608. if (!!envIds && envIds.length === 1) {
  1609. return envIds[0];
  1610. }
  1611. } else {
  1612. await http.put({
  1613. url: `/api/envs`,
  1614. headers: {
  1615. "content-type": "application/json"
  1616. },
  1617. body: {
  1618. name: name,
  1619. value: value,
  1620. id: id
  1621. }
  1622. }).then(resp => {
  1623. if (resp.body.code === 200) {
  1624. logger.debug(`QINGLONG UPDATE ENV ${name} <${typeof value}> (${id})` + '\n' + `${JSON.stringify(value)}`);
  1625. return true;
  1626. } else {
  1627. logger.error(`Error adding environment variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1628. }
  1629. }).catch(err => {
  1630. logger.error(`Error adding environment variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1631. return false;
  1632. });
  1633. }
  1634. }
  1635. async function setEnvs(envs) {
  1636. let envIds = [];
  1637. await http.post({
  1638. url: `/api/envs`,
  1639. headers: {
  1640. "content-type": "application/json"
  1641. },
  1642. body: envs
  1643. }).then(resp => {
  1644. if (resp.body.code === 200) {
  1645. resp.body.data.forEach(element => {
  1646. logger.debug(`QINGLONG ADD ENV ${element.name} <${typeof element.value}> (${element.id})` + '\n' + `${JSON.stringify(element)}`);
  1647. envIds.push(element.id);
  1648. });
  1649. } else {
  1650. logger.error(`Error adding environments variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1651. }
  1652. }).catch(err => {
  1653. logger.error(`Error adding environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1654. });
  1655. return envIds;
  1656. }
  1657. async function delEnvs(ids) {
  1658. return await http.delete({
  1659. url: `/api/envs`,
  1660. headers: {
  1661. accept: "application/json",
  1662. "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  1663. connection: "keep-alive",
  1664. "content-type": "application/json;charset=UTF-8",
  1665. "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"
  1666. },
  1667. body: ids
  1668. }).then(resp => {
  1669. if (resp.body.code === 200) {
  1670. logger.debug(`QINGLONG DELETE ENV IDS: ${ids}`);
  1671. return true;
  1672. } else {
  1673. logger.error(`Error deleting environments variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1674. return false;
  1675. }
  1676. }).catch(err => {
  1677. logger.error(`Error deleting environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1678. });
  1679. }
  1680. async function getEnvs(name = null, searchValue = "", retired = 0) {
  1681. let envs = [];
  1682. await http.get({
  1683. url: `/api/envs`,
  1684. headers: {
  1685. "content-type": "application/json"
  1686. },
  1687. params: {
  1688. searchValue: searchValue
  1689. }
  1690. }).then(resp => {
  1691. if (resp.body.code === 200) {
  1692. const allEnvs = resp.body.data;
  1693. if (!!name) {
  1694. let _envs = [];
  1695. for (const env of allEnvs) {
  1696. if (env.name === name) {
  1697. envs.push(env);
  1698. }
  1699. }
  1700. envs = _envs;
  1701. }
  1702. envs = allEnvs;
  1703. } else {
  1704. throw new Error(`Error reading environment variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1705. }
  1706. }).catch(err => {
  1707. throw new Error(`Error reading environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1708. });
  1709. return envs;
  1710. }
  1711. async function getEnv(id) {
  1712. let env = null;
  1713. const allEnvs = await getEnvs();
  1714. for (const _env of allEnvs) {
  1715. if (_env.id === id) {
  1716. env = _env;
  1717. break;
  1718. }
  1719. }
  1720. return env;
  1721. }
  1722. async function disableEnvs(ids) {
  1723. let result = false;
  1724. await http.put({
  1725. url: `/api/envs/disable`,
  1726. headers: {
  1727. accept: "application/json",
  1728. "accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  1729. connection: "keep-alive",
  1730. "content-type": "application/json;charset=UTF-8",
  1731. "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"
  1732. },
  1733. body: ids
  1734. }).then(resp => {
  1735. if (resp.body.code === 200) {
  1736. logger.debug(`QINGLONG DISABLED ENV IDS: ${ids}`);
  1737. result = true;
  1738. } else {
  1739. logger.error(`Error disabling environments variable from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1740. }
  1741. }).catch(err => {
  1742. logger.error(`Error disabling environments variable from QingLong Panel.` + '\n' + `${err.message || err}`);
  1743. });
  1744. return result;
  1745. }
  1746. async function enableEnvs(ids) {
  1747. let result = false;
  1748. await http.put({
  1749. url: `/api/envs/enable`,
  1750. headers: {
  1751. accept: "application/json",
  1752. "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  1753. connection: "keep-alive",
  1754. "content-type": "application/json;charset=UTF-8",
  1755. "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"
  1756. },
  1757. body: ids
  1758. }).then(resp => {
  1759. if (resp.body.code === 200) {
  1760. logger.debug(`QINGLONG ENABLED ENV IDS: ${ids}`);
  1761. result = true;
  1762. } else {
  1763. logger.error(`Error enabling environments variable from Qilong panel.` + '\n' + `${JSON.stringify(resp)}`);
  1764. }
  1765. }).catch(err => {
  1766. logger.error(`Error enabling environments variable from Qilong panel.` + '\n' + `${err.message || err}`);
  1767. });
  1768. return result;
  1769. }
  1770. async function addScript(name, path = "", content = "") {
  1771. let result = false;
  1772. await http.post({
  1773. url: `/api/scripts`,
  1774. headers: {
  1775. "content-type": "application/json"
  1776. },
  1777. body: {
  1778. filename: name,
  1779. path: path,
  1780. content: content
  1781. }
  1782. }).then(resp => {
  1783. if (resp.body.code === 200) {
  1784. result = true;
  1785. } else {
  1786. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1787. }
  1788. }).catch(err => {
  1789. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1790. });
  1791. return result;
  1792. }
  1793. async function getScript(name, path = "") {
  1794. let content = "";
  1795. await http.get({
  1796. url: `/api/scripts/${name}`,
  1797. params: {
  1798. path: path
  1799. }
  1800. }).then(resp => {
  1801. if (resp.body.code === 200) {
  1802. content = resp.body.data;
  1803. } else {
  1804. throw new Error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1805. }
  1806. }).catch(err => {
  1807. throw new Error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1808. });
  1809. return content;
  1810. }
  1811. async function editScript(name, path = "", content = "") {
  1812. let result = false;
  1813. await http.put({
  1814. url: `/api/scripts`,
  1815. headers: {
  1816. "content-type": "application/json"
  1817. },
  1818. body: {
  1819. filename: name,
  1820. path: path,
  1821. content: content
  1822. }
  1823. }).then(resp => {
  1824. if (resp.body.code === 200) {
  1825. result = true;
  1826. } else {
  1827. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1828. }
  1829. }).catch(err => {
  1830. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1831. });
  1832. return result;
  1833. }
  1834. async function delScript(name, path = "") {
  1835. let result = false;
  1836. await http.delete({
  1837. url: `/api/scripts`,
  1838. headers: {
  1839. "content-type": "application/json"
  1840. },
  1841. body: {
  1842. filename: name,
  1843. path: path
  1844. }
  1845. }).then(resp => {
  1846. if (resp.body.code === 200) {
  1847. result = true;
  1848. } else {
  1849. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${JSON.stringify(resp)}`);
  1850. }
  1851. }).catch(err => {
  1852. logger.error(`Error reading data from QingLong Panel.` + '\n' + `${err.message || err}`);
  1853. });
  1854. return result;
  1855. }
  1856. async function write(key, val, session = "") {
  1857. let qlContent = await getScript(magicJsonFileName, "");
  1858. let qlData = data.convertToObject(qlContent);
  1859. let writeResult = data.write(key, val, session, qlData);
  1860. qlContent = JSON.stringify(qlData, null, 4);
  1861. let editResult = await editScript(magicJsonFileName, "", qlContent);
  1862. return editResult && writeResult;
  1863. }
  1864. async function batchWrite(...args) {
  1865. let qlContent = await getScript(magicJsonFileName, "");
  1866. let qlData = data.convertToObject(qlContent);
  1867. for (let arg of args) {
  1868. data.write(arg[0], arg[1], typeof arg[2] !== "undefined" ? arg[2] : "", qlData);
  1869. }
  1870. qlContent = JSON.stringify(qlData, null, 4);
  1871. return await editScript(magicJsonFileName, "", qlContent);
  1872. }
  1873. async function update(key, val, session, comparator = data.defaultValueComparator) {
  1874. let qlContent = await getScript(magicJsonFileName, "");
  1875. let qlData = data.convertToObject(qlContent);
  1876. const updateResult = data.update(key, val, session, comparator, qlData);
  1877. let editScriptResult = false;
  1878. if (updateResult === true) {
  1879. qlContent = JSON.stringify(qlData, null, 4);
  1880. editScriptResult = await editScript(magicJsonFileName, "", qlContent);
  1881. }
  1882. return updateResult && editScriptResult;
  1883. }
  1884. async function batchUpdate(...args) {
  1885. let qlContent = await getScript(magicJsonFileName, "");
  1886. let qlData = data.convertToObject(qlContent);
  1887. for (let arg of args) {
  1888. data.update(arg[0], arg[1], typeof arg[2] !== "undefined" ? arg[2] : "", typeof arg[3] !== "undefined" ? arg["comparator"] : data.defaultValueComparator, qlData);
  1889. }
  1890. qlContent = JSON.stringify(qlData, null, 4);
  1891. return await editScript(magicJsonFileName, "", qlContent);
  1892. }
  1893. async function read(key, val, session = "", read_no_session = false) {
  1894. let qlContent = await getScript(magicJsonFileName, "");
  1895. let qlData = data.convertToObject(qlContent);
  1896. return data.read(key, val, session, read_no_session, qlData);
  1897. }
  1898. async function batchRead(...args) {
  1899. let qlContent = await getScript(magicJsonFileName, "");
  1900. let qlData = data.convertToObject(qlContent);
  1901. let results = [];
  1902. for (let arg of args) {
  1903. const result = data.read(arg[0], arg[1], typeof arg[2] !== "undefined" ? arg[2] : "", typeof arg[3] === "boolean" ? arg[3] : false, qlData);
  1904. results.push(result);
  1905. }
  1906. return results;
  1907. }
  1908. async function del(key, session = "") {
  1909. let qlContent = await getScript(magicJsonFileName, "");
  1910. let qlData = data.convertToObject(qlContent);
  1911. const delResult = data.del(key, session, qlData);
  1912. qlContent = JSON.stringify(qlData, null, 4);
  1913. const editResult = await editScript(magicJsonFileName, "", qlContent);
  1914. return delResult && editResult;
  1915. }
  1916. async function batchDel(...args) {
  1917. let qlContent = await getScript(magicJsonFileName, "");
  1918. let qlData = data.convertToObject(qlContent);
  1919. for (let arg of args) {
  1920. data.del(arg[0], typeof arg[1] !== "undefined" ? arg[1] : "", qlData);
  1921. }
  1922. qlContent = JSON.stringify(qlData, null, 4);
  1923. return await editScript(magicJsonFileName, "", qlContent);
  1924. }
  1925. async function allSessionNames(key) {
  1926. let qlContent = await getScript(magicJsonFileName, "");
  1927. let qlData = data.convertToObject(qlContent);
  1928. return data.allSessionNames(key, qlData);
  1929. }
  1930. async function allSessions(key) {
  1931. let qlContent = await getScript(magicJsonFileName, "");
  1932. let qlData = data.convertToObject(qlContent);
  1933. return data.allSessions(key, qlData);
  1934. }
  1935. return {
  1936. url: qlUrl || data.read("magic_qlurl"),
  1937. init: init,
  1938. getToken: getToken,
  1939. setEnv: setEnv,
  1940. setEnvs: setEnvs,
  1941. getEnv: getEnv,
  1942. getEnvs: getEnvs,
  1943. delEnvs: delEnvs,
  1944. disableEnvs: disableEnvs,
  1945. enableEnvs: enableEnvs,
  1946. addScript: addScript,
  1947. getScript: getScript,
  1948. editScript: editScript,
  1949. delScript: delScript,
  1950. write: write,
  1951. read: read,
  1952. del: del,
  1953. update: update,
  1954. batchWrite: batchWrite,
  1955. batchRead: batchRead,
  1956. batchUpdate: batchUpdate,
  1957. batchDel: batchDel,
  1958. allSessions: allSessions,
  1959. allSessionNames: allSessionNames
  1960. };
  1961. }