ToolKit.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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. pushWxMsg(summary, content, url, callback = () => { }) {
  601. let data = {
  602. appToken: "AT_rTc93GQYIdMU8XLRnoJaSea8WkfhSzhX",
  603. content: content,
  604. summary: summary,
  605. contentType: 1,
  606. topicIds: [],
  607. uids: [
  608. "UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"
  609. ],
  610. url: "",
  611. verifyPay: false
  612. };
  613. if (url) {
  614. data.url = url;
  615. }
  616. const headers = this.getJsonDoneHeaders();
  617. headers.Host = 'wxpusher.zjiecode.com';
  618. headers['Content-Type'] = 'application/json;charset=UTF-8';
  619. let options = {
  620. url: 'https://wxpusher.zjiecode.com/api/send/message',
  621. headers: headers,
  622. body: JSON.stringify(data),
  623. };
  624. this.post(options, callback);
  625. }
  626. getVal(key, defaultValue = "") {
  627. let value
  628. if (this.isSurge() || this.isLoon() || this.isStash()) {
  629. value = $persistentStore.read(key)
  630. } else if (this.isQuanX()) {
  631. value = $prefs.valueForKey(key)
  632. } else if (this.isNode()) {
  633. this.data = this.loadData()
  634. value = process.env[key] || this.data[key]
  635. } else {
  636. value = (this.data && this.data[key]) || null
  637. }
  638. return !value ? defaultValue : value
  639. }
  640. setVal(key, val) {
  641. if (this.isSurge() || this.isLoon() || this.isStash()) {
  642. return $persistentStore.write(val, key)
  643. } else if (this.isQuanX()) {
  644. return $prefs.setValueForKey(val, key)
  645. } else if (this.isNode()) {
  646. this.data = this.loadData()
  647. this.data[key] = val
  648. this.writeData()
  649. return true
  650. } else {
  651. return (this.data && this.data[key]) || null
  652. }
  653. }
  654. loadData() {
  655. if (this.isNode()) {
  656. this.fs = this.fs ? this.fs : require('fs')
  657. this.path = this.path ? this.path : require('path')
  658. const curDirDataFilePath = this.path.resolve(this.dataFile)
  659. const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
  660. const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
  661. const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
  662. if (isCurDirDataFile || isRootDirDataFile) {
  663. const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath
  664. try {
  665. return JSON.parse(this.fs.readFileSync(datPath))
  666. } catch (e) {
  667. return {}
  668. }
  669. } else return {}
  670. } else return {}
  671. }
  672. writeData() {
  673. if (this.isNode()) {
  674. this.fs = this.fs ? this.fs : require('fs')
  675. this.path = this.path ? this.path : require('path')
  676. const curDirDataFilePath = this.path.resolve(this.dataFile)
  677. const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
  678. const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
  679. const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
  680. const jsondata = JSON.stringify(this.data)
  681. if (isCurDirDataFile) {
  682. this.fs.writeFileSync(curDirDataFilePath, jsondata)
  683. } else if (isRootDirDataFile) {
  684. this.fs.writeFileSync(rootDirDataFilePath, jsondata)
  685. } else {
  686. this.fs.writeFileSync(curDirDataFilePath, jsondata)
  687. }
  688. }
  689. }
  690. adapterStatus(response) {
  691. if (response) {
  692. if (response.status) {
  693. response["statusCode"] = response.status
  694. } else if (response.statusCode) {
  695. response["status"] = response.statusCode
  696. }
  697. }
  698. return response
  699. }
  700. get(options, callback = () => { }) {
  701. if (this.isQuanX()) {
  702. if (typeof options == "string") options = {
  703. url: options
  704. }
  705. options["method"] = "GET"
  706. $task.fetch(options).then(response => {
  707. callback(null, this.adapterStatus(response), response.body)
  708. }, reason => callback(reason.error, null, null))
  709. }
  710. if (this.isSurge() || this.isLoon() || this.isStash()) $httpClient.get(options, (error, response, body) => {
  711. callback(error, this.adapterStatus(response), body)
  712. })
  713. if (this.isNode()) {
  714. this.node.request(options, (error, response, body) => {
  715. callback(error, this.adapterStatus(response), body)
  716. })
  717. }
  718. if (this.isJSBox()) {
  719. if (typeof options == "string") options = {
  720. url: options
  721. }
  722. options["header"] = options["headers"]
  723. options["handler"] = function (resp) {
  724. let error = resp.error
  725. if (error) error = JSON.stringify(resp.error)
  726. let body = resp.data
  727. if (typeof body == "object") body = JSON.stringify(resp.data)
  728. callback(error, this.adapterStatus(resp.response), body)
  729. }
  730. $http.get(options)
  731. }
  732. }
  733. post(options, callback = () => { }) {
  734. if (this.isQuanX()) {
  735. if (typeof options == "string") options = {
  736. url: options
  737. }
  738. options["method"] = "POST"
  739. $task.fetch(options).then(response => {
  740. callback(null, this.adapterStatus(response), response.body)
  741. }, reason => callback(reason.error, null, null))
  742. }
  743. if (this.isSurge() || this.isLoon() || this.isStash()) {
  744. $httpClient.post(options, (error, response, body) => {
  745. callback(error, this.adapterStatus(response), body)
  746. })
  747. }
  748. if (this.isNode()) {
  749. this.node.request.post(options, (error, response, body) => {
  750. callback(error, this.adapterStatus(response), body)
  751. })
  752. }
  753. if (this.isJSBox()) {
  754. if (typeof options == "string") options = {
  755. url: options
  756. }
  757. options["header"] = options["headers"]
  758. options["handler"] = function (resp) {
  759. let error = resp.error
  760. if (error) error = JSON.stringify(resp.error)
  761. let body = resp.data
  762. if (typeof body == "object") body = JSON.stringify(resp.data)
  763. callback(error, this.adapterStatus(resp.response), body)
  764. }
  765. $http.post(options)
  766. }
  767. }
  768. put(options, callback = () => { }) {
  769. if (this.isQuanX()) {
  770. // no test
  771. if (typeof options == "string") options = {
  772. url: options
  773. }
  774. options["method"] = "PUT"
  775. $task.fetch(options).then(response => {
  776. callback(null, this.adapterStatus(response), response.body)
  777. }, reason => callback(reason.error, null, null))
  778. }
  779. if (this.isSurge() || this.isLoon() || this.isStash()) {
  780. options.method = "PUT"
  781. $httpClient.put(options, (error, response, body) => {
  782. callback(error, this.adapterStatus(response), body)
  783. })
  784. }
  785. if (this.isNode()) {
  786. options.method = "PUT"
  787. this.node.request.put(options, (error, response, body) => {
  788. callback(error, this.adapterStatus(response), body)
  789. })
  790. }
  791. if (this.isJSBox()) {
  792. // no test
  793. if (typeof options == "string") options = {
  794. url: options
  795. }
  796. options["header"] = options["headers"]
  797. options["handler"] = function (resp) {
  798. let error = resp.error
  799. if (error) error = JSON.stringify(resp.error)
  800. let body = resp.data
  801. if (typeof body == "object") body = JSON.stringify(resp.data)
  802. callback(error, this.adapterStatus(resp.response), body)
  803. }
  804. $http.post(options)
  805. }
  806. }
  807. costTime() {
  808. let info = `${this.name}执行完毕!`
  809. if (this.isNode() && this.isExecComm) {
  810. info = `指令【${this.comm[1]}】执行完毕!`
  811. }
  812. const endTime = new Date().getTime()
  813. const ms = endTime - this.startTime
  814. const costTime = ms / 1000
  815. this.execCount++
  816. this.costTotalMs += ms
  817. this.log(`${info}耗时【${costTime}】秒\n总共执行【${this.execCount}】次,平均耗时【${((this.costTotalMs / this.execCount) / 1000).toFixed(4)}】秒`)
  818. this.setVal(this.costTotalStringKey, JSON.stringify(`${this.costTotalMs},${this.execCount}`))
  819. // this.setVal(this.execCountKey, JSON.stringify(0))
  820. // this.setVal(this.costTotalMsKey, JSON.stringify(0))
  821. }
  822. done(value = {}) {
  823. this.costTime()
  824. if (this.isSurge() || this.isQuanX() || this.isLoon() || this.isStash()) {
  825. $done(value)
  826. }
  827. }
  828. getRequestUrl() {
  829. return $request.url
  830. }
  831. getResponseBody() {
  832. if ($response) {
  833. return $response.body
  834. }
  835. }
  836. isGetCookie(reg) {
  837. return !!($request.method != 'OPTIONS' && this.getRequestUrl().match(reg))
  838. }
  839. isEmpty(obj) {
  840. return typeof obj == "undefined" || obj == null || obj == "" || obj == "null" || obj == "undefined" || obj.length === 0
  841. }
  842. randomString(len) {
  843. len = len || 32
  844. var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
  845. var maxPos = $chars.length
  846. var pwd = ''
  847. for (let i = 0; i < len; i++) {
  848. pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  849. }
  850. return pwd
  851. }
  852. /**
  853. * 自动补齐字符串
  854. * @param str 原始字符串
  855. * @param prefix 前缀
  856. * @param suffix 后缀
  857. * @param fill 补齐用字符
  858. * @param len 目标补齐长度,不包含前后缀
  859. * @param direction 方向:0往后补齐
  860. * @param ifCode 是否打码
  861. * @param clen 打码长度
  862. * @param startIndex 起始坐标
  863. * @param cstr 打码字符
  864. * @returns {*}
  865. */
  866. autoComplete(str, prefix, suffix, fill, len, direction, ifCode, clen, startIndex, cstr) {
  867. str += ''
  868. if (str.length < len) {
  869. while (str.length < len) {
  870. if (direction == 0) {
  871. str += fill
  872. } else {
  873. str = fill + str
  874. }
  875. }
  876. }
  877. if (ifCode) {
  878. let temp = ''
  879. for (var i = 0; i < clen; i++) {
  880. temp += cstr
  881. }
  882. str = str.substring(0, startIndex) + temp + str.substring(clen + startIndex)
  883. }
  884. str = prefix + str + suffix
  885. return this.toDBC(str)
  886. }
  887. /**
  888. * @param str 源字符串 "#{code}, #{value}"
  889. * @param param 用于替换的数据,结构如下
  890. * @param prefix 前缀 "#{"
  891. * @param suffix 后缀 "}"
  892. * {
  893. * "code": 1,
  894. * "value": 2
  895. * }
  896. * 按上面的传入,输出为"1, 2"
  897. * 对应的#{code}用param里面code的值替换,#{value}也是
  898. * @returns {*|void|string}
  899. */
  900. customReplace(str, param, prefix, suffix) {
  901. try {
  902. if (this.isEmpty(prefix)) {
  903. prefix = "#{"
  904. }
  905. if (this.isEmpty(suffix)) {
  906. suffix = "}"
  907. }
  908. for (let i in param) {
  909. str = str.replace(`${prefix}${i}${suffix}`, param[i])
  910. }
  911. } catch (e) {
  912. this.logErr(e)
  913. }
  914. return str
  915. }
  916. toDBC(txtstring) {
  917. var tmp = ""
  918. for (var i = 0; i < txtstring.length; i++) {
  919. if (txtstring.charCodeAt(i) == 32) {
  920. tmp = tmp + String.fromCharCode(12288)
  921. } else if (txtstring.charCodeAt(i) < 127) {
  922. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248)
  923. }
  924. }
  925. return tmp
  926. }
  927. hash(str) {
  928. let h = 0,
  929. i,
  930. chr
  931. for (i = 0; i < str.length; i++) {
  932. chr = str.charCodeAt(i)
  933. h = (h << 5) - h + chr
  934. h |= 0 // Convert to 32bit integer
  935. }
  936. return String(h)
  937. }
  938. /**
  939. * formatDate y:年 M:月 d:日 q:季 H:时 m:分 s:秒 S:毫秒
  940. */
  941. formatDate(date, format) {
  942. let o = {
  943. 'M+': date.getMonth() + 1,
  944. 'd+': date.getDate(),
  945. 'H+': date.getHours(),
  946. 'm+': date.getMinutes(),
  947. 's+': date.getSeconds(),
  948. 'q+': Math.floor((date.getMonth() + 3) / 3),
  949. 'S': date.getMilliseconds()
  950. }
  951. if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  952. for (let k in o)
  953. if (new RegExp('(' + k + ')').test(format))
  954. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  955. return format
  956. }
  957. objToQueryStr(obj, encode) {
  958. let str = ''
  959. for (const key in obj) {
  960. let value = obj[key]
  961. if (value != null && value !== '') {
  962. if (typeof value === 'object') {
  963. value = JSON.stringify(value)
  964. } else if (encode) {
  965. value = encodeURIComponent(value)
  966. }
  967. str += `${key}=${value}&`
  968. }
  969. }
  970. str = str.substring(0, str.length - 1)
  971. return str
  972. }
  973. parseQueryStr(str) {
  974. let obj = {}
  975. if (str.indexOf("?") > -1) {
  976. str = str.split("?")[1]
  977. }
  978. let arr = str.split("&")
  979. for (let i = 0; i < arr.length; i++) {
  980. let kv = arr[i].split("=")
  981. obj[kv[0]] = kv[1]
  982. }
  983. return obj
  984. }
  985. deepClone(obj, newObj) {
  986. newObj = newObj || {};
  987. for (let key in obj) {
  988. if (typeof obj[key] == 'object') {
  989. newObj[key] = (obj[key].constructor === Array) ? [] : {}
  990. this.deepClone(obj[key], newObj[key]);
  991. } else {
  992. newObj[key] = obj[key]
  993. }
  994. }
  995. return newObj;
  996. }
  997. getBaseDoneHeaders(mixHeaders = {}) {
  998. return Object.assign(
  999. {
  1000. 'Access-Control-Allow-Origin': '*',
  1001. 'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PUT,DELETE',
  1002. 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
  1003. },
  1004. mixHeaders
  1005. )
  1006. }
  1007. getHtmlDoneHeaders() {
  1008. return this.getBaseDoneHeaders({
  1009. 'Content-Type': 'text/html;charset=UTF-8'
  1010. })
  1011. }
  1012. getJsonDoneHeaders() {
  1013. return this.getBaseDoneHeaders({
  1014. 'Content-Type': 'text/json; charset=utf-8',
  1015. 'Connection': 'keep-alive'
  1016. })
  1017. }
  1018. })(scriptName, scriptId, options)
  1019. }