-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.js
More file actions
952 lines (884 loc) · 25.3 KB
/
server.js
File metadata and controls
952 lines (884 loc) · 25.3 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
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
/*
* @Author: Jerrykuku https://github.com/jerrykuku
* @Date: 2021-1-8
* @Version: v0.0.2
* @thanks: FanchangWang https://github.com/FanchangWang
*/
var express = require('express');
var session = require('express-session');
var compression = require('compression');
var bodyParser = require('body-parser');
var got = require('got');
var path = require('path');
var fs = require('fs');
var { execSync, exec } = require('child_process');
const { createProxyMiddleware } = require('http-proxy-middleware');
const JD_UA = `jdapp;android;10.0.5;8.0.0;${randPhoneId()};network/wifi;Mozilla/5.0 (Linux; Android 8.0.0; HTC U-3w Build/OPR6.170623.013; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36`;
var rootPath = path.resolve(__dirname, '/jd/');
// config.sh 文件所在目录
var confFile = path.join(rootPath, 'config/config.sh');
// config.sample.sh 文件所在目录
var sampleFile = path.join(rootPath, 'sample/config.sample.sh');
// crontab.list 文件所在目录
var crontabFile = path.join(rootPath, 'config/crontab.list');
// bot.json 文件所在目录
var botFile = path.join(rootPath, 'config/bot.json');
// config.sh 文件备份目录
var confBakDir = path.join(rootPath, 'config/bak/');
// auth.json 文件目录
var authConfigFile = path.join(rootPath, 'config/auth.json');
// Share Code 文件目录
var shareCodeDir = path.join(rootPath, 'log/jd_get_share_code/');
// diy.sh 文件目录
var diyFile = path.join(rootPath, 'config/diy.sh');
// 日志目录
var logPath = path.join(rootPath, 'log/');
// 脚本目录
var ScriptsPath = path.join(rootPath, 'scripts/');
var authError = '错误的用户名密码,请重试';
var loginFaild = '请先登录!';
var configString = 'config sample crontab shareCode diy bot';
var s_token,
cookies,
guid,
lsid,
lstoken,
okl_token,
token,
userCookie = '';
/**
* 随机iPhoneID
* @param {number} [length=6]
* @return {*}
*/
function randPhoneId() {
return Math.random().toString(36).slice(2, 10) +
Math.random().toString(36).slice(2, 10) +
Math.random().toString(36).slice(2, 10) +
Math.random().toString(36).slice(2, 10) +
Math.random().toString(36).slice(2, 10);
}
function praseSetCookies(response) {
s_token = response.body.s_token;
guid = response.headers['set-cookie'][0];
guid = guid.substring(guid.indexOf('=') + 1, guid.indexOf(';'));
lsid = response.headers['set-cookie'][2];
lsid = lsid.substring(lsid.indexOf('=') + 1, lsid.indexOf(';'));
lstoken = response.headers['set-cookie'][3];
lstoken = lstoken.substring(lstoken.indexOf('=') + 1, lstoken.indexOf(';'));
cookies =
'guid=' + guid + '; lang=chs; lsid=' + lsid + '; lstoken=' + lstoken + '; ';
}
function getCookie(response) {
var TrackerID = response.headers['set-cookie'][0];
TrackerID = TrackerID.substring(
TrackerID.indexOf('=') + 1,
TrackerID.indexOf(';')
);
var pt_key = response.headers['set-cookie'][1];
pt_key = pt_key.substring(pt_key.indexOf('=') + 1, pt_key.indexOf(';'));
var pt_pin = response.headers['set-cookie'][2];
pt_pin = pt_pin.substring(pt_pin.indexOf('=') + 1, pt_pin.indexOf(';'));
var pt_token = response.headers['set-cookie'][3];
pt_token = pt_token.substring(
pt_token.indexOf('=') + 1,
pt_token.indexOf(';')
);
var pwdt_id = response.headers['set-cookie'][4];
pwdt_id = pwdt_id.substring(pwdt_id.indexOf('=') + 1, pwdt_id.indexOf(';'));
var s_key = response.headers['set-cookie'][5];
s_key = s_key.substring(s_key.indexOf('=') + 1, s_key.indexOf(';'));
var s_pin = response.headers['set-cookie'][6];
s_pin = s_pin.substring(s_pin.indexOf('=') + 1, s_pin.indexOf(';'));
cookies =
'TrackerID=' +
TrackerID +
'; pt_key=' +
pt_key +
'; pt_pin=' +
pt_pin +
'; pt_token=' +
pt_token +
'; pwdt_id=' +
pwdt_id +
'; s_key=' +
s_key +
'; s_pin=' +
s_pin +
'; wq_skey=';
var userCookie = 'pt_key=' + pt_key + ';pt_pin=' + pt_pin + ';';
console.log('\n############ 登录成功,获取到 Cookie #############\n\n');
console.log('Cookie1="' + userCookie + '"\n');
console.log('\n####################################################\n\n');
return userCookie;
}
async function step1() {
try {
s_token, cookies, guid, lsid, lstoken, okl_token, (token = '');
let timeStamp = new Date().getTime();
let url =
'https://plogin.m.jd.com/cgi-bin/mm/new_login_entrance?lang=chs&appid=300&returnurl=https://wq.jd.com/passport/LoginRedirect?state=' +
timeStamp +
'&returnurl=https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport';
const response = await got(url, {
responseType: 'json',
headers: {
Connection: 'Keep-Alive',
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json, text/plain, */*',
'Accept-Language': 'zh-cn',
Referer:
'https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wq.jd.com/passport/LoginRedirect?state=' +
timeStamp +
'&returnurl=https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport',
'User-Agent': JD_UA,
Host: 'plogin.m.jd.com',
},
});
praseSetCookies(response);
} catch (error) {
cookies = '';
console.log(error.response.body);
}
}
async function step2() {
try {
if (cookies == '') {
return 0;
}
let timeStamp = new Date().getTime();
let url =
'https://plogin.m.jd.com/cgi-bin/m/tmauthreflogurl?s_token=' +
s_token +
'&v=' +
timeStamp +
'&remember=true';
const response = await got.post(url, {
responseType: 'json',
json: {
lang: 'chs',
appid: 300,
returnurl:
'https://wqlogin2.jd.com/passport/LoginRedirect?state=' +
timeStamp +
'&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action',
source: 'wq_passport',
},
headers: {
Connection: 'Keep-Alive',
'Content-Type': 'application/x-www-form-urlencoded; Charset=UTF-8',
Accept: 'application/json, text/plain, */*',
Cookie: cookies,
Referer:
'https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=' +
timeStamp +
'&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport',
'User-Agent': JD_UA,
Host: 'plogin.m.jd.com',
},
});
token = response.body.token;
okl_token = response.headers['set-cookie'][0];
okl_token = okl_token.substring(
okl_token.indexOf('=') + 1,
okl_token.indexOf(';')
);
var qrUrl =
'https://plogin.m.jd.com/cgi-bin/m/tmauth?appid=300&client_type=m&token=' +
token;
return qrUrl;
} catch (error) {
console.log(error.response.body);
return 0;
}
}
var i = 0;
async function checkLogin() {
try {
if (cookies == '') {
return 0;
}
let timeStamp = new Date().getTime();
let url =
'https://plogin.m.jd.com/cgi-bin/m/tmauthchecktoken?&token=' +
token +
'&ou_state=0&okl_token=' +
okl_token;
const response = await got.post(url, {
responseType: 'json',
form: {
lang: 'chs',
appid: 300,
returnurl:
'https://wqlogin2.jd.com/passport/LoginRedirect?state=1100399130787&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action',
source: 'wq_passport',
},
headers: {
Referer:
'https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=' +
timeStamp +
'&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport',
Cookie: cookies,
Connection: 'Keep-Alive',
'Content-Type': 'application/x-www-form-urlencoded; Charset=UTF-8',
Accept: 'application/json, text/plain, */*',
'User-Agent': JD_UA,
},
});
return response;
} catch (error) {
console.log(error.response.body);
let res = {};
res.body = { check_ip: 0, errcode: 222, message: '出错' };
res.headers = {};
return res;
}
}
/**
* 检查 config.sh 以及 config.sample.sh 文件是否存在
*/
function checkConfigFile() {
if (!fs.existsSync(confFile)) {
console.error(rootPath);
console.error('脚本启动失败,config.sh 文件不存在!');
process.exit(1);
}
if (!fs.existsSync(sampleFile)) {
console.error('脚本启动失败,config.sample.sh 文件不存在!');
process.exit(1);
}
}
/**
* 检查 config/bak/ 备份目录是否存在,不存在则创建
*/
function mkdirConfigBakDir() {
if (!fs.existsSync(confBakDir)) {
fs.mkdirSync(confBakDir);
}
}
/**
* 备份 config.sh 文件
*/
function bakConfFile(file) {
mkdirConfigBakDir();
let date = new Date();
let bakConfFile =
confBakDir +
file +
'_' +
date.getFullYear() +
'-' +
date.getMonth() +
'-' +
date.getDay() +
'-' +
date.getHours() +
'-' +
date.getMinutes() +
'-' +
date.getMilliseconds();
let oldConfContent = '';
switch (file) {
case 'config.sh':
oldConfContent = getFileContentByName(confFile);
fs.writeFileSync(bakConfFile, oldConfContent);
break;
case 'crontab.list':
oldConfContent = getFileContentByName(crontabFile);
fs.writeFileSync(bakConfFile, oldConfContent);
break;
case 'diy.sh':
oldConfContent = getFileContentByName(diyFile);
fs.writeFileSync(bakConfFile, oldConfContent);
break;
case 'bot.json':
oldConfContent = getFileContentByName(botFile);
fs.writeFileSync(bakConfFile, oldConfContent);
break;
default:
break;
}
}
/**
* 将 post 提交内容写入 config.sh 文件(同时备份旧的 config.sh 文件到 bak 目录)
* @param content
*/
function saveNewConf(file, content) {
bakConfFile(file);
switch (file) {
case 'config.sh':
fs.writeFileSync(confFile, content);
break;
case 'crontab.list':
fs.writeFileSync(crontabFile, content);
execSync('crontab ' + crontabFile);
break;
case 'diy.sh':
fs.writeFileSync(diyFile, content);
break;
case 'bot.json':
fs.writeFileSync(botFile, content);
break;
default:
break;
}
}
/**
* 获取文件内容
* @param fileName 文件路径
* @returns {string}
*/
function getFileContentByName(fileName) {
if (fs.existsSync(fileName)) {
return fs.readFileSync(fileName, 'utf8');
}
return '';
}
/**
* 获取目录中最后修改的文件的路径
* @param dir 目录路径
* @returns {string} 最新文件路径
*/
function getLastModifyFilePath(dir) {
var filePath = '';
if (fs.existsSync(dir)) {
var lastmtime = 0;
var arr = fs.readdirSync(dir);
arr.forEach(function (item) {
var fullpath = path.join(dir, item);
var stats = fs.statSync(fullpath);
if (stats.isFile()) {
if (stats.mtimeMs >= lastmtime) {
filePath = fullpath;
}
}
});
}
return filePath;
}
var app = express();
// gzip压缩
app.use(compression({ level: 6, filter: shouldCompress }));
function shouldCompress(req, res) {
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false;
}
// fallback to standard filter function
return compression.filter(req, res);
}
app.use(
session({
secret: 'secret',
name: `connect.${Math.random()}`,
resave: true,
saveUninitialized: true,
})
);
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// ttyd proxy
app.use(
'/shell',
createProxyMiddleware({
target: 'http://localhost:7681',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/shell': '/',
},
})
);
/**
* 登录页面
*/
app.get('/', function (request, response) {
if (request.session.loggedin) {
response.redirect('./home');
} else {
response.sendFile(path.join(__dirname + '/public/auth.html'));
}
});
/**
* 用户名密码
*/
app.get('/changepwd', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/pwd.html'));
} else {
response.redirect('/');
}
});
/**
* terminal
*/
app.get('/terminal', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/terminal.html'));
} else {
response.redirect('/');
}
});
/**
* 获取二维码链接
*/
app.get('/qrcode', function (request, response) {
if (request.session.loggedin) {
(async () => {
try {
await step1();
const qrurl = await step2();
if (qrurl != 0) {
response.send({ err: 0, qrcode: qrurl });
} else {
response.send({ err: 1, msg: '错误' });
}
} catch (err) {
response.send({ err: 1, msg: err });
}
})();
} else {
response.send({ err: 1, msg: loginFaild });
}
});
/**
* 获取返回的cookie信息
*/
app.get('/cookie', function (request, response) {
if (request.session.loggedin && cookies != '') {
(async () => {
try {
const cookie = await checkLogin();
if (cookie.body.errcode == 0) {
let ucookie = getCookie(cookie);
response.send({ err: 0, cookie: ucookie });
} else {
response.send({ err: cookie.body.errcode, msg: cookie.body.message });
}
} catch (err) {
response.send({ err: 1, msg: err });
}
})();
} else {
response.send({ err: 1, msg: loginFaild });
}
});
/**
* 获取各种配置文件api
*/
app.get('/api/config/:key', function (request, response) {
if (request.session.loggedin) {
if (configString.indexOf(request.params.key) > -1) {
switch (request.params.key) {
case 'config':
content = getFileContentByName(confFile);
break;
case 'sample':
content = getFileContentByName(sampleFile);
break;
case 'crontab':
content = getFileContentByName(crontabFile);
break;
case 'shareCode':
let shareCodeFile = getLastModifyFilePath(shareCodeDir);
content = getFileContentByName(shareCodeFile);
break;
case 'diy':
content = getFileContentByName(diyFile);
break;
case 'bot':
content = getFileContentByName(botFile);
break;
default:
break;
}
response.setHeader('Content-Type', 'text/plain');
response.send(content);
} else {
response.send('no config');
}
} else {
response.send(loginFaild);
}
});
/**
* 首页 配置页面
*/
app.get('/home', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/home.html'));
} else {
response.redirect('/');
}
});
/**
* 对比 配置页面
*/
app.get('/diff', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/diff.html'));
} else {
response.redirect('/');
}
});
/**
* Share Code 页面
*/
app.get('/shareCode', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/shareCode.html'));
} else {
response.redirect('/');
}
});
/**
* crontab 配置页面
*/
app.get('/crontab', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/crontab.html'));
} else {
response.redirect('/');
}
});
/**
* 自定义脚本 页面
*/
app.get('/diy', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/diy.html'));
} else {
response.redirect('/');
}
});
/**
* Bot 页面
*/
app.get('/bot', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/bot.html'));
} else {
response.redirect('/');
}
});
/**
* 手动执行脚本 页面
*/
app.get('/run', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/run.html'));
} else {
response.redirect('/');
}
});
app.post('/runCmd', function (request, response) {
if (request.session.loggedin) {
const cmd = `cd ${rootPath};` + request.body.cmd;
const delay = request.body.delay || 0;
// console.log('before exec');
// exec maxBuffer 20MB
exec(cmd, { maxBuffer: 1024 * 1024 * 20 }, (error, stdout, stderr) => {
// console.log(error, stdout, stderr);
// 根据传入延时返回数据,有时太快会出问题
setTimeout(() => {
if (error) {
console.error(`执行的错误: ${error}`);
response.send({
err: 1,
msg: stdout ? `${stdout}${error}` : `${error}`,
});
return;
}
if (stdout) {
// console.log(`stdout: ${stdout}`)
response.send({ err: 0, msg: `${stdout}` });
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
response.send({ err: 1, msg: `${stderr}` });
return;
}
response.send({ err: 0, msg: '执行结束,无结果返回。' });
}, delay);
});
} else {
response.redirect('/');
}
});
/**
* 使用jsName获取最新的日志
*/
app.get('/runLog/:jsName', function (request, response) {
if (request.session.loggedin) {
const jsName = request.params.jsName;
let shareCodeFile = getLastModifyFilePath(
path.join(rootPath, `log/${jsName}/`)
);
if (jsName === 'rm_log') {
shareCodeFile = path.join(rootPath, `log/${jsName}.log`);
}
if (shareCodeFile) {
const content = getFileContentByName(shareCodeFile);
response.setHeader('Content-Type', 'text/plain');
response.send(content);
} else {
response.send('no logs');
}
} else {
response.send(loginFaild);
}
});
/**
* auth
*/
app.post('/auth', function (request, response) {
let username = request.body.username;
let password = request.body.password;
fs.readFile(authConfigFile, 'utf8', function (err, data) {
if (err) console.log(err);
var con = JSON.parse(data);
if (username && password) {
if (username == con.user && password == con.password) {
request.session.loggedin = true;
request.session.username = username;
response.send({ err: 0 });
} else {
response.send({ err: 1, msg: authError });
}
} else {
response.send({ err: 1, msg: '请输入用户名密码!' });
}
});
});
/**
* change pwd
*/
app.post('/changepass', function (request, response) {
if (request.session.loggedin) {
let username = request.body.username;
let password = request.body.password;
let config = {
user: username,
password: password,
};
if (username && password) {
fs.writeFile(authConfigFile, JSON.stringify(config), function (err) {
if (err) {
response.send({ err: 1, msg: '写入错误请重试!' });
} else {
response.send({ err: 0, msg: '更新成功!' });
}
});
} else {
response.send({ err: 1, msg: '请输入用户名密码!' });
}
} else {
response.send(loginFaild);
}
});
/**
* change pwd
*/
app.get('/logout', function (request, response) {
request.session.destroy();
response.redirect('/');
});
/**
* save config
*/
app.post('/api/save', function (request, response) {
if (request.session.loggedin) {
let postContent = request.body.content;
let postfile = request.body.name;
saveNewConf(postfile, postContent);
response.send({
err: 0,
title: '保存成功! ',
msg: '将自动刷新页面查看修改后的 ' + postfile + ' 文件',
});
} else {
response.send({ err: 1, title: '保存失败! ', msg: loginFaild });
}
});
/**
* 日志查询 页面
*/
app.get('/log', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/tasklog.html'));
} else {
response.redirect('/');
}
});
/**
* 日志列表
*/
app.get('/api/logs', function (request, response) {
if (request.session.loggedin) {
var fileList = fs.readdirSync(logPath, 'utf-8');
var dirs = [];
var rootFiles = [];
for (var i = 0; i < fileList.length; i++) {
var stat = fs.lstatSync(logPath + fileList[i]);
// 是目录,需要继续
if (stat.isDirectory()) {
var fileListTmp = fs.readdirSync(logPath + '/' + fileList[i], 'utf-8');
fileListTmp.reverse();
var dirMap = {
dirName: fileList[i],
files: fileListTmp,
};
dirs.push(dirMap);
} else {
rootFiles.push(fileList[i]);
}
}
dirs.push({
dirName: '@',
files: rootFiles,
});
var result = { dirs };
response.send(result);
} else {
response.redirect('/');
}
});
/**
* 日志文件
*/
app.get('/api/logs/:dir/:file', function (request, response) {
if (request.session.loggedin) {
let filePath;
if (request.params.dir === '@') {
filePath = logPath + request.params.file;
} else {
filePath = logPath + request.params.dir + '/' + request.params.file;
}
var content = getFileContentByName(filePath);
response.setHeader('Content-Type', 'text/plain');
response.send(content);
} else {
response.redirect('/');
}
});
/**
* 查看脚本 页面
*/
app.get('/viewScripts', function (request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/viewScripts.html'));
} else {
response.redirect('/');
}
});
/**
* 脚本列表
*/
app.get('/api/scripts', function (request, response) {
if (request.session.loggedin) {
var fileList = fs.readdirSync(ScriptsPath, 'utf-8');
var dirs = [];
var rootFiles = [];
var excludeRegExp = /(git)|(node_modules)|(icon)/;
for (var i = 0; i < fileList.length; i++) {
var stat = fs.lstatSync(ScriptsPath + fileList[i]);
// 是目录,需要继续
if (stat.isDirectory()) {
var fileListTmp = fs.readdirSync(
ScriptsPath + '/' + fileList[i],
'utf-8'
);
fileListTmp.reverse();
if (excludeRegExp.test(fileList[i])) {
continue;
}
var dirMap = {
dirName: fileList[i],
files: fileListTmp,
};
dirs.push(dirMap);
} else {
if (excludeRegExp.test(fileList[i])) {
continue;
}
rootFiles.push(fileList[i]);
}
}
dirs.push({
dirName: '@',
files: rootFiles,
});
var result = { dirs };
response.send(result);
} else {
response.redirect('/');
}
});
/**
* 脚本文件
*/
app.get('/api/scripts/:dir/:file', function (request, response) {
if (request.session.loggedin) {
let filePath;
if (request.params.dir === '@') {
filePath = ScriptsPath + request.params.file;
} else {
filePath = ScriptsPath + request.params.dir + '/' + request.params.file;
}
var content = getFileContentByName(filePath);
response.setHeader('Content-Type', 'text/plain');
response.send(content);
} else {
response.redirect('/');
}
});
/**
* 更新已经存在的Cookie & 自动添加新Cookie
* */
app.post('/updateCookie', function (request, response) {
if (request.body.cookie) {
let { cookie, userMsg, cookieTime } = request.body; //cookie和扫描时填写的备注信息以及扫描时cookie时间戳
if (!cookieTime) cookieTime = new Date().getTime() + new Date().getTimezoneOffset() * 60 * 1000 + 8 * 60 * 60 * 1000;
const cookieExpireTime = cookieTime + 60 * 60 * 1000 * 24 * 25;//cookie过期的时间戳(这里以25天计算)
const content = getFileContentByName(confFile);
const lines = content.split('\n');
const pt_pin = cookie.match(/pt_pin=.+?;/)[0];
let updateFlag = false;
let lastIndex = 0;
let maxCookieCount = 0;
let msg = `${userMsg ? ' #用户备注:' + userMsg + ' 过期时间(25天):' + new Date(cookieExpireTime).toLocaleString() : '#过期时间(25天):' + new Date(cookieExpireTime).toLocaleString()}`;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.startsWith('Cookie')) {
maxCookieCount = line.split('=')[0].split('Cookie')[1];
lastIndex = i;
if (
line.match(/pt_pin=.+?;/) &&
line.match(/pt_pin=.+?;/)[0] == pt_pin
) {
const head = line.split('=')[0];
const newLine = [head, '=', '"', cookie, '"', `${msg}`].join('');
lines[i] = newLine;
updateFlag = true;
}
}
}
if (!updateFlag) {
const newLine = `Cookie${Number(maxCookieCount) + 1}="${cookie}" ${msg}`;
lines.splice(lastIndex + 1, 0, newLine);
}
saveNewConf('config.sh', lines.join('\n'));
response.send({
err: 0,
msg: updateFlag ? `Cookie更新成功,当前Cookie数量:${Number(maxCookieCount)}个` : `Cookie新增成功,当前Cookie数量:${Number(maxCookieCount) + 1}个`,
});
} else {
response.send({ msg: '参数错误', err: -1 });
}
});
checkConfigFile();
app.listen(5678, () => {
console.log('应用正在监听 5678 端口!');
});