MagicJS3.js 75 KB

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