MagicJS3.js 70 KB

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