MagicJS3.js 75 KB

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