forked from chavyleung/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chavy.box.js
2285 lines (2252 loc) · 111 KB
/
chavy.box.js
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const $ = new Env('BoxJs')
$.version = '0.6.18'
$.versionType = 'beta'
$.KEY_sessions = 'chavy_boxjs_sessions'
$.KEY_versions = 'chavy_boxjs_versions'
$.KEY_userCfgs = 'chavy_boxjs_userCfgs'
$.KEY_globalBaks = 'chavy_boxjs_globalBaks'
$.KEY_curSessions = 'chavy_boxjs_cur_sessions'
/**
* ===================================
* 持久化属性: BoxJs 公开的数据结构
* ===================================
*/
// 存储用户访问`BoxJs`时使用的域名
$.KEY_boxjs_host = 'boxjs_host'
$.json = $.name
$.html = $.name
!(async () => {
// 勿扰模式
$.isMute = [true, 'true'].includes($.getdata('@chavy_boxjs_userCfgs.isMute'))
const path = getPath($request.url)
// 处理主页请求 => / 或 /home
if (/(^\/home|^\/?$)/.test(path)) {
await handleHome()
}
// 处理主页请求 => /app
if (/(^\/app$)/.test(path)) {
await handleHome()
}
// 处理主页请求 => /sub
else if (/^\/sub/.test(path)) {
await handleSub()
}
// 处理 App 请求 => /app
else if (/^\/app/.test(path)) {
const [, appId] = path.split('/app/')
await handleApp(decodeURIComponent(decodeURIComponent(appId)))
}
// 处理 Api 请求 => /api
else if (/^\/api/.test(path)) {
$.isapi = true
await handleApi()
}
// 处理 Api 请求 => /my
else if (/^\/my/.test(path)) {
await handleMy()
}
// 处理 revert 请求 => /revert
else if (/^\/revert/.test(path)) {
await handleRevert()
}
})()
.catch((e) => {
$.logErr(e)
})
.finally(() => {
// 记录当前使用哪个域名访问
$.setdata(getHost($request.url), $.KEY_boxjs_host)
if ($.isapi) {
$.done({ body: $.json })
} else {
if ($.isSurge() || $.isLoon()) {
$.done({ response: { status: 200, body: $.html } })
} else if ($.isQuanX()) {
$.done({ status: 'HTTP/1.1 200', headers: { 'Content-Type': 'text/html; charset=utf-8' }, body: $.html })
} else {
$.done()
}
}
})
/**
* http://boxjs.com/ => `http://boxjs.com`
* http://boxjs.com/app/jd => `http://boxjs.com`
*/
function getHost(url) {
return url.slice(0, url.indexOf('/', 8))
}
/**
* https://dns.google/ => ``
* https://dns.google/api => `/api`
*/
function getPath(url) {
// 如果以`/`结尾, 去掉最后一个`/`
const end = url.lastIndexOf('/') === url.length - 1 ? -1 : undefined
// slice第二个参数传 undefined 会直接截到最后
// indexOf第二个参数用来跳过前面的 "https://"
return url.slice(url.indexOf('/', 8), end)
}
function getSystemCfgs() {
return {
env: $.isLoon() ? 'Loon' : $.isQuanX() ? 'QuanX' : $.isSurge() ? 'Surge' : 'Node',
version: $.version,
versionType: $.versionType,
envs: [
{
id: 'Surge',
icons: [
'https://raw.githubusercontent.com/Orz-3/mini/none/surge.png',
'https://raw.githubusercontent.com/Orz-3/task/master/surge.png'
]
},
{
id: 'QuanX',
icons: [
'https://raw.githubusercontent.com/Orz-3/mini/none/quanX.png',
'https://raw.githubusercontent.com/Orz-3/task/master/quantumultx.png'
]
},
{
id: 'Loon',
icons: [
'https://raw.githubusercontent.com/Orz-3/mini/none/loon.png',
'https://raw.githubusercontent.com/Orz-3/task/master/loon.png'
]
}
],
chavy: {
id: 'Chavy Scripts',
icon: 'https://avatars3.githubusercontent.com/u/29748519',
repo: 'https://github.com/chavyleung/scripts'
},
senku: { id: 'GideonSenku', icon: 'https://avatars1.githubusercontent.com/u/39037656', repo: 'https://github.com/GideonSenku' },
orz3: { id: 'Orz-3', icon: 'https://raw.githubusercontent.com/Orz-3/task/master/Orz-3.png', repo: 'https://github.com/Orz-3/' },
boxjs: {
id: 'BoxJs',
show: false,
icon: 'https://raw.githubusercontent.com/Orz-3/task/master/box.png',
icons: ['https://raw.githubusercontent.com/Orz-3/mini/master/box.png', 'https://raw.githubusercontent.com/Orz-3/task/master/box.png'],
repo: 'https://github.com/chavyleung/scripts'
},
contributors: []
}
}
function getSystemApps() {
const sysapps = [
{
id: 'BoxSetting',
name: '偏好设置',
descs: ['可设置 http-api 地址 & 超时时间 (Surge TF)', '可设置明暗两种主题下的主色调'],
keys: ['@chavy_boxjs_userCfgs.httpapi', '@chavy_boxjs_userCfgs.color_dark_primary', '@chavy_boxjs_userCfgs.color_light_primary'],
settings: [
{
id: '@chavy_boxjs_userCfgs.httpapis',
name: 'HTTP-API (Surge TF)',
val: '',
type: 'textarea',
placeholder: ',examplekey@127.0.0.1:6166',
autoGrow: true,
rows: 2,
desc: '示例: ,examplekey@127.0.0.1:6166! 注意: 以逗号开头, 逗号分隔多个地址, 可加回车'
},
{
id: '@chavy_boxjs_userCfgs.httpapi_timeout',
name: 'HTTP-API Timeout (Surge TF)',
val: 20,
type: 'number',
desc: '如果脚本作者指定了超时时间, 会优先使用脚本指定的超时时间.'
},
{ id: '@chavy_boxjs_userCfgs.color_light_primary', name: '明亮色调', canvas: true, val: '#F7BB0E', type: 'colorpicker', desc: '' },
{ id: '@chavy_boxjs_userCfgs.color_dark_primary', name: '暗黑色调', canvas: true, val: '#2196F3', type: 'colorpicker', desc: '' }
],
author: '@chavyleung',
repo: 'https://github.com/chavyleung/scripts/blob/master/box/switcher/box.switcher.js',
icons: [
'https://raw.githubusercontent.com/chavyleung/scripts/master/box/icons/BoxSetting.mini.png',
'https://raw.githubusercontent.com/chavyleung/scripts/master/box/icons/BoxSetting.png'
]
},
{
id: 'BoxSwitcher',
name: '会话切换',
desc: '打开静默运行后, 切换会话将不再发出系统通知 \n注: 不影响日志记录',
keys: [],
settings: [{ id: 'CFG_BoxSwitcher_isSilent', name: '静默运行', val: false, type: 'boolean', desc: '切换会话时不发出系统通知!' }],
author: '@chavyleung',
repo: 'https://github.com/chavyleung/scripts/blob/master/box/switcher/box.switcher.js',
icons: [
'https://raw.githubusercontent.com/chavyleung/scripts/master/box/icons/BoxSwitcher.mini.png',
'https://raw.githubusercontent.com/chavyleung/scripts/master/box/icons/BoxSwitcher.png'
],
script: 'https://raw.githubusercontent.com/chavyleung/scripts/master/box/switcher/box.switcher.js'
}
]
sysapps.sort((a, b) => a.id.localeCompare(b.id))
wrapapps(sysapps)
return sysapps
}
function getUserCfgs() {
const defcfgs = { favapps: [], appsubs: [], appsubCaches: {}, httpapi: 'examplekey@127.0.0.1:6166' }
const userCfgsStr = $.getdata($.KEY_userCfgs)
return userCfgsStr ? Object.assign(defcfgs, JSON.parse(userCfgsStr)) : defcfgs
}
function getGlobalBaks() {
const globalBaksStr = $.getdata($.KEY_globalBaks)
return globalBaksStr ? JSON.parse(globalBaksStr) : []
}
function refreshAppSub(sub, usercfgs) {
return new Promise((resolve) => {
const suburl = sub.url.replace(/[ ]|[\r\n]/g, '')
$.get({ url: suburl }, (err, resp, data) => {
try {
const respsub = JSON.parse(data)
if (Array.isArray(respsub.apps)) {
respsub._raw = sub
respsub.updateTime = new Date()
usercfgs.appsubCaches[suburl] = respsub
console.log(`更新订阅, 成功! ${suburl}`)
}
} catch (e) {
$.logErr(e, resp)
sub.isErr = true
sub.apps = []
sub._raw = JSON.parse(JSON.stringify(sub))
sub.updateTime = new Date()
usercfgs.appsubCaches[suburl] = sub
console.log(`更新订阅, 失败! ${suburl}`)
} finally {
resolve()
}
})
})
}
async function refreshAppSubs(subId) {
$.msg($.name, '更新订阅: 开始!')
const usercfgs = getUserCfgs()
const refreshActs = []
if (subId) {
const sub = usercfgs.appsubs.find((sub) => sub.id === subId)
refreshActs.push(refreshAppSub(sub, usercfgs))
} else {
for (let subIdx = 0; subIdx < usercfgs.appsubs.length; subIdx++) {
const sub = usercfgs.appsubs[subIdx]
refreshActs.push(refreshAppSub(sub, usercfgs))
}
}
await Promise.all(refreshActs)
$.setdata(JSON.stringify(usercfgs), $.KEY_userCfgs)
console.log(`全部订阅, 完成!`)
const endTime = new Date().getTime()
const costTime = (endTime - $.startTime) / 1000
$.msg($.name, `更新订阅: 完成! 🕛 ${costTime} 秒`)
}
function getAppSubs() {
const usercfgs = getUserCfgs()
const appsubs = []
for (let subIdx = 0; subIdx < usercfgs.appsubs.length; subIdx++) {
const sub = usercfgs.appsubs[subIdx]
const suburl = sub.url.replace(/[ ]|[\r\n]/g, '')
const cachedsub = usercfgs.appsubCaches[suburl]
if (cachedsub && Array.isArray(cachedsub.apps)) {
cachedsub._raw = sub
cachedsub.apps.forEach((app) => (app.datas = []))
wrapapps(cachedsub.apps)
appsubs.push(cachedsub)
} else {
sub.isErr = true
sub.apps = []
sub._raw = JSON.parse(JSON.stringify(sub))
appsubs.push(sub)
}
}
return appsubs
}
function getUserApps() {
return []
}
function wrapapps(apps) {
apps.forEach((app) => {
// 获取持久化数据
app.datas = Array.isArray(app.datas) ? app.datas : []
app.keys.forEach((key) => {
const valdat = $.getdata(key)
const val = [undefined, null, 'null', ''].includes(valdat) ? null : valdat
app.datas.push({ key, val })
})
Array.isArray(app.settings) &&
app.settings.forEach((setting) => {
const valdat = $.getdata(setting.id)
const val = [undefined, null, 'null', ''].includes(valdat) ? null : valdat
setting.defval = setting.val
if (setting.type === 'boolean') {
setting.val = val === null ? setting.val : val === 'true'
} else if (setting.type === 'int') {
setting.val = val * 1 || setting.val
} else if (setting.type === 'checkboxes') {
if (![null, undefined].includes(valdat)) {
setting.val = valdat ? valdat.split(',') : []
}
} else {
setting.val = val || setting.val
}
app.author = app.author ? app.author : '@anonymous'
app.repo = app.repo ? app.repo : '作者很神秘, 没有留下任何线索!'
})
// 判断是否收藏应用
const usercfgs = getUserCfgs()
const favapps = usercfgs && usercfgs.favapps
if (favapps) {
app.isFav = favapps.findIndex((appId) => app.id === appId) > -1 ? true : false
}
})
}
function getSessions() {
const sessionstr = $.getdata($.KEY_sessions)
const sessions = sessionstr ? JSON.parse(sessionstr) : []
return Array.isArray(sessions) ? sessions : []
}
function getCurSessions(appId) {
const curSessionsstr = $.getdata($.KEY_curSessions)
return ![undefined, null, 'null', ''].includes(curSessionsstr) ? JSON.parse(curSessionsstr) : {}
}
async function getVersions() {
let vers = []
await new Promise((resolve) => {
setTimeout(resolve, 1000)
const verurl = `https://gitee.com/chavyleung/scripts/raw/master/box/release/box.release.json`
$.get({ url: verurl }, (err, resp, data) => {
try {
const _data = JSON.parse(data)
vers = Array.isArray(_data.releases) ? _data.releases : vers
} catch (e) {
$.logErr(e, resp)
} finally {
resolve()
}
})
})
return vers
}
async function handleApi() {
const data = JSON.parse($request.body)
// 保存会话
if (data.cmd === 'saveSession') {
const session = data.val
const sessions = getSessions()
sessions.push(session)
const savesuc = $.setdata(JSON.stringify(sessions), $.KEY_sessions)
$.subt = `保存会话: ${savesuc ? '成功' : '失败'} (${session.appName})`
$.desc = []
$.desc.push(
`会话名称: ${session.name}`,
`应用名称: ${session.appName}`,
`会话编号: ${session.id}`,
`应用编号: ${session.appId}`,
`数据: ${JSON.stringify(session)}`
)
$.msg($.name, $.subt, $.desc.join('\n'))
}
// 保存至指定会话
else if (data.cmd === 'saveSessionTo') {
const { fromapp, toSession } = data.val
const sessions = getSessions()
const session = sessions.find((s) => s.id === toSession.id)
session.datas = fromapp.datas
const savesuc = $.setdata(JSON.stringify(sessions), $.KEY_sessions)
$.subt = `保存会话: ${savesuc ? '成功' : '失败'} (${session.appName})`
$.desc = []
$.desc.push(
`会话名称: ${session.name}`,
`应用名称: ${session.appName}`,
`会话编号: ${session.id}`,
`应用编号: ${session.appId}`,
`数据: ${JSON.stringify(session)}`
)
$.msg($.name, $.subt, $.desc.join('\n'))
}
// 修改指定会话
else if (data.cmd === 'onModSession') {
const sessiondat = data.val
const sessions = getSessions()
const session = sessions.find((s) => s.id === sessiondat.id)
session.name = sessiondat.name
session.datas = sessiondat.datas
const savesuc = $.setdata(JSON.stringify(sessions), $.KEY_sessions)
$.subt = `保存会话: ${savesuc ? '成功' : '失败'} (${session.appName})`
$.desc = []
$.desc.push(
`会话名称: ${session.name}`,
`应用名称: ${session.appName}`,
`会话编号: ${session.id}`,
`应用编号: ${session.appId}`,
`数据: ${JSON.stringify(session)}`
)
$.msg($.name, $.subt, $.desc.join('\n'))
}
// 保存当前会话
else if (data.cmd === 'saveCurAppSession') {
const app = data.val
let isAllSaveSuc = true
app.datas.forEach((data) => {
const oldval = $.getdata(data.key)
const newval = data.val ? data.val : ''
const savesuc = $.setdata(`${newval}`, data.key)
isAllSaveSuc = !savesuc ? false : isAllSaveSuc
$.log('', `❕ ${app.name}, 保存设置: ${data.key} ${savesuc ? '成功' : '失败'}!`, `旧值: ${oldval}`, `新值: ${newval}`)
})
$.subt = `保存会话: ${isAllSaveSuc ? '成功' : '失败'} (${app.name})`
$.msg($.name, $.subt, '')
}
// 保存设置
else if (data.cmd === 'saveSettings') {
$.log(`❕ ${$.name}, 保存设置!`)
const settings = data.val
if (Array.isArray(settings)) {
settings.forEach((setting) => {
const oldval = $.getdata(setting.id)
const newval = `${setting.val}`
const usesuc = $.setdata(newval, setting.id)
$.log(`❕ ${$.name}, 保存设置: ${setting.id} ${usesuc ? '成功' : '失败'}!`, `旧值: ${oldval}`, `新值: ${newval}`)
$.setdata(newval, setting.id)
})
$.subt = `保存设置: 成功! `
$.msg($.name, $.subt, '')
}
}
// 应用会话
else if (data.cmd === 'useSession') {
$.log(`❕ ${$.name}, 应用会话!`)
const curSessions = getCurSessions()
const session = data.val
const sessions = getSessions()
const sessionIdx = sessions.findIndex((s) => session.id === s.id)
if (sessions.splice(sessionIdx, 1) !== -1) {
session.datas.forEach((data) => {
const oldval = $.getdata(data.key)
const newval = data.val
const isNull = (val) => [undefined, null, 'null', 'undefined', ''].includes(val)
const usesuc = $.setdata(isNull(newval) ? '' : `${newval}`, data.key)
$.log(`❕ ${$.name}, 替换数据: ${data.key} ${usesuc ? '成功' : '失败'}!`, `旧值: ${oldval}`, `新值: ${newval}`)
})
curSessions[session.appId] = session.id
$.setdata(JSON.stringify(curSessions), $.KEY_curSessions)
$.subt = `应用会话: 成功 (${session.appName})`
$.desc = []
$.desc.push(
`会话名称: ${session.name}`,
`应用名称: ${session.appName}`,
`会话编号: ${session.id}`,
`应用编号: ${session.appId}`,
`数据: ${JSON.stringify(session)}`
)
$.msg($.name, $.subt, $.desc.join('\n'))
}
}
// 删除会话
else if (data.cmd === 'delSession') {
const session = data.val
const sessions = getSessions()
const sessionIdx = sessions.findIndex((s) => session.id === s.id)
if (sessions.splice(sessionIdx, 1) !== -1) {
const delsuc = $.setdata(JSON.stringify(sessions), $.KEY_sessions) ? '成功' : '失败'
$.subt = `删除会话: ${delsuc ? '成功' : '失败'} (${session.appName})`
$.desc = []
$.desc.push(
`会话名称: ${session.name}`,
`会话编号: ${session.id}`,
`应用名称: ${session.appName}`,
`应用编号: ${session.appId}`,
`数据: ${JSON.stringify(session)}`
)
$.msg($.name, $.subt, $.desc.join('\n'))
}
}
// 保存用户偏好
else if (data.cmd === 'saveUserCfgs') {
const usercfgs = data.val
$.setdata(JSON.stringify(usercfgs), $.KEY_userCfgs)
}
// 添加应用订阅
else if (data.cmd === 'addAppSub') {
$.msg($.name, '添加订阅: 开始!')
const sub = data.val
const usercfgs = getUserCfgs()
usercfgs.appsubs.push(sub)
await refreshAppSub(sub, usercfgs)
$.setdata(JSON.stringify(usercfgs), $.KEY_userCfgs)
const endTime = new Date().getTime()
const costTime = (endTime - $.startTime) / 1000
$.msg($.name, `添加订阅: 完成! 🕛 ${costTime} 秒`)
}
// 删除应用订阅
else if (data.cmd === 'delAppSub') {
const subId = data.val
const usercfgs = getUserCfgs()
const subIdx = usercfgs.appsubs.findIndex((s) => s.id === subId)
if (usercfgs.appsubs.splice(subIdx, 1) !== -1) {
const delsuc = $.setdata(JSON.stringify(usercfgs), $.KEY_userCfgs) ? '成功' : '失败'
$.subt = `删除订阅: ${delsuc ? '成功' : '失败'}`
$.msg($.name, $.subt, '')
}
}
// 全局备份
else if (data.cmd === 'globalBak') {
const baks = getGlobalBaks()
baks.push(data.val)
const baksuc = $.setdata(JSON.stringify(baks), $.KEY_globalBaks)
$.subt = `全局备份: ${baksuc ? '成功' : '失败'}`
$.msg($.name, $.subt, '')
}
// 删除全局备份
else if (data.cmd === 'delGlobalBak') {
const baks = getGlobalBaks()
const bakIdx = baks.findIndex((b) => b.id === data.val)
if (baks.splice(bakIdx, 1) !== -1) {
const delsuc = $.setdata(JSON.stringify(baks), $.KEY_globalBaks) ? '成功' : '失败'
$.subt = `删除备份: ${delsuc ? '成功' : '失败'}`
$.msg($.name, $.subt, '')
}
}
// 还原全局备份
else if (data.cmd === 'revertGlobalBak') {
const baks = getGlobalBaks()
const bakobj = baks.find((b) => b.id === data.val)
if (bakobj && bakobj.bak) {
const { chavy_boxjs_sessions, chavy_boxjs_sysCfgs, chavy_boxjs_userCfgs, chavy_boxjs_sysApps, ...datas } = bakobj.bak
$.setdata(JSON.stringify(chavy_boxjs_sessions), $.KEY_sessions)
$.setdata(JSON.stringify(chavy_boxjs_userCfgs), $.KEY_userCfgs)
const isNull = (val) => [undefined, null, 'null', 'undefined', ''].includes(val)
Object.keys(datas).forEach((datkey) => $.setdata(isNull(datas[datkey]) ? '' : `${datas[datkey]}`, datkey))
$.subt = '还原备份: 成功'
$.msg($.name, $.subt, $.desc)
} else {
$.subt = '还原备份: 失败'
$.desc = `找不到备份: ${data.val}`
$.msg($.name, $.subt, $.desc)
}
}
// 刷新应用订阅
else if (data.cmd === 'refreshAppSubs') {
await refreshAppSubs(data && data.val)
}
// 抹掉订阅缓存
else if (data.cmd === 'revertSubCaches') {
console.log(data.cmd)
const usercfgs = getUserCfgs()
usercfgs.appsubCaches = {}
const delsuc = $.setdata(JSON.stringify(usercfgs), $.KEY_userCfgs)
$.subt = `抹掉订阅缓存: ${delsuc ? '成功' : '失败'}`
$.msg($.name, $.subt)
}
// 抹掉备份
else if (data.cmd === 'revertBaks') {
const delsuc = $.setdata('', $.KEY_globalBaks) ? '成功' : '失败'
$.subt = `抹掉备份: ${delsuc ? '成功' : '失败'}`
$.msg($.name, $.subt)
}
// 抹掉会话
else if (data.cmd === 'revertSessions') {
const delsuc = $.setdata('', $.KEY_sessions) ? '成功' : '失败'
$.setdata('', $.KEY_curSessions)
$.subt = `抹掉会话: ${delsuc ? '成功' : '失败'}`
$.msg($.name, $.subt)
}
// 运行脚本
else if (data.cmd === 'runScript') {
const httpapi = $.getdata('@chavy_boxjs_userCfgs.httpapi')
const ishttpapi = /.*?@.*?:[0-9]+/.test(httpapi)
const { script_url, script_timeout } = data.val
if ($.isSurge() && ishttpapi) {
const runOpts = { timeout: script_timeout }
await $.getScript(script_url).then((script) => $.runScript(script, runOpts))
} else {
$.getScript(script_url).then((script) => {
// 避免被执行脚本误认为是 rewrite 环境
// 所以需要 `$request = undefined`
$request = undefined
eval(script)
})
}
}
}
async function getBoxData() {
const box = {
sessions: getSessions(),
curSessions: getCurSessions(),
versions: await getVersions(),
sysapps: getSystemApps(),
userapps: getUserApps(),
appsubs: getAppSubs(),
syscfgs: getSystemCfgs(),
usercfgs: getUserCfgs(),
globalbaks: getGlobalBaks()
}
const apps = []
apps.push(...box.sysapps)
box.appsubs.forEach((sub) => apps.push(...sub.apps))
box.usercfgs.favapps = box.usercfgs.favapps.filter((favappId) => apps.find((app) => app.id === favappId))
return box
}
async function handleHome() {
const box = await getBoxData()
$.html = printHtml(JSON.stringify(box))
if (box.usercfgs.isDebugFormat) {
console.log(printHtml(`'\${data}'`, `'\${appId}'`, `\${curview}`))
} else if (box.usercfgs.isDebugData) {
console.log($.html)
}
}
async function handleApp(appId) {
const box = await getBoxData()
const apps = []
const cursysapp = box.sysapps.find((app) => app.id === appId)
if (cursysapp) {
apps.push(cursysapp)
}
box.appsubs.filter((sub) => sub.enable !== false).forEach((sub) => apps.push(...sub.apps))
const curapp = apps.find((app) => app.id === appId)
if (curapp.script && $.isSurge()) {
await $.getScript(curapp.script).then((script) => (curapp.script_text = script))
}
$.html = printHtml(JSON.stringify(box), appId)
if (box.usercfgs.isDebugFormat) {
console.log(printHtml(`'\${data}'`, `'\${appId}'`, `\${curview}`))
} else if (box.usercfgs.isDebugData) {
console.log($.html)
}
}
async function handleSub() {
const box = await getBoxData()
$.html = printHtml(JSON.stringify(box), null, 'sub')
if (box.usercfgs.isDebugFormat) {
console.log(printHtml(`'\${data}'`, `'\${appId}'`, `\${curview}`))
} else if (box.usercfgs.isDebugData) {
console.log($.html)
}
}
async function handleMy() {
const box = await getBoxData()
$.html = printHtml(JSON.stringify(box), null, 'my')
if (box.usercfgs.isDebugFormat) {
console.log(printHtml(`'\${data}'`, `'\${appId}'`, `\${curview}`))
} else if (box.usercfgs.isDebugData) {
console.log($.html)
}
}
async function handleRevert() {
$.html = printRevertHtml()
}
function printRevertHtml() {
return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>BoxJs</title>
<meta charset="utf-8" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<link rel="Bookmark" href="https://raw.githubusercontent.com/chavyleung/scripts/master/BOXJS.png" />
<link rel="shortcut icon" href="https://raw.githubusercontent.com/chavyleung/scripts/master/BOXJS.png" />
<link rel="apple-touch-icon" href="https://raw.githubusercontent.com/chavyleung/scripts/master/BOXJS.png" />
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet" />
</head>
<body>
<div id="app">
<v-app v-cloak>
<v-container>
<v-card class="mt-4">
<v-card-title>抹掉订阅缓存</v-card-title>
<v-card-text>
<p class="">该操作会抹掉: <font class="error--text">订阅缓存</font></p>
如果添加、更新了订阅后出现白屏现象, 可以尝试抹掉用户设置 <br />
注意: 该操作不会删掉订阅, 只会清空订阅缓存
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-dialog v-model="ui.revertSubCachesDialog.show" persistent max-width="290">
<template v-slot:activator="{ on, attrs }">
<v-btn small text color="error" v-on="on">抹掉</v-btn>
</template>
<v-card>
<v-card-title class="headline">确定抹掉订阅?</v-card-title>
<v-card-text>该操作不可逆, 请注意备份!</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="grey darken-1" text @click="ui.revertSubCachesDialog.show = false">取消</v-btn>
<v-btn color="green darken-1" text @click="revertSubCaches()">确定</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-card-actions>
</v-card>
<v-card class="mt-4">
<v-card-title>抹掉全局备份</v-card-title>
<v-card-text>
<p>该操作会抹掉: <font class="error--text">全局备份</font></p>
如果备份、导入备份后出现 VPN 断开重连现象, 可尝试抹掉所有备份
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-dialog v-model="ui.revertBaksDialog.show" persistent max-width="290">
<template v-slot:activator="{ on, attrs }">
<v-btn small text color="error" v-on="on">抹掉</v-btn>
</template>
<v-card>
<v-card-title class="headline">确定抹掉备份?</v-card-title>
<v-card-text>该操作不可逆, 请注意备份!</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="grey darken-1" text @click="ui.revertBaksDialog.show = false">取消</v-btn>
<v-btn color="green darken-1" text @click="revertBaks()">确定</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-card-actions>
</v-card>
<v-card class="mt-4">
<v-card-title>抹掉所有会话</v-card-title>
<v-card-text>
<p>该操作会抹掉: <font class="error--text">所有会话</font></p>
如果切换会话时出现不符预期现象, 可尝试抹掉所有会话
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-dialog v-model="ui.revertSessionsDialog.show" persistent max-width="290">
<template v-slot:activator="{ on, attrs }">
<v-btn small text color="error" v-on="on">抹掉</v-btn>
</template>
<v-card>
<v-card-title class="headline">确定抹掉会话?</v-card-title>
<v-card-text>该操作不可逆, 请注意备份!</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="grey darken-1" text @click="ui.revertSessionsDialog.show = false">取消</v-btn>
<v-btn color="green darken-1" text @click="revertSessions()">确定</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-card-actions>
</v-card>
<v-overlay v-model="ui.overlay.show" :opacity="0.7">
<v-progress-circular indeterminate size="64"></v-progress-circular>
</v-overlay>
</v-container>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.19.2/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
vuetify: new Vuetify({ theme: { dark: true } }),
data() {
return {
ui: {
overlay: { show: false },
revertSubCachesDialog: {show: false},
revertBaksDialog: {show: false},
revertSessionsDialog: {show: false}
}
}
},
computed: {
},
watch: {
},
methods: {
revertSubCaches: function() {
this.ui.revertSubCachesDialog.show = false
this.ui.overlay.show = true
axios.post('/api', JSON.stringify({ cmd: 'revertSubCaches', val: null })).finally(() => {
this.ui.overlay.show = false
})
},
revertBaks: function() {
this.ui.revertBaksDialog.show = false
this.ui.overlay.show = true
axios.post('/api', JSON.stringify({ cmd: 'revertBaks', val: null })).finally(() => {
this.ui.overlay.show = false
})
},
revertSessions: function() {
this.ui.revertSessionsDialog.show = false
this.ui.overlay.show = true
axios.post('/api', JSON.stringify({ cmd: 'revertSessions', val: null })).finally(() => {
this.ui.overlay.show = false
})
}
}
})
</script>
</body>
</html>
`
}
function printHtml(data, appId = '', curview = 'app') {
return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>BoxJs</title>
<meta charset="utf-8" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<link rel="Bookmark" href="https://raw.githubusercontent.com/chavyleung/scripts/master/BOXJS.png" />
<link rel="shortcut icon" href="https://raw.githubusercontent.com/chavyleung/scripts/master/BOXJS.png" />
<link rel="apple-touch-icon" href="https://raw.githubusercontent.com/chavyleung/scripts/master/BOXJS.png" />
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet" />
<style>
[v-cloak] {
display: none;
}
body {
padding-top: constant(safe-area-inset-top) !important;
padding-top: env(safe-area-inset-top);
}
.text-pre-wrap {
white-space: pre-wrap !important;
}
.v-app-bar,
.v-navigation-drawer__content {
box-sizing: content-box;
padding-top: constant(safe-area-inset-top);
padding-top: env(safe-area-inset-top);
}
.v-app-bar .v-autocomplete {
box-sizing: border-box;
}
.v-bottom-navigation,
.v-bottom-sheet {
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
}
.v-bottom-navigation {
box-sizing: content-box;
}
.v-bottom-navigation button {
box-sizing: border-box;
}
.v-main.safe {
margin-bottom: 56px;
margin-bottom: calc(56px + constant(safe-area-inset-bottom));
margin-bottom: calc(56px + env(safe-area-inset-bottom));
}
.v-main .v-main__wrap {
padding-bottom: 68px;
padding-bottom: calc(68px + constant(safe-area-inset-bottom));
padding-bottom: calc(68px + env(safe-area-inset-bottom));
}
.v-main.safe .v-main__wrap {
padding-bottom: 68px;
}
.v-speed-dial {
bottom: calc(12px + constant(safe-area-inset-bottom));
bottom: calc(12px + env(safe-area-inset-bottom));
}
.v-speed-dial.has-nav {
bottom: calc(68px + constant(safe-area-inset-bottom));
bottom: calc(68px + env(safe-area-inset-bottom));
}
</style>
</head>
<body>
<div id="app">
<v-app v-scroll="onScroll" v-cloak>
<v-app-bar app dense :color="darkMode || !window.navigator.standalone ? undefined : $vuetify.theme.themes.light.primary">
<v-menu bottom left v-if="['app', 'home', 'log', 'sub'].includes(ui.curview) && box.syscfgs.env !== ''">
<template v-slot:activator="{ on }">
<v-btn icon v-on="on">
<v-avatar size="26">
<img :src="box.syscfgs.envs.find(e=>e.id===box.syscfgs.env).icons[iconIdx]" alt="box.syscfgs.env" />
</v-avatar>
</v-btn>
</template>
<v-list dense>
<v-list-item v-for="(env, envIdx) in box.syscfgs.envs" :key="env.id" @click="box.syscfgs.env=env.id">
<v-list-item-avatar size="24"><v-img :src="env.icons[iconIdx]"></v-img></v-list-item-avatar>
<v-list-item-title>{{ env.id }}</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
<v-btn :dark="fullscreen" icon @click="ui.curview = ui.bfview" v-else><v-icon>mdi-chevron-left</v-icon></v-btn>
<v-autocomplete v-model="ui.autocomplete.curapp" :items="apps" :filter="appfilter" :menu-props="{ closeOnContentClick: true, overflowY: true }" :label="'BoxJs - v' + box.syscfgs.version" no-data-text="未实现" dense hide-details solo>
<template v-slot:item="{ item }">
<v-list-item @click="goAppSessionView(item)">
<v-list-item-avatar>
<img v-if="item.icons" :src="item.icons[iconIdx]" />
<img v-else :src="ui.icons[iconIdx]" />
</v-list-item-avatar>
<v-list-item-content>
<v-list-item-title>{{ item.name }} ({{ item.id }})</v-list-item-title>
<v-list-item-subtitle>{{ item.repo }}</v-list-item-subtitle>
<v-list-item-subtitle>{{ item.author }}</v-list-item-subtitle>
</v-list-item-content>
<v-list-item-action>
<v-btn icon v-if="item.isFav" @click.stop="onFav(item)">
<v-icon v-if="darkMode && box.usercfgs.isTransparentIcons" color="white">mdi-star</v-icon>
<v-icon v-else color="yellow darken-2">mdi-star</v-icon>
</v-btn>
<v-btn icon v-else @click.stop="onFav(item)"><v-icon color="grey">mdi-star-outline</v-icon></v-btn>
</v-list-item-action>
</v-list-item>
</template>
</v-autocomplete>
<v-btn icon @click="ui.drawer.show = true">
<v-avatar size="26">
<img :src="box.syscfgs.orz3.icon" :alt="box.syscfgs.orz3.repo" />
</v-avatar>
</v-btn>
</v-app-bar>
<v-fab-transition>
<v-speed-dial v-show="ui.box.show && !box.usercfgs.isHideBoxIcon" fixed fab bottom direction="top" :left="ui.drawer.show || box.usercfgs.isLeftBoxIcon" :right="!box.usercfgs.isLeftBoxIcon === true" :class="box.usercfgs.isHideNavi ? '' : 'has-nav'">
<template v-slot:activator>
<v-btn fab text @dblclick="onReload">
<v-avatar><img :src="box.syscfgs.boxjs.icons[iconIdx]" :alt="box.syscfgs.boxjs.repo" /></v-avatar>
</v-btn>
</template>
<v-btn dark v-if="!box.usercfgs.isHideHelp" fab small color="grey" @click="ui.versheet.show = true">
<v-icon>mdi-help</v-icon>
</v-btn>
<v-btn dark fab small color="pink" @click="box.usercfgs.isLeftBoxIcon = !box.usercfgs.isLeftBoxIcon, onUserCfgsChange()">
<v-icon v-if="!box.usercfgs.isLeftBoxIcon">mdi-format-horizontal-align-left</v-icon>
<v-icon v-else>mdi-format-horizontal-align-right</v-icon>
</v-btn>
<v-btn dark fab small color="indigo" @click="ui.impGlobalBakDialog.show = true">
<v-icon>mdi-database-import</v-icon>
</v-btn>
<v-btn dark fab small color="success" @click="" v-clipboard:copy="JSON.stringify(boxdat)" v-clipboard:success="onCopy">
<v-icon>mdi-export-variant</v-icon>
</v-btn>
<v-btn dark v-if="!box.usercfgs.isHideRefresh" fab small color="orange" @click="reload">
<v-icon>mdi-refresh</v-icon>
</v-btn>
</v-speed-dial>
</v-fab-transition>
<v-navigation-drawer v-model="ui.drawer.show" app temporary right>
<v-list dense nav>
<v-list-item dense @click="onLink(box.syscfgs.chavy.repo)">
<v-list-item-avatar><img :src="box.syscfgs.chavy.icon" /></v-list-item-avatar>
<v-list-item-content>
<v-list-item-title>{{ box.syscfgs.chavy.id }}</v-list-item-title>
<v-list-item-subtitle>{{ box.syscfgs.chavy.repo }}</v-list-item-subtitle>
</v-list-item-content>
</v-list-item>
<v-list-item dense @click="onLink(box.syscfgs.senku.repo)">
<v-list-item-avatar><img :src="box.syscfgs.senku.icon" /></v-list-item-avatar>
<v-list-item-content>
<v-list-item-title>{{ box.syscfgs.senku.id }}</v-list-item-title>
<v-list-item-subtitle>{{ box.syscfgs.senku.repo }}</v-list-item-subtitle>
</v-list-item-content>
</v-list-item>
<v-divider></v-divider>
<v-list-item class="pt-1">
<v-row align="center" justify="start" no-gutters>
<v-col v-for="(c, cIdx) in box.syscfgs.contributors" cols="2" :key="c.id">
<v-avatar class="ma-1" size="26" @click="onGoToRepo(c.repo)">
<img :src="c.icon" />
</v-avatar>
</v-col>
</v-row>
</v-list-item>
<v-divider></v-divider>
<v-list-item v-if="box.syscfgs.env === 'Surge'">
<v-list-item-content>
<v-select v-if="box.usercfgs.httpapis" hide-details v-model="box.usercfgs.httpapi" :items="box.usercfgs.httpapis.split(',')" @change="onUserCfgsChange" label="HTTP-API (Surge TF)"> </v-select>
<v-text-field v-else label="HTTP-API (Surge TF)" v-model="box.usercfgs.httpapi" hint="Surge http-api 地址." placeholder="examplekey@127.0.0.1:6166" persistent-hint @change="onUserCfgsChange" :rules="[(val)=> /.*?@.*?:[0-9]+/.test(val) || '格式错误: examplekey@127.0.0.1:6166']"> </v-text-field>
</v-list-item-content>
</v-list-item>
<v-list-item>
<v-list-item-content>
<v-select hide-details v-model="box.usercfgs.theme" :items="[{text: '跟随系统', value: 'auto'}, {text: '暗黑', value: 'dark'}, {text: '明亮', value: 'light'}]" label="颜色主题"> </v-select>
</v-list-item-content>
</v-list-item>
<v-list-item class="mt-4">
<v-switch dense class="mt-0" label="透明图标" v-model="box.usercfgs.isTransparentIcons" @change="onUserCfgsChange" :disabled="!darkMode" :hide-details="darkMode" :persistent-hint="true" hint="明亮主题下强制使用彩色图标"> </v-switch>