ToolKit.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /**
  2. * 根据自己的习惯整合各个开发者而形成的工具包(@NobyDa, @chavyleung)
  3. * 兼容surge,quantumult x,loon,node环境
  4. * 并且加入一些好用的方法
  5. * 方法如下:
  6. * isEmpty: 判断字符串是否是空(undefined,null,空串)
  7. * getRequestUrl: 获取请求的url(目前仅支持surge和quanx)
  8. * getResponseBody: 获取响应体(目前仅支持surge和quanx)
  9. * boxJsJsonBuilder:构建最简默认boxjs配置json
  10. * randomString: 生成随机字符串
  11. * autoComplete: 自动补齐字符串
  12. * customReplace: 自定义替换
  13. * hash: 字符串做hash
  14. *
  15. * ⚠️当开启当且仅当执行失败的时候通知选项,请在执行失败的地方执行execFail()
  16. *
  17. * @param scriptName 脚本名,用于通知时候的标题
  18. * @param scriptId 每个脚本唯一的id,用于存储持久化的时候加入key
  19. * @param options 传入一些参数,目前参数如下;
  20. * [email protected]:6166(这个是默认值,本人surge调试脚本用,可自行修改)
  21. * target_boxjs_json_path=/Users/lowking/Desktop/Scripts/lowking.boxjs.json(生成boxjs配置的目标文件路径)
  22. * @constructor
  23. */
  24. function ToolKit(scriptName, scriptId, options) {
  25. return new (class {
  26. constructor(scriptName, scriptId, options) {
  27. this.tgEscapeCharMapping = { '&': '&', '#': '#' }
  28. this.userAgent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`
  29. this.prefix = `lk`
  30. this.name = scriptName
  31. this.id = scriptId
  32. this.data = null
  33. this.dataFile = this.getRealPath(`${this.prefix}${this.id}.dat`)
  34. this.boxJsJsonFile = this.getRealPath(`${this.prefix}${this.id}.boxjs.json`)
  35. //surge http api等一些扩展参数
  36. this.options = options
  37. //命令行入参
  38. this.isExecComm = false
  39. //默认脚本开关
  40. this.isEnableLog = this.getVal(`${this.prefix}IsEnableLog${this.id}`)
  41. this.isEnableLog = this.isEmpty(this.isEnableLog) ? true : JSON.parse(this.isEnableLog)
  42. this.isNotifyOnlyFail = this.getVal(`${this.prefix}NotifyOnlyFail${this.id}`)
  43. this.isNotifyOnlyFail = this.isEmpty(this.isNotifyOnlyFail) ? false : JSON.parse(this.isNotifyOnlyFail)
  44. //tg通知开关
  45. this.isEnableTgNotify = this.getVal(`${this.prefix}IsEnableTgNotify${this.id}`)
  46. this.isEnableTgNotify = this.isEmpty(this.isEnableTgNotify) ? false : JSON.parse(this.isEnableTgNotify)
  47. this.tgNotifyUrl = this.getVal(`${this.prefix}TgNotifyUrl${this.id}`)
  48. this.isEnableTgNotify = this.isEnableTgNotify ? !this.isEmpty(this.tgNotifyUrl) : this.isEnableTgNotify
  49. //计时部分
  50. this.costTotalStringKey = `${this.prefix}CostTotalString${this.id}`
  51. this.costTotalString = this.getVal(this.costTotalStringKey)
  52. this.costTotalString = this.isEmpty(this.costTotalString) ? `0,0` : this.costTotalString.replace("\"", "")
  53. this.costTotalMs = this.costTotalString.split(",")[0]
  54. this.execCount = this.costTotalString.split(",")[1]
  55. this.costTotalMs = this.isEmpty(this.costTotalMs) ? 0 : parseInt(this.costTotalMs)
  56. this.execCount = this.isEmpty(this.execCount) ? 0 : parseInt(this.execCount)
  57. this.logSeparator = '\n██'
  58. this.now = new Date()
  59. this.startTime = this.now.getTime()
  60. this.node = (() => {
  61. if (this.isNode()) {
  62. const request = require('request')
  63. return ({ request })
  64. } else {
  65. return (null)
  66. }
  67. })()
  68. this.execStatus = true
  69. this.notifyInfo = []
  70. this.log(`${this.name}, 开始执行!`)
  71. this.initCache()
  72. this.checkRecordRequestBody()
  73. this.execComm()
  74. }
  75. checkRecordRequestBody() {
  76. if (!this.isRequest()) {
  77. return;
  78. }
  79. const reqBody = $request.body;
  80. if (!reqBody) {
  81. return;
  82. }
  83. const path = $request.path;
  84. const cacheKey = this.id + "#" + path.replace("/", "_");
  85. if (this.isQuanX()) $prefs.setValueForKey(reqBody, cacheKey);
  86. if (this.isLoon() || this.isSurge()) $persistentStore.write(reqBody, cacheKey);
  87. if (this.isNode()) {
  88. this.node.fs.writeFileSync(
  89. `${cacheKey}.json`,
  90. reqBody,
  91. {
  92. flag: "w"
  93. },
  94. (err) => console.log(err)
  95. );
  96. }
  97. }
  98. getRequestBody() {
  99. const path = $request.path;
  100. const cacheKey = this.id + "#" + path.replace("/", "_");
  101. if (this.isSurge() || this.isLoon()) {
  102. return $persistentStore.read(cacheKey);
  103. }
  104. if (this.isQuanX()) {
  105. return $prefs.valueForKey(cacheKey);
  106. }
  107. if (this.isNode()) {
  108. const fpath = `${cacheKey}.json`;
  109. if (!this.node.fs.existsSync(fpath)) {
  110. return JSON.parse(
  111. this.node.fs.readFileSync(fpath)
  112. );
  113. }
  114. }
  115. }
  116. // persistence
  117. // initialize cache
  118. initCache() {
  119. const pKey = this.getPersistKey();
  120. if (this.isQuanX()) this.cache = JSON.parse($prefs.valueForKey(pKey) || "{}");
  121. if (this.isLoon() || this.isSurge())
  122. this.cache = JSON.parse($persistentStore.read(pKey) || "{}");
  123. if (this.isNode()) {
  124. // create a json for root cache
  125. let fpath = "root.json";
  126. if (!this.node.fs.existsSync(fpath)) {
  127. this.node.fs.writeFileSync(
  128. fpath,
  129. JSON.stringify({}),
  130. {
  131. flag: "wx"
  132. },
  133. (err) => console.log(err)
  134. );
  135. }
  136. this.root = {};
  137. // create a json file with the given name if not exists
  138. fpath = `${pKey}.json`;
  139. if (!this.node.fs.existsSync(fpath)) {
  140. this.node.fs.writeFileSync(
  141. fpath,
  142. JSON.stringify({}),
  143. {
  144. flag: "wx"
  145. },
  146. (err) => console.log(err)
  147. );
  148. this.cache = {};
  149. } else {
  150. this.cache = JSON.parse(
  151. this.node.fs.readFileSync(`${pKey}.json`)
  152. );
  153. }
  154. }
  155. }
  156. getPersistKey() {
  157. return `${this.id}#privateCache`;
  158. }
  159. // store cache
  160. persistCache() {
  161. const pKey = this.getPersistKey();
  162. const data = JSON.stringify(this.cache, null, 2);
  163. if (this.isQuanX()) $prefs.setValueForKey(data, pKey);
  164. if (this.isLoon() || this.isSurge()) $persistentStore.write(data, pKey);
  165. if (this.isNode()) {
  166. this.node.fs.writeFileSync(
  167. `${pKey}.json`,
  168. data,
  169. {
  170. flag: "w"
  171. },
  172. (err) => console.log(err)
  173. );
  174. this.node.fs.writeFileSync(
  175. "root.json",
  176. JSON.stringify(this.root, null, 2),
  177. {
  178. flag: "w"
  179. },
  180. (err) => console.log(err)
  181. );
  182. }
  183. }
  184. write(data, key) {
  185. this.log(`SET ${key}`);
  186. if (key.indexOf("#") !== -1) {
  187. key = key.substr(1);
  188. if (isSurge || this.isLoon()) {
  189. return $persistentStore.write(data, key);
  190. }
  191. if (this.isQuanX()) {
  192. return $prefs.setValueForKey(data, key);
  193. }
  194. if (this.isNode()) {
  195. this.root[key] = data;
  196. }
  197. } else {
  198. this.cache[key] = data;
  199. }
  200. this.persistCache();
  201. }
  202. read(key) {
  203. this.log(`READ ${key}`);
  204. if (key.indexOf("#") !== -1) {
  205. key = key.substr(1);
  206. if (this.isSurge() || this.isLoon()) {
  207. return $persistentStore.read(key);
  208. }
  209. if (this.isQuanX()) {
  210. return $prefs.valueForKey(key);
  211. }
  212. if (this.isNode()) {
  213. return this.root[key];
  214. }
  215. } else {
  216. return this.cache[key];
  217. }
  218. }
  219. delete(key) {
  220. this.log(`DELETE ${key}`);
  221. if (key.indexOf("#") !== -1) {
  222. key = key.substr(1);
  223. if (this.isSurge() || this.isLoon()) {
  224. return $persistentStore.write(null, key);
  225. }
  226. if (this.isQuanX()) {
  227. return $prefs.removeValueForKey(key);
  228. }
  229. if (this.isNode()) {
  230. delete this.root[key];
  231. }
  232. } else {
  233. delete this.cache[key];
  234. }
  235. this.persistCache();
  236. }
  237. //当执行命令的目录不是脚本所在目录时,自动把文件路径改成指令传入的路径并返回完整文件路径
  238. getRealPath(fileName) {
  239. if (this.isNode()) {
  240. let targetPath = process.argv.slice(1, 2)[0].split("/")
  241. targetPath[targetPath.length - 1] = fileName
  242. return targetPath.join("/")
  243. }
  244. return fileName
  245. }
  246. /**
  247. * http://boxjs.com/ => http://boxjs.com
  248. * http://boxjs.com/app/jd => http://boxjs.com
  249. */
  250. getUrlHost(url) {
  251. return url.slice(0, url.indexOf('/', 8))
  252. }
  253. /**
  254. * http://boxjs.com/ =>
  255. * http://boxjs.com/api/getdata => /api/getdata
  256. */
  257. getUrlPath(url) {
  258. // 如果以结尾, 去掉最后一个/
  259. const end = url.lastIndexOf('/') === url.length - 1 ? -1 : undefined
  260. // slice第二个参数传 undefined 会直接截到最后
  261. // indexOf第二个参数用来跳过前面的 "https://"
  262. return url.slice(url.indexOf('/', 8), end)
  263. }
  264. async execComm() {
  265. //支持node命令,实现发送手机测试
  266. if (this.isNode()) {
  267. this.comm = process.argv.slice(1)
  268. let isHttpApiErr = false
  269. if (this.comm[1] == "p") {
  270. this.isExecComm = true
  271. //phone
  272. this.log(`开始执行指令【${this.comm[1]}】=> 发送到手机测试脚本!`);
  273. if (this.isEmpty(this.options) || this.isEmpty(this.options.httpApi)) {
  274. this.log(`未设置options,使用默认值`)
  275. //设置默认值
  276. if (this.isEmpty(this.options)) {
  277. this.options = {}
  278. }
  279. this.options.httpApi = `[email protected]:6166`
  280. } else {
  281. //判断格式
  282. if (!/.*?@.*?:[0-9]+/.test(this.options.httpApi)) {
  283. isHttpApiErr = true
  284. this.log(`❌httpApi格式错误!格式:[email protected]:6166`)
  285. this.done()
  286. }
  287. }
  288. if (!isHttpApiErr) {
  289. this.callApi(this.comm[2])
  290. }
  291. }
  292. }
  293. }
  294. callApi(timeout) {
  295. // 直接用接收到文件路径,解决在不同目录下都可以使用 node xxxx/xxx.js p 指令发送脚本给手机执行
  296. // let fname = this.getCallerFileNameAndLine().split(":")[0].replace("[", "")
  297. let fname = this.comm[0]
  298. this.log(`获取【${fname}】内容传给手机`)
  299. let scriptStr = ''
  300. this.fs = this.fs ? this.fs : require('fs')
  301. this.path = this.path ? this.path : require('path')
  302. const curDirDataFilePath = this.path.resolve(fname)
  303. const rootDirDataFilePath = this.path.resolve(process.cwd(), fname)
  304. const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
  305. const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
  306. if (isCurDirDataFile || isRootDirDataFile) {
  307. const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath
  308. try {
  309. scriptStr = this.fs.readFileSync(datPath)
  310. } catch (e) {
  311. scriptStr = ''
  312. }
  313. } else {
  314. scriptStr = ''
  315. }
  316. let options = {
  317. url: `http://${this.options.httpApi.split("@")[1]}/v1/scripting/evaluate`,
  318. headers: {
  319. "X-Key": `${this.options.httpApi.split("@")[0]}`
  320. },
  321. body: {
  322. "script_text": `${scriptStr}`,
  323. "mock_type": "cron",
  324. "timeout": (!this.isEmpty(timeout) && timeout > 5) ? timeout : 5
  325. },
  326. json: true
  327. }
  328. this.post(options, (_error, _response, _data) => {
  329. this.log(`已将脚本【${fname}】发给手机!`)
  330. this.done()
  331. })
  332. }
  333. getCallerFileNameAndLine() {
  334. let error
  335. try {
  336. throw Error('')
  337. } catch (err) {
  338. error = err
  339. }
  340. const stack = error.stack
  341. const stackArr = stack.split('\n')
  342. let callerLogIndex = 1
  343. if (callerLogIndex !== 0) {
  344. const callerStackLine = stackArr[callerLogIndex]
  345. this.path = this.path ? this.path : require('path')
  346. return `[${callerStackLine.substring(callerStackLine.lastIndexOf(this.path.sep) + 1, callerStackLine.lastIndexOf(':'))}]`
  347. } else {
  348. return '[-]'
  349. }
  350. }
  351. getFunName(fun) {
  352. var ret = fun.toString()
  353. ret = ret.substr('function '.length)
  354. ret = ret.substr(0, ret.indexOf('('))
  355. return ret
  356. }
  357. boxJsJsonBuilder(info, param) {
  358. if (this.isNode()) {
  359. let boxjsJsonPath = "/Users/lowking/Desktop/Scripts/lowking.boxjs.json"
  360. // 从传入参数param读取配置的boxjs的json文件路径
  361. if (param && param.hasOwnProperty("target_boxjs_json_path")) {
  362. boxjsJsonPath = param["target_boxjs_json_path"]
  363. }
  364. if (!this.fs.existsSync(boxjsJsonPath)) {
  365. return
  366. }
  367. if (!this.isJsonObject(info) || !this.isJsonObject(param)) {
  368. this.log("构建BoxJsJson传入参数格式错误,请传入json对象")
  369. return
  370. }
  371. this.log('using node')
  372. let needAppendKeys = ["settings", "keys"]
  373. const domain = 'https://raw.githubusercontent.com/Orz-3'
  374. let boxJsJson = {}
  375. let scritpUrl = '#lk{script_url}'
  376. if (param && param.hasOwnProperty('script_url')) {
  377. scritpUrl = this.isEmpty(param['script_url']) ? "#lk{script_url}" : param['script_url']
  378. }
  379. boxJsJson.id = `${this.prefix}${this.id}`
  380. boxJsJson.name = this.name
  381. boxJsJson.desc_html = `⚠️使用说明</br>详情【<a href='${scritpUrl}?raw=true'><font class='red--text'>点我查看</font></a>】`
  382. boxJsJson.icons = [`${domain}/mini/master/Alpha/${this.id.toLocaleLowerCase()}.png`, `${domain}/mini/master/Color/${this.id.toLocaleLowerCase()}.png`]
  383. boxJsJson.keys = []
  384. boxJsJson.settings = [
  385. {
  386. "id": `${this.prefix}IsEnableLog${this.id}`,
  387. "name": "开启/关闭日志",
  388. "val": true,
  389. "type": "boolean",
  390. "desc": "默认开启"
  391. },
  392. {
  393. "id": `${this.prefix}NotifyOnlyFail${this.id}`,
  394. "name": "只当执行失败才通知",
  395. "val": false,
  396. "type": "boolean",
  397. "desc": "默认关闭"
  398. },
  399. {
  400. "id": `${this.prefix}IsEnableTgNotify${this.id}`,
  401. "name": "开启/关闭Telegram通知",
  402. "val": false,
  403. "type": "boolean",
  404. "desc": "默认关闭"
  405. },
  406. {
  407. "id": `${this.prefix}TgNotifyUrl${this.id}`,
  408. "name": "Telegram通知地址",
  409. "val": "",
  410. "type": "text",
  411. "desc": "Tg的通知地址,如:https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="
  412. }
  413. ]
  414. boxJsJson.author = "#lk{author}"
  415. boxJsJson.repo = "#lk{repo}"
  416. boxJsJson.script = `${scritpUrl}?raw=true`
  417. // 除了settings和keys追加,其他的都覆盖
  418. if (!this.isEmpty(info)) {
  419. for (let i in needAppendKeys) {
  420. let key = needAppendKeys[i]
  421. if (!this.isEmpty(info[key])) {
  422. // 处理传入的每项设置
  423. if (key === 'settings') {
  424. for (let i = 0; i < info[key].length; i++) {
  425. let input = info[key][i]
  426. for (let j = 0; j < boxJsJson.settings.length; j++) {
  427. let def = boxJsJson.settings[j]
  428. if (input.id === def.id) {
  429. // id相同,就使用外部传入的配置
  430. boxJsJson.settings.splice(j, 1)
  431. }
  432. }
  433. }
  434. }
  435. boxJsJson[key] = boxJsJson[key].concat(info[key])
  436. }
  437. delete info[key]
  438. }
  439. }
  440. Object.assign(boxJsJson, info)
  441. if (this.isNode()) {
  442. this.fs = this.fs ? this.fs : require('fs')
  443. this.path = this.path ? this.path : require('path')
  444. const curDirDataFilePath = this.path.resolve(this.boxJsJsonFile)
  445. const rootDirDataFilePath = this.path.resolve(process.cwd(), this.boxJsJsonFile)
  446. const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
  447. const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
  448. const jsondata = JSON.stringify(boxJsJson, null, '\t')
  449. if (isCurDirDataFile) {
  450. this.fs.writeFileSync(curDirDataFilePath, jsondata)
  451. } else if (isRootDirDataFile) {
  452. this.fs.writeFileSync(rootDirDataFilePath, jsondata)
  453. } else {
  454. this.fs.writeFileSync(curDirDataFilePath, jsondata)
  455. }
  456. // 写到项目的boxjs订阅json中
  457. let boxjsJson = JSON.parse(this.fs.readFileSync(boxjsJsonPath))
  458. if (boxjsJson.hasOwnProperty("apps") && Array.isArray(boxjsJson["apps"]) && boxjsJson["apps"].length > 0) {
  459. let apps = boxjsJson.apps
  460. let targetIdx = apps.indexOf(apps.filter((app) => {
  461. return app.id == boxJsJson.id
  462. })[0])
  463. if (targetIdx >= 0) {
  464. boxjsJson.apps[targetIdx] = boxJsJson
  465. } else {
  466. boxjsJson.apps.push(boxJsJson)
  467. }
  468. let ret = JSON.stringify(boxjsJson, null, 2)
  469. if (!this.isEmpty(param)) {
  470. for (const key in param) {
  471. let val = ''
  472. if (param.hasOwnProperty(key)) {
  473. val = param[key]
  474. } else if (key === 'author') {
  475. val = '@lowking'
  476. } else if (key === 'repo') {
  477. val = 'https://github.com/lowking/Scripts'
  478. }
  479. ret = ret.replace(`#lk{${key}}`, val)
  480. }
  481. }
  482. // 全部处理完毕检查是否有漏掉未配置的参数,进行提醒
  483. const regex = /(?:#lk\{)(.+?)(?=\})/
  484. let m = regex.exec(ret)
  485. if (m !== null) {
  486. this.log('生成BoxJs还有未配置的参数,请参考https://github.com/lowking/Scripts/blob/master/util/example/ToolKitDemo.js#L17-L18传入参数:\n')
  487. }
  488. let loseParamSet = new Set()
  489. while ((m = regex.exec(ret)) !== null) {
  490. loseParamSet.add(m[1])
  491. ret = ret.replace(`#lk{${m[1]}}`, ``)
  492. }
  493. loseParamSet.forEach(p => {
  494. console.log(`${p} `)
  495. })
  496. this.fs.writeFileSync(boxjsJsonPath, ret)
  497. }
  498. }
  499. }
  500. }
  501. isJsonObject(obj) {
  502. return typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length
  503. }
  504. appendNotifyInfo(info, type) {
  505. if (type == 1) {
  506. this.notifyInfo = info
  507. } else {
  508. this.notifyInfo.push(info)
  509. }
  510. }
  511. prependNotifyInfo(info) {
  512. this.notifyInfo.splice(0, 0, info)
  513. }
  514. execFail() {
  515. this.execStatus = false
  516. }
  517. isRequest() {
  518. return typeof $request != "undefined"
  519. }
  520. isSurge() {
  521. return typeof $httpClient != "undefined"
  522. }
  523. isQuanX() {
  524. return typeof $task != "undefined"
  525. }
  526. isLoon() {
  527. return typeof $loon != "undefined"
  528. }
  529. isJSBox() {
  530. return typeof $app != "undefined" && typeof $http != "undefined"
  531. }
  532. isStash() {
  533. return 'undefined' !== typeof $environment && $environment['stash-version']
  534. }
  535. isNode() {
  536. return typeof require == "function" && !this.isJSBox()
  537. }
  538. sleep(time) {
  539. return new Promise((resolve) => setTimeout(resolve, time))
  540. }
  541. log(message) {
  542. if (this.isEnableLog) console.log(`${this.logSeparator}${message}`)
  543. }
  544. logErr(message) {
  545. this.execStatus = true
  546. if (this.isEnableLog) {
  547. console.log(`${this.logSeparator}${this.name}执行异常:`)
  548. console.log(message)
  549. console.log('\n' + `${message.message}`)
  550. }
  551. }
  552. msg(subtitle, message, openUrl, mediaUrl) {
  553. if (!this.isRequest() && this.isNotifyOnlyFail && this.execStatus) {
  554. //开启了当且仅当执行失败的时候通知,并且执行成功了,这时候不通知
  555. } else {
  556. if (this.isEmpty(message)) {
  557. if (Array.isArray(this.notifyInfo)) {
  558. message = this.notifyInfo.join("\n")
  559. } else {
  560. message = this.notifyInfo
  561. }
  562. }
  563. if (!this.isEmpty(message)) {
  564. if (this.isEnableTgNotify) {
  565. this.log(`${this.name}Tg通知开始`)
  566. //处理特殊字符
  567. for (let key in this.tgEscapeCharMapping) {
  568. if (!this.tgEscapeCharMapping.hasOwnProperty(key)) {
  569. continue
  570. }
  571. message = message.replace(key, this.tgEscapeCharMapping[key])
  572. }
  573. this.get({
  574. url: encodeURI(`${this.tgNotifyUrl}📌${this.name}` + '\n' + `${message}`)
  575. }, (_error, _statusCode, _body) => {
  576. this.log(`Tg通知完毕`)
  577. })
  578. } else {
  579. let options = {}
  580. const hasOpenUrl = !this.isEmpty(openUrl)
  581. const hasMediaUrl = !this.isEmpty(mediaUrl)
  582. if (this.isQuanX()) {
  583. if (hasOpenUrl) options["open-url"] = openUrl
  584. if (hasMediaUrl) options["media-url"] = mediaUrl
  585. $notify(this.name, subtitle, message, options)
  586. }
  587. if (this.isSurge() || this.isStash()) {
  588. if (hasOpenUrl) options["url"] = openUrl
  589. $notification.post(this.name, subtitle, message, options)
  590. }
  591. if (this.isNode()) this.log("⭐️" + this.name + "\n" + subtitle + "\n" + message)
  592. if (this.isJSBox()) $push.schedule({
  593. title: this.name,
  594. body: subtitle ? subtitle + "\n" + message : message
  595. })
  596. }
  597. }
  598. }
  599. }
  600. getVal(key, defaultValue = "") {
  601. let value
  602. if (this.isSurge() || this.isLoon() || this.isStash()) {
  603. value = $persistentStore.read(key)
  604. } else if (this.isQuanX()) {
  605. value = $prefs.valueForKey(key)
  606. } else if (this.isNode()) {
  607. this.data = this.loadData()
  608. value = process.env[key] || this.data[key]
  609. } else {
  610. value = (this.data && this.data[key]) || null
  611. }
  612. return !value ? defaultValue : value
  613. }
  614. setVal(key, val) {
  615. if (this.isSurge() || this.isLoon() || this.isStash()) {
  616. return $persistentStore.write(val, key)
  617. } else if (this.isQuanX()) {
  618. return $prefs.setValueForKey(val, key)
  619. } else if (this.isNode()) {
  620. this.data = this.loadData()
  621. this.data[key] = val
  622. this.writeData()
  623. return true
  624. } else {
  625. return (this.data && this.data[key]) || null
  626. }
  627. }
  628. loadData() {
  629. if (this.isNode()) {
  630. this.fs = this.fs ? this.fs : require('fs')
  631. this.path = this.path ? this.path : require('path')
  632. const curDirDataFilePath = this.path.resolve(this.dataFile)
  633. const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
  634. const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
  635. const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
  636. if (isCurDirDataFile || isRootDirDataFile) {
  637. const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath
  638. try {
  639. return JSON.parse(this.fs.readFileSync(datPath))
  640. } catch (e) {
  641. return {}
  642. }
  643. } else return {}
  644. } else return {}
  645. }
  646. writeData() {
  647. if (this.isNode()) {
  648. this.fs = this.fs ? this.fs : require('fs')
  649. this.path = this.path ? this.path : require('path')
  650. const curDirDataFilePath = this.path.resolve(this.dataFile)
  651. const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
  652. const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
  653. const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
  654. const jsondata = JSON.stringify(this.data)
  655. if (isCurDirDataFile) {
  656. this.fs.writeFileSync(curDirDataFilePath, jsondata)
  657. } else if (isRootDirDataFile) {
  658. this.fs.writeFileSync(rootDirDataFilePath, jsondata)
  659. } else {
  660. this.fs.writeFileSync(curDirDataFilePath, jsondata)
  661. }
  662. }
  663. }
  664. adapterStatus(response) {
  665. if (response) {
  666. if (response.status) {
  667. response["statusCode"] = response.status
  668. } else if (response.statusCode) {
  669. response["status"] = response.statusCode
  670. }
  671. }
  672. return response
  673. }
  674. get(options, callback = () => { }) {
  675. if (this.isQuanX()) {
  676. if (typeof options == "string") options = {
  677. url: options
  678. }
  679. options["method"] = "GET"
  680. $task.fetch(options).then(response => {
  681. callback(null, this.adapterStatus(response), response.body)
  682. }, reason => callback(reason.error, null, null))
  683. }
  684. if (this.isSurge() || this.isLoon() || this.isStash()) $httpClient.get(options, (error, response, body) => {
  685. callback(error, this.adapterStatus(response), body)
  686. })
  687. if (this.isNode()) {
  688. this.node.request(options, (error, response, body) => {
  689. callback(error, this.adapterStatus(response), body)
  690. })
  691. }
  692. if (this.isJSBox()) {
  693. if (typeof options == "string") options = {
  694. url: options
  695. }
  696. options["header"] = options["headers"]
  697. options["handler"] = function (resp) {
  698. let error = resp.error
  699. if (error) error = JSON.stringify(resp.error)
  700. let body = resp.data
  701. if (typeof body == "object") body = JSON.stringify(resp.data)
  702. callback(error, this.adapterStatus(resp.response), body)
  703. }
  704. $http.get(options)
  705. }
  706. }
  707. post(options, callback = () => { }) {
  708. if (this.isQuanX()) {
  709. if (typeof options == "string") options = {
  710. url: options
  711. }
  712. options["method"] = "POST"
  713. $task.fetch(options).then(response => {
  714. callback(null, this.adapterStatus(response), response.body)
  715. }, reason => callback(reason.error, null, null))
  716. }
  717. if (this.isSurge() || this.isLoon() || this.isStash()) {
  718. $httpClient.post(options, (error, response, body) => {
  719. callback(error, this.adapterStatus(response), body)
  720. })
  721. }
  722. if (this.isNode()) {
  723. this.node.request.post(options, (error, response, body) => {
  724. callback(error, this.adapterStatus(response), body)
  725. })
  726. }
  727. if (this.isJSBox()) {
  728. if (typeof options == "string") options = {
  729. url: options
  730. }
  731. options["header"] = options["headers"]
  732. options["handler"] = function (resp) {
  733. let error = resp.error
  734. if (error) error = JSON.stringify(resp.error)
  735. let body = resp.data
  736. if (typeof body == "object") body = JSON.stringify(resp.data)
  737. callback(error, this.adapterStatus(resp.response), body)
  738. }
  739. $http.post(options)
  740. }
  741. }
  742. put(options, callback = () => { }) {
  743. if (this.isQuanX()) {
  744. // no test
  745. if (typeof options == "string") options = {
  746. url: options
  747. }
  748. options["method"] = "PUT"
  749. $task.fetch(options).then(response => {
  750. callback(null, this.adapterStatus(response), response.body)
  751. }, reason => callback(reason.error, null, null))
  752. }
  753. if (this.isSurge() || this.isLoon() || this.isStash()) {
  754. options.method = "PUT"
  755. $httpClient.put(options, (error, response, body) => {
  756. callback(error, this.adapterStatus(response), body)
  757. })
  758. }
  759. if (this.isNode()) {
  760. options.method = "PUT"
  761. this.node.request.put(options, (error, response, body) => {
  762. callback(error, this.adapterStatus(response), body)
  763. })
  764. }
  765. if (this.isJSBox()) {
  766. // no test
  767. if (typeof options == "string") options = {
  768. url: options
  769. }
  770. options["header"] = options["headers"]
  771. options["handler"] = function (resp) {
  772. let error = resp.error
  773. if (error) error = JSON.stringify(resp.error)
  774. let body = resp.data
  775. if (typeof body == "object") body = JSON.stringify(resp.data)
  776. callback(error, this.adapterStatus(resp.response), body)
  777. }
  778. $http.post(options)
  779. }
  780. }
  781. costTime() {
  782. let info = `${this.name}执行完毕!`
  783. if (this.isNode() && this.isExecComm) {
  784. info = `指令【${this.comm[1]}】执行完毕!`
  785. }
  786. const endTime = new Date().getTime()
  787. const ms = endTime - this.startTime
  788. const costTime = ms / 1000
  789. this.execCount++
  790. this.costTotalMs += ms
  791. this.log(`${info}耗时【${costTime}】秒\n总共执行【${this.execCount}】次,平均耗时【${((this.costTotalMs / this.execCount) / 1000).toFixed(4)}】秒`)
  792. this.setVal(this.costTotalStringKey, JSON.stringify(`${this.costTotalMs},${this.execCount}`))
  793. // this.setVal(this.execCountKey, JSON.stringify(0))
  794. // this.setVal(this.costTotalMsKey, JSON.stringify(0))
  795. }
  796. done(value = {}) {
  797. this.costTime()
  798. if (this.isSurge() || this.isQuanX() || this.isLoon() || this.isStash()) {
  799. $done(value)
  800. }
  801. }
  802. getRequestUrl() {
  803. return $request.url
  804. }
  805. getResponseBody() {
  806. if ($response) {
  807. return $response.body
  808. }
  809. }
  810. isGetCookie(reg) {
  811. return !!($request.method != 'OPTIONS' && this.getRequestUrl().match(reg))
  812. }
  813. isEmpty(obj) {
  814. return typeof obj == "undefined" || obj == null || obj == "" || obj == "null" || obj == "undefined" || obj.length === 0
  815. }
  816. randomString(len) {
  817. len = len || 32
  818. var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
  819. var maxPos = $chars.length
  820. var pwd = ''
  821. for (let i = 0; i < len; i++) {
  822. pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  823. }
  824. return pwd
  825. }
  826. /**
  827. * 自动补齐字符串
  828. * @param str 原始字符串
  829. * @param prefix 前缀
  830. * @param suffix 后缀
  831. * @param fill 补齐用字符
  832. * @param len 目标补齐长度,不包含前后缀
  833. * @param direction 方向:0往后补齐
  834. * @param ifCode 是否打码
  835. * @param clen 打码长度
  836. * @param startIndex 起始坐标
  837. * @param cstr 打码字符
  838. * @returns {*}
  839. */
  840. autoComplete(str, prefix, suffix, fill, len, direction, ifCode, clen, startIndex, cstr) {
  841. str += ''
  842. if (str.length < len) {
  843. while (str.length < len) {
  844. if (direction == 0) {
  845. str += fill
  846. } else {
  847. str = fill + str
  848. }
  849. }
  850. }
  851. if (ifCode) {
  852. let temp = ''
  853. for (var i = 0; i < clen; i++) {
  854. temp += cstr
  855. }
  856. str = str.substring(0, startIndex) + temp + str.substring(clen + startIndex)
  857. }
  858. str = prefix + str + suffix
  859. return this.toDBC(str)
  860. }
  861. /**
  862. * @param str 源字符串 "#{code}, #{value}"
  863. * @param param 用于替换的数据,结构如下
  864. * @param prefix 前缀 "#{"
  865. * @param suffix 后缀 "}"
  866. * {
  867. * "code": 1,
  868. * "value": 2
  869. * }
  870. * 按上面的传入,输出为"1, 2"
  871. * 对应的#{code}用param里面code的值替换,#{value}也是
  872. * @returns {*|void|string}
  873. */
  874. customReplace(str, param, prefix, suffix) {
  875. try {
  876. if (this.isEmpty(prefix)) {
  877. prefix = "#{"
  878. }
  879. if (this.isEmpty(suffix)) {
  880. suffix = "}"
  881. }
  882. for (let i in param) {
  883. str = str.replace(`${prefix}${i}${suffix}`, param[i])
  884. }
  885. } catch (e) {
  886. this.logErr(e)
  887. }
  888. return str
  889. }
  890. toDBC(txtstring) {
  891. var tmp = ""
  892. for (var i = 0; i < txtstring.length; i++) {
  893. if (txtstring.charCodeAt(i) == 32) {
  894. tmp = tmp + String.fromCharCode(12288)
  895. } else if (txtstring.charCodeAt(i) < 127) {
  896. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248)
  897. }
  898. }
  899. return tmp
  900. }
  901. hash(str) {
  902. let h = 0,
  903. i,
  904. chr
  905. for (i = 0; i < str.length; i++) {
  906. chr = str.charCodeAt(i)
  907. h = (h << 5) - h + chr
  908. h |= 0 // Convert to 32bit integer
  909. }
  910. return String(h)
  911. }
  912. /**
  913. * formatDate y:年 M:月 d:日 q:季 H:时 m:分 s:秒 S:毫秒
  914. */
  915. formatDate(date, format) {
  916. let o = {
  917. 'M+': date.getMonth() + 1,
  918. 'd+': date.getDate(),
  919. 'H+': date.getHours(),
  920. 'm+': date.getMinutes(),
  921. 's+': date.getSeconds(),
  922. 'q+': Math.floor((date.getMonth() + 3) / 3),
  923. 'S': date.getMilliseconds()
  924. }
  925. if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  926. for (let k in o)
  927. if (new RegExp('(' + k + ')').test(format))
  928. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  929. return format
  930. }
  931. objToQueryStr(obj, encode) {
  932. let str = ''
  933. for (const key in obj) {
  934. let value = obj[key]
  935. if (value != null && value !== '') {
  936. if (typeof value === 'object') {
  937. value = JSON.stringify(value)
  938. } else if (encode) {
  939. value = encodeURIComponent(value)
  940. }
  941. str += `${key}=${value}&`
  942. }
  943. }
  944. str = str.substring(0, str.length - 1)
  945. return str
  946. }
  947. parseQueryStr(str) {
  948. let obj = {};
  949. let str1 = str.split("?");
  950. let str2 = str1[1].split("&"); //["a=1", "b=2", "c=3"]
  951. for (let i = 0; i < str2.length; i++) {
  952. let str3 = str2[i].split("=");
  953. obj[str3[0]] = str3[1]
  954. }
  955. return obj
  956. }
  957. })(scriptName, scriptId, options)
  958. }