forked from sngxpro/AutoSyncScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToolKit.js
More file actions
652 lines (605 loc) · 26.1 KB
/
ToolKit.js
File metadata and controls
652 lines (605 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/**
* 根据自己的习惯整合各个开发者而形成的工具包(@NobyDa, @chavyleung)
* 兼容surge,quantumult x,loon,node环境
* 并且加入一些好用的方法
* 方法如下:
* isEmpty: 判断字符串是否是空(undefined,null,空串)
* getRequestUrl: 获取请求的url(目前仅支持surge和quanx)
* getResponseBody: 获取响应体(目前仅支持surge和quanx)
* boxJsJsonBuilder:构建最简默认boxjs配置json
* randomString: 生成随机字符串
* autoComplete: 自动补齐字符串
* customReplace: 自定义替换
* hash: 字符串做hash
*
* ⚠️当开启当且仅当执行失败的时候通知选项,请在执行失败的地方执行execFail()
*
* @param scriptName 脚本名,用于通知时候的标题
* @param scriptId 每个脚本唯一的id,用于存储持久化的时候加入key
* @param options 传入一些参数,目前参数如下;
* httpApi=ffff@3.3.3.18:6166(这个是默认值,本人surge调试脚本用,可自行修改)
* @constructor
*/
function ToolKit(scriptName, scriptId, options) {
return new (class {
constructor(scriptName, scriptId, options) {
this.tgEscapeCharMapping = {'&':'&', '#':'#'}
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`
this.prefix = `lk`
this.name = scriptName
this.id = scriptId
this.data = null
this.dataFile = `${this.prefix}${this.id}.dat`
this.boxJsJsonFile = `${this.prefix}${this.id}.boxjs.json`
//surge http api等一些扩展参数
this.options = options
//命令行入参
this.isExecComm = false
//默认脚本开关
this.isEnableLog = this.getVal(`${this.prefix}IsEnableLog${this.id}`)
this.isEnableLog = this.isEmpty(this.isEnableLog) ? true : JSON.parse(this.isEnableLog)
this.isNotifyOnlyFail = this.getVal(`${this.prefix}NotifyOnlyFail${this.id}`)
this.isNotifyOnlyFail = this.isEmpty(this.isNotifyOnlyFail) ? false : JSON.parse(this.isNotifyOnlyFail)
//tg通知开关
this.isEnableTgNotify = this.getVal(`${this.prefix}IsEnableTgNotify${this.id}`)
this.isEnableTgNotify = this.isEmpty(this.isEnableTgNotify) ? false : JSON.parse(this.isEnableTgNotify)
this.tgNotifyUrl = this.getVal(`${this.prefix}TgNotifyUrl${this.id}`)
this.isEnableTgNotify = this.isEnableTgNotify ? !this.isEmpty(this.tgNotifyUrl) : this.isEnableTgNotify
//计时部分
this.costTotalStringKey = `${this.prefix}CostTotalString${this.id}`
this.costTotalString = this.getVal(this.costTotalStringKey)
this.costTotalString = this.isEmpty(this.costTotalString) ? `0,0` : this.costTotalString.replace("\"", "")
this.costTotalMs = this.costTotalString.split(",")[0]
this.execCount = this.costTotalString.split(",")[1]
this.costTotalMs = this.isEmpty(this.costTotalMs) ? 0 : parseInt(this.costTotalMs)
this.execCount = this.isEmpty(this.execCount) ? 0 : parseInt(this.execCount)
this.logSeparator = '\n██'
this.startTime = new Date().getTime()
this.node = (() => {
if (this.isNode()) {
const request = require('request')
return ({request})
} else {
return (null)
}
})()
this.execStatus = true
this.notifyInfo = []
this.log(`${this.name}, 开始执行!`)
this.execComm()
}
async execComm() {
//支持node命令,实现发送手机测试
if (this.isNode()) {
this.comm = process.argv.slice(2)
let isHttpApiErr = false
if (this.comm[0] == "p") {
this.isExecComm = true
//phone
this.log(`开始执行指令【${this.comm[0]}】=> 发送到手机测试脚本!`)
if (this.isEmpty(this.options) || this.isEmpty(this.options.httpApi)) {
this.log(`未设置options,使用默认值`)
//设置默认值
if (this.isEmpty(this.options)) {
this.options = {}
}
this.options.httpApi = `ffff@10.0.0.9:6166`
} else {
//判断格式
if (!/.*?@.*?:[0-9]+/.test(this.options.httpApi)) {
isHttpApiErr = true
this.log(`❌httpApi格式错误!格式:ffff@3.3.3.18:6166`)
this.done()
}
}
if (!isHttpApiErr) {
await this.callApi(this.comm[1]);
}
}
}
}
callApi(timeout) {
let fname = this.getCallerFileNameAndLine().split(":")[0].replace("[", "")
this.log(`获取【${fname}】内容传给手机`)
let scriptStr = ''
this.fs = this.fs ? this.fs : require('fs')
this.path = this.path ? this.path : require('path')
const curDirDataFilePath = this.path.resolve(fname)
const rootDirDataFilePath = this.path.resolve(process.cwd(), fname)
const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
if (isCurDirDataFile || isRootDirDataFile) {
const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath
try {
scriptStr = this.fs.readFileSync(datPath)
} catch (e) {
scriptStr = ''
}
} else {
scriptStr = ''
}
let options = {
url: `http://${this.options.httpApi.split("@")[1]}/v1/scripting/evaluate`,
headers: {
"X-Key": `${this.options.httpApi.split("@")[0]}`
},
body: {
"script_text": `${scriptStr}`,
"mock_type": "cron",
"timeout": (!this.isEmpty(timeout) && timeout > 5) ? timeout : 5
},
json: true
}
this.post(options, (error, response, data) => {
this.log(`已将脚本【${fname}】发给手机!`)
this.done()
})
}
getCallerFileNameAndLine(){
let error
try {
throw Error('')
} catch (err) {
error = err
}
const stack = error.stack
const stackArr = stack.split('\n')
let callerLogIndex = 1
if (callerLogIndex !== 0) {
const callerStackLine = stackArr[callerLogIndex]
this.path = this.path ? this.path : require('path')
return `[${callerStackLine.substring(callerStackLine.lastIndexOf(this.path.sep) + 1, callerStackLine.lastIndexOf(':'))}]`
} else {
return '[-]'
}
}
getFunName(fun) {
var ret = fun.toString();
ret = ret.substr('function '.length);
ret = ret.substr(0, ret.indexOf('('));
return ret;
}
boxJsJsonBuilder(info) {
if (this.isNode()) {
this.log('using node')
let needAppendKeys = ["keys", "settings"]
const domain = 'https://raw.githubusercontent.com/Orz-3'
let boxJsJson = {}
boxJsJson.id = `${this.prefix}${this.id}`
boxJsJson.name = this.name
boxJsJson.desc_html = "⚠️使用说明</br>详情【<a href='script_url?raw=true'><font class='red--text'>点我查看</font></a>】"
boxJsJson.icons = [`${domain}/mini/master/${this.id.toLocaleLowerCase()}.png`,`${domain}/task/master/${this.id.toLocaleLowerCase()}.png`]
boxJsJson.keys = []
boxJsJson.settings = [
{
"id": `${this.prefix}IsEnableLog${this.id}`,
"name": "开启/关闭日志",
"val": true,
"type": "boolean",
"desc": "默认开启"
},
{
"id": `${this.prefix}NotifyOnlyFail${this.id}`,
"name": "只当执行失败才通知",
"val": false,
"type": "boolean",
"desc": "默认关闭"
},
{
"id": `${this.prefix}IsEnableTgNotify${this.id}`,
"name": "开启/关闭Telegram通知",
"val": false,
"type": "boolean",
"desc": "默认关闭"
},
{
"id": `${this.prefix}TgNotifyUrl${this.id}`,
"name": "Telegram通知地址",
"val": "",
"type": "text",
"desc": "Tg的通知地址,如:https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="
}
]
boxJsJson.author = "@lowking"
boxJsJson.repo = "https://github.com/lowking/Scripts"
boxJsJson.script = "script_url?raw=true"
//除了settings和keys追加,其他的都覆盖
if (!this.isEmpty(info)) {
for (let i in needAppendKeys) {
let key = needAppendKeys[i]
if (!this.isEmpty(info[key])) {
boxJsJson[key] = boxJsJson[key].concat(info[key])
}
delete info[key]
}
}
Object.assign(boxJsJson, info)
if (this.isNode()) {
this.fs = this.fs ? this.fs : require('fs')
this.path = this.path ? this.path : require('path')
const curDirDataFilePath = this.path.resolve(this.boxJsJsonFile)
const rootDirDataFilePath = this.path.resolve(process.cwd(), this.boxJsJsonFile)
const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
const jsondata = JSON.stringify(boxJsJson, null, '\t')
if (isCurDirDataFile) {
this.fs.writeFileSync(curDirDataFilePath, jsondata)
} else if (isRootDirDataFile) {
this.fs.writeFileSync(rootDirDataFilePath, jsondata)
} else {
this.fs.writeFileSync(curDirDataFilePath, jsondata)
}
}
}
}
appendNotifyInfo(info, type) {
if (type == 1) {
this.notifyInfo = info
} else {
this.notifyInfo.push(info)
}
}
prependNotifyInfo(info) {
this.notifyInfo.splice(0, 0, info)
}
execFail() {
this.execStatus = false
}
isRequest() {
return typeof $request != "undefined"
}
isSurge() {
return typeof $httpClient != "undefined"
}
isQuanX() {
return typeof $task != "undefined"
}
isLoon() {
return typeof $loon != "undefined"
}
isJSBox() {
return typeof $app != "undefined" && typeof $http != "undefined"
}
isNode() {
return typeof require == "function" && !this.isJSBox()
}
sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time))
}
log(message) {
if (this.isEnableLog) console.log(`${this.logSeparator}${message}`)
}
logErr(message) {
this.execStatus = true
if (this.isEnableLog) {
console.log(`${this.logSeparator}${this.name}执行异常:`)
console.log(message)
console.log(`\n${message.message}`)
}
}
msg(subtitle, message, openUrl, mediaUrl) {
if (!this.isRequest() && this.isNotifyOnlyFail && this.execStatus) {
//开启了当且仅当执行失败的时候通知,并且执行成功了,这时候不通知
} else {
if (this.isEmpty(message)) {
if (Array.isArray(this.notifyInfo)) {
message = this.notifyInfo.join("\n")
} else {
message = this.notifyInfo
}
}
if (!this.isEmpty(message)) {
if (this.isEnableTgNotify) {
this.log(`${this.name}Tg通知开始`)
//处理特殊字符
for (let key in this.tgEscapeCharMapping) {
if (!this.tgEscapeCharMapping.hasOwnProperty(key)) {
continue
}
message = message.replace(key, this.tgEscapeCharMapping[key])
}
this.get({
url: encodeURI(`${this.tgNotifyUrl}📌${this.name}\n${message}`)
}, (error, statusCode, body) => {
this.log(`Tg通知完毕`)
})
} else {
let options = {}
const hasOpenUrl = !this.isEmpty(openUrl)
const hasMediaUrl = !this.isEmpty(mediaUrl)
if (this.isQuanX()) {
if(hasOpenUrl) options["open-url"] = openUrl
if(hasMediaUrl) options["media-url"] = mediaUrl
$notify(this.name, subtitle, message, options)
}
if (this.isSurge()) {
if(hasOpenUrl) options["url"] = openUrl
$notification.post(this.name, subtitle, message, options)
}
if (this.isNode()) this.log("⭐️" + this.name + subtitle + message)
if (this.isJSBox()) $push.schedule({
title: this.name,
body: subtitle ? subtitle + "\n" + message : message
})
}
}
}
}
getVal(key) {
if (this.isSurge() || this.isLoon()) {
return $persistentStore.read(key)
} else if (this.isQuanX()) {
return $prefs.valueForKey(key)
} else if (this.isNode()) {
this.data = this.loadData()
return this.data[key]
} else {
return (this.data && this.data[key]) || null
}
}
setVal(key, val) {
if (this.isSurge() || this.isLoon()) {
return $persistentStore.write(val, key)
} else if (this.isQuanX()) {
return $prefs.setValueForKey(val, key)
} else if (this.isNode()) {
this.data = this.loadData()
this.data[key] = val
this.writeData()
return true
} else {
return (this.data && this.data[key]) || null
}
}
loadData() {
if (this.isNode()) {
this.fs = this.fs ? this.fs : require('fs')
this.path = this.path ? this.path : require('path')
const curDirDataFilePath = this.path.resolve(this.dataFile)
const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
if (isCurDirDataFile || isRootDirDataFile) {
const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath
try {
return JSON.parse(this.fs.readFileSync(datPath))
} catch (e) {
return {}
}
} else return {}
} else return {}
}
writeData() {
if (this.isNode()) {
this.fs = this.fs ? this.fs : require('fs')
this.path = this.path ? this.path : require('path')
const curDirDataFilePath = this.path.resolve(this.dataFile)
const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
const jsondata = JSON.stringify(this.data)
if (isCurDirDataFile) {
this.fs.writeFileSync(curDirDataFilePath, jsondata)
} else if (isRootDirDataFile) {
this.fs.writeFileSync(rootDirDataFilePath, jsondata)
} else {
this.fs.writeFileSync(curDirDataFilePath, jsondata)
}
}
}
adapterStatus(response) {
if (response) {
if (response.status) {
response["statusCode"] = response.status
} else if (response.statusCode) {
response["status"] = response.statusCode
}
}
return response
}
get(options, callback = () => {}) {
if (this.isQuanX()) {
if (typeof options == "string") options = {
url: options
}
options["method"] = "GET"
$task.fetch(options).then(response => {
callback(null, this.adapterStatus(response), response.body)
}, reason => callback(reason.error, null, null))
}
if (this.isSurge()) $httpClient.get(options, (error, response, body) => {
callback(error, this.adapterStatus(response), body)
})
if (this.isNode()) {
this.node.request(options, (error, response, body) => {
callback(error, this.adapterStatus(response), body)
})
}
if (this.isJSBox()) {
if (typeof options == "string") options = {
url: options
}
options["header"] = options["headers"]
options["handler"] = function (resp) {
let error = resp.error
if (error) error = JSON.stringify(resp.error)
let body = resp.data
if (typeof body == "object") body = JSON.stringify(resp.data)
callback(error, this.adapterStatus(resp.response), body)
}
$http.get(options)
}
}
post(options, callback = () => {}) {
if (this.isQuanX()) {
if (typeof options == "string") options = {
url: options
}
options["method"] = "POST"
$task.fetch(options).then(response => {
callback(null, this.adapterStatus(response), response.body)
}, reason => callback(reason.error, null, null))
}
if (this.isSurge()) {
$httpClient.post(options, (error, response, body) => {
callback(error, this.adapterStatus(response), body)
})
}
if (this.isNode()) {
this.node.request.post(options, (error, response, body) => {
callback(error, this.adapterStatus(response), body)
})
}
if (this.isJSBox()) {
if (typeof options == "string") options = {
url: options
}
options["header"] = options["headers"]
options["handler"] = function (resp) {
let error = resp.error
if (error) error = JSON.stringify(resp.error)
let body = resp.data
if (typeof body == "object") body = JSON.stringify(resp.data)
callback(error, this.adapterStatus(resp.response), body)
}
$http.post(options)
}
}
costTime() {
let info = `${this.name}执行完毕!`
if (this.isNode() && this.isExecComm) {
info = `指令【${this.comm[0]}】执行完毕!`
}
const endTime = new Date().getTime()
const ms = endTime - this.startTime
const costTime = ms / 1000
this.execCount++
this.costTotalMs += ms
this.log(`${info}耗时【${costTime}】秒\n总共执行【${this.execCount}】次,平均耗时【${((this.costTotalMs / this.execCount) / 1000).toFixed(4)}】秒`)
this.setVal(this.costTotalStringKey, JSON.stringify(`${this.costTotalMs},${this.execCount}`))
// this.setVal(this.execCountKey, JSON.stringify(0))
// this.setVal(this.costTotalMsKey, JSON.stringify(0))
}
done(value) {
let key = `body`
if (this.isRequest()) {
if (this.isQuanX()) key = `content`
if (this.isSurge()) key = `body`
} else {
this.costTime()
}
let obj = {}
obj[key] = value
if (this.isQuanX()) this.isRequest() ? $done(obj) : null
if (this.isSurge()) this.isRequest() ? $done(obj) : $done()
}
getRequestUrl() {
return $request.url
}
getResponseBody() {
return $response.body
}
isGetCookie(reg) {
return !!($request.method != 'OPTIONS' && this.getRequestUrl().match(reg))
}
isEmpty(obj) {
return typeof obj == "undefined" || obj == null || obj == "" || obj == "null" || obj == "undefined" || obj.length === 0
}
randomString(len) {
len = len || 32
var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
var maxPos = $chars.length
var pwd = ''
for (let i = 0; i < len; i++) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
}
return pwd
}
/**
* 自动补齐字符串
* @param str 原始字符串
* @param prefix 前缀
* @param suffix 后缀
* @param fill 补齐用字符
* @param len 目标补齐长度,不包含前后缀
* @param direction 方向:0往后补齐
* @param ifCode 是否打码
* @param clen 打码长度
* @param startIndex 起始坐标
* @param cstr 打码字符
* @returns {*}
*/
autoComplete(str, prefix, suffix, fill, len, direction, ifCode, clen, startIndex, cstr) {
str += ``
if (str.length < len) {
while (str.length < len) {
if (direction == 0) {
str += fill
} else {
str = fill + str
}
}
}
if (ifCode) {
let temp = ``
for (var i = 0; i < clen; i++) {
temp += cstr
}
str = str.substring(0, startIndex) + temp + str.substring(clen + startIndex)
}
str = prefix + str + suffix
return this.toDBC(str)
}
/**
* @param str 源字符串 "#{code}, #{value}"
* @param param 用于替换的数据,结构如下
* @param prefix 前缀 "#{"
* @param suffix 后缀 "}"
* {
* "code": 1,
* "value": 2
* }
* 按上面的传入,输出为"1, 2"
* 对应的#{code}用param里面code的值替换,#{value}也是
* @returns {*|void|string}
*/
customReplace(str, param, prefix, suffix) {
try {
if (this.isEmpty(prefix)) {
prefix = "#{"
}
if (this.isEmpty(suffix)) {
suffix = "}"
}
for (let i in param) {
str = str.replace(`${prefix}${i}${suffix}`, param[i])
}
} catch (e) {
this.logErr(e)
}
return str
}
toDBC(txtstring) {
var tmp = ""
for (var i = 0; i < txtstring.length; i++) {
if (txtstring.charCodeAt(i) == 32) {
tmp = tmp + String.fromCharCode(12288)
} else if (txtstring.charCodeAt(i) < 127) {
tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248)
}
}
return tmp
}
hash(str) {
let h = 0,
i,
chr
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i)
h = (h << 5) - h + chr
h |= 0 // Convert to 32bit integer
}
return String(h)
}
})(scriptName, scriptId, options)
}