MagicJS3.js 69 KB

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