ToolKit.js 43 KB

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