mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98dfa4c425 | ||
|
|
5bf08b76de | ||
|
|
5c5b4f804e | ||
|
|
6455245d11 | ||
|
|
2ff3d9c601 | ||
|
|
d342fbf29f | ||
|
|
f865018cd6 | ||
|
|
3b9a4f0834 | ||
|
|
67bc305950 | ||
|
|
97f128d59f | ||
|
|
e25885c4d9 | ||
|
|
c285026339 | ||
|
|
6c34045a48 | ||
|
|
e1e6261b4f | ||
|
|
697bcb5922 | ||
|
|
e05b0a2491 | ||
|
|
e1655455d8 | ||
|
|
9921dab064 | ||
|
|
403ab7f0f0 | ||
|
|
9bc7ca4094 | ||
|
|
e924aa76b0 | ||
|
|
0c46606e14 | ||
|
|
dbfa4049f5 | ||
|
|
622fe2a8f8 | ||
|
|
7bce5c4f6a | ||
|
|
1f7f2c8971 | ||
|
|
437a849c2a | ||
|
|
8f7261dd50 | ||
|
|
76fa82c3a7 | ||
|
|
46c9774efa | ||
|
|
1bc64a23e3 | ||
|
|
cc9a17afa3 | ||
|
|
fcbcfc3a03 | ||
|
|
0144f3b131 | ||
|
|
518436d5ca | ||
|
|
1961a6b913 | ||
|
|
5edebdd5f3 | ||
|
|
48edf2c212 | ||
|
|
9b16dca9da | ||
|
|
9479c2498c | ||
|
|
4a18bcabe2 | ||
|
|
34f690c53d | ||
|
|
e70cd6579f | ||
|
|
99c047e9c7 | ||
|
|
978ae326f8 | ||
|
|
b01f27f2d3 | ||
|
|
4d34e0dd96 | ||
|
|
9b0065e533 | ||
|
|
34a51feee9 | ||
|
|
679091de59 | ||
|
|
c6220cb920 | ||
|
|
633b30269c | ||
|
|
8ad26267d8 | ||
|
|
7cfb125682 | ||
|
|
a2dc5de5ce | ||
|
|
4f41ff29ec | ||
|
|
13d95b8c19 | ||
|
|
335c13ab44 | ||
|
|
015cdc10a7 | ||
|
|
a5075ab28f | ||
|
|
2e3c3274c7 | ||
|
|
443c581955 | ||
|
|
5e41faf590 | ||
|
|
0579fb83d3 | ||
|
|
2864845d5b | ||
|
|
659dddace7 | ||
|
|
b096f30558 | ||
|
|
dcfb72143a | ||
|
|
c63bcd7706 | ||
|
|
bac306f9b3 | ||
|
|
a6fd96e97b | ||
|
|
7edd91f923 | ||
|
|
66df445bd5 | ||
|
|
5c03034bb4 | ||
|
|
0eab181d46 | ||
|
|
f6f95308c7 | ||
|
|
e93cad91b4 | ||
|
|
08ee61b179 | ||
|
|
0ab756665e | ||
|
|
3570cddce0 | ||
|
|
a2d9f1a5db | ||
|
|
0c6a214e55 | ||
|
|
095fcdbe69 | ||
|
|
3afb1d18f6 | ||
|
|
4526c84330 | ||
|
|
a9cc1cb4b9 | ||
|
|
7acf1eace3 | ||
|
|
bb2e8cb287 | ||
|
|
3b389259c1 | ||
|
|
310ce55b09 | ||
|
|
4662e3fec2 | ||
|
|
10fab9d415 | ||
|
|
acecf01cbe | ||
|
|
b95fb9cda4 | ||
|
|
23fd595582 | ||
|
|
468d05cb10 | ||
|
|
88c2e5d160 | ||
|
|
8cf491b802 | ||
|
|
5886e78299 | ||
|
|
591ef9781c | ||
|
|
52fef96c1c | ||
|
|
d5fd9c57ec | ||
|
|
8a7d6a1c13 | ||
|
|
1745c72981 | ||
|
|
b98b7646cb | ||
|
|
1446e925ec | ||
|
|
799cda1e3e | ||
|
|
d2e0231341 | ||
|
|
9e0aa655a0 | ||
|
|
e303c73d44 | ||
|
|
e5e8e66d6b | ||
|
|
0bb3381122 | ||
|
|
2c5bf2bd6b | ||
|
|
83763b00ae | ||
|
|
47fc795c97 | ||
|
|
6a59bf7af3 | ||
|
|
6f185570d6 | ||
|
|
8b8336d9d0 | ||
|
|
a1e1d6ed3f | ||
|
|
df3e209534 | ||
|
|
851408860e | ||
|
|
d92ea23b0e | ||
|
|
d83641db92 | ||
|
|
48f262e1f3 | ||
|
|
bc49a7db50 | ||
|
|
49975b461c | ||
|
|
3ccb635956 | ||
|
|
074a90e0ac | ||
|
|
526f927436 | ||
|
|
fae7fad915 | ||
|
|
56132ceb8b | ||
|
|
3c3fce0a5a | ||
|
|
8139384961 | ||
|
|
734cc94048 | ||
|
|
91dbb7770d | ||
|
|
707709837d | ||
|
|
e868e65208 | ||
|
|
b19ad2a13b | ||
|
|
98ccccf6ab | ||
|
|
0a6166c557 | ||
|
|
5ee00e52a8 | ||
|
|
ff2b4e0b2f | ||
|
|
8fdd8db51b | ||
|
|
f113eb7ba8 | ||
|
|
40bc25ed5f | ||
|
|
cd3eab5d35 | ||
|
|
7038e15ad2 | ||
|
|
c72abd29ec | ||
|
|
5efc3d2228 | ||
|
|
8ac3f83c79 | ||
|
|
b31b054d0c | ||
|
|
fb4a87f5ce | ||
|
|
049c73880b | ||
|
|
7b2c54f6a6 | ||
|
|
23bda39812 | ||
|
|
90af5801ee | ||
|
|
543c241bc6 | ||
|
|
19a58a3510 | ||
|
|
73c6fd18ed | ||
|
|
409297c6aa | ||
|
|
4272b9ea35 | ||
|
|
3c5c5b0bbc | ||
|
|
802b2d722e | ||
|
|
8f90d3f8ff | ||
|
|
f93cbbf508 | ||
|
|
2ba8756bd3 | ||
|
|
8013de56c9 | ||
|
|
4af9b22442 | ||
|
|
8a392170cf | ||
|
|
6385e053ae | ||
|
|
2789119882 | ||
|
|
3e0553c3e8 | ||
|
|
5e16ace1e7 | ||
|
|
0ca23cc4ca | ||
|
|
4949457001 | ||
|
|
8ae13fe823 | ||
|
|
fdf672092a | ||
|
|
48dd6ea826 | ||
|
|
68bb4f15e2 | ||
|
|
9c6d9ec22d | ||
|
|
ac075ace73 | ||
|
|
eb58774ee9 | ||
|
|
04613bf9a9 | ||
|
|
4194f1964d | ||
|
|
42c64c82d7 | ||
|
|
d44a8966f2 | ||
|
|
ff44330aa1 | ||
|
|
ed259e8168 | ||
|
|
444836975d | ||
|
|
3756fa93e4 | ||
|
|
064b52b306 | ||
|
|
648dc51474 | ||
|
|
7c0bc32759 | ||
|
|
d4b6cc5e4d | ||
|
|
75fca715e3 | ||
|
|
6e9a4a29ef | ||
|
|
78f643c50f | ||
|
|
2db4f1ba87 | ||
|
|
5741dbb78c | ||
|
|
88cf671465 | ||
|
|
29f082dea2 | ||
|
|
9a55968ed6 | ||
|
|
6ec6e25855 | ||
|
|
af48bc378b | ||
|
|
3f5ae4bcb9 | ||
|
|
c6624e9001 | ||
|
|
5530ce76e3 | ||
|
|
654b51e476 | ||
|
|
6428ac3624 | ||
|
|
c36450f436 | ||
|
|
dcea231249 | ||
|
|
f236119bd6 | ||
|
|
cb870fad85 | ||
|
|
44e2caedfc | ||
|
|
c0b5192296 | ||
|
|
ba43882c0b | ||
|
|
dfc706e16d | ||
|
|
25b03d4345 | ||
|
|
4e8f36d9a4 | ||
|
|
8f4d67ffa7 | ||
|
|
ad47277149 | ||
|
|
98c2a37ab6 | ||
|
|
f2fea47336 | ||
|
|
e274d3e2f9 | ||
|
|
36f4c3c02c | ||
|
|
ae891f8e55 | ||
|
|
c874dc9705 | ||
|
|
23bfbeb995 | ||
|
|
a75df03243 | ||
|
|
e44a2b5995 | ||
|
|
f23e7a9e49 | ||
|
|
e08f0cd308 | ||
|
|
1ebcfd8001 | ||
|
|
5168b044a3 | ||
|
|
931638b687 | ||
|
|
4d9bbcfd3f | ||
|
|
b0e3b26369 | ||
|
|
1e55f4065d | ||
|
|
518e8903a3 | ||
|
|
6e56a55f6f | ||
|
|
967071ad4e | ||
|
|
d23fcfaa5a | ||
|
|
a2f2306430 | ||
|
|
144b543091 | ||
|
|
e4ad8f512e | ||
|
|
591a5006da | ||
|
|
281ed6cfba | ||
|
|
7354a61184 | ||
|
|
04037f29e5 | ||
|
|
6b124bad89 | ||
|
|
54d99a4954 | ||
|
|
9947594366 | ||
|
|
d7ff934336 | ||
|
|
dc27856441 | ||
|
|
bd28682769 | ||
|
|
2060e62da4 | ||
|
|
70eac1e747 | ||
|
|
6f5a5fe066 | ||
|
|
8d24949202 | ||
|
|
f7b6237355 | ||
|
|
daf6f94c51 | ||
|
|
687d16e21b | ||
|
|
70571a9d34 | ||
|
|
4da8d8fe1e | ||
|
|
952cdc0e3f | ||
|
|
2de189d189 | ||
|
|
3edc6e83d7 | ||
|
|
31a5386cfe | ||
|
|
0198ebbbff | ||
|
|
ce3df8704d | ||
|
|
1b4ca3a684 | ||
|
|
e31c2c0955 | ||
|
|
4e389865b5 | ||
|
|
e5d8adf955 | ||
|
|
9a3181bc44 | ||
|
|
2f05c95422 | ||
|
|
bc5a3a2028 | ||
|
|
1fe91508f6 | ||
|
|
b9253c8191 | ||
|
|
7516acbc41 | ||
|
|
3b3d45da29 | ||
|
|
918d68d140 | ||
|
|
a3f56be299 | ||
|
|
f8f63890e5 | ||
|
|
9e997410ab | ||
|
|
529880642f | ||
|
|
d2590edab3 | ||
|
|
32eec68278 | ||
|
|
05ed8c9f4b | ||
|
|
bc281ee4d7 | ||
|
|
3e88314d0a | ||
|
|
141defd845 | ||
|
|
b9e49b181a | ||
|
|
102e447f78 | ||
|
|
f3de8435f1 | ||
|
|
06723407d2 | ||
|
|
db8dfb32cf | ||
|
|
a7117e4442 | ||
|
|
53414e5d70 | ||
|
|
7bbc776759 | ||
|
|
f123c0bfe1 | ||
|
|
830865ff77 | ||
|
|
15fc6f975c | ||
|
|
4582711867 | ||
|
|
1eb64720d1 | ||
|
|
29f5134fb4 | ||
|
|
55ffd85d48 | ||
|
|
075165f89d | ||
|
|
42dabbf4c0 | ||
|
|
999b5d325f | ||
|
|
027c3f584c | ||
|
|
2d3ebe6087 | ||
|
|
f016e6734a | ||
|
|
9f0503f138 | ||
|
|
f74821895e | ||
|
|
872519a213 | ||
|
|
dcd39ea6d8 | ||
|
|
a4a76ec235 | ||
|
|
87a265191c | ||
|
|
6f4736bddf | ||
|
|
e85742a293 | ||
|
|
28ea160004 | ||
|
|
99d881fc0d | ||
|
|
5d6ac7f07c | ||
|
|
a23dbfe5e1 | ||
|
|
2d818a19d1 | ||
|
|
be89fd4ff7 | ||
|
|
6d2edaaaf8 | ||
|
|
19afbd06c0 | ||
|
|
718964ab86 | ||
|
|
0dadd4e6cc | ||
|
|
57e7d756cb | ||
|
|
9f5fb30334 | ||
|
|
ec8c339f6e | ||
|
|
728d84cb15 | ||
|
|
a7b5a0f4c5 | ||
|
|
b009d3e3fd | ||
|
|
559defc8d6 | ||
|
|
98cc983473 | ||
|
|
6d42a680b1 | ||
|
|
1602f829ba | ||
|
|
c4a4764762 | ||
|
|
ac32117e78 | ||
|
|
3b5bcf8f16 | ||
|
|
8735321e34 | ||
|
|
be76ff4675 | ||
|
|
15678b029c | ||
|
|
05d47be1c8 | ||
|
|
106b34e33a | ||
|
|
488fbd2bbb | ||
|
|
b82c630e3f | ||
|
|
5a01c41bbb | ||
|
|
471e778a61 | ||
|
|
68e576a5e3 | ||
|
|
8c74fca362 | ||
|
|
026fc43695 | ||
|
|
4f925b92d0 | ||
|
|
4200d5e530 | ||
|
|
32ca72133a | ||
|
|
7708638267 | ||
|
|
cb24d3c9fa | ||
|
|
07c63e285e | ||
|
|
a5e8d5cb80 | ||
|
|
8892e8833e | ||
|
|
25af639eef | ||
|
|
58383e9022 | ||
|
|
d244650432 | ||
|
|
f338537ea0 | ||
|
|
8d2c62d6d1 | ||
|
|
8b1906c786 | ||
|
|
3f29c1aa4e | ||
|
|
31ff0476a6 | ||
|
|
b3ed824b2e | ||
|
|
ec97242415 | ||
|
|
d54faf8044 | ||
|
|
5f380b55d1 | ||
|
|
8d46115823 | ||
|
|
cc24e51cd7 | ||
|
|
7a5e6dba51 | ||
|
|
ad1ee0d2ef | ||
|
|
e4f7461b62 | ||
|
|
a9e0a934a7 | ||
|
|
2a23b838f6 | ||
|
|
1afc791e0b | ||
|
|
05cf51afa0 | ||
|
|
76b6677f5a | ||
|
|
af74afd10d | ||
|
|
46512142fa | ||
|
|
6f13cc6e6f | ||
|
|
9dab6660d0 | ||
|
|
89ddfd20cd | ||
|
|
c9bd27ec4f | ||
|
|
2e937ad5ae | ||
|
|
39d3d53614 | ||
|
|
456b4c4136 | ||
|
|
a90e536403 | ||
|
|
d96206ef66 | ||
|
|
ef71e13139 | ||
|
|
189826c5db | ||
|
|
bdecdce118 | ||
|
|
460a1750f4 | ||
|
|
d2c2ea8d3b | ||
|
|
cb12d8ffec | ||
|
|
5bb1afe5c6 | ||
|
|
7caabe9063 | ||
|
|
1695b8c0fe | ||
|
|
0927682abf | ||
|
|
cde4646fe1 | ||
|
|
8c410377b9 | ||
|
|
312aaf18de | ||
|
|
ac2979381f | ||
|
|
03c5c7bbea | ||
|
|
513de1a792 | ||
|
|
c6a8b93b70 | ||
|
|
4c8e097448 | ||
|
|
4e7a5c637d | ||
|
|
f1a51638a5 | ||
|
|
9dcc547ac7 | ||
|
|
bb47d67d0b | ||
|
|
f6a122e5ea | ||
|
|
5523d537dc | ||
|
|
5a21247cbb | ||
|
|
419c5a7c5b | ||
|
|
468ff9c1af | ||
|
|
ebb6290468 | ||
|
|
85d8565241 | ||
|
|
bd35725b3c | ||
|
|
fb6a80e306 | ||
|
|
2c9b283b75 | ||
|
|
0218405998 | ||
|
|
aa59e9a44b | ||
|
|
f9e2e22b85 | ||
|
|
d27ca56a2d | ||
|
|
bf40447ba4 | ||
|
|
89f7b99a94 | ||
|
|
c71d34cbac | ||
|
|
b97ad5cb6b | ||
|
|
081793e1fb | ||
|
|
f76b7d3b35 | ||
|
|
95448418c0 | ||
|
|
199070f829 | ||
|
|
1fa296a53e | ||
|
|
caa8bd7e7f | ||
|
|
22d097aa08 | ||
|
|
5dbfc65e7f | ||
|
|
03e6f18e54 | ||
|
|
84357e9dcc | ||
|
|
8bb8a29400 | ||
|
|
1b893f35ba | ||
|
|
5be421b4ea | ||
|
|
8ad325686d | ||
|
|
54e58c1e08 | ||
|
|
8818a779b5 | ||
|
|
cc65b6c8bb | ||
|
|
523f583516 | ||
|
|
89539deff1 | ||
|
|
6907d520ed | ||
|
|
eae2d6d17a | ||
|
|
82dd9114fd | ||
|
|
58e047fe0e | ||
|
|
d703769d43 | ||
|
|
be6ca54d9c | ||
|
|
a5cadfbcab | ||
|
|
5e3be8fcd1 | ||
|
|
8b5347dd44 | ||
|
|
24f6070f9e | ||
|
|
d00f2cd33b | ||
|
|
8276a19012 | ||
|
|
c769c598b8 | ||
|
|
d687e79b6c | ||
|
|
8fac58d73f | ||
|
|
b2ba86b212 | ||
|
|
92673b4a17 | ||
|
|
85facc039a | ||
|
|
24f33431de | ||
|
|
36533ab7e2 | ||
|
|
97d170c8b1 | ||
|
|
1413999ac3 | ||
|
|
0d23f8a962 | ||
|
|
d0b13a04cc | ||
|
|
fca7b02656 | ||
|
|
2afbfa08c6 | ||
|
|
5fe63666b0 | ||
|
|
9ee08acf29 | ||
|
|
bc7f406968 | ||
|
|
00ee90792f | ||
|
|
4a8c90365e | ||
|
|
d0e46224dc | ||
|
|
54dd90e7c5 | ||
|
|
7ef3de1367 | ||
|
|
ce6aa23d5b | ||
|
|
dc819bcf8e | ||
|
|
b0595656bb | ||
|
|
1dac54b7e7 | ||
|
|
95ea085e1e | ||
|
|
ec5f6d20cb | ||
|
|
aa288c89b3 | ||
|
|
ea419a98ae | ||
|
|
0f0c79f52f | ||
|
|
38df66a5b1 | ||
|
|
0051260171 | ||
|
|
f6dc0e020f | ||
|
|
6f2e7b9459 | ||
|
|
384e3f09da | ||
|
|
747f4552e0 | ||
|
|
1db13653bf | ||
|
|
d05304f839 | ||
|
|
0b551ddc0d | ||
|
|
f117f6b39c | ||
|
|
0c54ca95d9 | ||
|
|
bcbc8a633f | ||
|
|
73963c89fc | ||
|
|
793d14f04b | ||
|
|
ef32181f36 | ||
|
|
419f59818b | ||
|
|
2bda3a276a | ||
|
|
5e5b28ef29 | ||
|
|
8dfbe93135 | ||
|
|
810c6ca76c | ||
|
|
912b4ddb76 | ||
|
|
6b41df3497 | ||
|
|
3e62fedc73 | ||
|
|
a10ffef38f | ||
|
|
816ce31279 | ||
|
|
4e58a640e4 | ||
|
|
43925d6630 | ||
|
|
b688461137 | ||
|
|
1e85528889 | ||
|
|
eb4976ed6b | ||
|
|
7dd87220ab | ||
|
|
9927461ea9 | ||
|
|
84c7ffc509 | ||
|
|
ee52f09bcb | ||
|
|
531fc48bdf | ||
|
|
0581a7ab10 | ||
|
|
f0d2d57584 | ||
|
|
cb154437ac | ||
|
|
7ea9a8aa57 | ||
|
|
7e34f4990d | ||
|
|
f0f2c6b537 | ||
|
|
f71b3d0378 | ||
|
|
7d6e1d3e3d | ||
|
|
cf5f1b6f25 | ||
|
|
903007e6ca | ||
|
|
d6614acf66 | ||
|
|
86df495b67 | ||
|
|
71b0c10997 | ||
|
|
e273c59d78 | ||
|
|
baea40f157 | ||
|
|
a809b89bb0 | ||
|
|
89e08953cb | ||
|
|
e154cf65b6 | ||
|
|
d7162a24be | ||
|
|
16532720d7 | ||
|
|
012ee2419d | ||
|
|
7e4fe2f1b3 | ||
|
|
5a95b72607 | ||
|
|
4d27055605 | ||
|
|
e2b9578253 | ||
|
|
57fd8f378c | ||
|
|
a726f224f8 | ||
|
|
d502ac6e0f | ||
|
|
f6a828f0af | ||
|
|
0a53a7001e | ||
|
|
0ab5494744 | ||
|
|
e60cf15f39 | ||
|
|
b53db97b98 | ||
|
|
f12c75f91b | ||
|
|
3df1a14f72 | ||
|
|
712f105d34 | ||
|
|
4ea757fece | ||
|
|
d8b32f63ea | ||
|
|
771b81afaf | ||
|
|
a4f4c6ac15 | ||
|
|
ae22cf064e | ||
|
|
fbb8e1bd31 | ||
|
|
47202ef66c | ||
|
|
f46c70dcbd | ||
|
|
c7a837e33d | ||
|
|
544e2e8331 | ||
|
|
a62ccbc0db | ||
|
|
891619ad55 | ||
|
|
a3a62f65dd | ||
|
|
3131f197b8 | ||
|
|
e13d9ed51b | ||
|
|
1b5f4a0f9d | ||
|
|
c9c4043a4e | ||
|
|
bb59dd977a | ||
|
|
c2b213a37c | ||
|
|
559f4418d1 | ||
|
|
2149bca7b8 | ||
|
|
be5db82b79 | ||
|
|
01163e3ea3 | ||
|
|
7f986fdb2d | ||
|
|
38e1ba67af | ||
|
|
d3d2e0887e | ||
|
|
a2650715b3 | ||
|
|
8c0685202e | ||
|
|
5b6843b5c0 | ||
|
|
ba341b69ac | ||
|
|
ca89f03724 | ||
|
|
5461325e69 | ||
|
|
e96a2818b7 | ||
|
|
355f06a3cf | ||
|
|
f6e6cfa71c | ||
|
|
9cdfa2ef79 | ||
|
|
6fab22099d | ||
|
|
925819b3aa | ||
|
|
6f96900ab9 | ||
|
|
43bc29b25c | ||
|
|
e13ff86ff6 | ||
|
|
3f3d572932 | ||
|
|
a0ce1562ac | ||
|
|
ee84cbca51 | ||
|
|
3ed5cb48b5 | ||
|
|
499ba5fb99 | ||
|
|
c2f036c370 | ||
|
|
326580b3c8 | ||
|
|
bf59351cf9 | ||
|
|
a954fc3942 | ||
|
|
160a66af23 | ||
|
|
4edbd29b19 | ||
|
|
b6b97478d1 | ||
|
|
27a871e537 | ||
|
|
738b0f9a4a | ||
|
|
1a56dd8ac6 | ||
|
|
672d440725 | ||
|
|
3625b7c0de | ||
|
|
e75a683173 | ||
|
|
89ed8527d6 | ||
|
|
5a5f4b8065 | ||
|
|
d2e23341eb | ||
|
|
233081149b | ||
|
|
5d19ee0ab5 | ||
|
|
653b1cef20 | ||
|
|
f3ecf6e7a0 | ||
|
|
35d8f0a7e8 | ||
|
|
e863dd322a | ||
|
|
fa6dec969f | ||
|
|
58cd05fd09 | ||
|
|
2e6ca5419d | ||
|
|
a29392bb08 | ||
|
|
4dc9c9aa75 | ||
|
|
03c9f79549 | ||
|
|
46aaeb4eac | ||
|
|
4d20bb0de6 | ||
|
|
e001686627 | ||
|
|
931f02ef8e | ||
|
|
a9be3e6376 | ||
|
|
aedd369fc4 | ||
|
|
a1016b7f22 | ||
|
|
603432aa87 | ||
|
|
cd23967ae0 | ||
|
|
dfb159c4ad | ||
|
|
0318f03283 | ||
|
|
9ddf6986e4 | ||
|
|
a28ed9281e | ||
|
|
9cc776aded | ||
|
|
349f14a7fc | ||
|
|
fae26efb88 | ||
|
|
64d0bb18b1 | ||
|
|
864ce071f6 | ||
|
|
5a55934029 | ||
|
|
1f061ad059 | ||
|
|
32f0774df2 | ||
|
|
3206ff6a1e | ||
|
|
2f5e946979 | ||
|
|
5a6d3739d4 | ||
|
|
fa018b84a7 | ||
|
|
a686206e21 | ||
|
|
6132d13261 | ||
|
|
f64c78919d | ||
|
|
1a1067966c | ||
|
|
ec545cabcd | ||
|
|
40b0e90c0d | ||
|
|
5e94be21aa | ||
|
|
417ae8bbde | ||
|
|
acde7ebef6 | ||
|
|
a424e8df7c | ||
|
|
2eed5cba14 | ||
|
|
19e7c238f6 | ||
|
|
f3c939e442 | ||
|
|
3bcf3431d3 | ||
|
|
20d6308bc7 | ||
|
|
96b0127811 | ||
|
|
68cc792d6c | ||
|
|
d0f7449b57 | ||
|
|
b41c1f1d2e | ||
|
|
9a8b72fe3f | ||
|
|
b16f8b96dc | ||
|
|
128429a6a9 | ||
|
|
b849d8b526 | ||
|
|
47b06c3487 | ||
|
|
40e0d143f4 | ||
|
|
c1269d9dde | ||
|
|
6a81ba9069 | ||
|
|
61883776f2 | ||
|
|
f7752cec3a | ||
|
|
6f96c84a16 | ||
|
|
a2ce3304de | ||
|
|
ee0b47d101 | ||
|
|
3b3dd4c26d | ||
|
|
bee1f9968e | ||
|
|
65691cf7c9 | ||
|
|
7b7bcf600d | ||
|
|
18cd7bfa6f | ||
|
|
8c14a31967 | ||
|
|
6c840b435e | ||
|
|
eca615c066 | ||
|
|
22bb785139 | ||
|
|
62fca3dfe2 | ||
|
|
9936097086 | ||
|
|
50dd235e39 | ||
|
|
606bac2e43 | ||
|
|
90ede97797 | ||
|
|
1545cde58a | ||
|
|
8481d81257 | ||
|
|
0688d4f318 | ||
|
|
ab5ab951d7 | ||
|
|
0ca640acbd | ||
|
|
235f99c0ca | ||
|
|
31fdf7f12c | ||
|
|
bd6d711212 | ||
|
|
62596f27ef | ||
|
|
1b88853a8d | ||
|
|
3c5925ff67 | ||
|
|
7d5687d504 | ||
|
|
6b74cccc34 | ||
|
|
1becb26aaf | ||
|
|
bd2917822e | ||
|
|
9c82db4471 | ||
|
|
e4f11156f6 | ||
|
|
c7de19d3b5 | ||
|
|
65ade4b996 | ||
|
|
2b70851074 | ||
|
|
b7b983229b | ||
|
|
ac548433c0 | ||
|
|
02a1afb477 | ||
|
|
e959466898 | ||
|
|
5c5aef64b0 | ||
|
|
86e8b1383c | ||
|
|
9f7bf1f6b8 | ||
|
|
2ff3869608 | ||
|
|
8d21401f88 | ||
|
|
b92daedea2 | ||
|
|
021d89379a | ||
|
|
2b61204233 | ||
|
|
1da1659b51 | ||
|
|
1302a6daa0 | ||
|
|
160dbe780c | ||
|
|
d047cf0d77 | ||
|
|
0c2a2af308 | ||
|
|
bd8953ea81 | ||
|
|
a479f0fbce | ||
|
|
2e00e80e96 | ||
|
|
0bf4aec74e | ||
|
|
bcac3deb6e | ||
|
|
596f93623e | ||
|
|
c74a1bc20c | ||
|
|
795d1b938d | ||
|
|
bad247c51c | ||
|
|
950aed3522 | ||
|
|
8a7bd53f24 | ||
|
|
04230cbd1c | ||
|
|
d0a7e67138 | ||
|
|
56517fd345 | ||
|
|
6315425a7b | ||
|
|
c42299766c | ||
|
|
ef9fa02145 | ||
|
|
51869b6a84 | ||
|
|
d12953a345 | ||
|
|
9f727cd54b | ||
|
|
3de567191e | ||
|
|
b212762417 | ||
|
|
d5f619ff74 | ||
|
|
87027f8a8c | ||
|
|
6fa8a678bf | ||
|
|
f2aa355389 | ||
|
|
b3ef432c6f | ||
|
|
860a1e4dc6 | ||
|
|
f5b322649d | ||
|
|
746650b49a | ||
|
|
43ddc54a70 | ||
|
|
bdfa08bb78 | ||
|
|
07e58a484c | ||
|
|
a652e1e190 | ||
|
|
ec0deeff06 | ||
|
|
7335e2c299 | ||
|
|
003cdd1e06 | ||
|
|
efa1fcfbdf | ||
|
|
7acda0c039 | ||
|
|
cb86fda169 | ||
|
|
324d106693 | ||
|
|
0644edb62e | ||
|
|
0f31cb5fcc | ||
|
|
c80a9d1e65 | ||
|
|
b26d0b4887 | ||
|
|
ed93b919ba | ||
|
|
b1077443a3 | ||
|
|
9455ca64a2 | ||
|
|
d6ebd2699e | ||
|
|
632514d36e | ||
|
|
686baa56f4 | ||
|
|
a3006af7b8 | ||
|
|
ec529bfca6 | ||
|
|
a661b6bd38 | ||
|
|
73e85c2def | ||
|
|
6819487a43 | ||
|
|
14b20873c7 | ||
|
|
bd1ca7e975 | ||
|
|
c01ec828e2 | ||
|
|
47abdb0f36 | ||
|
|
6d4568cdcd | ||
|
|
2068ef7053 | ||
|
|
5655591215 | ||
|
|
feb22f25b8 | ||
|
|
c054259806 | ||
|
|
b179649078 | ||
|
|
a75561399d | ||
|
|
fa02df0d8f | ||
|
|
f17642b243 | ||
|
|
43773222f8 | ||
|
|
91a5e13cf2 | ||
|
|
be4efbad5d | ||
|
|
da3e63e6c3 | ||
|
|
2d427c0670 | ||
|
|
97184d22c3 | ||
|
|
f1cc7641fb | ||
|
|
ca9d742359 | ||
|
|
1d82310ca1 | ||
|
|
687afce245 | ||
|
|
26d986d4a8 | ||
|
|
120599c778 | ||
|
|
54945f2183 | ||
|
|
f48b91dc0a | ||
|
|
4c1551c309 | ||
|
|
558478be16 | ||
|
|
4e403d3d8a | ||
|
|
a79fd74130 | ||
|
|
af2f3deeab | ||
|
|
c15ff89746 | ||
|
|
5b585e0cda | ||
|
|
6619374571 | ||
|
|
9fc8fdd9d1 | ||
|
|
900d279bf6 | ||
|
|
265760146f | ||
|
|
74fa8ffcd1 | ||
|
|
e5313e63a9 | ||
|
|
f482796cdf | ||
|
|
aa08f489d7 | ||
|
|
1cc54b5da6 | ||
|
|
0baf0d23ae | ||
|
|
646443deb5 | ||
|
|
39fb23c025 | ||
|
|
698c463c3a | ||
|
|
6c87634bb3 | ||
|
|
0a9e9e972d | ||
|
|
bb0ad6c325 | ||
|
|
f2dac51a62 | ||
|
|
9534cda1f9 | ||
|
|
27226e7222 | ||
|
|
c51621ee04 | ||
|
|
c78e4447fa | ||
|
|
2d7e525024 | ||
|
|
ecee9e2acd | ||
|
|
d607619f8f | ||
|
|
e8e275cd79 | ||
|
|
4147025406 | ||
|
|
35539a4ccc | ||
|
|
b7a359714f | ||
|
|
bf43bfbd92 | ||
|
|
1265e465d0 | ||
|
|
8f195b964f | ||
|
|
a285efdd85 | ||
|
|
fafb68dbf0 | ||
|
|
3dc87329f1 | ||
|
|
7fc15518b3 | ||
|
|
eb196bd40d | ||
|
|
0cbfca979e | ||
|
|
b3ac81b7b7 | ||
|
|
bb40111d38 | ||
|
|
29a3bea6e4 | ||
|
|
ab4f167bda | ||
|
|
035c69898f | ||
|
|
00cb915f48 | ||
|
|
97baff8baf | ||
|
|
e4da2edf56 | ||
|
|
c1e08ba9f0 | ||
|
|
f00566624d | ||
|
|
2bb55294fc | ||
|
|
86c3e9a843 | ||
|
|
3a998a37f0 | ||
|
|
7eed47cd8e | ||
|
|
8cef0b6216 | ||
|
|
930541d5d6 | ||
|
|
f3518d0cad | ||
|
|
45e2c43997 | ||
|
|
6c0f932ae8 | ||
|
|
5832bf9140 | ||
|
|
47bba19bec | ||
|
|
1e58254f4c | ||
|
|
7739cef7b8 | ||
|
|
9b73392c5e | ||
|
|
79e5b2fb84 | ||
|
|
8ce1a33bd3 | ||
|
|
8ae61f1b23 | ||
|
|
a973c93c04 | ||
|
|
9c0f14aa89 | ||
|
|
f78d72db4c | ||
|
|
fb0c1c6993 | ||
|
|
4d99695e4c | ||
|
|
18321943d6 | ||
|
|
67819d2817 | ||
|
|
ad74e014ef | ||
|
|
bf661dffcf | ||
|
|
11484175c8 | ||
|
|
7bc5004683 | ||
|
|
1d01508164 | ||
|
|
4cae9bcfb9 | ||
|
|
9c84c7bd38 | ||
|
|
5a5e81eae0 | ||
|
|
b0f6bb3ea6 | ||
|
|
0c004606b5 | ||
|
|
fa4978389c | ||
|
|
8b8359b08f | ||
|
|
1d4fec3979 | ||
|
|
bb4123805c | ||
|
|
f49f605c11 | ||
|
|
5496689d7c | ||
|
|
bad8bbdb7c | ||
|
|
76184227a4 | ||
|
|
bbc9ee120d | ||
|
|
85093b2856 | ||
|
|
8c355b6159 | ||
|
|
622037ee98 | ||
|
|
54bb13aad0 | ||
|
|
61e41269ba | ||
|
|
f7cffe3d2d | ||
|
|
0cd39f0c97 | ||
|
|
c09b22358b | ||
|
|
18215b8336 | ||
|
|
f0fae716cc | ||
|
|
7092be97eb | ||
|
|
d9a9d2ee4f | ||
|
|
f86892cef0 | ||
|
|
a48b915675 | ||
|
|
5e13264393 | ||
|
|
ff481ef7f3 | ||
|
|
82a4485792 | ||
|
|
538876f529 | ||
|
|
609a31455b | ||
|
|
2d6da9ebfe | ||
|
|
594e871744 | ||
|
|
95074eb028 |
@@ -10,3 +10,4 @@ SECRET='whyour'
|
||||
QINIU_AK=''
|
||||
QINIU_SK=''
|
||||
QINIU_SCOPE=''
|
||||
TEMP=''
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
name: "\U0001F41E Bug report"
|
||||
description: Create a report to help us improve
|
||||
body:
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Qinglong version
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps-to-reproduce
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: |
|
||||
What do we need to do after opening your repro in order to make the bug happen? Clear and concise reproduction instructions are important for us to be able to triage your issue in a timely manner. Note that you can use [Markdown](https://guides.github.com/features/mastering-markdown/) to format lists and code.
|
||||
placeholder: Steps to reproduce
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: What is expected?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: actually-happening
|
||||
attributes:
|
||||
label: What is actually happening?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: system-info
|
||||
attributes:
|
||||
label: System Info
|
||||
description: Output of `npx envinfo --system --binaries --browsers`
|
||||
render: shell
|
||||
placeholder: System, Binaries, Browsers
|
||||
- type: textarea
|
||||
id: additional-comments
|
||||
attributes:
|
||||
label: Any additional comments?
|
||||
description: e.g. some background/context of how you ran into this bug.
|
||||
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Telegram Chat
|
||||
url: https://t.me/jiao_long
|
||||
about: Ask questions and discuss with other Qinglong users in real time.
|
||||
- name: Questions & Discussions
|
||||
url: https://github.com/whyour/qinglong/discussions/new?category=q-a
|
||||
about: Use GitHub discussions for message-board style questions and discussions.
|
||||
@@ -0,0 +1,40 @@
|
||||
name: "\U0001F680 New feature proposal"
|
||||
description: Suggest an idea for this project
|
||||
labels: [":sparkles: feature request"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for your interest in the project and taking the time to fill out this feature report!
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
attributes:
|
||||
label: Clear and concise description of the problem
|
||||
description: "Explain your use case, context, and rationale behind this feature request. More importantly, what is the **end user experience** you are trying to build that led to the need for this feature?"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: suggested-solution
|
||||
attributes:
|
||||
label: Suggested solution
|
||||
description: "In module [xy] we could provide following implementation..."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternative
|
||||
attributes:
|
||||
label: Alternative
|
||||
description: Clear and concise description of any alternative solutions or features you've considered.
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Any other context or screenshots about the feature request here.
|
||||
- type: checkboxes
|
||||
id: checkboxes
|
||||
attributes:
|
||||
label: Validations
|
||||
description: Before submitting the issue, please make sure you do the following
|
||||
options:
|
||||
- label: Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
|
||||
required: true
|
||||
@@ -0,0 +1,31 @@
|
||||
## PR Type
|
||||
What kind of change does this PR introduce?
|
||||
|
||||
<!-- Please check the one that applies to this PR using "x". -->
|
||||
|
||||
- [ ] Bugfix
|
||||
- [ ] Feature
|
||||
- [ ] Code style update (formatting, local variables)
|
||||
- [ ] Refactoring (no functional changes, no api changes)
|
||||
- [ ] Other... Please describe:
|
||||
|
||||
|
||||
## What is the current behavior?
|
||||
<!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->
|
||||
|
||||
Issue Number: N/A
|
||||
|
||||
|
||||
## What is the new behavior?
|
||||
|
||||
|
||||
## Does this PR introduce a breaking change?
|
||||
|
||||
- [ ] Yes
|
||||
- [ ] No
|
||||
|
||||
|
||||
<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->
|
||||
|
||||
|
||||
## Other information
|
||||
@@ -0,0 +1,7 @@
|
||||
# Comment to be posted to on PRs from first time contributors in your repository
|
||||
newPRWelcomeComment: |
|
||||
💖 Thanks for opening this pull request! 💖
|
||||
Please be patient and we will get back to you as soon as we can.
|
||||
# Comment to be posted to on pull requests merged by a first time user
|
||||
firstPRMergeComment: >
|
||||
Congrats on merging your first pull request! 🎉🎉🎉
|
||||
@@ -5,28 +5,55 @@ on:
|
||||
branches:
|
||||
- 'master'
|
||||
- 'develop'
|
||||
# Sequence of patterns matched against refs/tags
|
||||
tags:
|
||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||
schedule:
|
||||
# 参考 https://jasonet.co/posts/scheduled-actions/
|
||||
# note: 这里是GMT时间,北京时间减去八小时即可。如北京时间 22:30 => GMT 14:30
|
||||
# minute hour day month dayOfWeek
|
||||
- cron: '00 14 * * *' # GMT 14:00 => 北京时间 22:00
|
||||
#- cron: '30 16 * * *' # GMT 16:30(前一天) => 北京时间 00:30
|
||||
- cron: '00 14 * * *' # GMT 15:00 => 北京时间 23:00
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
to_gitlab:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pixta-dev/repository-mirroring-action@v1
|
||||
with:
|
||||
target_repo_url:
|
||||
git@gitlab.com:whyour/qinglong.git
|
||||
ssh_private_key:
|
||||
${{ secrets.GITLAB_SSH_PK }}
|
||||
|
||||
to_gitee:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pixta-dev/repository-mirroring-action@v1
|
||||
with:
|
||||
target_repo_url:
|
||||
git@gitee.com:whyour/qinglong.git
|
||||
ssh_private_key:
|
||||
${{ secrets.GITLAB_SSH_PK }}
|
||||
|
||||
build-static:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: build front and back
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm install
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build:front
|
||||
pnpm build:back
|
||||
|
||||
@@ -34,6 +61,9 @@ jobs:
|
||||
env:
|
||||
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
||||
GITHUB_BRANCH: ${{ github.ref_name }}
|
||||
REPO_GITEE: git@gitee.com:whyour/qinglong-static.git
|
||||
REPO_GITLAB: git@gitlab.com:whyour/qinglong-static.git
|
||||
PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
||||
run: |
|
||||
mkdir -p tmp
|
||||
cd ./tmp
|
||||
@@ -44,7 +74,19 @@ jobs:
|
||||
git commit --allow-empty -m "copy static at $(date +'%Y-%m-%d %H:%M:%S')"
|
||||
git push --force --quiet "https://${{ secrets.API_TOKEN }}@${GITHUB_REPO}.git" ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
||||
|
||||
mkdir -p ~/.ssh
|
||||
echo "${PRIVATE_KEY}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
|
||||
export GIT_SSH_COMMAND="ssh -v -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no -l git"
|
||||
git remote add gitee "${REPO_GITEE}"
|
||||
git remote add gitlab "${REPO_GITLAB}"
|
||||
git push --force --quiet gitee ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
||||
git push --force --quiet gitlab ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
||||
|
||||
build:
|
||||
if: github.ref != 'refs/heads/master'
|
||||
|
||||
needs: build-static
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
@@ -55,14 +97,17 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
|
||||
- name: Set time zone
|
||||
uses: szenius/set-timezone@v1.0
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
timezoneLinux: "Asia/Shanghai"
|
||||
timezoneMacos: "Asia/Shanghai"
|
||||
timezoneWindows: "China Standard Time"
|
||||
version: latest
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup timezone
|
||||
uses: zcong1993/setup-timezone@master
|
||||
with:
|
||||
timezone: Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v2
|
||||
@@ -108,9 +153,16 @@ jobs:
|
||||
build-args: |
|
||||
MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||
context: docker/
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||
context: .
|
||||
file: ./docker/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache,mode=max
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
/npm-debug.log*
|
||||
/yarn-error.log
|
||||
/yarn.lock
|
||||
/pnpm-lock.yaml
|
||||
/package-lock.json
|
||||
|
||||
# production
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
import { defineConfig } from 'umi';
|
||||
import { defineConfig } from '@umijs/max';
|
||||
const CompressionPlugin = require('compression-webpack-plugin');
|
||||
|
||||
export default defineConfig({
|
||||
hash: true,
|
||||
layout: false,
|
||||
antd: {},
|
||||
outputPath: 'static/dist',
|
||||
nodeModulesTransform: {
|
||||
type: 'none',
|
||||
fastRefresh: true,
|
||||
favicons: ['./images/favicon.svg'],
|
||||
mfsu: {
|
||||
strategy: 'eager',
|
||||
},
|
||||
fastRefresh: {},
|
||||
esbuild: {},
|
||||
webpack5: {},
|
||||
dynamicImport: {
|
||||
loading: '@/components/pageLoading',
|
||||
},
|
||||
favicon: '/images/g5.ico',
|
||||
publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
|
||||
proxy: {
|
||||
'/api/public': {
|
||||
target: 'http://127.0.0.1:5400/',
|
||||
@@ -26,7 +22,7 @@ export default defineConfig({
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
chainWebpack: (config) => {
|
||||
chainWebpack: ((config: any) => {
|
||||
config.plugin('compression-webpack-plugin').use(
|
||||
new CompressionPlugin({
|
||||
algorithm: 'gzip',
|
||||
@@ -35,13 +31,13 @@ export default defineConfig({
|
||||
minRatio: 0.6,
|
||||
}),
|
||||
);
|
||||
},
|
||||
}) as any,
|
||||
externals: {
|
||||
react: 'window.React',
|
||||
'react-dom': 'window.ReactDOM',
|
||||
},
|
||||
scripts: [
|
||||
'https://gw.alipayobjects.com/os/lib/react/16.13.1/umd/react.production.min.js',
|
||||
'https://gw.alipayobjects.com/os/lib/react-dom/16.13.1/umd/react-dom.production.min.js',
|
||||
headScripts: [
|
||||
'https://gw.alipayobjects.com/os/lib/react/18.2.0/umd/react.production.min.js',
|
||||
'https://gw.alipayobjects.com/os/lib/react-dom/18.2.0/umd/react-dom.production.min.js',
|
||||
],
|
||||
});
|
||||
|
||||
+15
-7
@@ -1,6 +1,6 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/whyour/qinglong">
|
||||
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||
<img width="150" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -22,7 +22,7 @@ Timed task management panel with python3, javaScript, shell, typescript support
|
||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||
</div>
|
||||
|
||||
[](https://whyour.cn)
|
||||
[](https://whyour.cn)
|
||||
|
||||
[简体中文](./README.md) | English
|
||||
|
||||
@@ -41,7 +41,7 @@ Timed task management panel with python3, javaScript, shell, typescript support
|
||||
### Local Deployment
|
||||
|
||||
```bash
|
||||
# To be completed
|
||||
# To be refined, see the development steps first (not supported on windows yet)
|
||||
```
|
||||
|
||||
### Podman Deployment
|
||||
@@ -57,11 +57,10 @@ https://podman.io/getting-started/installation
|
||||
```bash
|
||||
podman run -dit \
|
||||
--network bridge \
|
||||
-v $PWD/ql:/ql/data \
|
||||
-v $PWD/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--name qinglong \
|
||||
--hostname qinglong \
|
||||
--restart unless-stopped \
|
||||
docker.io/whyour/qinglong:latest
|
||||
```
|
||||
|
||||
@@ -96,7 +95,7 @@ systemctl restart docker
|
||||
|
||||
```bash
|
||||
docker run -dit \
|
||||
-v $PWD/ql:/ql/data \
|
||||
-v $PWD/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--name qinglong \
|
||||
--hostname qinglong \
|
||||
@@ -124,6 +123,10 @@ docker-compose up -d
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
3. access
|
||||
|
||||
Open your browser and visit http://{ip}:5700
|
||||
|
||||
## Use
|
||||
|
||||
1. built-in commands
|
||||
@@ -158,6 +161,10 @@ task <file_path> now
|
||||
task <file_path> conc <env_name> <account_number>(Optional)
|
||||
# Specify the account to execute and run immediately regardless of whether a random delay is set
|
||||
task <file_path> desi <env_name> <account_number>
|
||||
# Set task timeout
|
||||
task -m <max_time> <file_path>
|
||||
# Print task log in real time, no need to carry this parameter when creating timed tasks
|
||||
task -l <file_path>
|
||||
```
|
||||
|
||||
2. parameter description
|
||||
@@ -172,6 +179,7 @@ task <file_path> desi <env_name> <account_number>
|
||||
* file_path: File path for task execution
|
||||
* env_name: The name of the environment variable that needs to be concurrent or specified at the time of task execution
|
||||
* account_number: Specify the account number of an environment variable to be executed when the task is executed
|
||||
* max_time: Timeout, suffix "s" for seconds (default), "m" for minutes, "h" for hours, "d" for days
|
||||
|
||||
## Links
|
||||
|
||||
@@ -179,7 +187,7 @@ task <file_path> desi <env_name> <account_number>
|
||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||
- [Ant Design](https://ant.design)
|
||||
- [Ant Design Pro](https://pro.ant.design/)
|
||||
- [Umijs3.0](https://umijs.org)
|
||||
- [Umijs](https://umijs.org)
|
||||
- [darkreader](https://github.com/darkreader/darkreader)
|
||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/whyour/qinglong">
|
||||
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||
<img width="150" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||
</div>
|
||||
|
||||
[](https://whyour.cn)
|
||||
[](https://whyour.cn)
|
||||
|
||||
简体中文 | [English](./README-en.md)
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
### 本机部署
|
||||
|
||||
```bash
|
||||
# 待完善
|
||||
# 待完善,可先参考开发步骤 (windows暂时不支持)
|
||||
```
|
||||
|
||||
### podman 部署
|
||||
@@ -57,11 +57,10 @@ https://podman.io/getting-started/installation
|
||||
```bash
|
||||
podman run -dit \
|
||||
--network bridge \
|
||||
-v $PWD/ql:/ql/data \
|
||||
-v $PWD/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--name qinglong \
|
||||
--hostname qinglong \
|
||||
--restart unless-stopped \
|
||||
docker.io/whyour/qinglong:latest
|
||||
```
|
||||
|
||||
@@ -97,7 +96,7 @@ systemctl restart docker
|
||||
|
||||
```bash
|
||||
docker run -dit \
|
||||
-v $PWD/ql:/ql/data \
|
||||
-v $PWD/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--name qinglong \
|
||||
--hostname qinglong \
|
||||
@@ -125,6 +124,10 @@ docker-compose up -d
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
3. 访问
|
||||
|
||||
打开你的浏览器,访问 http://{ip}:5700
|
||||
|
||||
## 使用
|
||||
|
||||
1. 内置命令
|
||||
@@ -157,21 +160,26 @@ task <file_path> now
|
||||
task <file_path> conc <env_name> <account_number>(可选的)
|
||||
# 指定账号执行,无论是否设置了随机延迟,均立即运行
|
||||
task <file_path> desi <env_name> <account_number>
|
||||
# 设置任务超时时间
|
||||
task -m <max_time> <file_path>
|
||||
# 实时打印任务日志,创建定时任务时,不用携带此参数
|
||||
task -l <file_path>
|
||||
```
|
||||
|
||||
2. 参数说明
|
||||
|
||||
* file_url: 脚本地址
|
||||
* repo_url: 仓库地址
|
||||
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串
|
||||
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串
|
||||
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响
|
||||
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串,多个竖线分割
|
||||
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串,多个竖线分割
|
||||
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响,多个竖线分割
|
||||
* extensions: 拉取仓库的文件后缀,多个竖线分割
|
||||
* branch: 拉取仓库的分支
|
||||
* extensions: 拉取仓库的文件后缀
|
||||
* days: 需要保留的日志的天数
|
||||
* file_path: 任务执行时的文件路径
|
||||
* env_name: 任务执行时需要并发或者指定时的环境变量名称
|
||||
* account_number: 任务执行时指定某个环境变量需要执行的账号序号
|
||||
* max_time: 超时时间,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
||||
|
||||
## 链接
|
||||
|
||||
@@ -179,7 +187,7 @@ task <file_path> desi <env_name> <account_number>
|
||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||
- [Ant Design](https://ant.design)
|
||||
- [Ant Design Pro](https://pro.ant.design/)
|
||||
- [Umijs3.0](https://umijs.org)
|
||||
- [Umijs](https://umijs.org)
|
||||
- [darkreader](https://github.com/darkreader/darkreader)
|
||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||
|
||||
|
||||
+149
-1
@@ -2,6 +2,7 @@ import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import CronService from '../services/cron';
|
||||
import CronViewService from '../services/cronView';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import cron_parser from 'cron-parser';
|
||||
const route = Router();
|
||||
@@ -9,11 +10,141 @@ const route = Router();
|
||||
export default (app: Router) => {
|
||||
app.use('/crons', route);
|
||||
|
||||
route.get(
|
||||
'/views',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.list();
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/views',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().required(),
|
||||
sorts: Joi.array().optional().allow(null),
|
||||
filters: Joi.array().optional(),
|
||||
filterRelation: Joi.string().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().required(),
|
||||
id: Joi.number().required(),
|
||||
sorts: Joi.array().optional().allow(null),
|
||||
filters: Joi.array().optional(),
|
||||
filterRelation: Joi.string().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
if (req.body.type === 1) {
|
||||
return res.send({ code: 400, message: '参数错误' });
|
||||
} else {
|
||||
const data = await cronViewService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
}
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.delete(
|
||||
'/views',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views/move',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
fromIndex: Joi.number().required(),
|
||||
toIndex: Joi.number().required(),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.move(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views/disable',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.disabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views/enable',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.enabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.crontabs(req.query.searchValue as string);
|
||||
const data = await cronService.crontabs(req.query as any);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
@@ -21,6 +152,21 @@ export default (app: Router) => {
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/detail',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.find(req.query as any);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/',
|
||||
celebrate({
|
||||
@@ -29,6 +175,7 @@ export default (app: Router) => {
|
||||
schedule: Joi.string().required(),
|
||||
name: Joi.string().optional(),
|
||||
labels: Joi.array().optional(),
|
||||
sub_id: Joi.number().optional().allow(null),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -185,6 +332,7 @@ export default (app: Router) => {
|
||||
command: Joi.string().required(),
|
||||
schedule: Joi.string().required(),
|
||||
name: Joi.string().optional().allow(null),
|
||||
sub_id: Joi.number().optional().allow(null),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
|
||||
+49
-2
@@ -3,8 +3,21 @@ import { Container } from 'typedi';
|
||||
import EnvService from '../services/env';
|
||||
import { Logger } from 'winston';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import multer from 'multer';
|
||||
import config from '../config';
|
||||
import fs from 'fs';
|
||||
const route = Router();
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, config.scriptPath);
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, file.originalname);
|
||||
},
|
||||
});
|
||||
const upload = multer({ storage: storage });
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/envs', route);
|
||||
|
||||
@@ -26,7 +39,9 @@ export default (app: Router) => {
|
||||
body: Joi.array().items(
|
||||
Joi.object({
|
||||
value: Joi.string().required(),
|
||||
name: Joi.string().required(),
|
||||
name: Joi.string()
|
||||
.required()
|
||||
.pattern(/^[a-zA-Z_][0-9a-zA-Z_]*$/),
|
||||
remarks: Joi.string().optional().allow(''),
|
||||
}),
|
||||
),
|
||||
@@ -94,7 +109,6 @@ export default (app: Router) => {
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.move(req.params.id, req.body);
|
||||
@@ -177,4 +191,37 @@ export default (app: Router) => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/upload',
|
||||
upload.single('env'),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const envService = Container.get(EnvService);
|
||||
const fileContent = await fs.promises.readFile(req!.file!.path, 'utf8');
|
||||
const parseContent = JSON.parse(fileContent);
|
||||
const data = Array.isArray(parseContent)
|
||||
? parseContent
|
||||
: [parseContent];
|
||||
if (data.every((x) => x.name && x.value)) {
|
||||
const result = await envService.create(
|
||||
data.map((x) => ({
|
||||
name: x.name,
|
||||
value: x.value,
|
||||
remarks: x.remarks,
|
||||
})),
|
||||
);
|
||||
return res.send({ code: 200, data: result });
|
||||
} else {
|
||||
return res.send({
|
||||
code: 400,
|
||||
message: '文件缺少name或者value字段,参考导出文件格式',
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
+32
-1
@@ -3,8 +3,9 @@ import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import * as fs from 'fs';
|
||||
import config from '../config';
|
||||
import { getFileContentByName, readDirs } from '../config/util';
|
||||
import { emptyDir, getFileContentByName, readDirs } from '../config/util';
|
||||
import { join } from 'path';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
const route = Router();
|
||||
const blacklist = ['.tmp'];
|
||||
|
||||
@@ -45,4 +46,34 @@ export default (app: Router) => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.delete(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
path: Joi.string().allow(''),
|
||||
type: Joi.string().optional()
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
let { filename, path, type } = req.body as {
|
||||
filename: string;
|
||||
path: string;
|
||||
type: string;
|
||||
};
|
||||
const filePath = join(config.logPath, path, filename);
|
||||
if (type === 'directory') {
|
||||
emptyDir(filePath);
|
||||
} else {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
};
|
||||
|
||||
+51
-7
@@ -4,6 +4,7 @@ import {
|
||||
readDirs,
|
||||
getLastModifyFilePath,
|
||||
readDir,
|
||||
emptyDir,
|
||||
} from '../config/util';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
@@ -77,11 +78,13 @@ export default (app: Router) => {
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let { filename, path, content, originFilename } = req.body as {
|
||||
let { filename, path, content, originFilename, directory } =
|
||||
req.body as {
|
||||
filename: string;
|
||||
path: string;
|
||||
content: string;
|
||||
originFilename: string;
|
||||
directory: string;
|
||||
};
|
||||
|
||||
if (!path) {
|
||||
@@ -105,11 +108,19 @@ export default (app: Router) => {
|
||||
return res.send({ code: 200 });
|
||||
}
|
||||
|
||||
if (directory) {
|
||||
fs.mkdirSync(join(path, directory), { recursive: true });
|
||||
return res.send({ code: 200 });
|
||||
}
|
||||
|
||||
if (!originFilename) {
|
||||
originFilename = filename;
|
||||
}
|
||||
const originFilePath = `${path}${originFilename.replace(/\//g, '')}`;
|
||||
const filePath = `${path}${filename.replace(/\//g, '')}`;
|
||||
const originFilePath = join(
|
||||
path,
|
||||
`${originFilename.replace(/\//g, '')}`,
|
||||
);
|
||||
const filePath = join(path, `${filename.replace(/\//g, '')}`);
|
||||
if (fs.existsSync(originFilePath)) {
|
||||
fs.copyFileSync(
|
||||
originFilePath,
|
||||
@@ -159,17 +170,23 @@ export default (app: Router) => {
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
path: Joi.string().allow(''),
|
||||
type: Joi.string().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let { filename, path } = req.body as {
|
||||
let { filename, path, type } = req.body as {
|
||||
filename: string;
|
||||
path: string;
|
||||
type: string;
|
||||
};
|
||||
const filePath = join(config.scriptPath, path, filename);
|
||||
if (type === 'directory') {
|
||||
emptyDir(filePath);
|
||||
} else {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -238,23 +255,50 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
content: Joi.string().optional().allow(''),
|
||||
path: Joi.string().optional().allow(''),
|
||||
pid: Joi.number().optional().allow(''),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let { filename, content, path } = req.body;
|
||||
let { filename, path, pid } = req.body;
|
||||
const { name, ext } = parse(filename);
|
||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||
|
||||
const scriptService = Container.get(ScriptService);
|
||||
const result = await scriptService.stopScript(filePath);
|
||||
const result = await scriptService.stopScript(filePath, pid);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/rename',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
path: Joi.string().allow(''),
|
||||
newFilename: Joi.string().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
let { filename, path, type, newFilename } = req.body as {
|
||||
filename: string;
|
||||
path: string;
|
||||
type: string;
|
||||
newFilename: string;
|
||||
};
|
||||
const filePath = join(config.scriptPath, path, filename);
|
||||
const newPath = join(config.scriptPath, path, newFilename);
|
||||
fs.renameSync(filePath, newPath);
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
@@ -49,6 +49,9 @@ export default (app: Router) => {
|
||||
sub_after: Joi.string().optional().allow('').allow(null),
|
||||
schedule_type: Joi.string().required(),
|
||||
alias: Joi.string().required(),
|
||||
proxy: Joi.string().optional().allow('').allow(null),
|
||||
autoAddCron: Joi.boolean().optional().allow('').allow(null),
|
||||
autoDelCron: Joi.boolean().optional().allow('').allow(null),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -177,6 +180,9 @@ export default (app: Router) => {
|
||||
sub_before: Joi.string().optional().allow('').allow(null),
|
||||
sub_after: Joi.string().optional().allow('').allow(null),
|
||||
alias: Joi.string().required(),
|
||||
proxy: Joi.string().optional().allow('').allow(null),
|
||||
autoAddCron: Joi.boolean().optional().allow('').allow(null),
|
||||
autoDelCron: Joi.boolean().optional().allow('').allow(null),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
|
||||
+24
-4
@@ -7,6 +7,9 @@ import SystemService from '../services/system';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import UserService from '../services/user';
|
||||
import { EnvModel } from '../data/env';
|
||||
import { parseVersion, promiseExec } from '../config/util';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
const route = Router();
|
||||
|
||||
export default (app: Router) => {
|
||||
@@ -18,10 +21,22 @@ export default (app: Router) => {
|
||||
const userService = Container.get(UserService);
|
||||
const authInfo = await userService.getUserInfo();
|
||||
const envCount = await EnvModel.count();
|
||||
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
||||
|
||||
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||
const version = currentVersionFile.match(versionRegx)![1];
|
||||
const { version, changeLog, changeLogLink } = await parseVersion(
|
||||
config.versionFile,
|
||||
);
|
||||
const lastCommitTime = (
|
||||
await promiseExec(
|
||||
`cd ${config.rootPath} && git show -s --format=%ai | head -1`,
|
||||
)
|
||||
).replace('\n', '');
|
||||
const lastCommitId = (
|
||||
await promiseExec(`cd ${config.rootPath} && git rev-parse --short HEAD`)
|
||||
).replace('\n', '');
|
||||
const branch = (
|
||||
await promiseExec(
|
||||
`cd ${config.rootPath} && git symbolic-ref --short HEAD`,
|
||||
)
|
||||
).replace('\n', '');
|
||||
|
||||
let isInitialized = true;
|
||||
if (
|
||||
@@ -37,6 +52,11 @@ export default (app: Router) => {
|
||||
data: {
|
||||
isInitialized,
|
||||
version,
|
||||
lastCommitTime: dayjs(lastCommitTime).unix(),
|
||||
lastCommitId,
|
||||
branch,
|
||||
changeLog,
|
||||
changeLogLink,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
+2
-4
@@ -1,10 +1,8 @@
|
||||
import 'reflect-metadata'; // We need this in order to use @Decorators
|
||||
|
||||
import config from './config';
|
||||
|
||||
import express from 'express';
|
||||
|
||||
import Logger from './loaders/logger';
|
||||
import path from 'path';
|
||||
|
||||
async function startServer() {
|
||||
const app = express();
|
||||
@@ -19,7 +17,7 @@ async function startServer() {
|
||||
|
||||
const server = app
|
||||
.listen(config.port, () => {
|
||||
Logger.debug(`✌️ Back server launched on port ${config.port}`);
|
||||
Logger.debug(`✌️ 后端服务启动成功!`);
|
||||
})
|
||||
.on('error', (err) => {
|
||||
Logger.error(err);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export const LOG_END_SYMBOL = ' ';
|
||||
|
||||
export const TASK_COMMAND = 'task';
|
||||
export const QL_COMMAND = 'ql';
|
||||
|
||||
export const TASK_PREFIX = `${TASK_COMMAND} `;
|
||||
export const QL_PREFIX = `${QL_COMMAND} `;
|
||||
+15
-4
@@ -4,10 +4,21 @@ import { createRandomString } from './util';
|
||||
|
||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
const lastVersionFile = `http://qn.whyour.cn/version.ts?v=${Date.now()}`;
|
||||
if (!process.env.QL_DIR) {
|
||||
// 声明QL_DIR环境变量
|
||||
let qlHomePath = path.join(__dirname, '../../');
|
||||
// 生产环境
|
||||
if (qlHomePath.endsWith('/static/')) {
|
||||
qlHomePath = path.join(qlHomePath, '../');
|
||||
}
|
||||
process.env.QL_DIR = qlHomePath.replace(/\/$/g, '');
|
||||
}
|
||||
|
||||
const lastVersionFile = `https://qn.whyour.cn/version.yaml`;
|
||||
|
||||
const rootPath = process.env.QL_DIR as string;
|
||||
const envFound = dotenv.config({ path: path.join(rootPath, '.env') });
|
||||
|
||||
const envFound = dotenv.config();
|
||||
const rootPath = process.cwd();
|
||||
const dataPath = path.join(rootPath, 'data/');
|
||||
const samplePath = path.join(rootPath, 'sample/');
|
||||
const configPath = path.join(dataPath, 'config/');
|
||||
@@ -29,7 +40,7 @@ const sqliteFile = path.join(samplePath, 'database.sqlite');
|
||||
const authError = '错误的用户名密码,请重试';
|
||||
const loginFaild = '请先登录!';
|
||||
const configString = 'config sample crontab shareCode diy';
|
||||
const versionFile = path.join(rootPath, 'src/version.ts');
|
||||
const versionFile = path.join(rootPath, 'version.yaml');
|
||||
|
||||
if (envFound.error) {
|
||||
throw new Error("⚠️ Couldn't find .env file ⚠️");
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Subscription } from '../data/subscription';
|
||||
import isNil from 'lodash/isNil';
|
||||
|
||||
export function formatUrl(doc: Subscription) {
|
||||
let url = doc.url;
|
||||
let host = '';
|
||||
if (doc.type === 'private-repo') {
|
||||
if (doc.pull_type === 'ssh-key') {
|
||||
host = doc.url!.replace(/.*\@([^\:]+)\:.*/, '$1');
|
||||
url = doc.url!.replace(host, doc.alias);
|
||||
} else {
|
||||
host = doc.url!.replace(/.*\:\/\/([^\/]+)\/.*/, '$1');
|
||||
const { username, password } = doc.pull_option as any;
|
||||
url = doc.url!.replace(host, `${username}:${password}@${host}`);
|
||||
}
|
||||
}
|
||||
return { url, host };
|
||||
}
|
||||
|
||||
export function formatCommand(doc: Subscription, url?: string) {
|
||||
let command = `SUB_ID=${doc.id} ql `;
|
||||
let _url = url || formatUrl(doc).url;
|
||||
const {
|
||||
type,
|
||||
whitelist,
|
||||
blacklist,
|
||||
dependences,
|
||||
branch,
|
||||
extensions,
|
||||
proxy,
|
||||
autoAddCron,
|
||||
autoDelCron,
|
||||
} = doc;
|
||||
if (type === 'file') {
|
||||
command += `raw "${_url}"`;
|
||||
} else {
|
||||
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${dependences || ''
|
||||
}" "${branch || ''}" "${extensions || ''}" "${proxy || ''}" "${isNil(autoAddCron) ? true : Boolean(autoAddCron)
|
||||
}" "${isNil(autoDelCron) ? true : Boolean(autoDelCron)}"`;
|
||||
}
|
||||
return command;
|
||||
}
|
||||
+150
-8
@@ -3,6 +3,10 @@ import * as path from 'path';
|
||||
import got from 'got';
|
||||
import iconv from 'iconv-lite';
|
||||
import { exec } from 'child_process';
|
||||
import FormData from 'form-data';
|
||||
import psTreeFun from 'pstree.remy';
|
||||
import { promisify } from 'util';
|
||||
import { load } from 'js-yaml';
|
||||
|
||||
export function getFileContentByName(fileName: string) {
|
||||
if (fs.existsSync(fileName)) {
|
||||
@@ -283,6 +287,20 @@ enum FileType {
|
||||
'file',
|
||||
}
|
||||
|
||||
interface IFile {
|
||||
title: string;
|
||||
key: string;
|
||||
type: 'directory' | 'file';
|
||||
parent: string;
|
||||
mtime: number;
|
||||
children?: IFile[];
|
||||
}
|
||||
|
||||
export function dirSort(a: IFile, b: IFile) {
|
||||
if (a.type !== b.type) return FileType[a.type] < FileType[b.type] ? -1 : 1;
|
||||
else if (a.mtime !== b.mtime) return a.mtime > b.mtime ? -1 : 1;
|
||||
}
|
||||
|
||||
export function readDirs(
|
||||
dir: string,
|
||||
baseDir: string = '',
|
||||
@@ -301,24 +319,21 @@ export function readDirs(
|
||||
title: file,
|
||||
key,
|
||||
type: 'directory',
|
||||
disabled: true,
|
||||
parent: relativePath,
|
||||
children: readDirs(subPath, baseDir).sort(
|
||||
(a: any, b: any) =>
|
||||
(FileType as any)[a.type] - (FileType as any)[b.type],
|
||||
),
|
||||
mtime: stats.mtime.getTime(),
|
||||
children: readDirs(subPath, baseDir).sort(dirSort),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: file,
|
||||
type: 'file',
|
||||
isLeaf: true,
|
||||
key,
|
||||
parent: relativePath,
|
||||
mtime: stats.mtime.getTime(),
|
||||
};
|
||||
});
|
||||
return result.sort(
|
||||
(a: any, b: any) => (FileType as any)[a.type] - (FileType as any)[b.type],
|
||||
);
|
||||
return result.sort(dirSort);
|
||||
}
|
||||
|
||||
export function readDir(
|
||||
@@ -344,6 +359,20 @@ export function readDir(
|
||||
return result;
|
||||
}
|
||||
|
||||
export function emptyDir(path: string) {
|
||||
const files = fs.readdirSync(path);
|
||||
files.forEach((file) => {
|
||||
const filePath = `${path}/${file}`;
|
||||
const stats = fs.statSync(filePath);
|
||||
if (stats.isDirectory()) {
|
||||
emptyDir(filePath);
|
||||
} else {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
});
|
||||
fs.rmdirSync(path);
|
||||
}
|
||||
|
||||
export function promiseExec(command: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(
|
||||
@@ -355,3 +384,116 @@ export function promiseExec(command: string): Promise<string> {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function parseHeaders(headers: string) {
|
||||
if (!headers) return {};
|
||||
|
||||
const parsed: any = {};
|
||||
let key;
|
||||
let val;
|
||||
let i;
|
||||
|
||||
headers &&
|
||||
headers.split('\n').forEach(function parser(line) {
|
||||
i = line.indexOf(':');
|
||||
key = line.substring(0, i).trim().toLowerCase();
|
||||
val = line.substring(i + 1).trim();
|
||||
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
|
||||
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
|
||||
});
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function parseBody(
|
||||
body: string,
|
||||
contentType:
|
||||
| 'application/json'
|
||||
| 'multipart/form-data'
|
||||
| 'application/x-www-form-urlencoded',
|
||||
) {
|
||||
if (!body) return '';
|
||||
|
||||
const parsed: any = {};
|
||||
let key;
|
||||
let val;
|
||||
let i;
|
||||
|
||||
body &&
|
||||
body.split('\n').forEach(function parser(line) {
|
||||
i = line.indexOf(':');
|
||||
key = line.substring(0, i).trim().toLowerCase();
|
||||
val = line.substring(i + 1).trim();
|
||||
|
||||
if (!key || parsed[key]) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const jsonValue = JSON.parse(val);
|
||||
parsed[key] = jsonValue;
|
||||
} catch (error) {
|
||||
parsed[key] = val;
|
||||
}
|
||||
});
|
||||
|
||||
switch (contentType) {
|
||||
case 'multipart/form-data':
|
||||
return Object.keys(parsed).reduce((p, c) => {
|
||||
p.append(c, parsed[c]);
|
||||
return p;
|
||||
}, new FormData());
|
||||
case 'application/x-www-form-urlencoded':
|
||||
return Object.keys(parsed).reduce((p, c) => {
|
||||
return p ? `${p}&${c}=${parsed[c]}` : `${c}=${parsed[c]}`;
|
||||
});
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function psTree(pid: number): Promise<number[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
psTreeFun(pid, (err: any, pids: number[]) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(pids.filter((x) => !isNaN(x)));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function killTask(pid: number) {
|
||||
const pids = await psTree(pid);
|
||||
// SIGALRM 14 时钟信号
|
||||
if (pids.length) {
|
||||
process.kill(pids[0], 14);
|
||||
} else {
|
||||
process.kill(pid, 14);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPid(name: string) {
|
||||
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
||||
const execAsync = promisify(exec);
|
||||
let pid = (await execAsync(taskCommand)).stdout;
|
||||
return Number(pid);
|
||||
}
|
||||
|
||||
interface IVersion {
|
||||
version: string;
|
||||
changeLogLink: string;
|
||||
changeLog: string;
|
||||
}
|
||||
|
||||
export async function parseVersion(path: string): Promise<IVersion> {
|
||||
return load(await promisify(fs.readFile)(path, 'utf8')) as IVersion;
|
||||
}
|
||||
|
||||
export async function parseContentVersion(content: string): Promise<IVersion> {
|
||||
return load(content) as IVersion;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export class Crontab {
|
||||
labels?: string[];
|
||||
last_running_time?: number;
|
||||
last_execution_time?: number;
|
||||
sub_id?: number;
|
||||
|
||||
constructor(options: Crontab) {
|
||||
this.name = options.name;
|
||||
@@ -37,6 +38,7 @@ export class Crontab {
|
||||
this.labels = options.labels || [];
|
||||
this.last_running_time = options.last_running_time || 0;
|
||||
this.last_execution_time = options.last_execution_time || 0;
|
||||
this.sub_id = options.sub_id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,4 +74,5 @@ export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||
labels: DataTypes.JSON,
|
||||
last_running_time: DataTypes.NUMBER,
|
||||
last_execution_time: DataTypes.NUMBER,
|
||||
sub_id: { type: DataTypes.NUMBER, allowNull: true },
|
||||
});
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
|
||||
export enum CronViewType {
|
||||
'系统' = 1,
|
||||
'个人',
|
||||
}
|
||||
|
||||
interface SortType {
|
||||
type: 'ASC' | 'DESC';
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface FilterType {
|
||||
property: string;
|
||||
operation: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export class CrontabView {
|
||||
name?: string;
|
||||
id?: number;
|
||||
position?: number;
|
||||
isDisabled?: 1 | 0;
|
||||
filters?: FilterType[];
|
||||
sorts?: SortType[];
|
||||
filterRelation?: 'and' | 'or';
|
||||
type?: CronViewType;
|
||||
|
||||
constructor(options: CrontabView) {
|
||||
this.name = options.name;
|
||||
this.id = options.id;
|
||||
this.position = options.position;
|
||||
this.isDisabled = options.isDisabled || 0;
|
||||
this.filters = options.filters;
|
||||
this.sorts = options.sorts;
|
||||
this.filterRelation = options.filterRelation;
|
||||
this.type = options.type || CronViewType.个人;
|
||||
}
|
||||
}
|
||||
|
||||
interface CronViewInstance
|
||||
extends Model<CrontabView, CrontabView>,
|
||||
CrontabView {}
|
||||
export const CrontabViewModel = sequelize.define<CronViewInstance>(
|
||||
'CrontabView',
|
||||
{
|
||||
name: {
|
||||
unique: 'name',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
position: DataTypes.NUMBER,
|
||||
isDisabled: DataTypes.NUMBER,
|
||||
filters: DataTypes.JSON,
|
||||
sorts: DataTypes.JSON,
|
||||
filterRelation: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true,
|
||||
},
|
||||
type: DataTypes.NUMBER,
|
||||
},
|
||||
);
|
||||
+4
-1
@@ -26,7 +26,10 @@ export enum EnvStatus {
|
||||
'disabled',
|
||||
}
|
||||
|
||||
export const initEnvPosition = 9999999999;
|
||||
export const maxPosition = 9000000000000000;
|
||||
export const initPosition = 4500000000000000;
|
||||
export const stepPosition = 10000000000;
|
||||
export const minPosition = 100;
|
||||
|
||||
interface EnvInstance extends Model<Env, Env>, Env {}
|
||||
export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
||||
|
||||
+12
-5
@@ -1,15 +1,22 @@
|
||||
import { Sequelize } from 'sequelize';
|
||||
import { Sequelize, Transaction } from 'sequelize';
|
||||
import config from '../config/index';
|
||||
|
||||
export const sequelize = new Sequelize({
|
||||
dialect: 'sqlite',
|
||||
storage: `${config.dbPath}database.sqlite`,
|
||||
logging: false,
|
||||
pool: {
|
||||
max: 6,
|
||||
min: 0,
|
||||
idle: 30000,
|
||||
retry: {
|
||||
max: 10,
|
||||
match: ['SQLITE_BUSY: database is locked'],
|
||||
},
|
||||
pool: {
|
||||
max: 5,
|
||||
min: 2,
|
||||
idle: 30000,
|
||||
acquire: 30000,
|
||||
evict: 10000,
|
||||
},
|
||||
transactionType: Transaction.TYPES.IMMEDIATE,
|
||||
});
|
||||
|
||||
export type ResponseType<T> = { code: number; data?: T; message?: string };
|
||||
|
||||
+39
-2
@@ -1,16 +1,22 @@
|
||||
import { IncomingHttpHeaders } from 'http';
|
||||
|
||||
export enum NotificationMode {
|
||||
'gotify' = 'gotify',
|
||||
'goCqHttpBot' = 'goCqHttpBot',
|
||||
'serverChan' = 'serverChan',
|
||||
'pushDeer' = 'pushDeer',
|
||||
'bark' = 'bark',
|
||||
'chat' = 'chat',
|
||||
'telegramBot' = 'telegramBot',
|
||||
'dingtalkBot' = 'dingtalkBot',
|
||||
'weWorkBot' = 'weWorkBot',
|
||||
'weWorkApp' = 'weWorkApp',
|
||||
'aibotk' = 'aibotk',
|
||||
'iGot' = 'iGot',
|
||||
'pushPlus' = 'pushPlus',
|
||||
'email' = 'email',
|
||||
'feishu' = 'feishu',
|
||||
'webhook' = 'webhook',
|
||||
}
|
||||
|
||||
abstract class NotificationBaseInfo {
|
||||
@@ -35,11 +41,17 @@ export class ServerChanNotification extends NotificationBaseInfo {
|
||||
|
||||
export class PushDeerNotification extends NotificationBaseInfo {
|
||||
public pushDeerKey = '';
|
||||
public pushDeerUrl = '';
|
||||
}
|
||||
|
||||
export class ChatNotification extends NotificationBaseInfo {
|
||||
public chatUrl = '';
|
||||
public chatToken = '';
|
||||
}
|
||||
|
||||
export class BarkNotification extends NotificationBaseInfo {
|
||||
public barkPush = '';
|
||||
public barkIcon = 'http://qn.whyour.cn/logo.png';
|
||||
public barkIcon = 'https://qn.whyour.cn/logo.png';
|
||||
public barkSound = '';
|
||||
public barkGroup = 'qinglong';
|
||||
}
|
||||
@@ -66,6 +78,12 @@ export class WeWorkAppNotification extends NotificationBaseInfo {
|
||||
public weWorkAppKey = '';
|
||||
}
|
||||
|
||||
export class AibotkNotification extends NotificationBaseInfo {
|
||||
public aibotkKey: string = '';
|
||||
public aibotkType: 'room' | 'contact' = 'room';
|
||||
public aibotkName: string = '';
|
||||
}
|
||||
|
||||
export class IGotNotification extends NotificationBaseInfo {
|
||||
public iGotPushKey = '';
|
||||
}
|
||||
@@ -81,16 +99,35 @@ export class EmailNotification extends NotificationBaseInfo {
|
||||
public emailPass: string = '';
|
||||
}
|
||||
|
||||
export class WebhookNotification extends NotificationBaseInfo {
|
||||
public webhookHeaders: string = '';
|
||||
public webhookBody: string = '';
|
||||
public webhookUrl: string = '';
|
||||
public webhookMethod: 'GET' | 'POST' | 'PUT' = 'GET';
|
||||
public webhookContentType:
|
||||
| 'application/json'
|
||||
| 'multipart/form-data'
|
||||
| 'application/x-www-form-urlencoded' = 'application/json';
|
||||
}
|
||||
|
||||
export class LarkNotification extends NotificationBaseInfo {
|
||||
public larkKey = '';
|
||||
}
|
||||
|
||||
export interface NotificationInfo
|
||||
extends GoCqHttpBotNotification,
|
||||
GotifyNotification,
|
||||
ServerChanNotification,
|
||||
PushDeerNotification,
|
||||
ChatNotification,
|
||||
BarkNotification,
|
||||
TelegramBotNotification,
|
||||
DingtalkBotNotification,
|
||||
WeWorkBotNotification,
|
||||
WeWorkAppNotification,
|
||||
AibotkNotification,
|
||||
IGotNotification,
|
||||
PushPlusNotification,
|
||||
EmailNotification {}
|
||||
EmailNotification,
|
||||
WebhookNotification,
|
||||
LarkNotification {}
|
||||
|
||||
@@ -28,6 +28,9 @@ export class Subscription {
|
||||
extensions?: string;
|
||||
sub_before?: string;
|
||||
sub_after?: string;
|
||||
proxy?: string;
|
||||
autoAddCron?: 1 | 0;
|
||||
autoDelCron?: 1 | 0;
|
||||
|
||||
constructor(options: Subscription) {
|
||||
this.id = options.id;
|
||||
@@ -54,6 +57,9 @@ export class Subscription {
|
||||
this.extensions = options.extensions;
|
||||
this.sub_before = options.sub_before;
|
||||
this.sub_after = options.sub_after;
|
||||
this.proxy = options.proxy;
|
||||
this.autoAddCron = options.autoAddCron ? 1 : 0;
|
||||
this.autoDelCron = options.autoDelCron ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,5 +108,8 @@ export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
||||
log_path: DataTypes.STRING,
|
||||
schedule_type: DataTypes.STRING,
|
||||
alias: { type: DataTypes.STRING, unique: 'alias' },
|
||||
proxy: { type: DataTypes.STRING, allowNull: true },
|
||||
autoAddCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||
autoDelCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||
},
|
||||
);
|
||||
|
||||
+30
-7
@@ -6,10 +6,11 @@ import { CrontabModel } from '../data/cron';
|
||||
import { DependenceModel } from '../data/dependence';
|
||||
import { AppModel } from '../data/open';
|
||||
import { AuthModel } from '../data/auth';
|
||||
import { sequelize } from '../data';
|
||||
import { fileExist } from '../config/util';
|
||||
import { SubscriptionModel } from '../data/subscription';
|
||||
import { CrontabViewModel } from '../data/cronView';
|
||||
import config from '../config';
|
||||
import { sequelize } from '../data';
|
||||
|
||||
export default async () => {
|
||||
try {
|
||||
@@ -19,13 +20,35 @@ export default async () => {
|
||||
await AuthModel.sync();
|
||||
await EnvModel.sync();
|
||||
await SubscriptionModel.sync();
|
||||
await CrontabViewModel.sync();
|
||||
|
||||
// try {
|
||||
// const queryInterface = sequelize.getQueryInterface();
|
||||
// await queryInterface.addIndex('Crontabs', ['command'], { unique: true });
|
||||
// await queryInterface.addIndex('Envs', ['name', 'value'], { unique: true });
|
||||
// await queryInterface.addIndex('Apps', ['name'], { unique: true });
|
||||
// } catch (error) { }
|
||||
// 初始化新增字段
|
||||
try {
|
||||
await sequelize.query(
|
||||
'alter table CrontabViews add column filterRelation VARCHAR(255)',
|
||||
);
|
||||
} catch (error) {}
|
||||
try {
|
||||
await sequelize.query(
|
||||
'alter table Subscriptions add column proxy VARCHAR(255)',
|
||||
);
|
||||
} catch (error) {}
|
||||
try {
|
||||
await sequelize.query('alter table CrontabViews add column type NUMBER');
|
||||
} catch (error) {}
|
||||
try {
|
||||
await sequelize.query(
|
||||
'alter table Subscriptions add column autoAddCron NUMBER',
|
||||
);
|
||||
} catch (error) {}
|
||||
try {
|
||||
await sequelize.query(
|
||||
'alter table Subscriptions add column autoDelCron NUMBER',
|
||||
);
|
||||
} catch (error) {}
|
||||
try {
|
||||
await sequelize.query('alter table Crontabs add column sub_id NUMBER');
|
||||
} catch (error) {}
|
||||
|
||||
// 2.10-2.11 升级
|
||||
const cronDbFile = path.join(config.rootPath, 'db/crontab.db');
|
||||
|
||||
+19
-7
@@ -3,7 +3,7 @@ import bodyParser from 'body-parser';
|
||||
import cors from 'cors';
|
||||
import routes from '../api';
|
||||
import config from '../config';
|
||||
import jwt from 'express-jwt';
|
||||
import jwt, { UnauthorizedError } from 'express-jwt';
|
||||
import fs from 'fs';
|
||||
import { getPlatform, getToken } from '../config/util';
|
||||
import Container from 'typedi';
|
||||
@@ -75,22 +75,24 @@ export default ({ app }: { app: Application }) => {
|
||||
if (
|
||||
!headerToken &&
|
||||
originPath &&
|
||||
config.apiWhiteList.includes(originPath) &&
|
||||
originPath !== '/api/crons/status'
|
||||
config.apiWhiteList.includes(originPath)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
||||
if (data) {
|
||||
if (data && headerToken) {
|
||||
const { token = '', tokens = {} } = JSON.parse(data);
|
||||
if (headerToken === token || tokens[req.platform] === headerToken) {
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
const err: any = new Error('UnauthorizedError');
|
||||
err.status = 401;
|
||||
const errorCode = headerToken ? 'invalid_token' : 'credentials_required';
|
||||
const errorMessage = headerToken
|
||||
? 'jwt malformed'
|
||||
: 'No authorization token was found';
|
||||
const err = new UnauthorizedError(errorCode, { message: errorMessage });
|
||||
next(err);
|
||||
});
|
||||
|
||||
@@ -168,7 +170,17 @@ export default ({ app }: { app: Application }) => {
|
||||
},
|
||||
);
|
||||
|
||||
app.use(Sentry.Handlers.errorHandler());
|
||||
app.use(
|
||||
Sentry.Handlers.errorHandler({
|
||||
shouldHandleError(error) {
|
||||
// 排除 SequelizeUniqueConstraintError / NotFound
|
||||
return (
|
||||
!['SequelizeUniqueConstraintError'].includes(error.name) ||
|
||||
!['Not Found'].includes(error.message)
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
app.use(
|
||||
(
|
||||
|
||||
@@ -4,16 +4,32 @@ import { Container } from 'typedi';
|
||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import CronService from '../services/cron';
|
||||
import EnvService from '../services/env';
|
||||
import _ from 'lodash';
|
||||
import groupBy from 'lodash/groupBy';
|
||||
import { DependenceModel } from '../data/dependence';
|
||||
import { Op } from 'sequelize';
|
||||
import config from '../config';
|
||||
import { CrontabViewModel, CronViewType } from '../data/cronView';
|
||||
import { initPosition } from '../data/env';
|
||||
|
||||
export default async () => {
|
||||
const cronService = Container.get(CronService);
|
||||
const envService = Container.get(EnvService);
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
|
||||
// 初始化新增默认全部任务视图
|
||||
CrontabViewModel.findAll({
|
||||
where: { type: CronViewType.系统, name: '全部任务' },
|
||||
raw: true,
|
||||
}).then((docs) => {
|
||||
if (docs.length === 0) {
|
||||
CrontabViewModel.create({
|
||||
name: '全部任务',
|
||||
type: CronViewType.系统,
|
||||
position: initPosition / 2,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化更新所有任务状态为空闲
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle },
|
||||
@@ -26,7 +42,7 @@ export default async () => {
|
||||
order: [['type', 'DESC']],
|
||||
raw: true,
|
||||
}).then(async (docs) => {
|
||||
const groups = _.groupBy(docs, 'type');
|
||||
const groups = groupBy(docs, 'type');
|
||||
const keys = Object.keys(groups).sort((a, b) => parseInt(b) - parseInt(a));
|
||||
for (const key of keys) {
|
||||
const group = groups[key];
|
||||
|
||||
@@ -5,7 +5,7 @@ import dotenv from 'dotenv';
|
||||
import Logger from './logger';
|
||||
import { fileExist } from '../config/util';
|
||||
|
||||
const rootPath = process.cwd();
|
||||
const rootPath = process.env.QL_DIR as string;;
|
||||
const dataPath = path.join(rootPath, 'data/');
|
||||
const configPath = path.join(dataPath, 'config/');
|
||||
const scriptPath = path.join(dataPath, 'scripts/');
|
||||
@@ -64,13 +64,5 @@ export default async () => {
|
||||
|
||||
dotenv.config({ path: confFile });
|
||||
|
||||
// 声明QL_DIR环境变量
|
||||
let qlHomePath = path.join(__dirname, '../../');
|
||||
// 生产环境
|
||||
if (qlHomePath.endsWith('/static/')) {
|
||||
qlHomePath = path.join(qlHomePath, '../');
|
||||
}
|
||||
process.env.QL_DIR = qlHomePath;
|
||||
|
||||
Logger.info('✌️ Init file down');
|
||||
};
|
||||
|
||||
+22
-10
@@ -1,36 +1,48 @@
|
||||
import { Container } from 'typedi';
|
||||
import _ from 'lodash';
|
||||
import SystemService from '../services/system';
|
||||
import ScheduleService from '../services/schedule';
|
||||
import SubscriptionService from '../services/subscription';
|
||||
import config from '../config';
|
||||
import { fileExist } from '../config/util';
|
||||
|
||||
export default async () => {
|
||||
const systemService = Container.get(SystemService);
|
||||
const scheduleService = Container.get(ScheduleService);
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
|
||||
// 生成内置token
|
||||
let tokenCommand = `ts-node-transpile-only ${config.rootPath}/back/token.ts`;
|
||||
const tokenFile = `${config.rootPath}static/build/token.js`;
|
||||
if (await fileExist(tokenFile)) {
|
||||
tokenCommand = `node ${tokenFile}`;
|
||||
}
|
||||
const cron = {
|
||||
id: NaN,
|
||||
name: '生成token',
|
||||
command: tokenCommand,
|
||||
};
|
||||
await scheduleService.cancelIntervalTask(cron);
|
||||
scheduleService.createIntervalTask(cron, {
|
||||
days: 28,
|
||||
});
|
||||
|
||||
// 运行删除日志任务
|
||||
const data = await systemService.getLogRemoveFrequency();
|
||||
if (data && data.info && data.info.frequency) {
|
||||
const cron = {
|
||||
const rmlogCron = {
|
||||
id: data.id,
|
||||
name: '删除日志',
|
||||
command: `ql rmlog ${data.info.frequency}`,
|
||||
};
|
||||
await scheduleService.createIntervalTask(cron, {
|
||||
await scheduleService.cancelIntervalTask(rmlogCron);
|
||||
scheduleService.createIntervalTask(rmlogCron, {
|
||||
days: data.info.frequency,
|
||||
runImmediately: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 运行所有订阅
|
||||
const subs = await subscriptionService.list();
|
||||
for (const sub of subs) {
|
||||
await subscriptionService.handleTask(
|
||||
sub,
|
||||
!sub.is_disabled,
|
||||
true,
|
||||
!sub.is_disabled,
|
||||
);
|
||||
subscriptionService.handleTask(sub, !sub.is_disabled, !sub.is_disabled);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2,16 +2,21 @@ import { Application } from 'express';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import * as Tracing from '@sentry/tracing';
|
||||
import Logger from './logger';
|
||||
import config from '../config';
|
||||
import fs from 'fs';
|
||||
import { parseVersion } from '../config/util';
|
||||
|
||||
export default async ({ expressApp }: { expressApp: Application }) => {
|
||||
const { version } = await parseVersion(config.versionFile);
|
||||
|
||||
export default ({ expressApp }: { expressApp: Application }) => {
|
||||
Sentry.init({
|
||||
dsn: 'https://f4b5b55fb3c645b29a5dc2d70a1a4ef4@o1098464.ingest.sentry.io/6122819',
|
||||
integrations: [
|
||||
new Sentry.Integrations.Http({ tracing: true }),
|
||||
new Tracing.Integrations.Express({ app: expressApp }),
|
||||
],
|
||||
|
||||
tracesSampleRate: 1.0,
|
||||
tracesSampleRate: 0.1,
|
||||
release: version,
|
||||
});
|
||||
|
||||
expressApp.use(Sentry.Handlers.requestHandler());
|
||||
|
||||
+3
-6
@@ -6,15 +6,12 @@ import config from './config';
|
||||
const app = express();
|
||||
|
||||
app.get('/api/public/panel/log', (req, res) => {
|
||||
exec(
|
||||
'pm2 logs panel --lines 500 --nostream --timestamp',
|
||||
(err, stdout, stderr) => {
|
||||
exec('tail -n 300 ~/.pm2/logs/panel-error.log', (err, stdout, stderr) => {
|
||||
if (err || stderr) {
|
||||
return res.send({ code: 400, message: (err && err.message) || stderr });
|
||||
}
|
||||
return res.send({ code: 200, data: stdout });
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
app
|
||||
@@ -22,7 +19,7 @@ app
|
||||
await require('./loaders/sentry').default({ expressApp: app });
|
||||
await require('./loaders/db').default();
|
||||
|
||||
Logger.debug(`✌️ Back server launched on port ${config.publicPort}`);
|
||||
Logger.debug(`✌️ 公共服务启动成功!`);
|
||||
})
|
||||
.on('error', (err) => {
|
||||
Logger.error(err);
|
||||
|
||||
+10
-9
@@ -4,6 +4,7 @@ import { exec } from 'child_process';
|
||||
import Logger from './loaders/logger';
|
||||
import { CrontabModel, CrontabStatus } from './data/cron';
|
||||
import config from './config';
|
||||
import { QL_PREFIX, TASK_PREFIX } from './config/const';
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -18,14 +19,18 @@ const run = async () => {
|
||||
_schedule &&
|
||||
_schedule.length > 5 &&
|
||||
task.status !== CrontabStatus.disabled &&
|
||||
!task.isDisabled
|
||||
!task.isDisabled &&
|
||||
task.schedule
|
||||
) {
|
||||
schedule.scheduleJob(task.schedule, function () {
|
||||
let command = task.command as string;
|
||||
if (!command.includes('task ') && !command.includes('ql ')) {
|
||||
command = `task ${command}`;
|
||||
if (
|
||||
!command.startsWith(TASK_PREFIX) &&
|
||||
!command.startsWith(QL_PREFIX)
|
||||
) {
|
||||
command = `${TASK_PREFIX}${command}`;
|
||||
}
|
||||
exec(command);
|
||||
exec(`ID=${task.id} ${command}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -43,11 +48,7 @@ app
|
||||
await require('./loaders/db').default();
|
||||
|
||||
await run();
|
||||
Logger.info(`
|
||||
################################################
|
||||
🛡️ Schedule listening on port: ${config.cronPort} 🛡️
|
||||
################################################
|
||||
`);
|
||||
Logger.debug('定时任务服务启动成功!');
|
||||
})
|
||||
.on('error', (err) => {
|
||||
Logger.error(err);
|
||||
|
||||
+203
-165
@@ -5,12 +5,16 @@ import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import { exec, execSync, spawn } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import cron_parser from 'cron-parser';
|
||||
import { getFileContentByName, concurrentRun, fileExist } from '../config/util';
|
||||
import {
|
||||
getFileContentByName,
|
||||
concurrentRun,
|
||||
fileExist,
|
||||
killTask,
|
||||
} from '../config/util';
|
||||
import { promises, existsSync } from 'fs';
|
||||
import { promisify } from 'util';
|
||||
import { Op } from 'sequelize';
|
||||
import { Op, where, col as colFn } from 'sequelize';
|
||||
import path from 'path';
|
||||
import dayjs from 'dayjs';
|
||||
import { TASK_PREFIX, QL_PREFIX } from '../config/const';
|
||||
|
||||
@Service()
|
||||
export default class CronService {
|
||||
@@ -28,7 +32,7 @@ export default class CronService {
|
||||
const tab = new Crontab(payload);
|
||||
tab.saved = false;
|
||||
const doc = await this.insert(tab);
|
||||
await this.set_crontab(this.isSixCron(doc));
|
||||
await this.set_crontab();
|
||||
return doc;
|
||||
}
|
||||
|
||||
@@ -37,9 +41,10 @@ export default class CronService {
|
||||
}
|
||||
|
||||
public async update(payload: Crontab): Promise<Crontab> {
|
||||
payload.saved = false;
|
||||
const newDoc = await this.updateDb(payload);
|
||||
await this.set_crontab(this.isSixCron(newDoc));
|
||||
const tab = new Crontab(payload);
|
||||
tab.saved = false;
|
||||
const newDoc = await this.updateDb(tab);
|
||||
await this.set_crontab();
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
@@ -78,7 +83,7 @@ export default class CronService {
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
await CrontabModel.destroy({ where: { id: ids } });
|
||||
await this.set_crontab(true);
|
||||
await this.set_crontab();
|
||||
}
|
||||
|
||||
public async pin(ids: number[]) {
|
||||
@@ -113,9 +118,84 @@ export default class CronService {
|
||||
}
|
||||
}
|
||||
|
||||
public async crontabs(searchText?: string): Promise<Crontab[]> {
|
||||
let query = {};
|
||||
private formatViewQuery(query: any, viewQuery: any) {
|
||||
if (viewQuery.filters && viewQuery.filters.length > 0) {
|
||||
const primaryOperate = viewQuery.filterRelation === 'or' ? Op.or : Op.and;
|
||||
if (!query[primaryOperate]) {
|
||||
query[primaryOperate] = [];
|
||||
}
|
||||
for (const col of viewQuery.filters) {
|
||||
const { property, value, operation } = col;
|
||||
let q: any = {};
|
||||
let operate2 = null;
|
||||
let operate = null;
|
||||
switch (operation) {
|
||||
case 'Reg':
|
||||
operate = Op.like;
|
||||
operate2 = Op.or;
|
||||
break;
|
||||
case 'NotReg':
|
||||
operate = Op.notLike;
|
||||
operate2 = Op.and;
|
||||
break;
|
||||
case 'In':
|
||||
q[Op.or] = [
|
||||
{
|
||||
[property]: value,
|
||||
},
|
||||
property === 'status' && value.includes(2)
|
||||
? { isDisabled: 1 }
|
||||
: {},
|
||||
];
|
||||
break;
|
||||
case 'Nin':
|
||||
q[Op.and] = [
|
||||
{
|
||||
[property]: {
|
||||
[Op.notIn]: value,
|
||||
},
|
||||
},
|
||||
property === 'status' && value.includes(2)
|
||||
? { isDisabled: { [Op.ne]: 1 } }
|
||||
: {},
|
||||
];
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (operate && operate2) {
|
||||
q[property] = {
|
||||
[Op.or]: [
|
||||
{
|
||||
[operate2]: [
|
||||
{ [operate]: `%${value}%` },
|
||||
{ [operate]: `%${encodeURIComponent(value)}%` },
|
||||
],
|
||||
},
|
||||
{
|
||||
[operate2]: [
|
||||
where(colFn(property), operate, `%${value}%`),
|
||||
where(
|
||||
colFn(property),
|
||||
operate,
|
||||
`%${encodeURIComponent(value)}%`,
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
query[primaryOperate].push(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private formatSearchText(query: any, searchText: string | undefined) {
|
||||
if (searchText) {
|
||||
if (!query[Op.and]) {
|
||||
query[Op.and] = [];
|
||||
}
|
||||
let q: any = {};
|
||||
const textArray = searchText.split(':');
|
||||
switch (textArray[0]) {
|
||||
case 'name':
|
||||
@@ -123,13 +203,11 @@ export default class CronService {
|
||||
case 'schedule':
|
||||
case 'label':
|
||||
const column = textArray[0] === 'label' ? 'labels' : textArray[0];
|
||||
query = {
|
||||
[column]: {
|
||||
q[column] = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${textArray[1]}%` },
|
||||
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
||||
],
|
||||
},
|
||||
};
|
||||
break;
|
||||
default:
|
||||
@@ -139,8 +217,7 @@ export default class CronService {
|
||||
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
||||
],
|
||||
};
|
||||
query = {
|
||||
[Op.or]: [
|
||||
q[Op.or] = [
|
||||
{
|
||||
name: reg,
|
||||
},
|
||||
@@ -153,17 +230,95 @@ export default class CronService {
|
||||
{
|
||||
labels: reg,
|
||||
},
|
||||
],
|
||||
};
|
||||
];
|
||||
break;
|
||||
}
|
||||
query[Op.and].push(q);
|
||||
}
|
||||
}
|
||||
|
||||
private formatFilterQuery(query: any, filterQuery: any) {
|
||||
if (filterQuery) {
|
||||
if (!query[Op.and]) {
|
||||
query[Op.and] = [];
|
||||
}
|
||||
const filterKeys: any = Object.keys(filterQuery);
|
||||
for (const key of filterKeys) {
|
||||
let q: any = {};
|
||||
if (!filterQuery[key]) continue;
|
||||
if (key === 'status' && filterQuery[key].includes(2)) {
|
||||
q = { [Op.or]: [{ [key]: filterQuery[key] }, { isDisabled: 1 }] };
|
||||
} else {
|
||||
q[key] = filterQuery[key];
|
||||
}
|
||||
query[Op.and].push(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private formatViewSort(order: string[][], viewQuery: any) {
|
||||
if (viewQuery.sorts && viewQuery.sorts.length > 0) {
|
||||
for (const { property, type } of viewQuery.sorts) {
|
||||
order.unshift([property, type]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async find(params: { log_path: string }): Promise<Crontab | null> {
|
||||
try {
|
||||
const result = await CrontabModel.findOne({ where: { ...params } });
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async crontabs(params?: {
|
||||
searchValue: string;
|
||||
page: string;
|
||||
size: string;
|
||||
sorter: string;
|
||||
filters: string;
|
||||
queryString: string;
|
||||
}): Promise<{ data: Crontab[]; total: number }> {
|
||||
const searchText = params?.searchValue;
|
||||
const page = Number(params?.page || '0');
|
||||
const size = Number(params?.size || '0');
|
||||
const viewQuery = JSON.parse(params?.queryString || '{}');
|
||||
const filterQuery = JSON.parse(params?.filters || '{}');
|
||||
const sorterQuery = JSON.parse(params?.sorter || '{}');
|
||||
|
||||
let query: any = {};
|
||||
let order = [
|
||||
['isPinned', 'DESC'],
|
||||
['isDisabled', 'ASC'],
|
||||
['status', 'ASC'],
|
||||
['createdAt', 'DESC'],
|
||||
];
|
||||
|
||||
this.formatViewQuery(query, viewQuery);
|
||||
this.formatSearchText(query, searchText);
|
||||
this.formatFilterQuery(query, filterQuery);
|
||||
this.formatViewSort(order, viewQuery);
|
||||
|
||||
if (sorterQuery) {
|
||||
const { field, type } = sorterQuery;
|
||||
if (field && type) {
|
||||
order.unshift([field, type]);
|
||||
}
|
||||
}
|
||||
let condition: any = {
|
||||
where: query,
|
||||
order: order,
|
||||
};
|
||||
if (page && size) {
|
||||
condition.offset = (page - 1) * size;
|
||||
condition.limit = size;
|
||||
}
|
||||
try {
|
||||
const result = await CrontabModel.findAll({
|
||||
where: query,
|
||||
order: [['createdAt', 'DESC']],
|
||||
});
|
||||
return result as any;
|
||||
const result = await CrontabModel.findAll(condition);
|
||||
const count = await CrontabModel.count({ where: query });
|
||||
return { data: result, total: count };
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
@@ -190,31 +345,11 @@ export default class CronService {
|
||||
for (const doc of docs) {
|
||||
if (doc.pid) {
|
||||
try {
|
||||
process.kill(-doc.pid);
|
||||
await killTask(doc.pid);
|
||||
} catch (error) {
|
||||
this.logger.silly(error);
|
||||
}
|
||||
}
|
||||
const err = await this.killTask(doc.command);
|
||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||
|
||||
const endTime = dayjs();
|
||||
const diffTimeStr = doc.last_execution_time
|
||||
? `,耗时 ${endTime.diff(
|
||||
dayjs(doc.last_execution_time * 1000),
|
||||
'second',
|
||||
)}`
|
||||
: '';
|
||||
if (logFileExist) {
|
||||
const str = err ? `\n${err}` : '';
|
||||
fs.appendFileSync(
|
||||
`${absolutePath}`,
|
||||
`${str}\n## 执行结束... ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)}${diffTimeStr}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await CrontabModel.update(
|
||||
@@ -223,42 +358,6 @@ export default class CronService {
|
||||
);
|
||||
}
|
||||
|
||||
public async killTask(name: string) {
|
||||
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
||||
const execAsync = promisify(exec);
|
||||
try {
|
||||
let pid = (await execAsync(taskCommand)).stdout;
|
||||
if (pid) {
|
||||
pid = (await execAsync(`pstree -p ${pid}`)).stdout;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
let pids = pid.match(/\(\d+/g);
|
||||
const killLogs = [];
|
||||
if (pids && pids.length > 0) {
|
||||
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
||||
pids = pids.slice(0, 3);
|
||||
for (const id of pids) {
|
||||
const c = `kill -9 ${id.slice(1)}`;
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync(c);
|
||||
if (stderr) {
|
||||
killLogs.push(stderr);
|
||||
}
|
||||
if (stdout) {
|
||||
killLogs.push(stdout);
|
||||
}
|
||||
} catch (error: any) {
|
||||
killLogs.push(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return killLogs.length > 0 ? JSON.stringify(killLogs) : '';
|
||||
} catch (e) {
|
||||
return JSON.stringify(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async runSingle(cronId: number): Promise<number> {
|
||||
return new Promise(async (resolve: any) => {
|
||||
const cron = await this.getDb({ id: cronId });
|
||||
@@ -276,14 +375,20 @@ export default class CronService {
|
||||
this.logger.silly('Original command: ' + command);
|
||||
|
||||
let cmdStr = command;
|
||||
if (!cmdStr.includes('task ') && !cmdStr.includes('ql ')) {
|
||||
cmdStr = `task ${cmdStr}`;
|
||||
if (!cmdStr.startsWith(TASK_PREFIX) && !cmdStr.startsWith(QL_PREFIX)) {
|
||||
cmdStr = `${TASK_PREFIX}${cmdStr}`;
|
||||
}
|
||||
if (cmdStr.endsWith('.js')) {
|
||||
if (
|
||||
cmdStr.endsWith('.js') ||
|
||||
cmdStr.endsWith('.py') ||
|
||||
cmdStr.endsWith('.pyc') ||
|
||||
cmdStr.endsWith('.sh') ||
|
||||
cmdStr.endsWith('.ts')
|
||||
) {
|
||||
cmdStr = `${cmdStr} now`;
|
||||
}
|
||||
|
||||
const cp = spawn(cmdStr, { shell: '/bin/bash' });
|
||||
const cp = spawn(`ID=${id} ${cmdStr}`, { shell: '/bin/bash' });
|
||||
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.running, pid: cp.pid },
|
||||
@@ -291,7 +396,7 @@ export default class CronService {
|
||||
);
|
||||
cp.stderr.on('data', (data) => {
|
||||
if (logFileExist) {
|
||||
fs.appendFileSync(`${absolutePath}`, `${data}`);
|
||||
fs.appendFileSync(`${absolutePath}`, `${data.toString()}`);
|
||||
}
|
||||
});
|
||||
cp.on('error', (err) => {
|
||||
@@ -302,16 +407,10 @@ export default class CronService {
|
||||
|
||||
cp.on('exit', async (code, signal) => {
|
||||
this.logger.info(
|
||||
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||
`任务 ${command} 进程id: ${cp.pid} 退出,退出码 ${code}`,
|
||||
);
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id } },
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
cp.on('close', async (code) => {
|
||||
this.logger.info(`${command} pid: ${cp.pid} closed ${code}`);
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id } },
|
||||
@@ -323,12 +422,12 @@ export default class CronService {
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||
await this.set_crontab(true);
|
||||
await this.set_crontab();
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||
await this.set_crontab(true);
|
||||
await this.set_crontab();
|
||||
}
|
||||
|
||||
public async log(id: number) {
|
||||
@@ -341,35 +440,17 @@ export default class CronService {
|
||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||
if (logFileExist) {
|
||||
return getFileContentByName(`${absolutePath}`);
|
||||
}
|
||||
const [, commandStr, url] = doc.command.split(/ +/);
|
||||
let logPath = this.getKey(commandStr);
|
||||
const isQlCommand = doc.command.startsWith('ql ');
|
||||
const key =
|
||||
(url && ['repo', 'raw'].includes(commandStr) && this.getKey(url)) ||
|
||||
logPath;
|
||||
if (isQlCommand) {
|
||||
logPath = 'update';
|
||||
}
|
||||
let logDir = `${config.logPath}${logPath}`;
|
||||
if (existsSync(logDir)) {
|
||||
let files = await promises.readdir(logDir);
|
||||
if (isQlCommand) {
|
||||
files = files.filter((x) => x.includes(key));
|
||||
}
|
||||
return getFileContentByName(`${logDir}/${files[files.length - 1]}`);
|
||||
} else {
|
||||
return '';
|
||||
return '任务未运行';
|
||||
}
|
||||
}
|
||||
|
||||
public async logs(id: number) {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc) {
|
||||
if (!doc || !doc.log_path) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (doc.log_path) {
|
||||
const relativeDir = path.dirname(`${doc.log_path}`);
|
||||
const dir = path.resolve(config.logPath, relativeDir);
|
||||
if (existsSync(dir)) {
|
||||
@@ -381,67 +462,26 @@ export default class CronService {
|
||||
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
||||
}))
|
||||
.sort((a, b) => b.time - a.time);
|
||||
}
|
||||
}
|
||||
|
||||
const [, commandStr, url] = doc.command.split(/ +/);
|
||||
let logPath = this.getKey(commandStr);
|
||||
const isQlCommand = doc.command.startsWith('ql ');
|
||||
const key =
|
||||
(url && ['repo', 'raw'].includes(commandStr) && this.getKey(url)) ||
|
||||
logPath;
|
||||
if (isQlCommand) {
|
||||
logPath = 'update';
|
||||
}
|
||||
let logDir = `${config.logPath}${logPath}`;
|
||||
if (existsSync(logDir)) {
|
||||
let files = await promises.readdir(logDir);
|
||||
if (isQlCommand) {
|
||||
files = files.filter((x) => x.includes(key));
|
||||
}
|
||||
return files
|
||||
.map((x) => ({
|
||||
filename: x,
|
||||
directory: logPath,
|
||||
time: fs.statSync(`${logDir}/${x}`).mtime.getTime(),
|
||||
}))
|
||||
.sort((a, b) => b.time - a.time);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private getKey(command: string): string {
|
||||
const start =
|
||||
command.lastIndexOf('/') !== -1 ? command.lastIndexOf('/') + 1 : 0;
|
||||
const end =
|
||||
command.lastIndexOf('.') !== -1
|
||||
? command.lastIndexOf('.')
|
||||
: command.length;
|
||||
|
||||
const tmpStr = command.substring(0, start - 1);
|
||||
let index = 0;
|
||||
if (tmpStr.lastIndexOf('/') !== -1 && tmpStr.startsWith('http')) {
|
||||
index = tmpStr.lastIndexOf('/');
|
||||
} else if (tmpStr.lastIndexOf(':') !== -1 && tmpStr.startsWith('git@')) {
|
||||
index = tmpStr.lastIndexOf(':');
|
||||
}
|
||||
if (index) {
|
||||
return `${tmpStr.substring(index + 1)}_${command.substring(start, end)}`;
|
||||
} else {
|
||||
return command.substring(start, end);
|
||||
}
|
||||
}
|
||||
|
||||
private make_command(tab: Crontab) {
|
||||
if (
|
||||
!tab.command.startsWith(TASK_PREFIX) &&
|
||||
!tab.command.startsWith(QL_PREFIX)
|
||||
) {
|
||||
tab.command = `${TASK_PREFIX}${tab.command}`;
|
||||
}
|
||||
const crontab_job_string = `ID=${tab.id} ${tab.command}`;
|
||||
return crontab_job_string;
|
||||
}
|
||||
|
||||
private async set_crontab(needReloadSchedule: boolean = false) {
|
||||
private async set_crontab() {
|
||||
const tabs = await this.crontabs();
|
||||
var crontab_string = '';
|
||||
tabs.forEach((tab) => {
|
||||
tabs.data.forEach((tab) => {
|
||||
const _schedule = tab.schedule && tab.schedule.split(/ +/);
|
||||
if (tab.isDisabled === 1 || _schedule!.length !== 5) {
|
||||
crontab_string += '# ';
|
||||
@@ -461,9 +501,7 @@ export default class CronService {
|
||||
fs.writeFileSync(config.crontabFile, crontab_string);
|
||||
|
||||
execSync(`crontab ${config.crontabFile}`);
|
||||
if (needReloadSchedule) {
|
||||
exec(`pm2 reload schedule`);
|
||||
}
|
||||
await CrontabModel.update({ saved: true }, { where: {} });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { CrontabView, CrontabViewModel } from '../data/cronView';
|
||||
import {
|
||||
initPosition,
|
||||
maxPosition,
|
||||
minPosition,
|
||||
stepPosition,
|
||||
} from '../data/env';
|
||||
|
||||
@Service()
|
||||
export default class CronViewService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public async create(payload: CrontabView): Promise<CrontabView> {
|
||||
let position = initPosition;
|
||||
const views = await this.list();
|
||||
if (views && views.length > 0 && views[views.length - 1].position) {
|
||||
position = views[views.length - 1].position as number;
|
||||
}
|
||||
position = position / 2;
|
||||
const tab = new CrontabView({ ...payload, position });
|
||||
const doc = await this.insert(tab);
|
||||
|
||||
await this.checkPosition(tab.position!);
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async insert(payload: CrontabView): Promise<CrontabView> {
|
||||
return await CrontabViewModel.create(payload, { returning: true });
|
||||
}
|
||||
|
||||
public async update(payload: CrontabView): Promise<CrontabView> {
|
||||
const newDoc = await this.updateDb(new CrontabView(payload));
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
public async updateDb(payload: CrontabView): Promise<CrontabView> {
|
||||
await CrontabViewModel.update(payload, { where: { id: payload.id } });
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
await CrontabViewModel.destroy({ where: { id: ids } });
|
||||
}
|
||||
|
||||
public async list(): Promise<CrontabView[]> {
|
||||
try {
|
||||
const result = await CrontabViewModel.findAll({
|
||||
where: {},
|
||||
order: [['position', 'DESC']],
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async getDb(query: any): Promise<CrontabView> {
|
||||
const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
|
||||
return doc && (doc.get({ plain: true }) as CrontabView);
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await CrontabViewModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await CrontabViewModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
private async checkPosition(position: number) {
|
||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
||||
if (precisionPosition < minPosition || precisionPosition > maxPosition) {
|
||||
const envs = await this.list();
|
||||
let position = initPosition;
|
||||
for (const env of envs) {
|
||||
position = position - stepPosition;
|
||||
await this.updateDb({ id: env.id, position });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getPrecisionPosition(position: number): number {
|
||||
return parseFloat(position.toPrecision(16));
|
||||
}
|
||||
|
||||
public async move({
|
||||
id,
|
||||
fromIndex,
|
||||
toIndex,
|
||||
}: {
|
||||
fromIndex: number;
|
||||
toIndex: number;
|
||||
id: number;
|
||||
}): Promise<CrontabView> {
|
||||
let targetPosition: number;
|
||||
const isUpward = fromIndex > toIndex;
|
||||
const views = await this.list();
|
||||
if (toIndex === 0 || toIndex === views.length - 1) {
|
||||
targetPosition = isUpward
|
||||
? views[0].position! * 2
|
||||
: views[toIndex].position! / 2;
|
||||
} else {
|
||||
targetPosition = isUpward
|
||||
? (views[toIndex].position! + views[toIndex - 1].position!) / 2
|
||||
: (views[toIndex].position! + views[toIndex + 1].position!) / 2;
|
||||
}
|
||||
const newDoc = await this.update({
|
||||
id,
|
||||
position: this.getPrecisionPosition(targetPosition),
|
||||
});
|
||||
|
||||
await this.checkPosition(targetPosition);
|
||||
return newDoc;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
unInstallDependenceCommandTypes,
|
||||
DependenceModel,
|
||||
} from '../data/dependence';
|
||||
import _ from 'lodash';
|
||||
import { spawn } from 'child_process';
|
||||
import SockService from './sock';
|
||||
import { Op } from 'sequelize';
|
||||
@@ -125,8 +124,11 @@ export default class DependenceService {
|
||||
return docs;
|
||||
}
|
||||
|
||||
private async find(query: any, sort?: any): Promise<Dependence[]> {
|
||||
const docs = await DependenceModel.findAll({ where: { ...query } });
|
||||
private async find(query: any, sort: any = []): Promise<Dependence[]> {
|
||||
const docs = await DependenceModel.findAll({
|
||||
where: { ...query },
|
||||
order: [...sort, ['createdAt', 'DESC']],
|
||||
});
|
||||
return docs;
|
||||
}
|
||||
|
||||
|
||||
+63
-30
@@ -1,10 +1,17 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { getFileContentByName } from '../config/util';
|
||||
import config from '../config';
|
||||
import * as fs from 'fs';
|
||||
import { Env, EnvModel, EnvStatus, initEnvPosition } from '../data/env';
|
||||
import _ from 'lodash';
|
||||
import {
|
||||
Env,
|
||||
EnvModel,
|
||||
EnvStatus,
|
||||
initPosition,
|
||||
maxPosition,
|
||||
minPosition,
|
||||
stepPosition,
|
||||
} from '../data/env';
|
||||
import groupBy from 'lodash/groupBy';
|
||||
import { Op } from 'sequelize';
|
||||
|
||||
@Service()
|
||||
@@ -13,17 +20,22 @@ export default class EnvService {
|
||||
|
||||
public async create(payloads: Env[]): Promise<Env[]> {
|
||||
const envs = await this.envs();
|
||||
let position = initEnvPosition;
|
||||
if (envs && envs.length > 0 && envs[envs.length - 1].position) {
|
||||
position = envs[envs.length - 1].position as number;
|
||||
let position = initPosition;
|
||||
if (
|
||||
envs &&
|
||||
envs.length > 0 &&
|
||||
typeof envs[envs.length - 1].position === 'number'
|
||||
) {
|
||||
position = envs[envs.length - 1].position!;
|
||||
}
|
||||
const tabs = payloads.map((x) => {
|
||||
position = position / 2;
|
||||
position = position - stepPosition;
|
||||
const tab = new Env({ ...x, position });
|
||||
return tab;
|
||||
});
|
||||
const docs = await this.insert(tabs);
|
||||
await this.set_envs();
|
||||
await this.checkPosition(tabs[tabs.length - 1].position!);
|
||||
return docs;
|
||||
}
|
||||
|
||||
@@ -37,7 +49,7 @@ export default class EnvService {
|
||||
}
|
||||
|
||||
public async update(payload: Env): Promise<Env> {
|
||||
const newDoc = await this.updateDb(payload);
|
||||
const newDoc = await this.updateDb(new Env(payload));
|
||||
await this.set_envs();
|
||||
return newDoc;
|
||||
}
|
||||
@@ -67,25 +79,44 @@ export default class EnvService {
|
||||
const envs = await this.envs();
|
||||
if (toIndex === 0 || toIndex === envs.length - 1) {
|
||||
targetPosition = isUpward
|
||||
? envs[0].position * 2
|
||||
: envs[toIndex].position / 2;
|
||||
? envs[0].position! + stepPosition
|
||||
: envs[toIndex].position! - stepPosition;
|
||||
} else {
|
||||
targetPosition = isUpward
|
||||
? (envs[toIndex].position + envs[toIndex - 1].position) / 2
|
||||
: (envs[toIndex].position + envs[toIndex + 1].position) / 2;
|
||||
? (envs[toIndex].position! + envs[toIndex - 1].position!) / 2
|
||||
: (envs[toIndex].position! + envs[toIndex + 1].position!) / 2;
|
||||
}
|
||||
|
||||
const newDoc = await this.update({
|
||||
id,
|
||||
position: targetPosition,
|
||||
position: this.getPrecisionPosition(targetPosition),
|
||||
});
|
||||
|
||||
await this.checkPosition(targetPosition, envs[toIndex].position!);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
public async envs(
|
||||
searchText: string = '',
|
||||
sort: any = { position: -1 },
|
||||
query: any = {},
|
||||
): Promise<Env[]> {
|
||||
private async checkPosition(position: number, edge: number = 0) {
|
||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
||||
if (
|
||||
precisionPosition < minPosition ||
|
||||
precisionPosition > maxPosition ||
|
||||
Math.abs(precisionPosition - edge) < minPosition
|
||||
) {
|
||||
const envs = await this.envs();
|
||||
let position = initPosition;
|
||||
for (const env of envs) {
|
||||
position = position - stepPosition;
|
||||
await this.updateDb({ id: env.id, position });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getPrecisionPosition(position: number): number {
|
||||
return parseFloat(position.toPrecision(16));
|
||||
}
|
||||
|
||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
||||
let condition = { ...query };
|
||||
if (searchText) {
|
||||
const encodeText = encodeURIComponent(searchText);
|
||||
@@ -112,7 +143,11 @@ export default class EnvService {
|
||||
};
|
||||
}
|
||||
try {
|
||||
const result = await this.find(condition, [['position', 'DESC']]);
|
||||
const result = await this.find(condition, [
|
||||
['status', 'ASC'],
|
||||
['position', 'DESC'],
|
||||
['createdAt', 'ASC'],
|
||||
]);
|
||||
return result as any;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
@@ -151,24 +186,22 @@ export default class EnvService {
|
||||
}
|
||||
|
||||
public async set_envs() {
|
||||
const envs = await this.envs(
|
||||
'',
|
||||
{ position: -1 },
|
||||
{ name: { [Op.not]: null } },
|
||||
);
|
||||
const groups = _.groupBy(envs, 'name');
|
||||
const envs = await this.envs('', {
|
||||
name: { [Op.not]: null },
|
||||
status: EnvStatus.normal,
|
||||
});
|
||||
const groups = groupBy(envs, 'name');
|
||||
let env_string = '';
|
||||
for (const key in groups) {
|
||||
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
||||
const group = groups[key];
|
||||
|
||||
// 忽略不符合bash要求的环境变量名称
|
||||
if (/^[a-zA-Z_][0-9a-zA-Z_]+$/.test(key)) {
|
||||
let value = _(group)
|
||||
.filter((x) => x.status !== EnvStatus.disabled)
|
||||
.map('value')
|
||||
if (/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(key)) {
|
||||
let value = group
|
||||
.map((x) => x.value)
|
||||
.join('&')
|
||||
.replace(/(\\)[^\n]/g, '\\\\')
|
||||
.replace(/(\\)[^n]/g, '\\\\')
|
||||
.replace(/(\\$)/, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.trim();
|
||||
|
||||
+152
-29
@@ -6,6 +6,7 @@ import got from 'got';
|
||||
import nodemailer from 'nodemailer';
|
||||
import crypto from 'crypto';
|
||||
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
||||
import { parseBody, parseHeaders } from '../config/util';
|
||||
|
||||
@Service()
|
||||
export default class NotificationService {
|
||||
@@ -17,20 +18,27 @@ export default class NotificationService {
|
||||
['goCqHttpBot', this.goCqHttpBot],
|
||||
['serverChan', this.serverChan],
|
||||
['pushDeer', this.pushDeer],
|
||||
['chat', this.chat],
|
||||
['bark', this.bark],
|
||||
['telegramBot', this.telegramBot],
|
||||
['dingtalkBot', this.dingtalkBot],
|
||||
['weWorkBot', this.weWorkBot],
|
||||
['weWorkApp', this.weWorkApp],
|
||||
['aibotk', this.aibotk],
|
||||
['iGot', this.iGot],
|
||||
['pushPlus', this.pushPlus],
|
||||
['email', this.email],
|
||||
['webhook', this.webhook],
|
||||
['lark', this.lark],
|
||||
]);
|
||||
|
||||
private timeout = 10000;
|
||||
private title = '';
|
||||
private content = '';
|
||||
private params!: Omit<NotificationInfo, 'type'>;
|
||||
private gotOption = {
|
||||
timeout: 30000,
|
||||
retry: 1,
|
||||
};
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
@@ -73,8 +81,7 @@ export default class NotificationService {
|
||||
const { gotifyUrl, gotifyToken, gotifyPriority } = this.params;
|
||||
const res: any = await got
|
||||
.post(`${gotifyUrl}/message?token=${gotifyToken}`, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
body: `title=${encodeURIComponent(
|
||||
this.title,
|
||||
)}&message=${encodeURIComponent(
|
||||
@@ -92,8 +99,7 @@ export default class NotificationService {
|
||||
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
||||
const res: any = await got
|
||||
.post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
json: { message: `${this.title}\n${this.content}` },
|
||||
headers: { Authorization: 'Bearer ' + goCqHttpBotToken },
|
||||
})
|
||||
@@ -108,8 +114,7 @@ export default class NotificationService {
|
||||
: `https://sc.ftqq.com/${serverChanKey}.send`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
body: `title=${this.title}&desp=${this.content}`,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
@@ -118,12 +123,11 @@ export default class NotificationService {
|
||||
}
|
||||
|
||||
private async pushDeer() {
|
||||
const { pushDeerKey } = this.params;
|
||||
const url = `https://api2.pushdeer.com/message/push`;
|
||||
const { pushDeerKey, pushDeerUrl } = this.params;
|
||||
const url = pushDeerUrl || `https://api2.pushdeer.com/message/push`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
body: `pushkey=${pushDeerKey}&text=${encodeURIComponent(
|
||||
this.title,
|
||||
)}&desp=${encodeURIComponent(this.content)}&type=markdown`,
|
||||
@@ -135,6 +139,19 @@ export default class NotificationService {
|
||||
);
|
||||
}
|
||||
|
||||
private async chat() {
|
||||
const { chatUrl, chatToken } = this.params;
|
||||
const url = `${chatUrl}${chatToken}`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
...this.gotOption,
|
||||
body: `payload={"text":"${this.title}\n${this.content}"}`,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
.json();
|
||||
return res.success;
|
||||
}
|
||||
|
||||
private async bark() {
|
||||
let { barkPush, barkIcon, barkSound, barkGroup } = this.params;
|
||||
if (!barkPush.startsWith('http') && !barkPush.startsWith('https')) {
|
||||
@@ -147,8 +164,7 @@ export default class NotificationService {
|
||||
)}?icon=${barkIcon}?sound=${barkSound}&group=${barkGroup}`;
|
||||
const res: any = await got
|
||||
.get(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
.json();
|
||||
@@ -186,8 +202,7 @@ export default class NotificationService {
|
||||
}
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
body: `chat_id=${telegramBotUserId}&text=${this.title}\n\n${this.content}&disable_web_page_preview=true`,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
agent,
|
||||
@@ -209,8 +224,7 @@ export default class NotificationService {
|
||||
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
json: {
|
||||
msgtype: 'text',
|
||||
text: {
|
||||
@@ -227,8 +241,7 @@ export default class NotificationService {
|
||||
const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${weWorkBotKey}`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
json: {
|
||||
msgtype: 'text',
|
||||
text: {
|
||||
@@ -245,10 +258,9 @@ export default class NotificationService {
|
||||
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
||||
weWorkAppKey.split(',');
|
||||
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken`;
|
||||
const { access_token } = await got
|
||||
const tokenRes: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
json: {
|
||||
corpid,
|
||||
corpsecret,
|
||||
@@ -296,10 +308,9 @@ export default class NotificationService {
|
||||
|
||||
const res: any = await got
|
||||
.post(
|
||||
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`,
|
||||
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${tokenRes.access_token}`,
|
||||
{
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
json: {
|
||||
touser,
|
||||
agentid,
|
||||
@@ -313,13 +324,53 @@ export default class NotificationService {
|
||||
return res.errcode === 0;
|
||||
}
|
||||
|
||||
private async aibotk() {
|
||||
const { aibotkKey, aibotkType, aibotkName } = this.params;
|
||||
let url = '';
|
||||
let json = {};
|
||||
switch (aibotkType) {
|
||||
case 'room':
|
||||
url = 'https://api-bot.aibotk.com/openapi/v1/chat/room';
|
||||
json = {
|
||||
apiKey: `${aibotkKey}`,
|
||||
roomName: `${aibotkName}`,
|
||||
message: {
|
||||
type: 1,
|
||||
content: `【青龙快讯】\n\n${this.title}\n${this.content}`,
|
||||
},
|
||||
};
|
||||
break;
|
||||
case 'contact':
|
||||
url = 'https://api-bot.aibotk.com/openapi/v1/chat/contact';
|
||||
json = {
|
||||
apiKey: `${aibotkKey}`,
|
||||
name: `${aibotkName}`,
|
||||
message: {
|
||||
type: 1,
|
||||
content: `【青龙快讯】\n\n${this.title}\n${this.content}`,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
...this.gotOption,
|
||||
json: {
|
||||
...json,
|
||||
},
|
||||
})
|
||||
.json();
|
||||
|
||||
return res.code === 0;
|
||||
}
|
||||
|
||||
private async iGot() {
|
||||
const { iGotPushKey } = this.params;
|
||||
const url = `https://push.hellyw.com/${iGotPushKey.toLowerCase()}`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
body: `title=${this.title}&content=${this.content}`,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
@@ -333,8 +384,7 @@ export default class NotificationService {
|
||||
const url = `https://www.pushplus.plus/send`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
...this.gotOption,
|
||||
json: {
|
||||
token: `${pushPlusToken}`,
|
||||
title: `${this.title}`,
|
||||
@@ -347,6 +397,21 @@ export default class NotificationService {
|
||||
return res.code === 200;
|
||||
}
|
||||
|
||||
private async lark() {
|
||||
const { larkKey } = this.params;
|
||||
const res: any = await got
|
||||
.post(`https://open.feishu.cn/open-apis/bot/v2/hook/${larkKey}`, {
|
||||
...this.gotOption,
|
||||
json: {
|
||||
msg_type: 'text',
|
||||
content: { text: `${this.title}\n\n${this.content}` },
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
.json();
|
||||
return res.StatusCode === 0;
|
||||
}
|
||||
|
||||
private async email() {
|
||||
const { emailPass, emailService, emailUser } = this.params;
|
||||
const transporter = nodemailer.createTransport({
|
||||
@@ -368,4 +433,62 @@ export default class NotificationService {
|
||||
|
||||
return !!info.messageId;
|
||||
}
|
||||
|
||||
private async webhook() {
|
||||
const {
|
||||
webhookUrl,
|
||||
webhookBody,
|
||||
webhookHeaders,
|
||||
webhookMethod,
|
||||
webhookContentType,
|
||||
} = this.params;
|
||||
|
||||
const { formatBody, formatUrl } = this.formatNotifyContent(
|
||||
webhookUrl,
|
||||
webhookBody,
|
||||
);
|
||||
if (!formatUrl && !formatBody) {
|
||||
return false;
|
||||
}
|
||||
const headers = parseHeaders(webhookHeaders);
|
||||
const body = parseBody(formatBody, webhookContentType);
|
||||
const bodyParam = this.formatBody(webhookContentType, body);
|
||||
const options = {
|
||||
method: webhookMethod,
|
||||
headers,
|
||||
...this.gotOption,
|
||||
allowGetBody: true,
|
||||
...bodyParam,
|
||||
};
|
||||
const res = await got(formatUrl, options);
|
||||
return String(res.statusCode).startsWith('20');
|
||||
}
|
||||
|
||||
private formatBody(contentType: string, body: any): object {
|
||||
if (!body) return {};
|
||||
switch (contentType) {
|
||||
case 'application/json':
|
||||
return { json: body };
|
||||
case 'multipart/form-data':
|
||||
return { form: body };
|
||||
case 'application/x-www-form-urlencoded':
|
||||
return { body };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private formatNotifyContent(url: string, body: string) {
|
||||
if (!url.includes('$title') && !body.includes('$title')) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
formatUrl: url
|
||||
.replaceAll('$title', encodeURIComponent(this.title))
|
||||
.replaceAll('$content', encodeURIComponent(this.content)),
|
||||
formatBody: body
|
||||
.replaceAll('$title', this.title)
|
||||
.replaceAll('$content', this.content),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+7
-15
@@ -119,7 +119,7 @@ export default class OpenService {
|
||||
(x) => x.expiration >= timestamp,
|
||||
);
|
||||
let tokens = invalidTokens;
|
||||
if (invalidTokens.length > 5) {
|
||||
if (invalidTokens.length >= 5) {
|
||||
tokens = [
|
||||
...invalidTokens.slice(0, 4),
|
||||
{ ...invalidTokens[4], expiration },
|
||||
@@ -145,7 +145,7 @@ export default class OpenService {
|
||||
}
|
||||
}
|
||||
|
||||
public async findSystemToken(): Promise<{
|
||||
public async generateSystemToken(): Promise<{
|
||||
value: string;
|
||||
expiration: number;
|
||||
}> {
|
||||
@@ -158,21 +158,13 @@ export default class OpenService {
|
||||
scopes: ['crons', 'system'],
|
||||
} as App);
|
||||
}
|
||||
const nowTime = Math.round(Date.now() / 1000);
|
||||
let token;
|
||||
if (
|
||||
!systemApp.tokens ||
|
||||
!systemApp.tokens.length ||
|
||||
nowTime > [...systemApp.tokens].pop()!.expiration
|
||||
) {
|
||||
const authToken = await this.authToken({
|
||||
const { data } = await this.authToken({
|
||||
client_id: systemApp.client_id,
|
||||
client_secret: systemApp.client_secret,
|
||||
});
|
||||
token = authToken.data;
|
||||
} else {
|
||||
token = [...systemApp.tokens].pop();
|
||||
}
|
||||
return token;
|
||||
return {
|
||||
...data,
|
||||
value: data.token,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+16
-15
@@ -5,8 +5,8 @@ import { ChildProcessWithoutNullStreams, exec, spawn } from 'child_process';
|
||||
import {
|
||||
ToadScheduler,
|
||||
LongIntervalJob,
|
||||
AsyncTask,
|
||||
SimpleIntervalSchedule,
|
||||
Task,
|
||||
} from 'toad-scheduler';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
@@ -42,7 +42,11 @@ export default class ScheduleService {
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
async runTask(command: string, callbacks: TaskCallbacks = {}) {
|
||||
async runTask(
|
||||
command: string,
|
||||
callbacks: TaskCallbacks = {},
|
||||
completionTime: 'start' | 'end' = 'end',
|
||||
) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const startTime = dayjs();
|
||||
@@ -52,14 +56,15 @@ export default class ScheduleService {
|
||||
|
||||
// TODO:
|
||||
callbacks.onStart?.(cp, startTime);
|
||||
completionTime === 'start' && resolve(cp.pid);
|
||||
|
||||
cp.stdout.on('data', async (data) => {
|
||||
await callbacks.onLog?.(data.toString());
|
||||
});
|
||||
|
||||
cp.stderr.on('data', async (data) => {
|
||||
this.logger.error(
|
||||
'执行任务 %s 失败,时间:%s, 错误信息:%j',
|
||||
this.logger.info(
|
||||
'[执行任务失败] %s,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
data.toString(),
|
||||
@@ -69,7 +74,7 @@ export default class ScheduleService {
|
||||
|
||||
cp.on('error', async (err) => {
|
||||
this.logger.error(
|
||||
'创建任务 %s 失败,时间:%s, 错误信息:%j',
|
||||
'[创建任务失败] %s,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
err,
|
||||
@@ -79,13 +84,12 @@ export default class ScheduleService {
|
||||
|
||||
cp.on('exit', async (code, signal) => {
|
||||
this.logger.info(
|
||||
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||
`[任务退出] ${command} 进程id: ${cp.pid},退出码 ${code}`,
|
||||
);
|
||||
});
|
||||
|
||||
cp.on('close', async (code) => {
|
||||
const endTime = dayjs();
|
||||
this.logger.info(`${command} pid: ${cp.pid} closed ${code}`);
|
||||
await callbacks.onEnd?.(
|
||||
cp,
|
||||
endTime,
|
||||
@@ -101,7 +105,6 @@ export default class ScheduleService {
|
||||
error,
|
||||
);
|
||||
await callbacks.onError?.(JSON.stringify(error));
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -151,12 +154,10 @@ export default class ScheduleService {
|
||||
name,
|
||||
command,
|
||||
);
|
||||
const task = new AsyncTask(
|
||||
const task = new Task(
|
||||
name,
|
||||
async () => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
await this.runTask(command, callbacks);
|
||||
});
|
||||
() => {
|
||||
this.runTask(command, callbacks);
|
||||
},
|
||||
(err) => {
|
||||
this.logger.error(
|
||||
@@ -169,7 +170,7 @@ export default class ScheduleService {
|
||||
);
|
||||
|
||||
const job = new LongIntervalJob(
|
||||
{ ...schedule, runImmediately: false },
|
||||
{ runImmediately: false, ...schedule },
|
||||
task,
|
||||
_id,
|
||||
);
|
||||
@@ -177,7 +178,7 @@ export default class ScheduleService {
|
||||
this.intervalSchedule.addIntervalJob(job);
|
||||
|
||||
if (runImmediately) {
|
||||
await this.runTask(command, callbacks);
|
||||
this.runTask(command, callbacks);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+17
-13
@@ -6,6 +6,8 @@ import SockService from './sock';
|
||||
import CronService from './cron';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import config from '../config';
|
||||
import { TASK_COMMAND } from '../config/const';
|
||||
import { getPid, killTask } from '../config/util';
|
||||
|
||||
@Service()
|
||||
export default class ScriptService {
|
||||
@@ -40,23 +42,25 @@ export default class ScriptService {
|
||||
|
||||
public async runScript(filePath: string) {
|
||||
const relativePath = path.relative(config.scriptPath, filePath);
|
||||
const command = `task -l ${relativePath} now`;
|
||||
this.scheduleService.runTask(command, this.taskCallbacks(filePath));
|
||||
const command = `${TASK_COMMAND} -l ${relativePath} now`;
|
||||
const pid = await this.scheduleService.runTask(
|
||||
command,
|
||||
this.taskCallbacks(filePath),
|
||||
'start',
|
||||
);
|
||||
|
||||
return { code: 200 };
|
||||
return { code: 200, data: pid };
|
||||
}
|
||||
|
||||
public async stopScript(filePath: string) {
|
||||
public async stopScript(filePath: string, pid: number) {
|
||||
let str = '';
|
||||
if (!pid) {
|
||||
const relativePath = path.relative(config.scriptPath, filePath);
|
||||
const err = await this.cronService.killTask(`task -l ${relativePath} now`);
|
||||
|
||||
const str = err ? `\n${err}` : '';
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message: `${str}\n## 执行结束... ${new Date()
|
||||
.toLocaleString('zh', { hour12: false })
|
||||
.replace(' 24:', ' 00:')} `,
|
||||
});
|
||||
pid = await getPid(`${TASK_COMMAND} -l ${relativePath} now`);
|
||||
}
|
||||
try {
|
||||
await killTask(pid);
|
||||
} catch (error) {}
|
||||
|
||||
return { code: 200 };
|
||||
}
|
||||
|
||||
+45
-11
@@ -1,8 +1,10 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import fs from 'fs';
|
||||
import fs, { existsSync } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { Subscription } from '../data/subscription';
|
||||
import { formatUrl } from '../config/subscription';
|
||||
|
||||
@Service()
|
||||
export default class SshKeyService {
|
||||
@@ -14,7 +16,7 @@ export default class SshKeyService {
|
||||
|
||||
private generatePrivateKeyFile(alias: string, key: string): void {
|
||||
try {
|
||||
fs.writeFileSync(`${this.sshPath}/${alias}`, key, {
|
||||
fs.writeFileSync(`${this.sshPath}/${alias}`, `${key}${os.EOL}`, {
|
||||
encoding: 'utf8',
|
||||
mode: '400',
|
||||
});
|
||||
@@ -32,23 +34,32 @@ export default class SshKeyService {
|
||||
|
||||
private removePrivateKeyFile(alias: string): void {
|
||||
try {
|
||||
const filePath = path.join(this.sshPath, alias);
|
||||
if (existsSync(filePath)) {
|
||||
fs.unlinkSync(`${this.sshPath}/${alias}`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('删除私钥文件失败', error);
|
||||
}
|
||||
}
|
||||
|
||||
private generateSingleSshConfig(alias: string, host: string): string {
|
||||
return `\nHost ${alias}\n Hostname ${host}\n IdentityFile ${this.sshPath}/${alias}\n StrictHostKeyChecking no`;
|
||||
private generateSingleSshConfig(
|
||||
alias: string,
|
||||
host: string,
|
||||
proxy?: string,
|
||||
): string {
|
||||
if (host === 'github.com') {
|
||||
host = `ssh.github.com\n Port 443\n HostkeyAlgorithms +ssh-rsa\n PubkeyAcceptedAlgorithms +ssh-rsa`;
|
||||
}
|
||||
const proxyStr = proxy ? ` ProxyCommand nc -v -x ${proxy} %h %p\n` : '';
|
||||
return `Host ${alias}\n Hostname ${host}\n IdentityFile ${this.sshPath}/${alias}\n StrictHostKeyChecking no\n${proxyStr}`;
|
||||
}
|
||||
|
||||
private generateSshConfig(configs: string[]) {
|
||||
try {
|
||||
for (const config of configs) {
|
||||
fs.appendFileSync(this.sshConfigFilePath, config, {
|
||||
fs.writeFileSync(this.sshConfigFilePath, configs.join('\n'), {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('写入ssh配置文件失败', error);
|
||||
}
|
||||
@@ -69,16 +80,39 @@ export default class SshKeyService {
|
||||
}
|
||||
}
|
||||
|
||||
public addSSHKey(key: string, alias: string, host: string): void {
|
||||
public addSSHKey(
|
||||
key: string,
|
||||
alias: string,
|
||||
host: string,
|
||||
proxy?: string,
|
||||
): void {
|
||||
this.generatePrivateKeyFile(alias, key);
|
||||
const config = this.generateSingleSshConfig(alias, host);
|
||||
const config = this.generateSingleSshConfig(alias, host, proxy);
|
||||
this.removeSshConfig(alias);
|
||||
this.generateSshConfig([config]);
|
||||
}
|
||||
|
||||
public removeSSHKey(alias: string, host: string): void {
|
||||
public removeSSHKey(alias: string, host: string, proxy?: string): void {
|
||||
this.removePrivateKeyFile(alias);
|
||||
const config = this.generateSingleSshConfig(alias, host);
|
||||
const config = this.generateSingleSshConfig(alias, host, proxy);
|
||||
this.removeSshConfig(config);
|
||||
}
|
||||
|
||||
public setSshConfig(docs: Subscription[]) {
|
||||
let result = [];
|
||||
for (const doc of docs) {
|
||||
if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
|
||||
const { alias, proxy } = doc;
|
||||
const { host } = formatUrl(doc);
|
||||
this.removePrivateKeyFile(alias);
|
||||
this.generatePrivateKeyFile(
|
||||
alias,
|
||||
(doc.pull_option as any).private_key,
|
||||
);
|
||||
const config = this.generateSingleSshConfig(alias, host, proxy);
|
||||
result.push(config);
|
||||
}
|
||||
}
|
||||
this.generateSshConfig(result);
|
||||
}
|
||||
}
|
||||
|
||||
+32
-120
@@ -13,15 +13,14 @@ import {
|
||||
spawn,
|
||||
} from 'child_process';
|
||||
import fs from 'fs';
|
||||
import cron_parser from 'cron-parser';
|
||||
import {
|
||||
getFileContentByName,
|
||||
concurrentRun,
|
||||
fileExist,
|
||||
createFile,
|
||||
killTask,
|
||||
} from '../config/util';
|
||||
import { promises, existsSync } from 'fs';
|
||||
import { promisify } from 'util';
|
||||
import { Op } from 'sequelize';
|
||||
import path from 'path';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
@@ -29,6 +28,8 @@ import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||
import SockService from './sock';
|
||||
import SshKeyService from './sshKey';
|
||||
import dayjs from 'dayjs';
|
||||
import { LOG_END_SYMBOL } from '../config/const';
|
||||
import { formatCommand, formatUrl } from '../config/subscription';
|
||||
|
||||
@Service()
|
||||
export default class SubscriptionService {
|
||||
@@ -42,23 +43,6 @@ export default class SubscriptionService {
|
||||
public async list(searchText?: string): Promise<Subscription[]> {
|
||||
let query = {};
|
||||
if (searchText) {
|
||||
const textArray = searchText.split(':');
|
||||
switch (textArray[0]) {
|
||||
case 'name':
|
||||
case 'command':
|
||||
case 'schedule':
|
||||
case 'label':
|
||||
const column = textArray[0] === 'label' ? 'labels' : textArray[0];
|
||||
query = {
|
||||
[column]: {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${textArray[1]}%` },
|
||||
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
||||
],
|
||||
},
|
||||
};
|
||||
break;
|
||||
default:
|
||||
const reg = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchText}%` },
|
||||
@@ -71,80 +55,33 @@ export default class SubscriptionService {
|
||||
name: reg,
|
||||
},
|
||||
{
|
||||
command: reg,
|
||||
},
|
||||
{
|
||||
schedule: reg,
|
||||
},
|
||||
{
|
||||
labels: reg,
|
||||
url: reg,
|
||||
},
|
||||
],
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const result = await SubscriptionModel.findAll({
|
||||
where: query,
|
||||
order: [['createdAt', 'DESC']],
|
||||
order: [
|
||||
['is_disabled', 'ASC'],
|
||||
['createdAt', 'DESC'],
|
||||
],
|
||||
});
|
||||
return result as any;
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private formatCommand(doc: Subscription, url?: string) {
|
||||
let command = 'ql ';
|
||||
let _url = url || this.formatUrl(doc).url;
|
||||
const { type, whitelist, blacklist, dependences, branch, extensions } = doc;
|
||||
if (type === 'file') {
|
||||
command += `raw "${_url}"`;
|
||||
} else {
|
||||
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${
|
||||
dependences || ''
|
||||
}" "${branch || ''}" "${extensions || ''}"`;
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
private formatUrl(doc: Subscription) {
|
||||
let url = doc.url;
|
||||
let host = '';
|
||||
if (doc.type === 'private-repo') {
|
||||
if (doc.pull_type === 'ssh-key') {
|
||||
host = doc.url!.replace(/.*\@([^\:]+)\:.*/, '$1');
|
||||
url = doc.url!.replace(host, doc.alias);
|
||||
} else {
|
||||
host = doc.url!.replace(/.*\:\/\/([^\/]+)\/.*/, '$1');
|
||||
const { username, password } = doc.pull_option as any;
|
||||
url = doc.url!.replace(host, `${username}:${password}@${host}`);
|
||||
}
|
||||
}
|
||||
return { url, host };
|
||||
}
|
||||
|
||||
public async handleTask(
|
||||
doc: Subscription,
|
||||
needCreate = true,
|
||||
needAddKey = true,
|
||||
runImmediately = false,
|
||||
) {
|
||||
const { url, host } = this.formatUrl(doc);
|
||||
if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
|
||||
if (needAddKey) {
|
||||
this.sshKeyService.addSSHKey(
|
||||
(doc.pull_option as any).private_key,
|
||||
doc.alias,
|
||||
host,
|
||||
);
|
||||
} else {
|
||||
this.sshKeyService.removeSSHKey(doc.alias, host);
|
||||
}
|
||||
}
|
||||
const { url } = formatUrl(doc);
|
||||
|
||||
doc.command = this.formatCommand(doc, url as string);
|
||||
doc.command = formatCommand(doc, url as string);
|
||||
|
||||
if (doc.schedule_type === 'crontab') {
|
||||
this.scheduleService.cancelCronTask(doc as any);
|
||||
@@ -167,6 +104,11 @@ export default class SubscriptionService {
|
||||
}
|
||||
}
|
||||
|
||||
private async setSshConfig() {
|
||||
const docs = await SubscriptionModel.findAll();
|
||||
this.sshKeyService.setSshConfig(docs);
|
||||
}
|
||||
|
||||
private async promiseExec(command: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(
|
||||
@@ -254,7 +196,7 @@ export default class SubscriptionService {
|
||||
absolutePath,
|
||||
`\n## 执行结束... ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)} 耗时 ${diff} 秒`,
|
||||
)} 耗时 ${diff} 秒${LOG_END_SYMBOL}`,
|
||||
);
|
||||
|
||||
await SubscriptionModel.update(
|
||||
@@ -285,6 +227,7 @@ export default class SubscriptionService {
|
||||
const tab = new Subscription(payload);
|
||||
const doc = await this.insert(tab);
|
||||
await this.handleTask(doc);
|
||||
await this.setSshConfig();
|
||||
return doc;
|
||||
}
|
||||
|
||||
@@ -293,8 +236,10 @@ export default class SubscriptionService {
|
||||
}
|
||||
|
||||
public async update(payload: Subscription): Promise<Subscription> {
|
||||
const newDoc = await this.updateDb(payload);
|
||||
const tab = new Subscription(payload);
|
||||
const newDoc = await this.updateDb(tab);
|
||||
await this.handleTask(newDoc, !newDoc.is_disabled);
|
||||
await this.setSshConfig();
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
@@ -337,9 +282,10 @@ export default class SubscriptionService {
|
||||
public async remove(ids: number[]) {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc, false, false);
|
||||
await this.handleTask(doc, false);
|
||||
}
|
||||
await SubscriptionModel.destroy({ where: { id: ids } });
|
||||
await this.setSshConfig();
|
||||
}
|
||||
|
||||
public async getDb(query: any): Promise<Subscription> {
|
||||
@@ -363,19 +309,18 @@ export default class SubscriptionService {
|
||||
for (const doc of docs) {
|
||||
if (doc.pid) {
|
||||
try {
|
||||
process.kill(-doc.pid);
|
||||
await killTask(doc.pid);
|
||||
} catch (error) {
|
||||
this.logger.silly(error);
|
||||
}
|
||||
}
|
||||
const command = this.formatCommand(doc);
|
||||
const err = await this.killTask(command);
|
||||
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
||||
const str = err ? `\n${err}` : '';
|
||||
|
||||
fs.appendFileSync(
|
||||
`${absolutePath}`,
|
||||
`${str}\n## 执行结束... ${dayjs().format('YYYY-MM-DD HH:mm:ss')} `,
|
||||
`\n## 执行结束... ${dayjs().format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)}${LOG_END_SYMBOL}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -385,48 +330,13 @@ export default class SubscriptionService {
|
||||
);
|
||||
}
|
||||
|
||||
public async killTask(name: string) {
|
||||
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
||||
const execAsync = promisify(exec);
|
||||
try {
|
||||
let pid = (await execAsync(taskCommand)).stdout;
|
||||
if (pid) {
|
||||
pid = (await execAsync(`pstree -p ${pid}`)).stdout;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
let pids = pid.match(/\(\d+/g);
|
||||
const killLogs = [];
|
||||
if (pids && pids.length > 0) {
|
||||
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
||||
for (const id of pids) {
|
||||
const c = `kill -9 ${id.slice(1)}`;
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync(c);
|
||||
if (stderr) {
|
||||
killLogs.push(stderr);
|
||||
}
|
||||
if (stdout) {
|
||||
killLogs.push(stdout);
|
||||
}
|
||||
} catch (error: any) {
|
||||
killLogs.push(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return killLogs.length > 0 ? JSON.stringify(killLogs) : '';
|
||||
} catch (e) {
|
||||
return JSON.stringify(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async runSingle(subscriptionId: number) {
|
||||
const subscription = await this.getDb({ id: subscriptionId });
|
||||
if (subscription.status !== SubscriptionStatus.queued) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = this.formatCommand(subscription);
|
||||
const command = formatCommand(subscription);
|
||||
|
||||
await this.scheduleService.runTask(
|
||||
command,
|
||||
@@ -435,19 +345,21 @@ export default class SubscriptionService {
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
await this.setSshConfig();
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc, false);
|
||||
}
|
||||
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
await this.setSshConfig();
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc);
|
||||
}
|
||||
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async log(id: number) {
|
||||
|
||||
+22
-26
@@ -2,7 +2,6 @@ import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import config from '../config';
|
||||
import * as fs from 'fs';
|
||||
import _ from 'lodash';
|
||||
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
||||
import { NotificationInfo } from '../data/notify';
|
||||
import NotificationService from './notify';
|
||||
@@ -10,6 +9,7 @@ import ScheduleService from './schedule';
|
||||
import { spawn } from 'child_process';
|
||||
import SockService from './sock';
|
||||
import got from 'got';
|
||||
import { parseContentVersion, parseVersion } from '../config/util';
|
||||
|
||||
@Service()
|
||||
export default class SystemService {
|
||||
@@ -70,9 +70,8 @@ export default class SystemService {
|
||||
};
|
||||
await this.scheduleService.cancelIntervalTask(cron);
|
||||
if (frequency > 0) {
|
||||
await this.scheduleService.createIntervalTask(cron, {
|
||||
this.scheduleService.createIntervalTask(cron, {
|
||||
days: frequency,
|
||||
runImmediately: true,
|
||||
});
|
||||
}
|
||||
return { code: 200, data: { ...cron } };
|
||||
@@ -80,32 +79,33 @@ export default class SystemService {
|
||||
|
||||
public async checkUpdate() {
|
||||
try {
|
||||
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
||||
const logRegx = /.*export const changeLog = \`((.*\n.*)+)\`;/;
|
||||
const currentVersionContent = await parseVersion(config.versionFile);
|
||||
|
||||
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||
const currentVersion = currentVersionFile.match(versionRegx)![1];
|
||||
|
||||
let lastVersion = '';
|
||||
let lastLog = '';
|
||||
let lastVersionContent;
|
||||
try {
|
||||
const result = await got.get(config.lastVersionFile, {
|
||||
timeout: 6000,
|
||||
retry: 0,
|
||||
});
|
||||
const lastVersionFileContent = result.body;
|
||||
lastVersion = lastVersionFileContent.match(versionRegx)![1];
|
||||
lastLog = lastVersionFileContent.match(logRegx)
|
||||
? lastVersionFileContent.match(logRegx)![1]
|
||||
: '';
|
||||
const result = await got.get(
|
||||
`${config.lastVersionFile}?t=${Date.now()}`,
|
||||
{
|
||||
timeout: 30000,
|
||||
},
|
||||
);
|
||||
lastVersionContent = await parseContentVersion(result.body);
|
||||
} catch (error) {}
|
||||
|
||||
if (!lastVersionContent) {
|
||||
lastVersionContent = currentVersionContent;
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
hasNewVersion: this.checkHasNewVersion(currentVersion, lastVersion),
|
||||
lastVersion,
|
||||
lastLog,
|
||||
hasNewVersion: this.checkHasNewVersion(
|
||||
currentVersionContent.version,
|
||||
lastVersionContent.version,
|
||||
),
|
||||
lastVersion: lastVersionContent.version,
|
||||
lastLog: lastVersionContent.changeLog,
|
||||
lastLogLink: lastVersionContent.changeLogLink,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
@@ -138,10 +138,6 @@ export default class SystemService {
|
||||
public async updateSystem() {
|
||||
const cp = spawn('ql -l update', { shell: '/bin/bash' });
|
||||
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateSystemVersion',
|
||||
message: `开始更新系统`,
|
||||
});
|
||||
cp.stdout.on('data', (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateSystemVersion',
|
||||
|
||||
+26
-13
@@ -3,7 +3,6 @@ import winston from 'winston';
|
||||
import { createRandomString, getNetIp, getPlatform } from '../config/util';
|
||||
import config from '../config';
|
||||
import * as fs from 'fs';
|
||||
import _ from 'lodash';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { authenticator } from '@otplib/preset-default';
|
||||
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
||||
@@ -65,32 +64,37 @@ export default class UserService {
|
||||
return this.initAuthInfo();
|
||||
}
|
||||
|
||||
if (retries > 2 && Date.now() - lastlogon < Math.pow(3, retries) * 1000) {
|
||||
const retriesTime = Math.pow(3, retries) * 1000;
|
||||
if (retries > 2 && timestamp - lastlogon < retriesTime) {
|
||||
const waitTime = Math.ceil(
|
||||
(retriesTime - (timestamp - lastlogon)) / 1000,
|
||||
);
|
||||
return {
|
||||
code: 410,
|
||||
message: `失败次数过多,请${Math.round(
|
||||
(Math.pow(3, retries) * 1000 - Date.now() + lastlogon) / 1000,
|
||||
)}秒后重试`,
|
||||
data: Math.round(
|
||||
(Math.pow(3, retries) * 1000 - Date.now() + lastlogon) / 1000,
|
||||
),
|
||||
message: `失败次数过多,请${waitTime}秒后重试`,
|
||||
data: waitTime,
|
||||
};
|
||||
}
|
||||
|
||||
const { ip, address } = await getNetIp(req);
|
||||
if (username === cUsername && password === cPassword) {
|
||||
if (twoFactorActivated && needTwoFactor) {
|
||||
if (
|
||||
username === cUsername &&
|
||||
password === cPassword &&
|
||||
twoFactorActivated &&
|
||||
needTwoFactor
|
||||
) {
|
||||
this.updateAuthInfo(content, {
|
||||
isTwoFactorChecking: true,
|
||||
});
|
||||
return {
|
||||
code: 420,
|
||||
message: '请输入两步验证token',
|
||||
message: '',
|
||||
};
|
||||
}
|
||||
|
||||
const { ip, address } = await getNetIp(req);
|
||||
if (username === cUsername && password === cPassword) {
|
||||
const data = createRandomString(50, 100);
|
||||
const expiration = twoFactorActivated ? 30 : 3;
|
||||
const expiration = twoFactorActivated ? 60 : 20;
|
||||
let token = jwt.sign({ data }, config.secret as any, {
|
||||
expiresIn: 60 * 60 * 24 * expiration,
|
||||
algorithm: 'HS384',
|
||||
@@ -155,8 +159,17 @@ export default class UserService {
|
||||
status: LoginStatus.fail,
|
||||
},
|
||||
});
|
||||
if (retries > 2) {
|
||||
const waitTime = Math.round(Math.pow(3, retries + 1));
|
||||
return {
|
||||
code: 410,
|
||||
message: `失败次数过多,请${waitTime}秒后重试`,
|
||||
data: waitTime,
|
||||
};
|
||||
} else {
|
||||
return { code: 400, message: config.authError };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return this.initAuthInfo();
|
||||
}
|
||||
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
import 'reflect-metadata';
|
||||
import OpenService from './services/open';
|
||||
import { Container } from 'typedi';
|
||||
import LoggerInstance from './loaders/logger';
|
||||
import fs from 'fs';
|
||||
import config from './config';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
const tokenFile = path.join(config.configPath, 'token.json');
|
||||
|
||||
async function getToken() {
|
||||
try {
|
||||
Container.set('logger', LoggerInstance);
|
||||
const openService = Container.get(OpenService);
|
||||
const appToken = await openService.generateSystemToken();
|
||||
console.log(appToken.value);
|
||||
await writeFile({
|
||||
value: appToken.value,
|
||||
expiration: appToken.expiration,
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function writeFile(data: any) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
fs.writeFile(
|
||||
tokenFile,
|
||||
`${JSON.stringify(data)}${os.EOL}`,
|
||||
{ encoding: 'utf8' },
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
getToken();
|
||||
+27
-12
@@ -1,20 +1,28 @@
|
||||
FROM node:alpine
|
||||
FROM python:3.10-alpine as builder
|
||||
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||
RUN set -x \
|
||||
&& apk update \
|
||||
&& apk add nodejs npm git \
|
||||
&& npm i -g pnpm \
|
||||
&& cd /tmp/build \
|
||||
&& pnpm install --prod
|
||||
|
||||
FROM python:3.10-alpine
|
||||
|
||||
ARG QL_MAINTAINER="whyour"
|
||||
LABEL maintainer="${QL_MAINTAINER}"
|
||||
ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
||||
ARG QL_BRANCH=master
|
||||
ARG QL_BRANCH=develop
|
||||
|
||||
ENV PNPM_HOME=/root/.local/share/pnpm \
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/share/pnpm:/root/.local/share/pnpm/global/5/node_modules:$PNPM_HOME \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/pnpm-global/5/node_modules:/usr/local/lib/node_modules:/root/.local/share/pnpm/global/5/node_modules \
|
||||
LANG=zh_CN.UTF-8 \
|
||||
SHELL=/bin/bash \
|
||||
PS1="\u@\h:\w \$ " \
|
||||
QL_DIR=/ql \
|
||||
QL_BRANCH=${QL_BRANCH}
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
RUN set -x \
|
||||
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
||||
&& apk update -f \
|
||||
@@ -29,30 +37,37 @@ RUN set -x \
|
||||
perl \
|
||||
openssl \
|
||||
nginx \
|
||||
python3 \
|
||||
nodejs \
|
||||
jq \
|
||||
openssh \
|
||||
py3-pip \
|
||||
npm \
|
||||
&& rm -rf /var/cache/apk/* \
|
||||
&& apk update \
|
||||
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||
&& echo "Asia/Shanghai" > /etc/timezone \
|
||||
&& git config --global user.email "qinglong@@users.noreply.github.com" \
|
||||
&& git config --global user.name "qinglong" \
|
||||
&& git config --global http.postBuffer 524288000 \
|
||||
&& npm install -g pnpm \
|
||||
&& pnpm add -g pm2 ts-node typescript tslib \
|
||||
&& git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||
&& rm -rf /root/.pnpm-store \
|
||||
&& rm -rf /root/.local/share/pnpm/store \
|
||||
&& rm -rf /root/.cache \
|
||||
&& rm -rf /root/.npm
|
||||
|
||||
ARG SOURCE_COMMIT
|
||||
RUN git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||
&& cd ${QL_DIR} \
|
||||
&& cp -f .env.example .env \
|
||||
&& chmod 777 ${QL_DIR}/shell/*.sh \
|
||||
&& chmod 777 ${QL_DIR}/docker/*.sh \
|
||||
&& pnpm install --prod \
|
||||
&& rm -rf /root/.pnpm-store \
|
||||
&& rm -rf /root/.local/share/pnpm/store \
|
||||
&& rm -rf /root/.cache \
|
||||
&& rm -rf /root/.npm \
|
||||
&& git clone -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
|
||||
&& mkdir -p ${QL_DIR}/static \
|
||||
&& cp -rf /static/* ${QL_DIR}/static \
|
||||
&& rm -rf /static
|
||||
|
||||
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||
|
||||
@@ -4,12 +4,17 @@ dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
link_shell
|
||||
|
||||
export isFirstStartServer=true
|
||||
|
||||
echo -e "======================1. 检测配置文件========================\n"
|
||||
make_dir /etc/nginx/conf.d
|
||||
make_dir /run/nginx
|
||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
||||
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
|
||||
pm2 l &>/dev/null
|
||||
|
||||
patch_version &>/dev/null
|
||||
echo
|
||||
|
||||
echo -e "======================2. 安装依赖========================\n"
|
||||
@@ -37,13 +42,13 @@ echo -e "定时任务启动成功...\n"
|
||||
|
||||
if [[ $AutoStartBot == true ]]; then
|
||||
echo -e "======================7. 启动bot========================\n"
|
||||
nohup ql bot >>$dir_log/start.log 2>&1 &
|
||||
nohup ql -l bot >$dir_log/bot.log 2>&1 &
|
||||
echo -e "bot后台启动中...\n"
|
||||
fi
|
||||
|
||||
if [[ $EnableExtraShell == true ]]; then
|
||||
echo -e "======================8. 执行自定义脚本========================\n"
|
||||
nohup ql extra >>$dir_log/start.log 2>&1 &
|
||||
nohup ql -l extra >$dir_log/extra.log 2>&1 &
|
||||
echo -e "自定义脚本后台执行中...\n"
|
||||
fi
|
||||
|
||||
|
||||
+11
-10
@@ -1,8 +1,8 @@
|
||||
upstream api {
|
||||
upstream baseApi {
|
||||
server 0.0.0.0:5600;
|
||||
}
|
||||
|
||||
upstream public {
|
||||
upstream publicApi {
|
||||
server 0.0.0.0:5400;
|
||||
}
|
||||
|
||||
@@ -13,31 +13,32 @@ map $http_upgrade $connection_upgrade {
|
||||
|
||||
server {
|
||||
listen 5700;
|
||||
listen [::]:5700 ipv6only=on;
|
||||
root /ql/static/dist;
|
||||
ssl_session_timeout 5m;
|
||||
|
||||
location /api/public {
|
||||
location QL_BASE_URL/api/public/ {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://public;
|
||||
proxy_pass http://publicApi/api/public/;
|
||||
}
|
||||
|
||||
location /api {
|
||||
location QL_BASE_URL/api/ {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://api;
|
||||
proxy_pass http://baseApi/api/;
|
||||
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
location /open {
|
||||
location QL_BASE_URL/open/ {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://api;
|
||||
proxy_pass http://baseApi/open/;
|
||||
}
|
||||
|
||||
gzip on;
|
||||
@@ -49,9 +50,9 @@ server {
|
||||
gzip_buffers 16 8k;
|
||||
gzip_http_version 1.0;
|
||||
|
||||
location / {
|
||||
location QL_BASE_URL/ {
|
||||
index index.html index.htm;
|
||||
try_files $uri $uri/ /index.html;
|
||||
try_files $uri $uri/ QL_BASE_URL/index.html;
|
||||
}
|
||||
|
||||
location ~ .*\.(html)$ {
|
||||
|
||||
+50
-26
@@ -2,16 +2,16 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "concurrently -n w: npm:start:*",
|
||||
"start:front": "umi dev",
|
||||
"start:front": "max dev",
|
||||
"start:back": "nodemon",
|
||||
"start:public": "ts-node back/public.ts",
|
||||
"build:front": "umi build",
|
||||
"start:public": "ts-node --transpile-only ./back/public.ts",
|
||||
"build:front": "max build",
|
||||
"build:back": "tsc -p tsconfig.back.json",
|
||||
"panel": "npm run build:back && node static/build/app.js",
|
||||
"schedule": "npm run build:back && node static/build/schedule.js",
|
||||
"public": "npm run build:back && node static/build/public.js",
|
||||
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
||||
"postinstall": "umi generate tmp 2>/dev/null || true",
|
||||
"postinstall": "max setup 2>/dev/null || true",
|
||||
"test": "umi-test",
|
||||
"test:coverage": "umi-test --coverage"
|
||||
},
|
||||
@@ -28,16 +28,34 @@
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
"ignoreMissing": [
|
||||
"react",
|
||||
"react-dom",
|
||||
"antd",
|
||||
"dva",
|
||||
"postcss",
|
||||
"webpack",
|
||||
"eslint",
|
||||
"stylelint",
|
||||
"redux",
|
||||
"@babel/core",
|
||||
"monaco-editor",
|
||||
"rc-field-form",
|
||||
"@types/lodash.merge",
|
||||
"rollup",
|
||||
"styled-components"
|
||||
],
|
||||
"allowedVersions": {
|
||||
"react": "17",
|
||||
"react-dom": "17"
|
||||
"react": "18",
|
||||
"react-dom": "18",
|
||||
"dva-core": "2"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@otplib/preset-default": "^12.0.1",
|
||||
"@sentry/node": "^7.0.0",
|
||||
"@sentry/tracing": "^7.0.0",
|
||||
"@sentry/node": "^7.12.1",
|
||||
"@sentry/tracing": "^7.12.1",
|
||||
"body-parser": "^1.19.2",
|
||||
"celebrate": "^15.0.1",
|
||||
"chokidar": "^3.5.3",
|
||||
@@ -48,21 +66,23 @@
|
||||
"express": "^4.17.3",
|
||||
"express-jwt": "^6.1.1",
|
||||
"express-urlrewrite": "^1.4.0",
|
||||
"form-data": "^4.0.0",
|
||||
"got": "^11.8.2",
|
||||
"hpagent": "^0.1.2",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"lodash": "^4.17.21",
|
||||
"multer": "^1.4.4",
|
||||
"nedb": "^1.8.0",
|
||||
"node-schedule": "^2.1.0",
|
||||
"nodemailer": "^6.7.2",
|
||||
"p-queue": "7.2.0",
|
||||
"pstree.remy": "^1.1.8",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"sequelize": "^6.20.1",
|
||||
"sequelize": "^6.25.5",
|
||||
"serve-handler": "^6.1.3",
|
||||
"sockjs": "^0.3.24",
|
||||
"sqlite3": "npm:@louislam/sqlite3@^15.0.6",
|
||||
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.2",
|
||||
"toad-scheduler": "^1.6.0",
|
||||
"typedi": "^0.10.0",
|
||||
"uuid": "^8.3.2",
|
||||
@@ -71,54 +91,58 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ant-design/icons": "^4.7.0",
|
||||
"@ant-design/pro-layout": "^6.33.1",
|
||||
"@monaco-editor/react": "^4.3.1",
|
||||
"@sentry/react": "^7.0.0",
|
||||
"@ant-design/pro-layout": "6.38.22",
|
||||
"@monaco-editor/react": "4.2.1",
|
||||
"@react-hook/resize-observer": "^1.2.6",
|
||||
"@sentry/react": "^7.12.1",
|
||||
"@types/body-parser": "^1.19.2",
|
||||
"@types/cors": "^2.8.12",
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/express-jwt": "^6.0.4",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"@types/jsonwebtoken": "^8.5.8",
|
||||
"@types/lodash": "^4.14.179",
|
||||
"@types/lodash": "^4.14.185",
|
||||
"@types/multer": "^1.4.7",
|
||||
"@types/nedb": "^1.8.12",
|
||||
"@types/node": "^17.0.21",
|
||||
"@types/node-schedule": "^1.3.2",
|
||||
"@types/nodemailer": "^6.4.4",
|
||||
"@types/qrcode.react": "^1.0.2",
|
||||
"@types/react": "^17.0.39",
|
||||
"@types/react-dom": "^17.0.13",
|
||||
"@types/react": "^18.0.20",
|
||||
"@types/react-copy-to-clipboard": "^5.0.4",
|
||||
"@types/react-dom": "^18.0.6",
|
||||
"@types/serve-handler": "^6.1.1",
|
||||
"@types/sockjs": "^0.3.33",
|
||||
"@types/sockjs-client": "^1.5.1",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@umijs/plugin-antd": "^0.15.0",
|
||||
"@umijs/plugin-esbuild": "^1.4.1",
|
||||
"@umijs/max": "^4.0.55",
|
||||
"@umijs/ssr-darkreader": "^4.9.45",
|
||||
"@umijs/test": "^3.5.21",
|
||||
"ansi-to-react": "^6.1.6",
|
||||
"antd": "^4.20.5",
|
||||
"antd": "^4.24.8",
|
||||
"antd-img-crop": "^4.2.3",
|
||||
"codemirror": "^5.65.2",
|
||||
"compression-webpack-plugin": "9.2.0",
|
||||
"concurrently": "^7.0.0",
|
||||
"lint-staged": "^12.3.4",
|
||||
"lint-staged": "^13.0.3",
|
||||
"monaco-editor": "0.33.0",
|
||||
"nodemon": "^2.0.15",
|
||||
"prettier": "^2.5.1",
|
||||
"qiniu": "^7.4.0",
|
||||
"qrcode.react": "^1.0.1",
|
||||
"query-string": "^7.1.1",
|
||||
"rc-tween-one": "^3.0.6",
|
||||
"react": "17.x",
|
||||
"react": "18.2.0",
|
||||
"react-codemirror2": "^7.2.1",
|
||||
"react-copy-to-clipboard": "^5.1.0",
|
||||
"react-diff-viewer": "^3.1.1",
|
||||
"react-dnd": "^14.0.2",
|
||||
"react-dnd-html5-backend": "^14.0.0",
|
||||
"react-dom": "17.x",
|
||||
"react-dom": "18.2.0",
|
||||
"react-split-pane": "^0.1.92",
|
||||
"sockjs-client": "^1.6.0",
|
||||
"ts-node": "^10.6.0",
|
||||
"typescript": "^4.6.2",
|
||||
"umi": "^3.5.21",
|
||||
"tslib": "^2.4.0",
|
||||
"typescript": "4.8.4",
|
||||
"umi-request": "^1.4.0",
|
||||
"vh-check": "^2.0.5",
|
||||
"webpack": "^5.70.0",
|
||||
|
||||
Generated
+15586
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 91 KiB |
+47
-3
@@ -16,9 +16,14 @@ DefaultCronRule=""
|
||||
## ql repo命令拉取脚本时需要拉取的文件后缀,直接写文件后缀名即可
|
||||
RepoFileExtensions="js py"
|
||||
|
||||
## 代理地址,支持http/https/socks,例如 http://127.0.0.1:7890
|
||||
## 代理地址,支持HTTP/SOCK5,例如 http://127.0.0.1:7890
|
||||
ProxyUrl=""
|
||||
|
||||
## 资源告警阙值,默认CPU 80%、内存80%、磁盘90%
|
||||
CpuWarn=80
|
||||
MemoryWarn=80
|
||||
DiskWarn=90
|
||||
|
||||
## 设置定时任务执行的超时时间,默认1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
||||
CommandTimeoutTime="1h"
|
||||
|
||||
@@ -29,6 +34,14 @@ MaxConcurrentNum="5"
|
||||
## 默认给javascript任务加随机延迟,如 RandomDelay="300" ,表示任务将在 1-300 秒内随机延迟一个秒数,然后再运行,取消延迟赋值为空
|
||||
RandomDelay="300"
|
||||
|
||||
## 需要随机延迟运行任务的文件后缀,直接写后缀名即可,多个后缀用空格分开,例如: js py ts
|
||||
## 默认仅给javascript任务加随机延迟,其它任务按定时规则准点运行。全部任务随机延迟赋值为空
|
||||
RandomDelayFileExtensions="js"
|
||||
|
||||
## 每小时的第几分钟准点运行任务,当在这些时间运行任务时将忽略 RandomDelay 配置,不会被随机延迟
|
||||
## 默认是第0分钟和第30分钟,例如21:00或21:30分的任务将会准点运行。不需要准点运行赋值为空
|
||||
RandomDelayIgnoredMinutes="0 30"
|
||||
|
||||
## 如果你自己会写shell脚本,并且希望在每次运行 ql update 命令时,额外运行你的 shell 脚本,请赋值为 "true",默认为true
|
||||
EnableExtraShell="true"
|
||||
|
||||
@@ -38,9 +51,12 @@ AutoStartBot=""
|
||||
## 是否使用第三方bot,默认不使用,使用时填入仓库地址,存到ql/repo目录下,文件夹命名为diybot
|
||||
BotRepoUrl=""
|
||||
|
||||
## 安装bot依赖时指定pip源,默认使用清华源,如不需要源,设置此参数为空
|
||||
## 安装python依赖时指定pip源
|
||||
PipMirror="https://pypi.doubanio.com/simple/"
|
||||
|
||||
## 安装node依赖时指定npm源
|
||||
NpmMirror="https://registry.npmmirror.com"
|
||||
|
||||
## 通知环境变量
|
||||
## 1. Server酱
|
||||
## https://sct.ftqq.com
|
||||
@@ -51,7 +67,7 @@ export PUSH_KEY=""
|
||||
## 下方填写app提供的设备码,例如:https://api.day.app/123 那么此处的设备码就是123
|
||||
export BARK_PUSH=""
|
||||
## 下方填写推送图标设置,自定义推送图标(需iOS15或以上)
|
||||
export BARK_ICON="http://qn.whyour.cn/logo.png"
|
||||
export BARK_ICON="https://qn.whyour.cn/logo.png"
|
||||
## 下方填写推送声音设置,例如choo,具体值请在bark-推送铃声-查看所有铃声
|
||||
export BARK_SOUND=""
|
||||
## 下方填写推送消息分组,默认为"QingLong"
|
||||
@@ -129,4 +145,32 @@ export GOTIFY_PRIORITY=0
|
||||
## deer_key 填写PushDeer的key
|
||||
export DEER_KEY=""
|
||||
|
||||
## 12. Chat
|
||||
## chat_url 填写synology chat地址,http://IP:PORT/webapi/***token=
|
||||
## chat_token 填写后面的token
|
||||
export CHAT_URL=""
|
||||
export CHAT_TOKEN=""
|
||||
|
||||
## 13. aibotk
|
||||
## 官方说明文档:http://wechat.aibotk.com/oapi/oapi?from=ql
|
||||
## aibotk_key (必填)填写智能微秘书个人中心的apikey
|
||||
export AIBOTK_KEY=""
|
||||
## aibotk_type (必填)填写发送的目标 room 或 contact, 填其他的不生效
|
||||
export AIBOTK_TYPE=""
|
||||
## aibotk_name (必填)填写群名或用户昵称,和上面的type类型要对应
|
||||
export AIBOTK_NAME=""
|
||||
|
||||
## 14. SMTP
|
||||
## 暂时只支持在 Python 中调用 notify.py 以发送 SMTP 邮件通知
|
||||
## smtp_server 填写 SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
|
||||
export SMTP_SERVER=""
|
||||
## smtp_ssl 填写 SMTP 发送邮件服务器是否使用 SSL,内容应为 true 或 false
|
||||
export SMTP_SSL="false"
|
||||
## smtp_email 填写 SMTP 收发件邮箱,通知将会由自己发给自己
|
||||
export SMTP_EMAIL=""
|
||||
## smtp_password 填写 SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
||||
export SMTP_PASSWORD=""
|
||||
## smtp_name 填写 SMTP 收发件人姓名,可随意填写
|
||||
export SMTP_NAME=""
|
||||
|
||||
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
||||
|
||||
+262
-76
@@ -38,12 +38,19 @@ let SCKEY = '';
|
||||
//此处填你申请的PushDeer KEY.
|
||||
//(环境变量名 DEER_KEY)
|
||||
let PUSHDEER_KEY = '';
|
||||
let PUSHDEER_URL = '';
|
||||
|
||||
// =======================================Synology Chat通知设置区域===========================================
|
||||
//此处填你申请的CHAT_URL与CHAT_TOKEN
|
||||
//(环境变量名 CHAT_URL CHAT_TOKEN)
|
||||
let CHAT_URL = '';
|
||||
let CHAT_TOKEN = '';
|
||||
|
||||
// =======================================Bark App通知设置区域===========================================
|
||||
//此处填你BarkAPP的信息(IP/设备码,例如:https://api.day.app/XXXXXXXX)
|
||||
let BARK_PUSH = '';
|
||||
//BARK app推送图标,自定义推送图标(需iOS15或以上)
|
||||
let BARK_ICON = 'http://qn.whyour.cn/logo.png';
|
||||
let BARK_ICON = 'https://qn.whyour.cn/logo.png';
|
||||
//BARK app推送铃声,铃声列表去APP查看复制填写
|
||||
let BARK_SOUND = '';
|
||||
//BARK app推送消息的分组, 默认为"QingLong"
|
||||
@@ -97,6 +104,39 @@ let IGOT_PUSH_KEY = '';
|
||||
let PUSH_PLUS_TOKEN = '';
|
||||
let PUSH_PLUS_USER = '';
|
||||
|
||||
// =======================================Cool Push设置区域=======================================
|
||||
//官方文档:https://cp.xuthus.cc/docs
|
||||
//QQ_SKEY: Cool Push登录授权后推送消息的调用代码Skey
|
||||
//QQ_MODE: 推送模式详情请登录获取QQ_SKEY后见https://cp.xuthus.cc/feat
|
||||
let QQ_SKEY = '';
|
||||
let QQ_MODE = '';
|
||||
|
||||
// =======================================智能微秘书设置区域=======================================
|
||||
//官方文档:http://wechat.aibotk.com/docs/about
|
||||
//AIBOTK_KEY: 填写智能微秘书个人中心的apikey
|
||||
//AIBOTK_TYPE:填写发送的目标 room 或 contact, 填其他的不生效
|
||||
//AIBOTK_NAME: 填写群名或用户昵称,和上面的type类型要对应
|
||||
let AIBOTK_KEY = '';
|
||||
let AIBOTK_TYPE = '';
|
||||
let AIBOTK_NAME = '';
|
||||
|
||||
// =======================================飞书机器人设置区域=======================================
|
||||
//官方文档:https://www.feishu.cn/hc/zh-CN/articles/360024984973
|
||||
//FSKEY 飞书机器人的 FSKEY
|
||||
let FSKEY = '';
|
||||
|
||||
// =======================================SMTP 邮件设置区域=======================================
|
||||
// SMTP_SERVER: 填写 SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
|
||||
// SMTP_SSL: 填写 SMTP 发送邮件服务器是否使用 SSL,内容应为 true 或 false
|
||||
// SMTP_EMAIL: 填写 SMTP 收发件邮箱,通知将会由自己发给自己
|
||||
// SMTP_PASSWORD: 填写 SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
||||
// SMTP_NAME: 填写 SMTP 收发件人姓名,可随意填写
|
||||
let SMTP_SERVER = '';
|
||||
let SMTP_SSL = 'false';
|
||||
let SMTP_EMAIL = '';
|
||||
let SMTP_PASSWORD = '';
|
||||
let SMTP_NAME = '';
|
||||
|
||||
//==========================云端环境变量的判断与接收=========================
|
||||
if (process.env.GOTIFY_URL) {
|
||||
GOTIFY_URL = process.env.GOTIFY_URL;
|
||||
@@ -124,6 +164,15 @@ if (process.env.PUSH_KEY) {
|
||||
|
||||
if (process.env.DEER_KEY) {
|
||||
PUSHDEER_KEY = process.env.DEER_KEY;
|
||||
PUSHDEER_URL = process.env.DEER_URL;
|
||||
}
|
||||
|
||||
if (process.env.CHAT_URL) {
|
||||
CHAT_URL = process.env.CHAT_URL;
|
||||
}
|
||||
|
||||
if (process.env.CHAT_TOKEN) {
|
||||
CHAT_TOKEN = process.env.CHAT_TOKEN;
|
||||
}
|
||||
|
||||
if (process.env.QQ_SKEY) {
|
||||
@@ -199,6 +248,36 @@ if (process.env.PUSH_PLUS_TOKEN) {
|
||||
if (process.env.PUSH_PLUS_USER) {
|
||||
PUSH_PLUS_USER = process.env.PUSH_PLUS_USER;
|
||||
}
|
||||
|
||||
if (process.env.AIBOTK_KEY) {
|
||||
AIBOTK_KEY = process.env.AIBOTK_KEY;
|
||||
}
|
||||
if (process.env.AIBOTK_TYPE) {
|
||||
AIBOTK_TYPE = process.env.AIBOTK_TYPE;
|
||||
}
|
||||
if (process.env.AIBOTK_NAME) {
|
||||
AIBOTK_NAME = process.env.AIBOTK_NAME;
|
||||
}
|
||||
|
||||
if (process.env.FSKEY) {
|
||||
FSKEY = process.env.FSKEY;
|
||||
}
|
||||
|
||||
if (process.env.SMTP_SERVER) {
|
||||
SMTP_SERVER = process.env.SMTP_SERVER;
|
||||
}
|
||||
if (process.env.SMTP_SSL) {
|
||||
SMTP_SSL = process.env.SMTP_SSL;
|
||||
}
|
||||
if (process.env.SMTP_EMAIL) {
|
||||
SMTP_EMAIL = process.env.SMTP_EMAIL;
|
||||
}
|
||||
if (process.env.SMTP_PASSWORD) {
|
||||
SMTP_PASSWORD = process.env.SMTP_PASSWORD;
|
||||
}
|
||||
if (process.env.SMTP_NAME) {
|
||||
SMTP_NAME = process.env.SMTP_NAME;
|
||||
}
|
||||
//==========================云端环境变量的判断与接收=========================
|
||||
|
||||
/**
|
||||
@@ -217,6 +296,16 @@ async function sendNotify(
|
||||
) {
|
||||
//提供6种通知
|
||||
desp += author; //增加作者信息,防止被贩卖等
|
||||
|
||||
// 根据标题跳过一些消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔
|
||||
let skipTitle = process.env.SKIP_PUSH_TITLE
|
||||
if(skipTitle) {
|
||||
if(skipTitle.split('\n').includes(text)) {
|
||||
console.info(text + "在SKIP_PUSH_TITLE环境变量内,跳过推送!");
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
serverNotify(text, desp), //微信server酱
|
||||
pushPlusNotify(text, desp), //pushplus(推送加)
|
||||
@@ -232,6 +321,11 @@ async function sendNotify(
|
||||
iGotNotify(text, desp, params), //iGot
|
||||
gobotNotify(text, desp), //go-cqhttp
|
||||
gotifyNotify(text, desp), //gotify
|
||||
ChatNotify(text, desp), //synolog chat
|
||||
PushDeerNotify(text, desp), //PushDeer
|
||||
aibotkNotify(text, desp), //智能微秘书
|
||||
fsBotNotify(text, desp), //飞书机器人
|
||||
smtpNotify(text, desp), //SMTP 邮件
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -272,7 +366,7 @@ function gotifyNotify(text, desp) {
|
||||
});
|
||||
}
|
||||
|
||||
function gobotNotify(text, desp, time = 2100) {
|
||||
function gobotNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (GOBOT_URL) {
|
||||
const options = {
|
||||
@@ -283,7 +377,6 @@ function gobotNotify(text, desp, time = 2100) {
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
setTimeout(() => {
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
@@ -296,9 +389,7 @@ function gobotNotify(text, desp, time = 2100) {
|
||||
} else if (data.retcode === 100) {
|
||||
console.log(`go-cqhttp发送通知消息异常: ${data.errmsg}\n`);
|
||||
} else {
|
||||
console.log(
|
||||
`go-cqhttp发送通知消息异常\n${JSON.stringify(data)}`,
|
||||
);
|
||||
console.log(`go-cqhttp发送通知消息异常\n${JSON.stringify(data)}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -307,14 +398,13 @@ function gobotNotify(text, desp, time = 2100) {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
}, time);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function serverNotify(text, desp, time = 2100) {
|
||||
function serverNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (SCKEY) {
|
||||
//微信server酱推送通知一个\n不会换行,需要两个\n才能换行,故做此替换
|
||||
@@ -329,7 +419,6 @@ function serverNotify(text, desp, time = 2100) {
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
setTimeout(() => {
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
@@ -344,9 +433,7 @@ function serverNotify(text, desp, time = 2100) {
|
||||
// 一分钟内发送相同的内容会触发
|
||||
console.log(`server酱发送通知消息异常: ${data.errmsg}\n`);
|
||||
} else {
|
||||
console.log(
|
||||
`server酱发送通知消息异常\n${JSON.stringify(data)}`,
|
||||
);
|
||||
console.log(`server酱发送通知消息异常\n${JSON.stringify(data)}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -355,27 +442,25 @@ function serverNotify(text, desp, time = 2100) {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
}, time);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function PushDeerNotify(text, desp, time = 2100) {
|
||||
function PushDeerNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (PUSHDEER_KEY) {
|
||||
// PushDeer 建议对消息内容进行 urlencode
|
||||
desp = encodeURI(desp);
|
||||
const options = {
|
||||
url: `https://api2.pushdeer.com/message/push`,
|
||||
url: PUSHDEER_URL || `https://api2.pushdeer.com/message/push`,
|
||||
body: `pushkey=${PUSHDEER_KEY}&text=${text}&desp=${desp}&type=markdown`,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
setTimeout(() => {
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
@@ -390,9 +475,7 @@ function PushDeerNotify(text, desp, time = 2100) {
|
||||
) {
|
||||
console.log('PushDeer发送通知消息成功🎉\n');
|
||||
} else {
|
||||
console.log(
|
||||
`PushDeer发送通知消息异常\n${JSON.stringify(data)}`,
|
||||
);
|
||||
console.log(`PushDeer发送通知消息异常\n${JSON.stringify(data)}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -401,80 +484,39 @@ function PushDeerNotify(text, desp, time = 2100) {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
}, time);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function CoolPush(text, desp) {
|
||||
function ChatNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (QQ_SKEY) {
|
||||
let options = {
|
||||
url: `https://push.xuthus.cc/${QQ_MODE}/${QQ_SKEY}`,
|
||||
if (CHAT_URL && CHAT_TOKEN) {
|
||||
// 对消息内容进行 urlencode
|
||||
desp = encodeURI(desp);
|
||||
const options = {
|
||||
url: `${CHAT_URL}${CHAT_TOKEN}`,
|
||||
body: `payload={"text":"${text}\n${desp}"}`,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
};
|
||||
|
||||
// 已知敏感词
|
||||
text = text.replace(/京豆/g, '豆豆');
|
||||
desp = desp.replace(/京豆/g, '');
|
||||
desp = desp.replace(/🐶/g, '');
|
||||
desp = desp.replace(/红包/g, 'H包');
|
||||
|
||||
switch (QQ_MODE) {
|
||||
case 'email':
|
||||
options.json = {
|
||||
t: text,
|
||||
c: desp,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
options.body = `${text}\n\n${desp}`;
|
||||
}
|
||||
|
||||
let pushMode = function (t) {
|
||||
switch (t) {
|
||||
case 'send':
|
||||
return '个人';
|
||||
case 'group':
|
||||
return 'QQ群';
|
||||
case 'wx':
|
||||
return '微信';
|
||||
case 'ww':
|
||||
return '企业微信';
|
||||
case 'email':
|
||||
return '邮件';
|
||||
default:
|
||||
return '未知方式';
|
||||
}
|
||||
};
|
||||
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log(`发送${pushMode(QQ_MODE)}通知调用API失败!!\n`);
|
||||
console.log('发送通知调用API失败!!\n');
|
||||
console.log(err);
|
||||
} else {
|
||||
data = JSON.parse(data);
|
||||
if (data.code === 200) {
|
||||
console.log(`酷推发送${pushMode(QQ_MODE)}通知消息成功🎉\n`);
|
||||
} else if (data.code === 400) {
|
||||
console.log(
|
||||
`QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${
|
||||
data.msg
|
||||
}\n`,
|
||||
);
|
||||
} else if (data.code === 503) {
|
||||
console.log(`QQ酷推出错,${data.message}:${data.data}\n`);
|
||||
if (data.success) {
|
||||
console.log('Chat发送通知消息成功🎉\n');
|
||||
} else {
|
||||
console.log(`酷推推送异常: ${JSON.stringify(data)}`);
|
||||
console.log(`Chat发送通知消息异常\n${JSON.stringify(data)}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e, resp);
|
||||
$.logErr(e);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
@@ -723,9 +765,9 @@ function qywxamNotify(text, desp) {
|
||||
timeout,
|
||||
};
|
||||
$.post(options_accesstoken, (err, resp, data) => {
|
||||
html = desp.replace(/\n/g, '<br/>');
|
||||
var json = JSON.parse(data);
|
||||
accesstoken = json.access_token;
|
||||
let html = desp.replace(/\n/g, '<br/>');
|
||||
let json = JSON.parse(data);
|
||||
let accesstoken = json.access_token;
|
||||
let options;
|
||||
|
||||
switch (QYWX_AM_AY[4]) {
|
||||
@@ -921,6 +963,150 @@ function pushPlusNotify(text, desp) {
|
||||
});
|
||||
}
|
||||
|
||||
function aibotkNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (AIBOTK_KEY && AIBOTK_TYPE && AIBOTK_NAME) {
|
||||
let json = {};
|
||||
let url = '';
|
||||
switch (AIBOTK_TYPE) {
|
||||
case 'room':
|
||||
url = 'https://api-bot.aibotk.com/openapi/v1/chat/room';
|
||||
json = {
|
||||
apiKey: `${AIBOTK_KEY}`,
|
||||
roomName: `${AIBOTK_NAME}`,
|
||||
message: {
|
||||
type: 1,
|
||||
content: `【青龙快讯】\n\n${text}\n${desp}`,
|
||||
},
|
||||
};
|
||||
break;
|
||||
case 'contact':
|
||||
url = 'https://api-bot.aibotk.com/openapi/v1/chat/contact';
|
||||
json = {
|
||||
apiKey: `${AIBOTK_KEY}`,
|
||||
name: `${AIBOTK_NAME}`,
|
||||
message: {
|
||||
type: 1,
|
||||
content: `【青龙快讯】\n\n${text}\n${desp}`,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
const options = {
|
||||
url: url,
|
||||
json,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log('智能微秘书发送通知消息失败!!\n');
|
||||
console.log(err);
|
||||
} else {
|
||||
data = JSON.parse(data);
|
||||
if (data.code === 0) {
|
||||
console.log('智能微秘书发送通知消息成功🎉。\n');
|
||||
} else {
|
||||
console.log(`${data.error}\n`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e, resp);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function fsBotNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (FSKEY) {
|
||||
const options = {
|
||||
url: `https://open.feishu.cn/open-apis/bot/v2/hook/${FSKEY}`,
|
||||
json: { msg_type: 'text', content: { text: `${text}\n\n${desp}` } },
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log('发送通知调用API失败!!\n');
|
||||
console.log(err);
|
||||
} else {
|
||||
data = JSON.parse(data);
|
||||
if (data.StatusCode === 0) {
|
||||
console.log('飞书发送通知消息成功🎉\n');
|
||||
} else {
|
||||
console.log(`${data.msg}\n`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e, resp);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function smtpNotify(text, desp) {
|
||||
if (![SMTP_SERVER, SMTP_EMAIL, SMTP_PASSWORD].every(Boolean)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const nodemailer = require('nodemailer');
|
||||
const transporter = nodemailer.createTransport(
|
||||
`${SMTP_SSL === 'true' ? 'smtps:' : 'smtp:'}//${SMTP_SERVER}`,
|
||||
{
|
||||
auth: {
|
||||
user: SMTP_EMAIL,
|
||||
pass: SMTP_PASSWORD,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const addr = SMTP_NAME ? `"${SMTP_NAME}" <${SMTP_EMAIL}>` : SMTP_EMAIL;
|
||||
const info = await transporter.sendMail({
|
||||
from: addr,
|
||||
to: addr,
|
||||
subject: text,
|
||||
text: desp,
|
||||
});
|
||||
|
||||
if (!!info.messageId) {
|
||||
console.log('SMTP发送通知消息成功🎉\n');
|
||||
return true;
|
||||
}
|
||||
console.log('SMTP发送通知消息失败!!\n');
|
||||
} catch (e) {
|
||||
console.log('SMTP发送通知消息出现错误!!\n');
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
|
||||
function smtpNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (SMTP_SERVER && SMTP_SSL && SMTP_EMAIL && SMTP_PASSWORD && SMTP_NAME) {
|
||||
// todo: Node.js并没有内置的 smtp 实现,需要调用外部库,因为不清楚这个文件的模块依赖情况,所以留给有缘人实现
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sendNotify,
|
||||
BARK_PUSH,
|
||||
|
||||
@@ -9,6 +9,10 @@ import re
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import smtplib
|
||||
from email.mime.text import MIMEText
|
||||
from email.header import Header
|
||||
from email.utils import formataddr
|
||||
|
||||
import requests
|
||||
|
||||
@@ -61,6 +65,10 @@ push_config = {
|
||||
'PUSH_KEY': '', # server 酱的 PUSH_KEY,兼容旧版与 Turbo 版
|
||||
|
||||
'DEER_KEY': '', # PushDeer 的 PUSHDEER_KEY
|
||||
'DEER_URL': '', # PushDeer 的 PUSHDEER_URL
|
||||
|
||||
'CHAT_URL': '', # synology chat url
|
||||
'CHAT_TOKEN': '', # synology chat token
|
||||
|
||||
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
||||
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
||||
@@ -78,6 +86,16 @@ push_config = {
|
||||
'TG_PROXY_AUTH': '', # tg 代理认证参数
|
||||
'TG_PROXY_HOST': '', # tg 机器人的 TG_PROXY_HOST
|
||||
'TG_PROXY_PORT': '', # tg 机器人的 TG_PROXY_PORT
|
||||
|
||||
'AIBOTK_KEY': '', # 智能微秘书 个人中心的apikey 文档地址:http://wechat.aibotk.com/docs/about
|
||||
'AIBOTK_TYPE': '', # 智能微秘书 发送目标 room 或 contact
|
||||
'AIBOTK_NAME': '', # 智能微秘书 发送群名 或者好友昵称和type要对应好
|
||||
|
||||
'SMTP_SERVER': '', # SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
|
||||
'SMTP_SSL': 'false', # SMTP 发送邮件服务器是否使用 SSL,填写 true 或 false
|
||||
'SMTP_EMAIL': '', # SMTP 收发件邮箱,通知将会由自己发给自己
|
||||
'SMTP_PASSWORD': '', # SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
||||
'SMTP_NAME': '', # SMTP 收发件人姓名,可随意填写
|
||||
}
|
||||
notify_function = []
|
||||
# fmt: on
|
||||
@@ -273,6 +291,9 @@ def pushdeer(title: str, content: str) -> None:
|
||||
print("PushDeer 服务启动")
|
||||
data = {"text": title, "desp": content, "type": "markdown", "pushkey": push_config.get("DEER_KEY")}
|
||||
url = 'https://api2.pushdeer.com/message/push'
|
||||
if push_config.get("DEER_URL"):
|
||||
url = push_config.get("DEER_URL")
|
||||
|
||||
response = requests.post(url, data=data).json()
|
||||
|
||||
if len(response.get("content").get("result")) > 0:
|
||||
@@ -281,6 +302,25 @@ def pushdeer(title: str, content: str) -> None:
|
||||
print("PushDeer 推送失败!错误信息:", response)
|
||||
|
||||
|
||||
def chat(title: str, content: str) -> None:
|
||||
"""
|
||||
通过Chat 推送消息
|
||||
"""
|
||||
if not push_config.get("CHAT_URL") or not push_config.get("CHAT_TOKEN"):
|
||||
print("chat 服务的 CHAT_URL或CHAT_TOKEN 未设置!!\n取消推送")
|
||||
return
|
||||
print("chat 服务启动")
|
||||
data = 'payload=' + json.dumps({'text': title + '\n' + content})
|
||||
url = push_config.get("CHAT_URL") + push_config.get("CHAT_TOKEN")
|
||||
response = requests.post(url, data=data)
|
||||
|
||||
if response.status_code == 200:
|
||||
print("Chat 推送成功!")
|
||||
else:
|
||||
print("Chat 推送失败!错误信息:", response)
|
||||
|
||||
|
||||
|
||||
def pushplus_bot(title: str, content: str) -> None:
|
||||
"""
|
||||
通过 push+ 推送消息。
|
||||
@@ -499,6 +539,63 @@ def telegram_bot(title: str, content: str) -> None:
|
||||
print("tg 推送失败!")
|
||||
|
||||
|
||||
def aibotk(title: str, content: str) -> None:
|
||||
"""
|
||||
使用 智能微秘书 推送消息。
|
||||
"""
|
||||
if not push_config.get("AIBOTK_KEY") or not push_config.get("AIBOTK_TYPE") or not push_config.get("AIBOTK_NAME"):
|
||||
print("智能微秘书 的 AIBOTK_KEY 或者 AIBOTK_TYPE 或者 AIBOTK_NAME 未设置!!\n取消推送")
|
||||
return
|
||||
print("智能微秘书 服务启动")
|
||||
|
||||
if push_config.get("AIBOTK_TYPE") == 'room':
|
||||
url = "https://api-bot.aibotk.com/openapi/v1/chat/room"
|
||||
data = {
|
||||
"apiKey": push_config.get("AIBOTK_KEY"),
|
||||
"roomName": push_config.get("AIBOTK_NAME"),
|
||||
"message": {"type": 1, "content": f'【青龙快讯】\n\n${title}\n${content}' }
|
||||
}
|
||||
else:
|
||||
url = "https://api-bot.aibotk.com/openapi/v1/chat/contact"
|
||||
data = {
|
||||
"apiKey": push_config.get("AIBOTK_KEY"),
|
||||
"name": push_config.get("AIBOTK_NAME"),
|
||||
"message": {"type": 1, "content": f'【青龙快讯】\n\n${title}\n${content}' }
|
||||
}
|
||||
body = json.dumps(data).encode(encoding="utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
response = requests.post(url=url, data=body, headers=headers).json()
|
||||
print(response)
|
||||
if response["code"] == 0:
|
||||
print("智能微秘书 推送成功!")
|
||||
else:
|
||||
print(f'智能微秘书 推送失败!{response["error"]}')
|
||||
|
||||
|
||||
def smtp(title: str, content: str) -> None:
|
||||
"""
|
||||
使用 SMTP 邮件 推送消息。
|
||||
"""
|
||||
if not push_config.get("SMTP_SERVER") or not push_config.get("SMTP_SSL") or not push_config.get("SMTP_EMAIL") or not push_config.get("SMTP_PASSWORD") or not push_config.get("SMTP_NAME"):
|
||||
print("SMTP 邮件 的 SMTP_SERVER 或者 SMTP_SSL 或者 SMTP_EMAIL 或者 SMTP_PASSWORD 或者 SMTP_NAME 未设置!!\n取消推送")
|
||||
return
|
||||
print("SMTP 邮件 服务启动")
|
||||
|
||||
message = MIMEText(content, 'plain', 'utf-8')
|
||||
message['From'] = formataddr((Header(push_config.get("SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL")))
|
||||
message['To'] = formataddr((Header(push_config.get("SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL")))
|
||||
message['Subject'] = Header(title, 'utf-8')
|
||||
|
||||
try:
|
||||
smtp_server = smtplib.SMTP_SSL(push_config.get("SMTP_SERVER")) if push_config.get("SMTP_SSL") == 'true' else smtplib.SMTP(push_config.get("SMTP_SERVER"))
|
||||
smtp_server.login(push_config.get("SMTP_EMAIL"), push_config.get("SMTP_PASSWORD"))
|
||||
smtp_server.sendmail(push_config.get("SMTP_EMAIL"), push_config.get("SMTP_EMAIL"), message.as_bytes())
|
||||
smtp_server.close()
|
||||
print("SMTP 邮件 推送成功!")
|
||||
except Exception as e:
|
||||
print(f'SMTP 邮件 推送失败!{e}')
|
||||
|
||||
|
||||
def one() -> str:
|
||||
"""
|
||||
获取一条一言。
|
||||
@@ -527,6 +624,8 @@ if push_config.get("PUSH_KEY"):
|
||||
notify_function.append(serverJ)
|
||||
if push_config.get("DEER_KEY"):
|
||||
notify_function.append(pushdeer)
|
||||
if push_config.get("CHAT_URL") and push_config.get("CHAT_TOKEN"):
|
||||
notify_function.append(chat)
|
||||
if push_config.get("PUSH_PLUS_TOKEN"):
|
||||
notify_function.append(pushplus_bot)
|
||||
if push_config.get("QMSG_KEY") and push_config.get("QMSG_TYPE"):
|
||||
@@ -537,6 +636,10 @@ if push_config.get("QYWX_KEY"):
|
||||
notify_function.append(wecom_bot)
|
||||
if push_config.get("TG_BOT_TOKEN") and push_config.get("TG_USER_ID"):
|
||||
notify_function.append(telegram_bot)
|
||||
if push_config.get("AIBOTK_KEY") and push_config.get("AIBOTK_TYPE") and push_config.get("AIBOTK_NAME"):
|
||||
notify_function.append(aibotk)
|
||||
if push_config.get("SMTP_SERVER") and push_config.get("SMTP_SSL") and push_config.get("SMTP_EMAIL") and push_config.get("SMTP_PASSWORD") and push_config.get("SMTP_NAME"):
|
||||
notify_function.append(smtp)
|
||||
|
||||
|
||||
def send(title: str, content: str) -> None:
|
||||
@@ -544,6 +647,13 @@ def send(title: str, content: str) -> None:
|
||||
print(f"{title} 推送内容为空!")
|
||||
return
|
||||
|
||||
# 根据标题跳过一些消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔
|
||||
skipTitle = os.getenv("SKIP_PUSH_TITLE")
|
||||
if skipTitle:
|
||||
if (title in re.split("\n", skipTitle)):
|
||||
print(f"{title} 在SKIP_PUSH_TITLE环境变量内,跳过推送!")
|
||||
return
|
||||
|
||||
hitokoto = push_config.get("HITOKOTO")
|
||||
|
||||
text = one() if hitokoto else ""
|
||||
|
||||
+2
-1
@@ -5,8 +5,9 @@
|
||||
"dependencies": {
|
||||
"crypto-js": "^4.0.0",
|
||||
"download": "^8.0.0",
|
||||
"http-server": "^0.12.3",
|
||||
"got": "^11.5.1",
|
||||
"http-server": "^0.12.3",
|
||||
"nodemailer": "^6.8.0",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"request": "^2.88.2",
|
||||
"tough-cookie": "^4.0.0",
|
||||
|
||||
+2
-2
@@ -5,14 +5,14 @@ const envFound = dotenv.config();
|
||||
const accessKey = process.env.QINIU_AK;
|
||||
const secretKey = process.env.QINIU_SK;
|
||||
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
|
||||
const key = 'version.ts';
|
||||
const key = 'version.yaml';
|
||||
const options = {
|
||||
scope: `${process.env.QINIU_SCOPE}:${key}`,
|
||||
};
|
||||
const putPolicy = new qiniu.rs.PutPolicy(options);
|
||||
const uploadToken = putPolicy.uploadToken(mac);
|
||||
|
||||
const localFile = 'src/version.ts';
|
||||
const localFile = 'version.yaml';
|
||||
const config = new qiniu.conf.Config({ zone: qiniu.zone.Zone_z1 });
|
||||
const formUploader = new qiniu.form_up.FormUploader(config);
|
||||
const putExtra = new qiniu.form_up.PutExtra(
|
||||
|
||||
+52
-14
@@ -1,7 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
get_token() {
|
||||
token=$(ts-node-transpile-only "$dir_shell/token.ts")
|
||||
if [[ -f $file_auth_token ]]; then
|
||||
token=$(cat $file_auth_token | jq -r .value)
|
||||
else
|
||||
local token_command="ts-node-transpile-only ${dir_root}/back/token.ts"
|
||||
local token_file="${dir_root}static/build/token.js"
|
||||
if [[ -f $token_file ]]; then
|
||||
token_command="node ${token_file}"
|
||||
fi
|
||||
token=$(eval "$token_command")
|
||||
fi
|
||||
}
|
||||
|
||||
add_cron_api() {
|
||||
@@ -10,10 +19,16 @@ add_cron_api() {
|
||||
local schedule=$(echo "$1" | awk -F ":" '{print $1}')
|
||||
local command=$(echo "$1" | awk -F ":" '{print $2}')
|
||||
local name=$(echo "$1" | awk -F ":" '{print $3}')
|
||||
local sub_id=$(echo "$1" | awk -F ":" '{print $4}')
|
||||
else
|
||||
local schedule=$1
|
||||
local command=$2
|
||||
local name=$3
|
||||
local sub_id=$4
|
||||
fi
|
||||
|
||||
if [[ ! $sub_id ]];then
|
||||
sub_id="null"
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
@@ -25,11 +40,11 @@ add_cron_api() {
|
||||
-H "Origin: http://0.0.0.0:5700" \
|
||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
||||
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\"}" \
|
||||
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "$name -> 添加成功"
|
||||
else
|
||||
@@ -64,8 +79,8 @@ update_cron_api() {
|
||||
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\",\"id\":\"$id\"}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "$name -> 更新成功"
|
||||
else
|
||||
@@ -96,8 +111,8 @@ update_cron_command_api() {
|
||||
--data-raw "{\"command\":\"$command\",\"id\":\"$id\"}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "$command -> 更新成功"
|
||||
else
|
||||
@@ -121,8 +136,8 @@ del_cron_api() {
|
||||
--data-raw "[$ids]" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "成功"
|
||||
else
|
||||
@@ -151,8 +166,8 @@ update_cron() {
|
||||
--data-raw "{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code != 200 ]]; then
|
||||
echo -e "\n## 更新任务状态失败(${message})\n" >>$dir_log/$log_path
|
||||
fi
|
||||
@@ -175,8 +190,8 @@ notify_api() {
|
||||
--data-raw "{\"title\":\"$title\",\"content\":\"$content\"}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "通知发送成功"
|
||||
else
|
||||
@@ -184,4 +199,27 @@ notify_api() {
|
||||
fi
|
||||
}
|
||||
|
||||
find_cron_api() {
|
||||
local params=$1
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/detail?$params&t=$currentTimeStamp" \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
-H "Origin: http://0.0.0.0:5700" \
|
||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
||||
--compressed
|
||||
)
|
||||
data=$(echo "$api" | jq -r .data)
|
||||
if [[ $data == 'null' ]]; then
|
||||
echo -e ""
|
||||
else
|
||||
name=$(echo "$api" | jq -r .data.name)
|
||||
echo -e "$name"
|
||||
fi
|
||||
}
|
||||
|
||||
get_token
|
||||
|
||||
+1
-2
@@ -35,8 +35,7 @@ fi
|
||||
cp -f "$repo_path/jbot/requirements.txt" "$dir_data"
|
||||
|
||||
cd $dir_data
|
||||
cat requirements.txt | while read LREAD
|
||||
do
|
||||
cat requirements.txt | while read LREAD; do
|
||||
if [[ ! $(pip3 show "${LREAD%%=*}" 2>/dev/null) ]]; then
|
||||
pip3 --default-timeout=100 install ${LREAD}
|
||||
fi
|
||||
|
||||
+9
-1
@@ -31,6 +31,7 @@ copy_dep() {
|
||||
echo -e "---> 2. 复制nginx配置文件\n"
|
||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
||||
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
|
||||
echo -e "---> 配置文件复制完成\n"
|
||||
}
|
||||
|
||||
@@ -86,10 +87,17 @@ check_pm2() {
|
||||
fi
|
||||
}
|
||||
|
||||
start_public() {
|
||||
echo -e "=====> 启动公开服务\n"
|
||||
pm2 delete public --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
|
||||
}
|
||||
|
||||
main() {
|
||||
echo -e "=====> 开始检测"
|
||||
npm i -g pnpm
|
||||
pnpm add -g pm2
|
||||
patch_version
|
||||
start_public
|
||||
copy_dep
|
||||
check_ql
|
||||
check_nginx
|
||||
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
## 导入通用变量与函数
|
||||
dir_shell=$QL_DIR/shell
|
||||
. $dir_shell/share.sh
|
||||
. $dir_shell/api.sh
|
||||
|
||||
trap "single_hanle" 2 20 15 14
|
||||
single_hanle() {
|
||||
handle_task_after "$@"
|
||||
exit 1
|
||||
}
|
||||
|
||||
random_delay() {
|
||||
local random_delay_max=$RandomDelay
|
||||
if [[ $random_delay_max ]] && [[ $random_delay_max -gt 0 ]]; then
|
||||
local file_param=$1
|
||||
local file_extensions=${RandomDelayFileExtensions-"js"}
|
||||
local ignored_minutes=${RandomDelayIgnoredMinutes-"0 30"}
|
||||
|
||||
if [[ -n $file_extensions ]]; then
|
||||
if ! echo "$file_param" | grep -qE "\.${file_extensions// /$|\\.}$"; then
|
||||
# echo -e "\n当前文件需要准点运行, 放弃随机延迟\n"
|
||||
return
|
||||
fi
|
||||
fi
|
||||
|
||||
local current_min
|
||||
current_min=$(date "+%-M")
|
||||
for minute in $ignored_minutes; do
|
||||
if [[ $current_min -eq $minute ]]; then
|
||||
# echo -e "\n当前时间需要准点运行, 放弃随机延迟\n"
|
||||
return
|
||||
fi
|
||||
done
|
||||
|
||||
local delay_second=$(($(gen_random_num "$random_delay_max") + 1))
|
||||
echo -e "\n命令未添加 \"now\",随机延迟 $delay_second 秒后执行\n"
|
||||
sleep $delay_second
|
||||
fi
|
||||
}
|
||||
|
||||
## scripts目录下所有可运行脚本数组
|
||||
gen_array_scripts() {
|
||||
local dir_current=$(pwd)
|
||||
local i="-1"
|
||||
cd $dir_scripts
|
||||
for file in $(ls); do
|
||||
if [[ -f $file ]] && [[ $file == *.js && $file != sendNotify.js ]]; then
|
||||
let i++
|
||||
array_scripts[i]=$(echo "$file" | perl -pe "s|$dir_scripts/||g")
|
||||
array_scripts_name[i]=$(grep "new Env" $file | awk -F "'|\"" '{print $2}' | head -1)
|
||||
[[ -z ${array_scripts_name[i]} ]] && array_scripts_name[i]="<未识别出活动名称>"
|
||||
fi
|
||||
done
|
||||
cd $dir_current
|
||||
}
|
||||
|
||||
## 使用说明
|
||||
usage() {
|
||||
gen_array_scripts
|
||||
echo -e "task命令运行本程序自动添加进crontab的脚本,需要输入脚本的绝对路径或去掉 “$dir_scripts/” 目录后的相对路径(定时任务中请写作相对路径),用法为:"
|
||||
echo -e "1.$cmd_task <file_name> # 依次执行,如果设置了随机延迟,将随机延迟一定秒数"
|
||||
echo -e "2.$cmd_task <file_name> now # 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日志,同时记录在日志文件中"
|
||||
echo -e "3.$cmd_task <file_name> conc <环境变量名称> <账号编号,空格分隔>(可选的) # 并发执行,无论是否设置了随机延迟,均立即运行,前台不产生日志,直接记录在日志文件中,且可指定账号执行"
|
||||
echo -e "4.$cmd_task <file_name> desi <环境变量名称> <账号编号,空格分隔> # 指定账号执行,无论是否设置了随机延迟,均立即运行"
|
||||
if [[ ${#array_scripts[*]} -gt 0 ]]; then
|
||||
echo -e "\n当前有以下脚本可以运行:"
|
||||
for ((i = 0; i < ${#array_scripts[*]}; i++)); do
|
||||
echo -e "$(($i + 1)). ${array_scripts_name[i]}:${array_scripts[i]}"
|
||||
done
|
||||
else
|
||||
echo -e "\n暂无脚本可以执行"
|
||||
fi
|
||||
}
|
||||
|
||||
## run nohup,$1:文件名,不含路径,带后缀
|
||||
run_nohup() {
|
||||
local file_name=$1
|
||||
nohup node $file_name &>$log_path &
|
||||
}
|
||||
|
||||
check_server() {
|
||||
if [[ $cpu_warn ]] && [[ $mem_warn ]] && [[ $disk_warn ]]; then
|
||||
local top_result=$(top -b -n 1)
|
||||
cpu_use=$(echo "$top_result" | grep CPU | grep -v -E 'grep|PID' | awk '{print $2}' | cut -f 1 -d "%" | head -n 1)
|
||||
|
||||
mem_free=$(free -m | grep "Mem" | awk '{print $3}' | head -n 1)
|
||||
mem_total=$(free -m | grep "Mem" | awk '{print $2}' | head -n 1)
|
||||
mem_use=$(printf "%d%%" $((mem_free * 100 / mem_total)) | cut -f 1 -d "%" | head -n 1)
|
||||
|
||||
disk_use=$(df -P | grep /dev | grep -v -E '(tmp|boot|shm)' | awk '{print $5}' | cut -f 1 -d "%" | head -n 1)
|
||||
if [[ $cpu_use -gt $cpu_warn ]] && [[ $cpu_warn ]] || [[ $mem_free -lt $mem_warn ]] || [[ $disk_use -gt $disk_warn ]]; then
|
||||
local resource=$(echo "$top_result" | grep -v -E 'grep|Mem|idle|Load|tr' | awk '{$2="";$3="";$4="";$5="";$7="";print $0}' | head -n 10 | tr '\n' '|' | sed s/\|/\\\\n/g)
|
||||
notify_api "服务器资源异常警告" "当前CPU占用 $cpu_use% 内存占用 $mem_use% 磁盘占用 $disk_use% \n资源占用详情 \n\n $resource"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
handle_task_before() {
|
||||
begin_time=$(format_time "$time_format" "$time")
|
||||
begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||
|
||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
|
||||
echo -e "## 开始执行... $begin_time\n"
|
||||
|
||||
[[ $is_macos -eq 0 ]] && check_server
|
||||
|
||||
if [[ -s $task_error_log_path ]]; then
|
||||
eval cat $task_error_log_path $cmd
|
||||
eval echo -e "加载 config.sh 出错,请手动检查" $cmd
|
||||
eval echo $cmd
|
||||
fi
|
||||
|
||||
. $file_task_before "$@"
|
||||
}
|
||||
|
||||
handle_task_after() {
|
||||
. $file_task_after "$@"
|
||||
|
||||
local etime=$(date "+$time_format")
|
||||
local end_time=$(format_time "$time_format" "$etime")
|
||||
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
||||
local diff_time=$(($end_timestamp - $begin_timestamp))
|
||||
|
||||
echo -e "\n\n## 执行结束... $end_time 耗时 $diff_time 秒 "
|
||||
|
||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
}
|
||||
|
||||
## 正常运行单个脚本,$1:传入参数
|
||||
run_normal() {
|
||||
local file_param=$1
|
||||
if [[ $# -eq 1 ]]; then
|
||||
random_delay "$file_param"
|
||||
fi
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ${file_param} != /* ]] && [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
|
||||
$timeoutCmd $which_program $file_param
|
||||
}
|
||||
|
||||
## 并发执行时,设定的 RandomDelay 不会生效,即所有任务立即执行
|
||||
run_concurrent() {
|
||||
local file_param="$1"
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|")
|
||||
if [[ ! $env_param ]]; then
|
||||
echo -e "\n 缺少并发运行的环境变量参数"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
local tempArr=$(echo $num_param | sed "s/-max/-${#array[@]}/g" | sed "s/max-/${#array[@]}-/g" | perl -pe "s|(\d+)(-\|~\|_)(\d+)|{\1..\3}|g")
|
||||
local runArr=($(eval echo $tempArr))
|
||||
runArr=($(awk -v RS=' ' '!a[$1]++' <<<${runArr[@]}))
|
||||
|
||||
local n=0
|
||||
for i in ${runArr[@]}; do
|
||||
array_run[n]=${array[$i - 1]}
|
||||
let n++
|
||||
done
|
||||
|
||||
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
single_log_time=$(date "+%Y-%m-%d-%H-%M-%S.%3N")
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
for i in "${!array[@]}"; do
|
||||
export ${env_param}=${array[i]}
|
||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
eval $timeoutCmd $which_program $file_param &>$single_log_path &
|
||||
done
|
||||
|
||||
wait
|
||||
for i in "${!array[@]}"; do
|
||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
cat $single_log_path
|
||||
[[ -f $single_log_path ]] && rm -f $single_log_path
|
||||
done
|
||||
}
|
||||
|
||||
run_designated() {
|
||||
local file_param="$1"
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|")
|
||||
if [[ ! $env_param ]] || [[ ! $num_param ]]; then
|
||||
echo -e "\n 缺少单独运行的参数 task xxx.js desi Test 1 3"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
local tempArr=$(echo $num_param | sed "s/-max/-${#array[@]}/g" | sed "s/max-/${#array[@]}-/g" | perl -pe "s|(\d+)(-\|~\|_)(\d+)|{\1..\3}|g")
|
||||
local runArr=($(eval echo $tempArr))
|
||||
runArr=($(awk -v RS=' ' '!a[$1]++' <<<${runArr[@]}))
|
||||
|
||||
local n=0
|
||||
for i in ${runArr[@]}; do
|
||||
array_run[n]=${array[$i - 1]}
|
||||
let n++
|
||||
done
|
||||
|
||||
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
$timeoutCmd $which_program $file_param
|
||||
}
|
||||
|
||||
## 运行其他命令
|
||||
run_else() {
|
||||
local file_param="$1"
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
|
||||
shift
|
||||
|
||||
$timeoutCmd $which_program $file_param "$@"
|
||||
}
|
||||
|
||||
## 命令检测
|
||||
main() {
|
||||
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.pyc ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||
case $# in
|
||||
1)
|
||||
run_normal "$1"
|
||||
;;
|
||||
*)
|
||||
case $2 in
|
||||
now)
|
||||
run_normal "$1" "$2"
|
||||
;;
|
||||
conc)
|
||||
run_concurrent "$1" "$3" "$*"
|
||||
;;
|
||||
desi)
|
||||
run_designated "$1" "$3" "$*"
|
||||
;;
|
||||
*)
|
||||
run_else "$@"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
elif [[ $# -eq 0 ]]; then
|
||||
echo
|
||||
usage
|
||||
else
|
||||
run_else "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
handle_task_before "$@"
|
||||
main "$@"
|
||||
handle_task_after "$@"
|
||||
+1
-1
@@ -13,7 +13,7 @@ git push
|
||||
echo -e "更新cdn文件"
|
||||
ts-node sample/tool.ts
|
||||
|
||||
string=$(cat src/version.ts | grep "version" | egrep "[^\']*" -o | egrep "\d\.*")
|
||||
string=$(cat version.yaml | grep "version" | egrep "[^ ]*" -o | egrep "\d\.*")
|
||||
version="v$string"
|
||||
echo -e "当前版本$version"
|
||||
|
||||
|
||||
+8
-2
@@ -6,7 +6,7 @@ dir_shell=$QL_DIR/shell
|
||||
|
||||
days=$1
|
||||
|
||||
## 删除运行js脚本的旧日志
|
||||
## 删除运行脚本的旧日志
|
||||
remove_js_log() {
|
||||
local log_full_path_list=$(find $dir_log/ -name "*.log")
|
||||
local diff_time
|
||||
@@ -18,7 +18,13 @@ remove_js_log() {
|
||||
else
|
||||
diff_time=$(($(date +%s) - $(date +%s -d "$log_date")))
|
||||
fi
|
||||
[[ $diff_time -gt $((${days} * 86400)) ]] && rm -vf $log
|
||||
if [[ $diff_time -gt $((${days} * 86400)) ]]; then
|
||||
local log_path=$(echo "$log" | sed "s,${dir_log},,g")
|
||||
local result=$(find_cron_api "log_path=$log_path")
|
||||
if [[ $result ]]; then
|
||||
rm -vf $log
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
+93
-24
@@ -24,6 +24,7 @@ file_sharecode=$dir_config/sharecode.sh
|
||||
file_config_user=$dir_config/config.sh
|
||||
file_auth_sample=$dir_sample/auth.sample.json
|
||||
file_auth_user=$dir_config/auth.json
|
||||
file_auth_token=$dir_config/token.json
|
||||
file_extra_shell=$dir_config/extra.sh
|
||||
file_task_before=$dir_config/task_before.sh
|
||||
file_task_after=$dir_config/task_after.sh
|
||||
@@ -66,6 +67,7 @@ import_config() {
|
||||
[[ -f $file_config_user ]] && . $file_config_user
|
||||
[[ -f $file_env ]] && . $file_env
|
||||
|
||||
ql_base_url=${QlBaseUrl:-""}
|
||||
command_timeout_time=${CommandTimeoutTime:-"1h"}
|
||||
proxy_url=${ProxyUrl:-""}
|
||||
file_extensions=${RepoFileExtensions:-"js py"}
|
||||
@@ -76,9 +78,17 @@ import_config() {
|
||||
else
|
||||
default_cron="$(random_range 0 59) $(random_range 0 23) * * *"
|
||||
fi
|
||||
|
||||
cpu_warn=${CpuWarn}
|
||||
mem_warn=${MemoryWarn}
|
||||
disk_warn=${DiskWarn}
|
||||
}
|
||||
|
||||
set_proxy() {
|
||||
local proxy="$1"
|
||||
if [[ $proxy ]]; then
|
||||
proxy_url="$proxy"
|
||||
fi
|
||||
if [[ $proxy_url ]]; then
|
||||
export http_proxy="${proxy_url}"
|
||||
export https_proxy="${proxy_url}"
|
||||
@@ -243,15 +253,13 @@ fix_config() {
|
||||
}
|
||||
|
||||
npm_install_sub() {
|
||||
set_proxy
|
||||
if [ $is_termux -eq 1 ]; then
|
||||
npm install --production --no-bin-links --registry=https://registry.npmmirror.com || npm install --production --no-bin-links
|
||||
npm install --production --no-bin-links
|
||||
elif ! type pnpm &>/dev/null; then
|
||||
npm install --production --registry=https://registry.npmmirror.com || npm install --production
|
||||
npm install --production
|
||||
else
|
||||
pnpm install --loglevel error --production --registry=https://registry.npmmirror.com || pnpm install --production --loglevel error
|
||||
pnpm install --loglevel error --production
|
||||
fi
|
||||
unset_proxy
|
||||
}
|
||||
|
||||
npm_install_1() {
|
||||
@@ -299,13 +307,14 @@ update_depend() {
|
||||
}
|
||||
|
||||
git_clone_scripts() {
|
||||
local url=$1
|
||||
local dir=$2
|
||||
local branch=$3
|
||||
local url="$1"
|
||||
local dir="$2"
|
||||
local branch="$3"
|
||||
local proxy="$4"
|
||||
[[ $branch ]] && local part_cmd="-b $branch "
|
||||
echo -e "开始克隆仓库 $url 到 $dir\n"
|
||||
|
||||
set_proxy
|
||||
set_proxy "$proxy"
|
||||
git clone $part_cmd $url $dir
|
||||
exit_status=$?
|
||||
unset_proxy
|
||||
@@ -315,15 +324,15 @@ git_pull_scripts() {
|
||||
local dir_current=$(pwd)
|
||||
local dir_work="$1"
|
||||
local branch="$2"
|
||||
local proxy="$3"
|
||||
cd $dir_work
|
||||
echo -e "开始更新仓库:$dir_work\n"
|
||||
echo -e "开始更新仓库:$dir_work"
|
||||
|
||||
set_proxy
|
||||
set_proxy "$proxy"
|
||||
git fetch --all
|
||||
git pull 1>/dev/null
|
||||
exit_status=$?
|
||||
git pull &>/dev/null
|
||||
unset_proxy
|
||||
reset_branch "$branch"
|
||||
|
||||
cd $dir_current
|
||||
}
|
||||
@@ -334,23 +343,25 @@ reset_romote_url() {
|
||||
local url=$2
|
||||
local branch="$3"
|
||||
|
||||
if [[ -d "$dir_work/.git" ]]; then
|
||||
cd $dir_work
|
||||
if [[ -d "$dir_work/.git" ]]; then
|
||||
[[ -f ".git/index.lock" ]] && rm -f .git/index.lock >/dev/null
|
||||
git remote set-url origin $url &>/dev/null
|
||||
|
||||
local part_cmd=""
|
||||
else
|
||||
git init
|
||||
git remote add origin $url &>/dev/null
|
||||
fi
|
||||
reset_branch "$branch"
|
||||
cd $dir_current
|
||||
fi
|
||||
}
|
||||
|
||||
reset_branch() {
|
||||
local branch="$1"
|
||||
local part_cmd="HEAD"
|
||||
if [[ $branch ]]; then
|
||||
part_cmd="origin/${branch}"
|
||||
git checkout -B "$branch"
|
||||
git branch --set-upstream-to=$part_cmd $branch
|
||||
git checkout -B "$branch" &>/dev/null
|
||||
git branch --set-upstream-to=$part_cmd $branch &>/dev/null
|
||||
fi
|
||||
git reset --hard $part_cmd &>/dev/null
|
||||
}
|
||||
@@ -371,10 +382,6 @@ reload_pm2() {
|
||||
echo -e "启动定时任务服务\n"
|
||||
pm2 delete schedule --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_static/build/schedule.js -n schedule --source-map-support --time &>/dev/null
|
||||
|
||||
echo -e "启动公开服务\n"
|
||||
pm2 delete public --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
|
||||
}
|
||||
|
||||
diff_time() {
|
||||
@@ -401,6 +408,17 @@ format_time() {
|
||||
fi
|
||||
}
|
||||
|
||||
format_log_time() {
|
||||
local format="$1"
|
||||
local time="$2"
|
||||
|
||||
if [[ $is_macos -eq 1 ]]; then
|
||||
echo $(date -j -f "$format" "$time" "+%Y-%m-%d-%H-%M-%S-%3N")
|
||||
else
|
||||
echo $(date -d "$time" "+%Y-%m-%d-%H-%M-%S-%3N")
|
||||
fi
|
||||
}
|
||||
|
||||
format_timestamp() {
|
||||
local format="$1"
|
||||
local time="$2"
|
||||
@@ -412,10 +430,61 @@ format_timestamp() {
|
||||
fi
|
||||
}
|
||||
|
||||
patch_version() {
|
||||
if [[ $PipMirror ]]; then
|
||||
pip3 config set global.index-url $PipMirror
|
||||
fi
|
||||
if [[ $NpmMirror ]]; then
|
||||
npm config set registry $NpmMirror
|
||||
fi
|
||||
|
||||
# 兼容pnpm@7
|
||||
pnpm setup &>/dev/null
|
||||
source ~/.bashrc
|
||||
pnpm install -g &>/dev/null
|
||||
|
||||
if [[ -f "$dir_root/db/cookie.db" ]]; then
|
||||
echo -e "检测到旧的db文件,拷贝为新db...\n"
|
||||
mv $dir_root/db/cookie.db $dir_root/db/env.db
|
||||
rm -rf $dir_root/db/cookie.db
|
||||
echo
|
||||
fi
|
||||
|
||||
pnpm add -g pm2 ts-node typescript tslib
|
||||
|
||||
git config --global pull.rebase false
|
||||
|
||||
cp -f $dir_root/.env.example $dir_root/.env
|
||||
|
||||
if [[ -d "$dir_root/db" ]]; then
|
||||
echo -e "检测到旧的db目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/config $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/scripts" ]]; then
|
||||
echo -e "检测到旧的scripts目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/scripts $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/log" ]]; then
|
||||
echo -e "检测到旧的log目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/log $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/config" ]]; then
|
||||
echo -e "检测到旧的config目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/config $dir_root/data
|
||||
echo
|
||||
fi
|
||||
}
|
||||
|
||||
init_env
|
||||
detect_termux
|
||||
detect_macos
|
||||
define_cmd
|
||||
fix_config
|
||||
|
||||
import_config $1 >$task_error_log_path 2>&1
|
||||
import_config $1 2>$task_error_log_path
|
||||
|
||||
+33
-332
@@ -21,71 +21,19 @@ define_program() {
|
||||
fi
|
||||
}
|
||||
|
||||
random_delay() {
|
||||
local random_delay_max=$RandomDelay
|
||||
if [[ $random_delay_max ]] && [[ $random_delay_max -gt 0 ]]; then
|
||||
local current_min=$(date "+%-M")
|
||||
if [[ $current_min -ne 0 ]] && [[ $current_min -ne 30 ]]; then
|
||||
delay_second=$(($(gen_random_num $random_delay_max) + 1))
|
||||
echo -e "\n命令未添加 \"now\",随机延迟 $delay_second 秒后再执行任务,如需立即终止,请按 CTRL+C...\n"
|
||||
sleep $delay_second
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
## scripts目录下所有可运行脚本数组
|
||||
gen_array_scripts() {
|
||||
local dir_current=$(pwd)
|
||||
local i="-1"
|
||||
cd $dir_scripts
|
||||
for file in $(ls); do
|
||||
if [[ -f $file ]] && [[ $file == *.js && $file != sendNotify.js ]]; then
|
||||
let i++
|
||||
array_scripts[i]=$(echo "$file" | perl -pe "s|$dir_scripts/||g")
|
||||
array_scripts_name[i]=$(grep "new Env" $file | awk -F "'|\"" '{print $2}' | head -1)
|
||||
[[ -z ${array_scripts_name[i]} ]] && array_scripts_name[i]="<未识别出活动名称>"
|
||||
fi
|
||||
done
|
||||
cd $dir_current
|
||||
}
|
||||
|
||||
## 使用说明
|
||||
usage() {
|
||||
define_cmd
|
||||
gen_array_scripts
|
||||
echo -e "task命令运行本程序自动添加进crontab的脚本,需要输入脚本的绝对路径或去掉 “$dir_scripts/” 目录后的相对路径(定时任务中请写作相对路径),用法为:"
|
||||
echo -e "1.$cmd_task <file_name> # 依次执行,如果设置了随机延迟,将随机延迟一定秒数"
|
||||
echo -e "2.$cmd_task <file_name> now # 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日志,同时记录在日志文件中"
|
||||
echo -e "3.$cmd_task <file_name> conc <环境变量名称> <账号编号,空格分隔>(可选的) # 并发执行,无论是否设置了随机延迟,均立即运行,前台不产生日志,直接记录在日志文件中,且可指定账号执行"
|
||||
echo -e "4.$cmd_task <file_name> desi <环境变量名称> <账号编号,空格分隔> # 指定账号执行,无论是否设置了随机延迟,均立即运行"
|
||||
if [[ ${#array_scripts[*]} -gt 0 ]]; then
|
||||
echo -e "\n当前有以下脚本可以运行:"
|
||||
for ((i = 0; i < ${#array_scripts[*]}; i++)); do
|
||||
echo -e "$(($i + 1)). ${array_scripts_name[i]}:${array_scripts[i]}"
|
||||
done
|
||||
else
|
||||
echo -e "\n暂无脚本可以执行"
|
||||
fi
|
||||
}
|
||||
|
||||
## run nohup,$1:文件名,不含路径,带后缀
|
||||
run_nohup() {
|
||||
local file_name=$1
|
||||
nohup node $file_name &>$log_path &
|
||||
}
|
||||
|
||||
## 正常运行单个脚本,$1:传入参数
|
||||
run_normal() {
|
||||
handle_log_path() {
|
||||
local file_param=$1
|
||||
define_program "$file_param"
|
||||
if [[ $file_param == *.js ]]; then
|
||||
if [[ $# -eq 1 ]]; then
|
||||
random_delay
|
||||
fi
|
||||
|
||||
if [[ -z $file_param ]];then
|
||||
file_param="task"
|
||||
fi
|
||||
|
||||
local time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_time="$time"
|
||||
local suffix=""
|
||||
if [[ ! -z $ID ]]; then
|
||||
suffix="_${ID}"
|
||||
fi
|
||||
time=$(date "+$mtime_format")
|
||||
log_time=$(format_log_time "$mtime_format" "$time")
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
@@ -97,294 +45,47 @@ run_normal() {
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_dir="${log_dir_tmp%.*}${suffix}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
|
||||
local begin_time=$(format_time "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
local begin_timestamp=$(format_timestamp "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
|
||||
eval $timeoutCmd $which_program $file_param $cmd
|
||||
|
||||
eval . $file_task_after "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local end_timestamp=$(date "+%s")
|
||||
local diff_time=$(expr $end_timestamp - $begin_timestamp)
|
||||
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||
}
|
||||
|
||||
## 并发执行时,设定的 RandomDelay 不会生效,即所有任务立即执行
|
||||
run_concurrent() {
|
||||
local file_param="$1"
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|")
|
||||
if [[ ! $env_param ]]; then
|
||||
echo -e "\n 缺少并发运行的环境变量参数"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
local tempArr=$(echo $num_param | perl -pe "s|(\d+)(-\|~\|_)(\d+)|{\1..\3}|g")
|
||||
local runArr=($(eval echo $tempArr))
|
||||
runArr=($(awk -v RS=' ' '!a[$1]++' <<< ${runArr[@]}))
|
||||
|
||||
local n=0
|
||||
for i in ${runArr[@]}; do
|
||||
array_run[n]=${array[$i - 1]}
|
||||
let n++
|
||||
done
|
||||
|
||||
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
define_program "$file_param"
|
||||
local time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_time="$time"
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
if [[ "$show_log" == "true" ]]; then
|
||||
cmd=""
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
|
||||
local begin_time=$(format_time "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
local begin_timestamp=$(format_timestamp "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
single_log_time=$(date "+%Y-%m-%d-%H-%M-%S.%N")
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
for i in "${!array[@]}"; do
|
||||
export ${env_param}=${array[i]}
|
||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
eval $timeoutCmd $which_program $file_param &>$single_log_path &
|
||||
done
|
||||
|
||||
wait
|
||||
for i in "${!array[@]}"; do
|
||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
eval cat $single_log_path $cmd
|
||||
[[ -f $single_log_path ]] && rm -f $single_log_path
|
||||
done
|
||||
|
||||
eval . $file_task_after "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local end_timestamp=$(date "+%s")
|
||||
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||
}
|
||||
|
||||
run_designated() {
|
||||
local file_param="$1"
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|")
|
||||
if [[ ! $env_param ]] || [[ ! $num_param ]]; then
|
||||
echo -e "\n 缺少单独运行的参数 task xxx.js desi Test 1 3"
|
||||
exit 1
|
||||
format_params() {
|
||||
time_format="%Y-%m-%d %H:%M:%S"
|
||||
mtime_format="%Y-%m-%d %H:%M:%S.%3N"
|
||||
timeoutCmd=""
|
||||
if type timeout &>/dev/null; then
|
||||
timeoutCmd="timeout --foreground -s 14 -k 10s $command_timeout_time "
|
||||
fi
|
||||
|
||||
define_program "$file_param"
|
||||
local time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_time="$time"
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
|
||||
local begin_time=$(format_time "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
local begin_timestamp=$(format_timestamp "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
local tempArr=$(echo $num_param | perl -pe "s|(\d+)(-\|~\|_)(\d+)|{\1..\3}|g")
|
||||
local runArr=($(eval echo $tempArr))
|
||||
runArr=($(awk -v RS=' ' '!a[$1]++' <<< ${runArr[@]}))
|
||||
|
||||
local n=0
|
||||
for i in ${runArr[@]}; do
|
||||
array_run[n]=${array[$i - 1]}
|
||||
let n++
|
||||
done
|
||||
|
||||
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
eval $timeoutCmd $which_program $file_param $cmd
|
||||
|
||||
eval . $file_task_after "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local end_timestamp=$(date "+%s")
|
||||
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||
# params=$(echo "$@" | sed -E 's/([^ ])&([^ ])/\1\\\&\2/g')
|
||||
}
|
||||
|
||||
## 运行其他命令
|
||||
run_else() {
|
||||
local file_param="$1"
|
||||
define_program "$file_param"
|
||||
local time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_time="$time"
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
|
||||
local begin_time=$(format_time "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
local begin_timestamp=$(format_timestamp "%Y-%m-%d-%H-%M-%S" "$time")
|
||||
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $@" | perl -pe "s|.*ID=(.*) $cmd_task $@\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
|
||||
shift
|
||||
eval $timeoutCmd $which_program "$file_param" "$@" $cmd
|
||||
|
||||
eval . $file_task_after "$file_param" "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local end_timestamp=$(date "+%s")
|
||||
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||
}
|
||||
|
||||
## 命令检测
|
||||
main() {
|
||||
show_log="false"
|
||||
while getopts ":l" opt
|
||||
do
|
||||
while getopts ":lm:" opt; do
|
||||
case $opt in
|
||||
l)
|
||||
show_log="true"
|
||||
;;
|
||||
m)
|
||||
max_time="$OPTARG"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
[[ "$show_log" == "true" ]] && shift $(($OPTIND - 1))
|
||||
|
||||
timeoutCmd=""
|
||||
if type timeout &>/dev/null; then
|
||||
timeoutCmd="timeout -k 10s $command_timeout_time "
|
||||
[[ $show_log ]] && shift $(($OPTIND - 1))
|
||||
if [[ $max_time ]]; then
|
||||
shift $(($OPTIND - 1))
|
||||
command_timeout_time="$max_time"
|
||||
fi
|
||||
|
||||
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||
case $# in
|
||||
1)
|
||||
run_normal "$1"
|
||||
;;
|
||||
*)
|
||||
case $2 in
|
||||
now)
|
||||
run_normal "$1" "$2"
|
||||
;;
|
||||
conc)
|
||||
run_concurrent "$1" "$3" "$*"
|
||||
;;
|
||||
desi)
|
||||
run_designated "$1" "$3" "$*"
|
||||
;;
|
||||
*)
|
||||
run_else "$@"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
format_params "$@"
|
||||
define_program "$@"
|
||||
handle_log_path "$@"
|
||||
|
||||
eval . $dir_shell/otask.sh "$cmd"
|
||||
[[ -f "$dir_log/$log_path" ]] && cat "$dir_log/$log_path"
|
||||
elif [[ $# -eq 0 ]]; then
|
||||
echo
|
||||
usage
|
||||
else
|
||||
run_else "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
exit 0
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import OpenService from '../back/services/open';
|
||||
import { Container } from 'typedi';
|
||||
import LoggerInstance from '../back/loaders/logger';
|
||||
import fs from 'fs';
|
||||
import config from '../back/config';
|
||||
import path from 'path';
|
||||
|
||||
const tokenFile = path.join(config.configPath, 'token.json');
|
||||
|
||||
async function getToken() {
|
||||
try {
|
||||
const data = await readFile();
|
||||
const nowTime = Math.round(Date.now() / 1000);
|
||||
if (data.value && data.expiration > nowTime) {
|
||||
console.log(data.value);
|
||||
} else {
|
||||
Container.set('logger', LoggerInstance);
|
||||
const openService = Container.get(OpenService);
|
||||
const appToken = await openService.findSystemToken();
|
||||
console.log(appToken.value);
|
||||
await writeFile({
|
||||
value: appToken.value,
|
||||
expiration: appToken.expiration,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function readFile() {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
fs.readFile(
|
||||
path.join(config.configPath, 'token.json'),
|
||||
{ encoding: 'utf8' },
|
||||
(err, data) => {
|
||||
if (err) {
|
||||
resolve({});
|
||||
} else {
|
||||
resolve(JSON.parse(data));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function writeFile(data: any) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
fs.writeFile(tokenFile, JSON.stringify(data), { encoding: 'utf8' }, () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getToken();
|
||||
+133
-152
@@ -26,33 +26,6 @@ diff_cron() {
|
||||
fi
|
||||
}
|
||||
|
||||
## 检测配置文件版本
|
||||
detect_config_version() {
|
||||
## 识别出两个文件的版本号
|
||||
ver_config_sample=$(grep " Version: " $file_config_sample | perl -pe "s|.+v((\d+\.?){3})|\1|")
|
||||
[[ -f $file_config_user ]] && ver_config_user=$(grep " Version: " $file_config_user | perl -pe "s|.+v((\d+\.?){3})|\1|")
|
||||
|
||||
## 删除旧的发送记录文件
|
||||
[[ -f $send_mark ]] && [[ $(cat $send_mark) != $ver_config_sample ]] && rm -f $send_mark
|
||||
|
||||
## 识别出更新日期和更新内容
|
||||
update_date=$(grep " Date: " $file_config_sample | awk -F ": " '{print $2}')
|
||||
update_content=$(grep " Update Content: " $file_config_sample | awk -F ": " '{print $2}')
|
||||
|
||||
## 如果是今天,并且版本号不一致,则发送通知
|
||||
if [[ -f $file_config_user ]] && [[ $ver_config_user != $ver_config_sample ]] && [[ $update_date == $(date "+%Y-%m-%d") ]]; then
|
||||
if [[ ! -f $send_mark ]]; then
|
||||
local notify_title="配置文件更新通知"
|
||||
local notify_content="更新日期: $update_date\n用户版本: $ver_config_user\n新的版本: $ver_config_sample\n更新内容: $update_content\n更新说明: 如需使用新功能请对照config.sample.sh,将相关新参数手动增加到你自己的config.sh中,否则请无视本消息。本消息只在该新版本配置文件更新当天发送一次。\n"
|
||||
echo -e $notify_content
|
||||
notify_api "$notify_title" "$notify_content"
|
||||
[[ $? -eq 0 ]] && echo $ver_config_sample >$send_mark
|
||||
fi
|
||||
else
|
||||
[[ -f $send_mark ]] && rm -f $send_mark
|
||||
fi
|
||||
}
|
||||
|
||||
## 输出是否有新的或失效的定时任务,$1:新的或失效的任务清单文件路径,$2:新/失效
|
||||
output_list_add_drop() {
|
||||
local list=$1
|
||||
@@ -124,7 +97,7 @@ add_cron() {
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron:" $file | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron " $file | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line="$default_cron"
|
||||
result=$(add_cron_api "$cron_line:$cmd_task $file:$cron_name")
|
||||
result=$(add_cron_api "$cron_line:$cmd_task $file:$cron_name:$SUB_ID")
|
||||
echo -e "$result"
|
||||
if [[ $detail ]]; then
|
||||
detail="${detail}${result}\n"
|
||||
@@ -144,6 +117,9 @@ update_repo() {
|
||||
local dependence="$4"
|
||||
local branch="$5"
|
||||
local extensions="$6"
|
||||
local proxy="$7"
|
||||
local autoAddCron="$8"
|
||||
local autoDelCron="$9"
|
||||
local tmp="${url%/*}"
|
||||
local authorTmp1="${tmp##*/}"
|
||||
local authorTmp2="${authorTmp1##*:}"
|
||||
@@ -156,13 +132,14 @@ update_repo() {
|
||||
local formatUrl="$url"
|
||||
if [[ -d ${repo_path}/.git ]]; then
|
||||
reset_romote_url ${repo_path} "${formatUrl}" "${branch}"
|
||||
git_pull_scripts ${repo_path} "${branch}"
|
||||
git_pull_scripts ${repo_path} "${branch}" "${proxy}"
|
||||
else
|
||||
git_clone_scripts "${formatUrl}" ${repo_path} "${branch}"
|
||||
rm -rf ${repo_path} &>/dev/null
|
||||
git_clone_scripts "${formatUrl}" ${repo_path} "${branch}" "${proxy}"
|
||||
fi
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新${repo_path}成功...\n"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
|
||||
else
|
||||
echo -e "\n更新${repo_path}失败,请检查网络...\n"
|
||||
fi
|
||||
@@ -170,24 +147,33 @@ update_repo() {
|
||||
|
||||
## 更新所有 raw 文件
|
||||
update_raw() {
|
||||
echo -e "--------------------------------------------------------------\n"
|
||||
local url="$1"
|
||||
local proxy="$2"
|
||||
local autoAddCron="$3"
|
||||
local autoDelCron="$4"
|
||||
|
||||
if [[ ! $autoAddCron ]];then
|
||||
autoAddCron=${AutoAddCron}
|
||||
fi
|
||||
if [[ ! $autoDelCron ]];then
|
||||
autoDelCron=${AutoDelCron}
|
||||
fi
|
||||
|
||||
local raw_url="$url"
|
||||
local suffix="${raw_url##*.}"
|
||||
local raw_file_name="${uniq_path}.${suffix}"
|
||||
echo -e "开始下载:${raw_url} \n\n保存路径:$dir_raw/${raw_file_name}\n"
|
||||
|
||||
set_proxy
|
||||
wget -q --no-check-certificate -O "$dir_raw/${raw_file_name}.new" ${raw_url}
|
||||
unset_proxy
|
||||
wget -q --no-check-certificate -e "http_proxy=${proxy};https_proxy=${proxy}" -O "$dir_raw/${raw_file_name}.new" ${raw_url}
|
||||
|
||||
if [[ $? -eq 0 ]]; then
|
||||
mv "$dir_raw/${raw_file_name}.new" "$dir_raw/${raw_file_name}"
|
||||
echo -e "下载 ${raw_file_name} 成功...\n"
|
||||
cd $dir_raw
|
||||
local filename="raw_${raw_file_name}"
|
||||
local cron_id=$(cat $list_crontab_user | grep -E "$cmd_task $filename" | perl -pe "s|.*ID=(.*) $cmd_task $filename\.*|\1|" | head -1 | head -1 | awk -F " " '{print $1}')
|
||||
local cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* $filename" | perl -pe "s|.*ID=(.*) $cmd_task.* $filename\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
cp -f $raw_file_name $dir_scripts/${filename}
|
||||
if [[ -z $cron_id ]] && [[ ${autoAddCron} == true ]]; then
|
||||
cron_line=$(
|
||||
perl -ne "{
|
||||
print if /.*([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*]( |,|\").*$raw_file_name/
|
||||
@@ -203,8 +189,7 @@ update_raw() {
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron:" $raw_file_name | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron " $raw_file_name | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line="$default_cron"
|
||||
if [[ -z $cron_id ]]; then
|
||||
result=$(add_cron_api "$cron_line:$cmd_task $filename:$cron_name")
|
||||
result=$(add_cron_api "$cron_line:$cmd_task $filename:$cron_name:$SUB_ID")
|
||||
echo -e "$result\n"
|
||||
notify_api "新增任务通知" "\n$result"
|
||||
# update_cron_api "$cron_line:$cmd_task $filename:$cron_name:$cron_id"
|
||||
@@ -218,19 +203,16 @@ update_raw() {
|
||||
|
||||
## 调用用户自定义的extra.sh
|
||||
run_extra_shell() {
|
||||
if [[ ${EnableExtraShell} == true ]]; then
|
||||
if [[ -f $file_extra_shell ]]; then
|
||||
echo -e "--------------------------------------------------------------\n"
|
||||
. $file_extra_shell
|
||||
else
|
||||
echo -e "$file_extra_shell文件不存在,跳过执行...\n"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
## 脚本用法
|
||||
usage() {
|
||||
echo -e "本脚本用法:"
|
||||
echo -e "ql命令使用方法:"
|
||||
echo -e "1. $cmd_update update # 更新并重启青龙"
|
||||
echo -e "2. $cmd_update extra # 运行自定义脚本"
|
||||
echo -e "3. $cmd_update raw <fileurl> # 更新单个脚本文件"
|
||||
@@ -244,41 +226,52 @@ usage() {
|
||||
|
||||
## 更新qinglong
|
||||
update_qinglong() {
|
||||
patch_version
|
||||
local mirror="gitee"
|
||||
local githubStatus=$(curl -s -m 2 -IL "https://google.com" | grep 200)
|
||||
if [[ ! -z $githubStatus ]]; then
|
||||
mirror="github"
|
||||
fi
|
||||
echo -e "使用 ${mirror} 源更新...\n"
|
||||
export isFirstStartServer=false
|
||||
|
||||
local no_restart="$1"
|
||||
local all_branch=$(git branch -a)
|
||||
local all_branch=$(cd ${dir_root} && git branch -a)
|
||||
local primary_branch="master"
|
||||
if [[ "${all_branch}" =~ "${current_branch}" ]]; then
|
||||
primary_branch="${current_branch}"
|
||||
fi
|
||||
[[ -f $dir_root/package.json ]] && ql_depend_old=$(cat $dir_root/package.json)
|
||||
reset_romote_url ${dir_root} "https://github.com/whyour/qinglong.git" ${primary_branch}
|
||||
reset_romote_url ${dir_root} "https://${mirror}.com/whyour/qinglong.git" ${primary_branch}
|
||||
git_pull_scripts $dir_root ${primary_branch}
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新青龙源文件成功...\n"
|
||||
reset_romote_url ${dir_root} "https://${mirror}.com/whyour/qinglong.git" ${primary_branch}
|
||||
cp -f $file_config_sample $dir_config/config.sample.sh
|
||||
detect_config_version
|
||||
update_depend
|
||||
|
||||
[[ -f $dir_root/package.json ]] && ql_depend_new=$(cat $dir_root/package.json)
|
||||
[[ "$ql_depend_old" != "$ql_depend_new" ]] && npm_install_2 $dir_root
|
||||
else
|
||||
echo -e "\n更新青龙源文件失败,请检查原因...\n"
|
||||
fi
|
||||
|
||||
local url="https://github.com/whyour/qinglong-static.git"
|
||||
update_qinglong_static "$1" "$primary_branch"
|
||||
else
|
||||
echo -e "\n更新青龙源文件失败,请检查网络...\n"
|
||||
fi
|
||||
}
|
||||
|
||||
update_qinglong_static() {
|
||||
local no_restart="$1"
|
||||
local primary_branch="$2"
|
||||
local url="https://${mirror}.com/whyour/qinglong-static.git"
|
||||
if [[ -d ${ql_static_repo}/.git ]]; then
|
||||
reset_romote_url ${ql_static_repo} ${url} ${primary_branch}
|
||||
git_pull_scripts ${ql_static_repo} ${primary_branch}
|
||||
else
|
||||
rm -rf ${ql_static_repo} &>/dev/null
|
||||
git_clone_scripts ${url} ${ql_static_repo} ${primary_branch}
|
||||
fi
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新青龙静态资源成功...\n"
|
||||
local static_version=$(cat $dir_root/src/version.ts | perl -pe "s|.*\'(.*)\';\.*|\1|" | head -1)
|
||||
echo -e "\n当前版本 $static_version...\n"
|
||||
reset_romote_url ${ql_static_repo} ${url} ${primary_branch}
|
||||
|
||||
rm -rf $dir_static/*
|
||||
cp -rf $ql_static_repo/* $dir_static
|
||||
@@ -289,55 +282,8 @@ update_qinglong() {
|
||||
reload_pm2
|
||||
fi
|
||||
else
|
||||
echo -e "\n更新青龙静态资源失败,请检查原因...\n"
|
||||
echo -e "\n更新青龙静态资源失败,请检查网络...\n"
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
patch_version() {
|
||||
if [[ -f "$dir_root/db/cookie.db" ]]; then
|
||||
echo -e "检测到旧的db文件,拷贝为新db...\n"
|
||||
mv $dir_root/db/cookie.db $dir_root/db/env.db
|
||||
rm -rf $dir_root/db/cookie.db
|
||||
echo
|
||||
fi
|
||||
|
||||
if ! type ts-node &>/dev/null; then
|
||||
pnpm i -g ts-node typescript tslib
|
||||
fi
|
||||
|
||||
# 兼容pnpm@7
|
||||
pnpm setup
|
||||
source ~/.bashrc
|
||||
|
||||
git config --global pull.rebase false
|
||||
|
||||
cp -f $dir_root/.env.example $dir_root/.env
|
||||
|
||||
if [[ -d "$dir_root/db" ]]; then
|
||||
echo -e "检测到旧的db目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/config $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/scripts" ]]; then
|
||||
echo -e "检测到旧的scripts目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/scripts $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/log" ]]; then
|
||||
echo -e "检测到旧的log目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/log $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/config" ]]; then
|
||||
echo -e "检测到旧的config目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/config $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
## 对比脚本
|
||||
@@ -349,6 +295,15 @@ diff_scripts() {
|
||||
local blackword="$4"
|
||||
local dependence="$5"
|
||||
local extensions="$6"
|
||||
local autoAddCron="$7"
|
||||
local autoDelCron="$8"
|
||||
|
||||
if [[ ! $autoAddCron ]];then
|
||||
autoAddCron=${AutoAddCron}
|
||||
fi
|
||||
if [[ ! $autoDelCron ]];then
|
||||
autoDelCron=${AutoDelCron}
|
||||
fi
|
||||
|
||||
gen_list_repo "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions"
|
||||
|
||||
@@ -358,13 +313,13 @@ diff_scripts() {
|
||||
|
||||
if [[ -s $list_drop ]]; then
|
||||
output_list_add_drop $list_drop "失效"
|
||||
if [[ ${AutoDelCron} == true ]]; then
|
||||
if [[ ${autoDelCron} == true ]]; then
|
||||
del_cron $list_drop $uniq_path
|
||||
fi
|
||||
fi
|
||||
if [[ -s $list_add ]]; then
|
||||
output_list_add_drop $list_add "新"
|
||||
if [[ ${AutoAddCron} == true ]]; then
|
||||
if [[ ${autoAddCron} == true ]]; then
|
||||
add_cron $list_add $uniq_path
|
||||
fi
|
||||
fi
|
||||
@@ -388,6 +343,9 @@ gen_list_repo() {
|
||||
local index=0
|
||||
if [[ $6 ]]; then
|
||||
file_extensions="$6"
|
||||
if [[ $file_extensions =~ "|" ]]; then
|
||||
file_extensions=$(echo $file_extensions | sed 's/|/ /g')
|
||||
fi
|
||||
fi
|
||||
for extension in $file_extensions; do
|
||||
if [[ $index -eq 0 ]]; then
|
||||
@@ -426,12 +384,12 @@ gen_list_repo() {
|
||||
filename=$(basename $file)
|
||||
cp -f $file "$dir_scripts/${uniq_path}/${filename}"
|
||||
echo "${uniq_path}/${filename}" >>"$dir_list_tmp/${uniq_path}_scripts.list"
|
||||
cron_id=$(cat $list_crontab_user | grep -E "$cmd_task ${uniq_path}_${filename}" | perl -pe "s|.*ID=(.*) $cmd_task ${uniq_path}_${filename}\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
if [[ $cron_id ]]; then
|
||||
result=$(update_cron_command_api "$cmd_task ${uniq_path}/${filename}:$cron_id")
|
||||
fi
|
||||
# cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* ${uniq_path}_${filename}" | perl -pe "s|.*ID=(.*) $cmd_task.* ${uniq_path}_${filename}\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
# if [[ $cron_id ]]; then
|
||||
# result=$(update_cron_command_api "$cmd_task ${uniq_path}/${filename}:$cron_id")
|
||||
# fi
|
||||
done
|
||||
grep -E "${cmd_task} ${uniq_path}" ${list_crontab_user} | perl -pe "s|.*ID=(.*) ${cmd_task} (${uniq_path}.*)\.*|\2|" | awk -F " " '{print $1}' | sort -u >"$dir_list_tmp/${uniq_path}_user.list"
|
||||
grep -E "${cmd_task}.* ${uniq_path}" ${list_crontab_user} | perl -pe "s|.*ID=(.*) ${cmd_task}.* (${uniq_path}.*)\.*|\2|" | awk -F " " '{print $1}' | sort -u >"$dir_list_tmp/${uniq_path}_user.list"
|
||||
cd $dir_current
|
||||
}
|
||||
|
||||
@@ -453,8 +411,7 @@ get_uniq_path() {
|
||||
main() {
|
||||
## for ql update
|
||||
show_log="false"
|
||||
while getopts ":l" opt
|
||||
do
|
||||
while getopts ":l" opt; do
|
||||
case $opt in
|
||||
l)
|
||||
show_log="true"
|
||||
@@ -463,85 +420,109 @@ main() {
|
||||
done
|
||||
[[ "$show_log" == "true" ]] && shift $(($OPTIND - 1))
|
||||
|
||||
local p1=$1
|
||||
local p2=$2
|
||||
local p3=$3
|
||||
local p4=$4
|
||||
local p5=$5
|
||||
local p6=$6
|
||||
local p7=$7
|
||||
local p1="${1}"
|
||||
local p2="${2}"
|
||||
local p3="${3}"
|
||||
local p4="${4}"
|
||||
local p5="${5}"
|
||||
local p6="${6}"
|
||||
local p7="${7}"
|
||||
local p8="${8}"
|
||||
local p9="${9}"
|
||||
local p10="${10}"
|
||||
local log_dir="${p1}"
|
||||
make_dir "$dir_log/$log_dir"
|
||||
local log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
local log_path="$dir_log/update/${log_time}_$p1.log"
|
||||
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local log_path="${log_dir}/${log_time}.log"
|
||||
local file_path="$dir_log/$log_path"
|
||||
|
||||
cmd=">> $file_path 2>&1"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
|
||||
local time_format="%Y-%m-%d %H:%M:%S"
|
||||
local time=$(date "+$time_format")
|
||||
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
|
||||
local begin_time=$(format_time "$time_format" "$time")
|
||||
|
||||
if [[ "$p1" != "repo" ]] && [[ "$p1" != "raw" ]]; then
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
fi
|
||||
|
||||
if [[ -s $task_error_log_path ]]; then
|
||||
eval cat $task_error_log_path $cmd
|
||||
eval echo -e "加载 config.sh 出错,请手动检查" $cmd
|
||||
eval echo $cmd
|
||||
fi
|
||||
|
||||
if [[ "$show_log" == "true" ]] && [[ $ID ]]; then
|
||||
eval echo -e "请移除 -l 参数" $cmd
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case $p1 in
|
||||
update)
|
||||
cmd=">> $log_path 2>&1"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
eval echo -e "## 开始执行... $begin_time\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
eval update_qinglong "$2" $cmd
|
||||
;;
|
||||
extra)
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||
run_extra_shell >>$log_path
|
||||
eval run_extra_shell $cmd
|
||||
;;
|
||||
repo)
|
||||
get_uniq_path "$p2" "$p6"
|
||||
if [[ -n $p2 ]]; then
|
||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7"
|
||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7" "$p8" "$p9" "$p10"
|
||||
else
|
||||
echo -e "命令输入错误...\n"
|
||||
usage
|
||||
eval echo -e "命令输入错误...\\\n" $cmd
|
||||
eval usage $cmd
|
||||
fi
|
||||
;;
|
||||
raw)
|
||||
get_uniq_path "$p2"
|
||||
if [[ -n $p2 ]]; then
|
||||
update_raw "$p2"
|
||||
update_raw "$p2" "$p3" "$p4"
|
||||
else
|
||||
echo -e "命令输入错误...\n"
|
||||
usage
|
||||
eval echo -e "命令输入错误...\\\n" $cmd
|
||||
eval usage $cmd
|
||||
fi
|
||||
;;
|
||||
rmlog)
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||
. $dir_shell/rmlog.sh "$p2" >>$log_path
|
||||
eval . $dir_shell/rmlog.sh "$p2" $cmd
|
||||
;;
|
||||
bot)
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||
. $dir_shell/bot.sh >>$log_path
|
||||
eval . $dir_shell/bot.sh $cmd
|
||||
;;
|
||||
check)
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||
. $dir_shell/check.sh >>$log_path
|
||||
eval . $dir_shell/check.sh $cmd
|
||||
;;
|
||||
resetlet)
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
auth_value=$(cat $file_auth_user | jq '.retries =0' -c)
|
||||
echo -e "重置登录错误次数成功 \n $auth_value" >>$log_path
|
||||
echo "$auth_value" >$file_auth_user
|
||||
eval echo -e "重置登录错误次数成功" $cmd
|
||||
;;
|
||||
resettfa)
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
auth_value=$(cat $file_auth_user | jq '.twoFactorActivated =false' | jq '.twoFactorActived =false' -c)
|
||||
echo -e "禁用两步验证成功 \n $auth_value" >>$log_path
|
||||
echo "$auth_value" >$file_auth_user
|
||||
eval echo -e "禁用两步验证成功" $cmd
|
||||
;;
|
||||
*)
|
||||
echo -e "命令输入错误...\n"
|
||||
usage
|
||||
eval echo -e "命令输入错误...\\\n" $cmd
|
||||
eval usage $cmd
|
||||
;;
|
||||
esac
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local diff_time=$(diff_time "%Y-%m-%d %H:%M:%S" "$begin_time" "$end_time")
|
||||
if [[ $p1 != "repo" ]] && [[ $p1 != "raw" ]]; then
|
||||
echo -e "\n## 执行结束... $end_time 耗时 $diff_time 秒" >>$log_path
|
||||
cat $log_path
|
||||
|
||||
local etime=$(date "+$time_format")
|
||||
local end_time=$(format_time "$time_format" "$etime")
|
||||
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
||||
local diff_time=$(($end_timestamp - $begin_timestamp))
|
||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
|
||||
if [[ "$p1" != "repo" ]] && [[ "$p1" != "raw" ]]; then
|
||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒 " $cmd
|
||||
fi
|
||||
|
||||
if [[ -f $file_path ]]; then
|
||||
cat $file_path
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import React, { useRef, useState, useEffect } from 'react';
|
||||
import { Tooltip, Typography } from 'antd';
|
||||
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';
|
||||
import { CopyToClipboard } from 'react-copy-to-clipboard';
|
||||
|
||||
const { Link } = Typography;
|
||||
|
||||
const Copy = ({ text }: { text: string }) => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copyIdRef = useRef<number>();
|
||||
|
||||
const copyText = (e?: React.MouseEvent) => {
|
||||
e?.preventDefault();
|
||||
e?.stopPropagation();
|
||||
|
||||
setCopied(true);
|
||||
|
||||
cleanCopyId();
|
||||
copyIdRef.current = window.setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
const cleanCopyId = () => {
|
||||
window.clearTimeout(copyIdRef.current!);
|
||||
};
|
||||
|
||||
return (
|
||||
<Link onClick={copyText} style={{ marginLeft: 1 }}>
|
||||
<CopyToClipboard text={text}>
|
||||
<Tooltip key="copy" title={copied ? '复制成功' : '复制'}>
|
||||
{copied ? <CheckOutlined /> : <CopyOutlined />}
|
||||
</Tooltip>
|
||||
</CopyToClipboard>
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
export default Copy;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createFromIconfontCN } from '@ant-design/icons';
|
||||
|
||||
const IconFont = createFromIconfontCN({
|
||||
scriptUrl: ['//at.alicdn.com/t/font_3354854_ds8pa06q1qa.js'],
|
||||
scriptUrl: ['//at.alicdn.com/t/c/font_3354854_ob5y15ewlyq.js'],
|
||||
});
|
||||
|
||||
export default IconFont;
|
||||
|
||||
@@ -50,6 +50,7 @@ const EditableTagGroup = ({
|
||||
{tag}
|
||||
</Tag>
|
||||
);
|
||||
|
||||
return (
|
||||
<span key={tag} style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||
{tagElem}
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
import React, {
|
||||
useRef,
|
||||
useEffect,
|
||||
useContext,
|
||||
createContext,
|
||||
useReducer,
|
||||
useState,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { throttle, isNumber, debounce } from 'lodash';
|
||||
|
||||
const initialState = {
|
||||
// 行高度
|
||||
rowHeight: 0,
|
||||
// 当前的scrollTop
|
||||
curScrollTop: 0,
|
||||
// 总行数
|
||||
totalLen: 0,
|
||||
};
|
||||
|
||||
function reducer(state, action) {
|
||||
const { curScrollTop, totalLen, ifScrollTopClear, scrollTop } = action;
|
||||
|
||||
let stateScrollTop = state.curScrollTop;
|
||||
switch (action.type) {
|
||||
// 改变trs 即 改变渲染的列表trs
|
||||
case 'changeTrs':
|
||||
return {
|
||||
...state,
|
||||
curScrollTop,
|
||||
};
|
||||
// 更改totalLen
|
||||
case 'changeTotalLen':
|
||||
if (totalLen === 0) {
|
||||
stateScrollTop = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
totalLen,
|
||||
curScrollTop: stateScrollTop,
|
||||
};
|
||||
|
||||
case 'reset':
|
||||
return {
|
||||
...state,
|
||||
curScrollTop: ifScrollTopClear ? 0 : scrollTop ?? state.curScrollTop,
|
||||
};
|
||||
default:
|
||||
throw new Error();
|
||||
}
|
||||
}
|
||||
|
||||
// ==============全局常量 ================== //
|
||||
const DEFAULT_VID = 'vtable';
|
||||
const vidMap = new Map();
|
||||
let preData = 0;
|
||||
|
||||
// ===============context ============== //
|
||||
const ScrollContext = createContext({
|
||||
dispatch: undefined,
|
||||
renderLen: 1,
|
||||
start: 0,
|
||||
offsetStart: 0,
|
||||
// =============
|
||||
rowHeight: initialState.rowHeight,
|
||||
totalLen: 0,
|
||||
vid: DEFAULT_VID,
|
||||
});
|
||||
|
||||
// =============组件 =================== //
|
||||
|
||||
function VCell(props: any): JSX.Element {
|
||||
const { children, ...restProps } = props;
|
||||
|
||||
return (
|
||||
<td {...restProps}>
|
||||
<div>{children[1]}</div>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
function VRow(props: any, ref: any): JSX.Element {
|
||||
const { rowHeight } = useContext(ScrollContext);
|
||||
|
||||
const { children, style, ...restProps } = props;
|
||||
|
||||
const trRef = useRef<HTMLTableRowElement>(null);
|
||||
|
||||
return (
|
||||
<tr
|
||||
{...restProps}
|
||||
ref={Object.prototype.hasOwnProperty.call(ref, 'current') ? ref : trRef}
|
||||
style={{
|
||||
...style,
|
||||
height: rowHeight || 'auto',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function VWrapper(props: any): JSX.Element {
|
||||
const { children, ...restProps } = props;
|
||||
|
||||
const { renderLen, start, dispatch, vid, totalLen } =
|
||||
useContext(ScrollContext);
|
||||
|
||||
const contents = useMemo(() => {
|
||||
return children[1];
|
||||
}, [children]);
|
||||
|
||||
const contentsLen = useMemo(() => {
|
||||
return contents?.length ?? 0;
|
||||
}, [contents]);
|
||||
|
||||
useEffect(() => {
|
||||
if (totalLen !== contentsLen) {
|
||||
dispatch({
|
||||
type: 'changeTotalLen',
|
||||
totalLen: contentsLen ?? 0,
|
||||
});
|
||||
}
|
||||
}, [contentsLen, dispatch, vid, totalLen]);
|
||||
|
||||
let tempNode = null;
|
||||
if (Array.isArray(contents) && contents.length) {
|
||||
tempNode = [
|
||||
children[0],
|
||||
contents.slice(start, start + (renderLen ?? 1)).map((item) => {
|
||||
if (Array.isArray(item)) {
|
||||
// 兼容antd v4.3.5 --- rc-table 7.8.1及以下
|
||||
return item[0];
|
||||
}
|
||||
// 处理antd ^v4.4.0 --- rc-table ^7.8.2
|
||||
return item;
|
||||
}),
|
||||
];
|
||||
} else {
|
||||
tempNode = children;
|
||||
}
|
||||
|
||||
return <tbody {...restProps}>{tempNode}</tbody>;
|
||||
}
|
||||
|
||||
function VTable(props: any, otherParams): JSX.Element {
|
||||
const { style, children, ...rest } = props;
|
||||
const { width, ...rest_style } = style;
|
||||
|
||||
const { vid, scrollY, resetScrollTopWhenDataChange, rowHeight, scrollTop } =
|
||||
otherParams ?? {};
|
||||
|
||||
const [state, dispatch] = useReducer(reducer, {
|
||||
...initialState,
|
||||
curScrollTop: scrollTop,
|
||||
rowHeight,
|
||||
});
|
||||
|
||||
const wrap_tableRef = useRef<HTMLDivElement>(null);
|
||||
const tableRef = useRef<HTMLTableElement>(null);
|
||||
|
||||
const ifChangeRef = useRef(false);
|
||||
|
||||
// 数据的总条数
|
||||
const [totalLen, setTotalLen] = useState<number>(
|
||||
children[1]?.props?.data?.length ?? 0,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setTotalLen(state.totalLen);
|
||||
}, [state.totalLen]);
|
||||
|
||||
// 组件卸载的清除操作
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
vidMap.delete(vid);
|
||||
};
|
||||
}, [vid]);
|
||||
|
||||
// 数据变更
|
||||
useEffect(() => {
|
||||
ifChangeRef.current = true;
|
||||
// console.log('数据变更')
|
||||
if (isNumber(children[1]?.props?.data?.length)) {
|
||||
dispatch({
|
||||
type: 'changeTotalLen',
|
||||
totalLen: children[1]?.props?.data?.length ?? 0,
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [children[1].props.data]);
|
||||
|
||||
// table总高度
|
||||
const tableHeight = useMemo<string | number>(() => {
|
||||
let temp: string | number = 'auto';
|
||||
|
||||
if (rowHeight && totalLen) {
|
||||
temp = rowHeight * totalLen;
|
||||
}
|
||||
return temp;
|
||||
}, [totalLen]);
|
||||
|
||||
// table的scrollY值
|
||||
const [tableScrollY, setTableScrollY] = useState(0);
|
||||
|
||||
// tableScrollY 随scrollY / tableHeight 进行变更
|
||||
useEffect(() => {
|
||||
let temp = 0;
|
||||
|
||||
if (typeof scrollY === 'string') {
|
||||
temp =
|
||||
(wrap_tableRef.current?.parentNode as HTMLElement)?.offsetHeight ?? 0;
|
||||
} else {
|
||||
temp = scrollY;
|
||||
}
|
||||
|
||||
// if (isNumber(tableHeight) && tableHeight < temp) {
|
||||
// temp = tableHeight;
|
||||
// }
|
||||
|
||||
// 处理tableScrollY <= 0的情况
|
||||
if (temp <= 0) {
|
||||
temp = 0;
|
||||
}
|
||||
|
||||
setTableScrollY(temp);
|
||||
}, [scrollY, tableHeight]);
|
||||
|
||||
// 渲染的条数
|
||||
const renderLen = useMemo<number>(() => {
|
||||
let temp = 1;
|
||||
if (rowHeight && totalLen && tableScrollY) {
|
||||
if (tableScrollY <= 0) {
|
||||
temp = 0;
|
||||
} else {
|
||||
const tempRenderLen = ((tableScrollY / rowHeight) | 0) + 10;
|
||||
// console.log('tempRenderLen', tempRenderLen)
|
||||
// temp = tempRenderLen > totalLen ? totalLen : tempRenderLen;
|
||||
temp = tempRenderLen;
|
||||
}
|
||||
}
|
||||
|
||||
return temp;
|
||||
}, [totalLen, tableScrollY]);
|
||||
|
||||
// 渲染中的第一条
|
||||
let start = rowHeight ? (state.curScrollTop / rowHeight) | 0 : 0;
|
||||
|
||||
start = start < 5 ? 0 : start - 5 + 1;
|
||||
|
||||
// 偏移量
|
||||
let offsetStart = state.curScrollTop % (rowHeight * 5);
|
||||
|
||||
if (start > 0) {
|
||||
offsetStart = offsetStart % rowHeight;
|
||||
}
|
||||
// console.log(offsetStart)
|
||||
// offsetStart= offsetStart%rowHeight
|
||||
// 用来优化向上滚动出现的空白
|
||||
if (state.curScrollTop && state.curScrollTop >= rowHeight * 5) {
|
||||
// start -= 1
|
||||
// if (offsetStart >= rowHeight) {
|
||||
// offsetStart +=
|
||||
// } else {
|
||||
offsetStart += rowHeight * 4;
|
||||
// }
|
||||
} else {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
// console.log(state.curScrollTop, start, offsetStart)
|
||||
|
||||
// 数据变更 操作scrollTop
|
||||
useEffect(() => {
|
||||
const scrollNode = wrap_tableRef.current?.parentNode as HTMLElement;
|
||||
if (ifChangeRef?.current) {
|
||||
// console.log(scrollNode)
|
||||
ifChangeRef.current = false;
|
||||
|
||||
if (resetScrollTopWhenDataChange) {
|
||||
// 重置scrollTop
|
||||
if (scrollNode) {
|
||||
scrollNode.scrollTop = 0;
|
||||
}
|
||||
|
||||
dispatch({ type: 'reset', ifScrollTopClear: true });
|
||||
} else {
|
||||
// console.log(preData)
|
||||
// scrollNode.scrollTop = preData+53
|
||||
// 不重置scrollTop 不清空curScrollTop
|
||||
dispatch({ type: 'reset', ifScrollTopClear: false });
|
||||
}
|
||||
}
|
||||
|
||||
if (vidMap.has(vid)) {
|
||||
vidMap.set(vid, {
|
||||
...vidMap.get(vid),
|
||||
scrollNode,
|
||||
});
|
||||
}
|
||||
}, [totalLen, resetScrollTopWhenDataChange, vid, children]);
|
||||
|
||||
useEffect(() => {
|
||||
const throttleScroll = throttle((e) => {
|
||||
const scrollTop: number = e?.target?.scrollTop ?? 0;
|
||||
// const scrollHeight: number = e?.target?.scrollHeight ?? 0
|
||||
// const clientHeight: number = e?.target?.clientHeight ?? 0
|
||||
if (scrollTop) {
|
||||
preData = scrollTop;
|
||||
}
|
||||
// 到底了 没有滚动条就不会触发reachEnd. 建议设置scrolly高度少点或者数据量多点.
|
||||
// 若renderLen大于totalLen, 置空curScrollTop. => table paddingTop会置空.
|
||||
dispatch({
|
||||
type: 'changeTrs',
|
||||
curScrollTop: renderLen <= totalLen ? scrollTop : 0,
|
||||
});
|
||||
}, 60);
|
||||
|
||||
const ref = wrap_tableRef?.current?.parentNode as HTMLElement;
|
||||
|
||||
if (ref) {
|
||||
ref.addEventListener('scroll', throttleScroll, { passive: true });
|
||||
}
|
||||
|
||||
return () => {
|
||||
ref.removeEventListener('scroll', throttleScroll);
|
||||
};
|
||||
}, [renderLen, totalLen]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="virtuallist"
|
||||
ref={wrap_tableRef}
|
||||
style={{
|
||||
width: '100%',
|
||||
position: 'relative',
|
||||
height: tableHeight,
|
||||
boxSizing: 'border-box',
|
||||
paddingTop: state.curScrollTop,
|
||||
}}
|
||||
>
|
||||
<ScrollContext.Provider
|
||||
value={{
|
||||
dispatch,
|
||||
start,
|
||||
offsetStart,
|
||||
renderLen,
|
||||
totalLen,
|
||||
vid,
|
||||
rowHeight,
|
||||
}}
|
||||
>
|
||||
<table
|
||||
{...rest}
|
||||
ref={tableRef}
|
||||
style={{
|
||||
...rest_style,
|
||||
width,
|
||||
position: 'relative',
|
||||
transform: `translateY(-${offsetStart}px)`,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</table>
|
||||
</ScrollContext.Provider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ================导出===================
|
||||
export function VList(props: {
|
||||
height: number;
|
||||
// 唯一标识
|
||||
vid?: string;
|
||||
rowHeight: number | string;
|
||||
reset?: boolean;
|
||||
scrollTop?: number | string;
|
||||
}): any {
|
||||
const { vid = DEFAULT_VID, rowHeight, height, reset, scrollTop } = props;
|
||||
|
||||
const resetScrollTopWhenDataChange = reset ?? true;
|
||||
|
||||
if (!vidMap.has(vid)) {
|
||||
vidMap.set(vid, { _id: vid });
|
||||
}
|
||||
|
||||
return {
|
||||
table: (p) =>
|
||||
VTable(p, {
|
||||
vid,
|
||||
scrollY: height,
|
||||
rowHeight,
|
||||
resetScrollTopWhenDataChange,
|
||||
scrollTop,
|
||||
}),
|
||||
body: {
|
||||
wrapper: VWrapper,
|
||||
row: VRow,
|
||||
cell: VCell,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
export default (
|
||||
treeData: any[],
|
||||
searchValue: string,
|
||||
{
|
||||
treeNodeFilterProp,
|
||||
}: {
|
||||
treeNodeFilterProp: string;
|
||||
},
|
||||
) => {
|
||||
return useMemo(() => {
|
||||
const keys: string[] = [];
|
||||
|
||||
if (!searchValue) {
|
||||
return { treeData, keys };
|
||||
}
|
||||
|
||||
const upperStr = searchValue.toUpperCase();
|
||||
function filterOptionFunc(_: string, dataNode: any[]) {
|
||||
const value = dataNode[treeNodeFilterProp as any];
|
||||
|
||||
return String(value).toUpperCase().includes(upperStr);
|
||||
}
|
||||
|
||||
function dig(list: any[], keepAll: boolean = false): any[] {
|
||||
return list
|
||||
.map((dataNode) => {
|
||||
const children = dataNode.children;
|
||||
|
||||
const match = keepAll || filterOptionFunc!(searchValue, dataNode);
|
||||
const childList = dig(children || [], match);
|
||||
|
||||
if (match || childList.length) {
|
||||
childList.length && keys.push(dataNode.key);
|
||||
return {
|
||||
...dataNode,
|
||||
children: childList,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter((node) => node);
|
||||
}
|
||||
|
||||
return { treeData: dig(treeData), keys };
|
||||
}, [treeData, searchValue, treeNodeFilterProp]);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { MutableRefObject, useLayoutEffect, useState } from 'react';
|
||||
import useResizeObserver from '@react-hook/resize-observer';
|
||||
import { getTableScroll } from '@/utils';
|
||||
|
||||
export default <T extends HTMLElement>(
|
||||
target: MutableRefObject<T>,
|
||||
extraHeight?: number,
|
||||
) => {
|
||||
const [height, setHeight] = useState<number>(0);
|
||||
|
||||
useResizeObserver(target, (entry) => {
|
||||
let _target = entry.target as any;
|
||||
if (!_target.classList.contains('ant-table-wrapper')) {
|
||||
_target = entry.target.querySelector('.ant-table-wrapper');
|
||||
}
|
||||
setHeight(getTableScroll({ extraHeight, target: _target as HTMLElement }));
|
||||
});
|
||||
return height;
|
||||
};
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ContainerOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import IconFont from '@/components/iconfont';
|
||||
import { BasicLayoutProps } from '@ant-design/pro-layout';
|
||||
|
||||
export default {
|
||||
route: {
|
||||
@@ -68,18 +69,18 @@ export default {
|
||||
icon: <IconFont type="ql-icon-dependence" />,
|
||||
component: '@/pages/dependence/index',
|
||||
},
|
||||
{
|
||||
path: '/log',
|
||||
name: '日志管理',
|
||||
icon: <IconFont type="ql-icon-log" />,
|
||||
component: '@/pages/log/index',
|
||||
},
|
||||
{
|
||||
path: '/diff',
|
||||
name: '对比工具',
|
||||
icon: <IconFont type="ql-icon-diff" />,
|
||||
component: '@/pages/diff/index',
|
||||
},
|
||||
{
|
||||
path: '/log',
|
||||
name: '任务日志',
|
||||
icon: <IconFont type="ql-icon-log" />,
|
||||
component: '@/pages/log/index',
|
||||
},
|
||||
{
|
||||
path: '/setting',
|
||||
name: '系统设置',
|
||||
@@ -93,4 +94,4 @@ export default {
|
||||
contentWidth: 'Fixed',
|
||||
splitMenus: false,
|
||||
siderWidth: 180,
|
||||
} as any;
|
||||
} as BasicLayoutProps;
|
||||
|
||||
+72
-17
@@ -9,9 +9,14 @@
|
||||
url('../assets/fonts/SourceCodePro-Regular.ttf') format('truetype');
|
||||
}
|
||||
|
||||
#root {
|
||||
height: 100vh;
|
||||
height: calc(100vh - var(--vh-offset, 0px));
|
||||
}
|
||||
|
||||
.ant-modal-body {
|
||||
max-height: calc(85vh - 110px);
|
||||
max-height: calc(85vh - var(--vh-offset, 110px));
|
||||
max-height: calc(80vh - 110px);
|
||||
max-height: calc(80vh - var(--vh-offset, 110px));
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
@@ -56,7 +61,13 @@
|
||||
overflow: auto;
|
||||
height: 100%;
|
||||
background-color: @component-background;
|
||||
padding: 16px;
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.ql-container-wrapper-has-tab {
|
||||
.ant-pro-grid-content.wide .ant-pro-page-container-children-content {
|
||||
padding-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +147,7 @@
|
||||
flex: 1;
|
||||
|
||||
.ant-pro-grid-content-children {
|
||||
height: calc(100% - 36px);
|
||||
height: 100%;
|
||||
|
||||
> div,
|
||||
.log-container,
|
||||
@@ -155,7 +166,7 @@
|
||||
&.env-wrapper,
|
||||
&.config-wrapper {
|
||||
.CodeMirror {
|
||||
width: calc(100vw - 80px);
|
||||
width: calc(100vw - 24px);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,8 +184,8 @@
|
||||
|
||||
.Resizer {
|
||||
background: @component-background;
|
||||
opacity: 0.2;
|
||||
z-index: 1;
|
||||
opacity: 0.8;
|
||||
z-index: 100;
|
||||
-moz-box-sizing: border-box;
|
||||
-webkit-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
@@ -237,7 +248,6 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
[data-dark='true'] {
|
||||
/* Change autocomplete styles in WebKit */
|
||||
input:-webkit-autofill,
|
||||
input:-webkit-autofill:hover,
|
||||
@@ -248,11 +258,11 @@
|
||||
select:-webkit-autofill,
|
||||
select:-webkit-autofill:hover,
|
||||
select:-webkit-autofill:focus {
|
||||
border: 1px solid @border-color-base;
|
||||
box-shadow: none;
|
||||
transition: background-color 5000s ease-in-out 0s;
|
||||
-webkit-text-fill-color: @text-color;
|
||||
caret-color: #e8e6f3 !important;
|
||||
caret-color: @text-color;
|
||||
color: @text-color;
|
||||
}
|
||||
|
||||
::placeholder {
|
||||
@@ -262,18 +272,25 @@
|
||||
.ant-select-selection-placeholder {
|
||||
opacity: 0.5 !important;
|
||||
}
|
||||
|
||||
.ant-pro-basicLayout-content {
|
||||
margin: 12px;
|
||||
|
||||
.ant-pro-page-container {
|
||||
margin: -12px;
|
||||
}
|
||||
|
||||
.ant-pro-page-container-warp .ant-page-header {
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.ant-pro-page-container-children-content {
|
||||
margin: 18px 18px 18px;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-pro-basicLayout-content {
|
||||
margin: 18px;
|
||||
|
||||
.ant-pro-page-container {
|
||||
margin: -18px -18px -18px;
|
||||
}
|
||||
.ant-pro-global-header {
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.ant-menu-item.ant-pro-sider-collapsed-button {
|
||||
@@ -331,3 +348,41 @@
|
||||
width: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
pre {
|
||||
word-break: break-all !important;
|
||||
white-space: break-spaces !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
.virtuallist {
|
||||
.ant-table-tbody > tr > td > div {
|
||||
white-space: unset !important;
|
||||
}
|
||||
}
|
||||
|
||||
.virtuallist .ant-table-tbody > tr > td > div {
|
||||
box-sizing: border-box;
|
||||
white-space: nowrap;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.virtuallist .ant-table-tbody > tr > td.ant-table-row-expand-icon-cell > div {
|
||||
overflow: inherit;
|
||||
}
|
||||
|
||||
.ant-table-bordered .virtuallist > table > .ant-table-tbody > tr > td {
|
||||
border-right: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.ant-table-column-title {
|
||||
flex: unset;
|
||||
}
|
||||
|
||||
.ant-table-column-sorters,
|
||||
.ant-table-filter-column {
|
||||
justify-content: unset;
|
||||
}
|
||||
|
||||
+100
-56
@@ -2,7 +2,7 @@ import React, { useEffect, useState, useRef } from 'react';
|
||||
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
|
||||
import * as DarkReader from '@umijs/ssr-darkreader';
|
||||
import defaultProps from './defaultProps';
|
||||
import { Link, history } from 'umi';
|
||||
import { Link, history, Outlet, useLocation } from '@umijs/max';
|
||||
import {
|
||||
LogoutOutlined,
|
||||
MenuFoldOutlined,
|
||||
@@ -13,23 +13,60 @@ import config from '@/utils/config';
|
||||
import { request } from '@/utils/http';
|
||||
import './index.less';
|
||||
import vhCheck from 'vh-check';
|
||||
import { version, changeLogLink, changeLog } from '../version';
|
||||
import { useCtx, useTheme } from '@/utils/hooks';
|
||||
import { message, Badge, Modal, Avatar, Dropdown, Menu, Image } from 'antd';
|
||||
import {
|
||||
message,
|
||||
Badge,
|
||||
Modal,
|
||||
Avatar,
|
||||
Dropdown,
|
||||
Menu,
|
||||
Image,
|
||||
Popover,
|
||||
Descriptions,
|
||||
Tooltip,
|
||||
MenuProps,
|
||||
} from 'antd';
|
||||
// @ts-ignore
|
||||
import SockJS from 'sockjs-client';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { init } from '../utils/init';
|
||||
import 'codemirror/mode/javascript/javascript';
|
||||
import 'codemirror/mode/python/python';
|
||||
import 'codemirror/mode/shell/shell';
|
||||
|
||||
export default function (props: any) {
|
||||
export interface SharedContext {
|
||||
headerStyle: React.CSSProperties;
|
||||
isPhone: boolean;
|
||||
theme: 'vs' | 'vs-dark';
|
||||
user: any;
|
||||
reloadUser: (needLoading?: boolean) => void;
|
||||
reloadTheme: () => void;
|
||||
socketMessage: any;
|
||||
systemInfo: TSystemInfo;
|
||||
}
|
||||
|
||||
interface TSystemInfo {
|
||||
branch: 'develop' | 'master';
|
||||
isInitialized: boolean;
|
||||
lastCommitId: string;
|
||||
lastCommitTime: number;
|
||||
version: string;
|
||||
changeLog: string;
|
||||
changeLogLink: string;
|
||||
}
|
||||
|
||||
export default function () {
|
||||
const location = useLocation();
|
||||
const ctx = useCtx();
|
||||
const { theme, reloadTheme } = useTheme();
|
||||
const [user, setUser] = useState<any>({});
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [systemInfo, setSystemInfo] = useState<{ isInitialized: boolean }>();
|
||||
const [systemInfo, setSystemInfo] = useState<TSystemInfo>();
|
||||
const ws = useRef<any>(null);
|
||||
const [socketMessage, setSocketMessage] = useState<any>();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [initLoading, setInitLoading] = useState<boolean>(true);
|
||||
const {
|
||||
enable: enableDarkMode,
|
||||
disable: disableDarkMode,
|
||||
@@ -53,17 +90,16 @@ export default function (props: any) {
|
||||
setSystemInfo(data);
|
||||
if (!data.isInitialized) {
|
||||
history.push('/initialization');
|
||||
setLoading(false);
|
||||
} else {
|
||||
init(data.version);
|
||||
getUser();
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
});
|
||||
})
|
||||
.finally(() => setInitLoading(false));
|
||||
};
|
||||
|
||||
const getUser = (needLoading = true) => {
|
||||
@@ -73,11 +109,9 @@ export default function (props: any) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200 && data.username) {
|
||||
setUser(data);
|
||||
if (props.location.pathname === '/') {
|
||||
if (location.pathname === '/') {
|
||||
history.push('/crontab');
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
needLoading && setLoading(false);
|
||||
})
|
||||
@@ -94,7 +128,7 @@ export default function (props: any) {
|
||||
if (systemInfo && systemInfo.isInitialized && !user) {
|
||||
getUser();
|
||||
}
|
||||
}, [props.location.pathname]);
|
||||
}, [location.pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!systemInfo) {
|
||||
@@ -112,7 +146,6 @@ export default function (props: any) {
|
||||
|
||||
useEffect(() => {
|
||||
vhCheck();
|
||||
init();
|
||||
|
||||
const _theme = localStorage.getItem('qinglong_dark_theme') || 'auto';
|
||||
if (typeof window === 'undefined') return;
|
||||
@@ -136,9 +169,11 @@ export default function (props: any) {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
if (!user || !user.username) return;
|
||||
ws.current = new SockJS(
|
||||
`${location.origin}/api/ws?token=${localStorage.getItem(config.authKey)}`,
|
||||
`${window.location.origin}/api/ws?token=${localStorage.getItem(
|
||||
config.authKey,
|
||||
)}`,
|
||||
);
|
||||
|
||||
ws.current.onmessage = (e: any) => {
|
||||
@@ -146,9 +181,9 @@ export default function (props: any) {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'ping') {
|
||||
if (data && data.message === 'hanhh') {
|
||||
console.log('websocket连接成功', e);
|
||||
console.log('WS connection succeeded !!!');
|
||||
} else {
|
||||
console.log('websocket连接失败', e);
|
||||
console.log('WS connection Failed !!!', e);
|
||||
}
|
||||
}
|
||||
setSocketMessage(data);
|
||||
@@ -183,30 +218,28 @@ export default function (props: any) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (
|
||||
['/login', '/initialization', '/error'].includes(props.location.pathname)
|
||||
) {
|
||||
document.title = `${
|
||||
(config.documentTitleMap as any)[props.location.pathname]
|
||||
} - 控制面板`;
|
||||
if (
|
||||
systemInfo?.isInitialized &&
|
||||
props.location.pathname === '/initialization'
|
||||
) {
|
||||
if (initLoading) {
|
||||
return <PageLoading />;
|
||||
}
|
||||
|
||||
if (['/login', '/initialization', '/error'].includes(location.pathname)) {
|
||||
if (systemInfo?.isInitialized && location.pathname === '/initialization') {
|
||||
history.push('/crontab');
|
||||
}
|
||||
|
||||
if (systemInfo || props.location.pathname === '/error') {
|
||||
return React.Children.map(props.children, (child) => {
|
||||
return React.cloneElement(child, {
|
||||
if (systemInfo || location.pathname === '/error') {
|
||||
return (
|
||||
<Outlet
|
||||
context={{
|
||||
...ctx,
|
||||
theme,
|
||||
user,
|
||||
reloadUser,
|
||||
reloadTheme,
|
||||
ws: ws.current,
|
||||
});
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,32 +249,41 @@ export default function (props: any) {
|
||||
!navigator.userAgent.includes('Chrome');
|
||||
const isQQBrowser = navigator.userAgent.includes('QQBrowser');
|
||||
|
||||
const menu = (
|
||||
<Menu
|
||||
className="side-menu-user-drop-menu"
|
||||
items={[{ label: '退出登录', key: 'logout', icon: <LogoutOutlined /> }]}
|
||||
onClick={logout}
|
||||
/>
|
||||
);
|
||||
const menu: MenuProps = {
|
||||
items: [
|
||||
{
|
||||
label: '退出登录',
|
||||
className: 'side-menu-user-drop-menu',
|
||||
onClick: logout,
|
||||
key: 'logout',
|
||||
icon: <LogoutOutlined />,
|
||||
},
|
||||
],
|
||||
};
|
||||
return loading ? (
|
||||
<PageLoading />
|
||||
) : (
|
||||
<ProLayout
|
||||
selectedKeys={[props.location.pathname]}
|
||||
selectedKeys={[location.pathname]}
|
||||
loading={loading}
|
||||
ErrorBoundary={Sentry.ErrorBoundary}
|
||||
logo={<Image preview={false} src="http://qn.whyour.cn/logo.png" />}
|
||||
logo={<Image preview={false} src="https://qn.whyour.cn/logo.png" />}
|
||||
// @ts-ignore
|
||||
title={
|
||||
<>
|
||||
<span style={{ fontSize: 16 }}>控制面板</span>
|
||||
<a
|
||||
href={changeLogLink}
|
||||
href={systemInfo?.changeLogLink}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
<Tooltip
|
||||
title={systemInfo?.branch === 'develop' ? '开发版' : '正式版'}
|
||||
>
|
||||
<Badge size="small" dot={systemInfo?.branch === 'develop'}>
|
||||
<span
|
||||
style={{
|
||||
fontSize: isFirefox ? 9 : 12,
|
||||
@@ -251,8 +293,10 @@ export default function (props: any) {
|
||||
letterSpacing: isQQBrowser ? -2 : 0,
|
||||
}}
|
||||
>
|
||||
v{version}
|
||||
v{systemInfo?.version}
|
||||
</span>
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
</a>
|
||||
</>
|
||||
}
|
||||
@@ -267,22 +311,21 @@ export default function (props: any) {
|
||||
return <Link to={menuItemProps.path}>{defaultDom}</Link>;
|
||||
}}
|
||||
pageTitleRender={(props, pageName, info) => {
|
||||
if (info && typeof info.pageName === 'string') {
|
||||
return `${info.pageName} - 控制面板`;
|
||||
}
|
||||
return '控制面板';
|
||||
const title =
|
||||
(config.documentTitleMap as any)[location.pathname] || '未找到';
|
||||
return `${title} - 控制面板`;
|
||||
}}
|
||||
onCollapse={setCollapsed}
|
||||
collapsed={collapsed}
|
||||
rightContentRender={() =>
|
||||
ctx.isPhone && (
|
||||
<Dropdown overlay={menu} placement="bottomRight" trigger={['click']}>
|
||||
<Dropdown menu={menu} placement="bottomRight" trigger={['click']}>
|
||||
<span className="side-menu-user-wrapper">
|
||||
<Avatar
|
||||
shape="square"
|
||||
size="small"
|
||||
icon={<UserOutlined />}
|
||||
src={`/api/static/${user.avatar}`}
|
||||
src={user.avatar ? `/api/static/${user.avatar}` : ''}
|
||||
/>
|
||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||
</span>
|
||||
@@ -298,13 +341,13 @@ export default function (props: any) {
|
||||
}}
|
||||
>
|
||||
{!collapsed && !ctx.isPhone && (
|
||||
<Dropdown overlay={menu} placement="topLeft" trigger={['hover']}>
|
||||
<Dropdown menu={menu} placement="topLeft" trigger={['hover']}>
|
||||
<span className="side-menu-user-wrapper">
|
||||
<Avatar
|
||||
shape="square"
|
||||
size="small"
|
||||
icon={<UserOutlined />}
|
||||
src={`/api/static/${user.avatar}`}
|
||||
src={user.avatar ? `/api/static/${user.avatar}` : ''}
|
||||
/>
|
||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||
</span>
|
||||
@@ -320,16 +363,17 @@ export default function (props: any) {
|
||||
)}
|
||||
{...defaultProps}
|
||||
>
|
||||
{React.Children.map(props.children, (child) => {
|
||||
return React.cloneElement(child, {
|
||||
<Outlet
|
||||
context={{
|
||||
...ctx,
|
||||
theme,
|
||||
user,
|
||||
reloadUser,
|
||||
reloadTheme,
|
||||
socketMessage,
|
||||
});
|
||||
})}
|
||||
systemInfo,
|
||||
}}
|
||||
/>
|
||||
</ProLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { Button, Result, Typography } from 'antd';
|
||||
|
||||
const { Link } = Typography;
|
||||
|
||||
const NotFound: React.FC = () => (
|
||||
<Result
|
||||
status="404"
|
||||
title="404"
|
||||
extra={
|
||||
<Button type="primary">
|
||||
<Link href="/">返回首页</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
|
||||
export default NotFound;
|
||||
@@ -11,8 +11,11 @@ import { PageContainer } from '@ant-design/pro-layout';
|
||||
import { request } from '@/utils/http';
|
||||
import Editor from '@monaco-editor/react';
|
||||
import { Controlled as CodeMirror } from 'react-codemirror2';
|
||||
import { useOutletContext } from '@umijs/max';
|
||||
import { SharedContext } from '@/layouts';
|
||||
|
||||
const Config = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const Config = () => {
|
||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
||||
const [value, setValue] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [title, setTitle] = useState('config.sh');
|
||||
@@ -22,8 +25,10 @@ const Config = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const [confirmLoading, setConfirmLoading] = useState(false);
|
||||
|
||||
const getConfig = (name: string) => {
|
||||
request.get(`${config.apiPrefix}configs/${name}`).then((data: any) => {
|
||||
setValue(data.data);
|
||||
request.get(`${config.apiPrefix}configs/${name}`).then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setValue(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -31,8 +36,10 @@ const Config = ({ headerStyle, isPhone, theme }: any) => {
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}configs/files`)
|
||||
.then((data: any) => {
|
||||
setData(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setData(data);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -47,8 +54,10 @@ const Config = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.post(`${config.apiPrefix}configs/save`, {
|
||||
data: { content, name: select },
|
||||
})
|
||||
.then((data: any) => {
|
||||
message.success(data.message);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('保存成功');
|
||||
}
|
||||
setConfirmLoading(false);
|
||||
});
|
||||
};
|
||||
@@ -71,6 +80,7 @@ const Config = ({ headerStyle, isPhone, theme }: any) => {
|
||||
loading={loading}
|
||||
extra={[
|
||||
<TreeSelect
|
||||
treeExpandAction="click"
|
||||
className="config-select"
|
||||
value={select}
|
||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||
|
||||
@@ -29,6 +29,7 @@ import config from '@/utils/config';
|
||||
import CronLogModal from './logModal';
|
||||
import Editor from '@monaco-editor/react';
|
||||
import IconFont from '@/components/iconfont';
|
||||
import { getCommandScript } from '@/utils';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
@@ -103,12 +104,10 @@ const CronDetailModal = ({
|
||||
fontSize: 12,
|
||||
lineNumbersMinChars: 3,
|
||||
fontFamily: 'Source Code Pro',
|
||||
folding: false,
|
||||
glyphMargin: false,
|
||||
wordWrap: 'on',
|
||||
}}
|
||||
onMount={(editor, monaco) => {
|
||||
console.log(monaco);
|
||||
editorRef.current = editor;
|
||||
}}
|
||||
/>
|
||||
@@ -124,9 +123,11 @@ const CronDetailModal = ({
|
||||
.get(
|
||||
`${config.apiPrefix}logs/${item.filename}?path=${item.directory || ''}`,
|
||||
)
|
||||
.then((data) => {
|
||||
setLog(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setLog(data);
|
||||
setIsLogModalVisible(true);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -138,34 +139,28 @@ const CronDetailModal = ({
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}crons/${cron.id}/logs`)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setLogs(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setLogs(data);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const getScript = () => {
|
||||
const cmd = cron.command.split(' ') as string[];
|
||||
if (cmd[0] === 'task') {
|
||||
const result = getCommandScript(cron.command);
|
||||
if (Array.isArray(result)) {
|
||||
setValidTabs(validTabs);
|
||||
if (cmd[1].startsWith('/ql/data/scripts')) {
|
||||
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
||||
}
|
||||
|
||||
let [p, s] = cmd[1].split('/');
|
||||
if (!s) {
|
||||
s = p;
|
||||
p = '';
|
||||
}
|
||||
const [s, p] = result;
|
||||
setScriptInfo({ parent: p, filename: s });
|
||||
request
|
||||
.get(`${config.apiPrefix}scripts/${s}?path=${p || ''}`)
|
||||
.then((data) => {
|
||||
setValue(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setValue(data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
} else if (result) {
|
||||
setValidTabs([validTabs[0]]);
|
||||
}
|
||||
};
|
||||
@@ -195,12 +190,10 @@ const CronDetailModal = ({
|
||||
content,
|
||||
},
|
||||
})
|
||||
.then((_data: any) => {
|
||||
if (_data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setValue(content);
|
||||
message.success(`保存成功`);
|
||||
} else {
|
||||
message.error(_data);
|
||||
}
|
||||
resolve(null);
|
||||
})
|
||||
@@ -228,14 +221,12 @@ const CronDetailModal = ({
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/run`, { data: [currentCron.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setCurrentCron({ ...currentCron, status: CrontabStatus.running });
|
||||
setTimeout(() => {
|
||||
getLogs();
|
||||
}, 1000);
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -260,11 +251,9 @@ const CronDetailModal = ({
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/stop`, { data: [currentCron.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setCurrentCron({ ...currentCron, status: CrontabStatus.idle });
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -297,14 +286,12 @@ const CronDetailModal = ({
|
||||
data: [currentCron.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setCurrentCron({
|
||||
...currentCron,
|
||||
isDisabled: currentCron.isDisabled === 1 ? 0 : 1,
|
||||
});
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -337,14 +324,12 @@ const CronDetailModal = ({
|
||||
data: [currentCron.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setCurrentCron({
|
||||
...currentCron,
|
||||
isPinned: currentCron.isPinned === 1 ? 0 : 1,
|
||||
});
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -379,7 +364,7 @@ const CronDetailModal = ({
|
||||
{currentCron.labels?.length > 0 &&
|
||||
currentCron.labels[0] !== '' &&
|
||||
currentCron.labels?.map((label: string, i: number) => (
|
||||
<Tag color="blue" style={{ marginRight: 5 }}>
|
||||
<Tag key={label} color="blue" style={{ marginRight: 5 }}>
|
||||
{label}
|
||||
</Tag>
|
||||
))}
|
||||
@@ -442,7 +427,7 @@ const CronDetailModal = ({
|
||||
</div>
|
||||
}
|
||||
centered
|
||||
visible={visible}
|
||||
open={visible}
|
||||
forceRender
|
||||
footer={false}
|
||||
onCancel={() => handleCancel()}
|
||||
|
||||
+101
-11
@@ -2,21 +2,12 @@
|
||||
margin-bottom: 0 !important;
|
||||
}
|
||||
|
||||
.cron {
|
||||
&:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.crontab-detail {
|
||||
.card-wrapper {
|
||||
height: 80vh;
|
||||
height: calc(80vh - var(--vh-offset, 0px));
|
||||
|
||||
.ant-card:last-child {
|
||||
.ant-card-body {
|
||||
height: calc(80vh - 238px);
|
||||
height: calc(80vh - var(--vh-offset, 0px) - 238px);
|
||||
height: calc(80vh - 367px);
|
||||
height: calc(80vh - var(--vh-offset, 0px) - 367px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
}
|
||||
@@ -101,3 +92,102 @@
|
||||
background: #fafafa;
|
||||
}
|
||||
}
|
||||
|
||||
.crontab-view {
|
||||
.ant-tabs-nav-wrap {
|
||||
flex: unset !important;
|
||||
}
|
||||
|
||||
.ant-tabs-nav-operations {
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.view-more {
|
||||
margin-left: 32px;
|
||||
padding: 8px 0;
|
||||
cursor: pointer;
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 0;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: #1890ff;
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 50px;
|
||||
}
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: #1890ff;
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 50px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.more-active {
|
||||
.ant-tabs-nav-list {
|
||||
.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
|
||||
color: unset;
|
||||
}
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 0 !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.view-create-modal-filters {
|
||||
display: flex;
|
||||
|
||||
.ant-space-item:nth-child(3) {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.view-create-modal-sorts {
|
||||
display: flex;
|
||||
|
||||
.ant-space-item:nth-child(2) {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
tr.drop-over-downward td {
|
||||
border-bottom: 2px dashed #1890ff;
|
||||
}
|
||||
|
||||
tr.drop-over-upward td {
|
||||
border-top: 2px dashed #1890ff;
|
||||
}
|
||||
|
||||
.view-manage-modal {
|
||||
.ant-modal-body {
|
||||
padding-top: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.view-filters-container.active {
|
||||
.filter-item > div > .ant-form-item-control {
|
||||
margin-left: 40px;
|
||||
}
|
||||
}
|
||||
|
||||
.log-modal {
|
||||
.log-container {
|
||||
overflow-y: auto;
|
||||
min-height: 300px;
|
||||
max-height: calc(80vh - 110px);
|
||||
max-height: calc(80vh - var(--vh-offset, 110px));
|
||||
|
||||
padding: 24px;
|
||||
margin: -24px;
|
||||
}
|
||||
}
|
||||
|
||||
+337
-170
@@ -1,4 +1,4 @@
|
||||
import React, { PureComponent, Fragment, useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef, useMemo } from 'react';
|
||||
import {
|
||||
Button,
|
||||
message,
|
||||
@@ -12,6 +12,9 @@ import {
|
||||
Typography,
|
||||
Input,
|
||||
Popover,
|
||||
Tabs,
|
||||
TablePaginationConfig,
|
||||
MenuProps,
|
||||
} from 'antd';
|
||||
import {
|
||||
ClockCircleOutlined,
|
||||
@@ -27,6 +30,11 @@ import {
|
||||
PauseCircleOutlined,
|
||||
FieldTimeOutlined,
|
||||
PushpinOutlined,
|
||||
DownOutlined,
|
||||
SettingOutlined,
|
||||
PlusOutlined,
|
||||
UnorderedListOutlined,
|
||||
CheckOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import config from '@/utils/config';
|
||||
import { PageContainer } from '@ant-design/pro-layout';
|
||||
@@ -36,9 +44,16 @@ import CronLogModal from './logModal';
|
||||
import CronDetailModal from './detail';
|
||||
import cron_parser from 'cron-parser';
|
||||
import { diffTime } from '@/utils/date';
|
||||
import { getTableScroll } from '@/utils/index';
|
||||
import { history } from 'umi';
|
||||
import { history, useOutletContext } from '@umijs/max';
|
||||
import './index.less';
|
||||
import ViewCreateModal from './viewCreateModal';
|
||||
import ViewManageModal from './viewManageModal';
|
||||
import { FilterValue, SorterResult } from 'antd/lib/table/interface';
|
||||
import { SharedContext } from '@/layouts';
|
||||
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
||||
import { getCommandScript, parseCrontab } from '@/utils';
|
||||
import { ColumnProps } from 'antd/lib/table';
|
||||
import { VList } from '../../components/vlist';
|
||||
|
||||
const { Text, Paragraph } = Typography;
|
||||
const { Search } = Input;
|
||||
@@ -70,22 +85,37 @@ enum OperationPath {
|
||||
'unpin',
|
||||
}
|
||||
|
||||
const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const columns: any = [
|
||||
export interface ICrontab {
|
||||
name: string;
|
||||
command: string;
|
||||
schedule: string;
|
||||
id: number;
|
||||
status: number;
|
||||
isDisabled?: 1 | 0;
|
||||
isPinned?: 1 | 0;
|
||||
labels?: string[];
|
||||
last_running_time?: number;
|
||||
last_execution_time?: number;
|
||||
nextRunTime: Date;
|
||||
}
|
||||
|
||||
const Crontab = () => {
|
||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
||||
const columns: ColumnProps<ICrontab>[] = [
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 150,
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any) => (
|
||||
<>
|
||||
<a
|
||||
onClick={() => {
|
||||
goToScriptManager(record);
|
||||
setDetailCron(record);
|
||||
setIsDetailModalVisible(true);
|
||||
}}
|
||||
>
|
||||
{record.labels?.length > 0 && record.labels[0] !== '' ? (
|
||||
{record.labels?.length > 0 && record.labels[0] !== '' && false ? (
|
||||
<Popover
|
||||
placement="right"
|
||||
trigger={isPhone ? 'click' : 'hover'}
|
||||
@@ -94,10 +124,12 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
{record.labels?.map((label: string) => (
|
||||
<Tag
|
||||
color="blue"
|
||||
key={label}
|
||||
style={{ cursor: 'point' }}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setSearchValue(`label:${label}`);
|
||||
setSearchText(`label:${label}`);
|
||||
}}
|
||||
>
|
||||
<a>{label}</a>
|
||||
@@ -122,33 +154,35 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
</>
|
||||
),
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => a.name.localeCompare(b.name),
|
||||
multiple: 2,
|
||||
compare: (a, b) => a?.name?.localeCompare(b?.name),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '命令',
|
||||
title: '命令/脚本',
|
||||
dataIndex: 'command',
|
||||
key: 'command',
|
||||
width: 250,
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any) => {
|
||||
width: 300,
|
||||
render: (text, record) => {
|
||||
return (
|
||||
<Paragraph
|
||||
style={{
|
||||
wordBreak: 'break-all',
|
||||
marginBottom: 0,
|
||||
textAlign: 'left',
|
||||
}}
|
||||
ellipsis={{ tooltip: text, rows: 2 }}
|
||||
>
|
||||
<a
|
||||
onClick={() => {
|
||||
goToScriptManager(record);
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</a>
|
||||
</Paragraph>
|
||||
);
|
||||
},
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => a.command.localeCompare(b.command),
|
||||
multiple: 3,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -156,22 +190,21 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
dataIndex: 'schedule',
|
||||
key: 'schedule',
|
||||
width: 110,
|
||||
align: 'center' as const,
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => a.schedule.localeCompare(b.schedule),
|
||||
multiple: 1,
|
||||
compare: (a, b) => a.schedule.localeCompare(b.schedule),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '最后运行时间',
|
||||
align: 'center' as const,
|
||||
dataIndex: 'last_execution_time',
|
||||
key: 'last_execution_time',
|
||||
width: 150,
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => {
|
||||
return a.last_execution_time - b.last_execution_time;
|
||||
compare: (a, b) => {
|
||||
return (a.last_execution_time || 0) - (b.last_execution_time || 0);
|
||||
},
|
||||
},
|
||||
render: (text: string, record: any) => {
|
||||
render: (text, record) => {
|
||||
const language = navigator.language || navigator.languages[0];
|
||||
return (
|
||||
<span
|
||||
@@ -192,14 +225,15 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
},
|
||||
{
|
||||
title: '最后运行时长',
|
||||
align: 'center' as const,
|
||||
width: 120,
|
||||
dataIndex: 'last_running_time',
|
||||
key: 'last_running_time',
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => {
|
||||
return a.last_running_time - b.last_running_time;
|
||||
},
|
||||
},
|
||||
render: (text: string, record: any) => {
|
||||
render: (text, record) => {
|
||||
return record.last_running_time
|
||||
? diffTime(record.last_running_time)
|
||||
: '-';
|
||||
@@ -207,14 +241,13 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
},
|
||||
{
|
||||
title: '下次运行时间',
|
||||
align: 'center' as const,
|
||||
width: 150,
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => {
|
||||
return a.nextRunTime - b.nextRunTime;
|
||||
},
|
||||
},
|
||||
render: (text: string, record: any) => {
|
||||
render: (text, record) => {
|
||||
const language = navigator.language || navigator.languages[0];
|
||||
return record.nextRunTime
|
||||
.toLocaleString(language, {
|
||||
@@ -223,13 +256,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.replace(' 24:', ' 00:');
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
title: '状态',
|
||||
key: 'status',
|
||||
dataIndex: 'status',
|
||||
align: 'center' as const,
|
||||
width: 85,
|
||||
width: 88,
|
||||
filters: [
|
||||
{
|
||||
text: '运行中',
|
||||
@@ -248,14 +279,14 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
value: 3,
|
||||
},
|
||||
],
|
||||
onFilter: (value: number, record: any) => {
|
||||
onFilter: (value, record) => {
|
||||
if (record.isDisabled && record.status !== 0) {
|
||||
return value === 2;
|
||||
} else {
|
||||
return record.status === value;
|
||||
}
|
||||
},
|
||||
render: (text: string, record: any) => (
|
||||
render: (text, record) => (
|
||||
<>
|
||||
{(!record.isDisabled || record.status !== CrontabStatus.idle) && (
|
||||
<>
|
||||
@@ -290,9 +321,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
align: 'center' as const,
|
||||
width: 100,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
render: (text, record, index) => {
|
||||
const isPc = !isPhone;
|
||||
return (
|
||||
<Space size="middle">
|
||||
@@ -300,6 +330,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Tooltip title={isPc ? '运行' : ''}>
|
||||
<a
|
||||
onClick={(e) => {
|
||||
setReset(false);
|
||||
e.stopPropagation();
|
||||
runCron(record, index);
|
||||
}}
|
||||
@@ -312,6 +343,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Tooltip title={isPc ? '停止' : ''}>
|
||||
<a
|
||||
onClick={(e) => {
|
||||
setReset(false);
|
||||
e.stopPropagation();
|
||||
stopCron(record, index);
|
||||
}}
|
||||
@@ -323,6 +355,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Tooltip title={isPc ? '日志' : ''}>
|
||||
<a
|
||||
onClick={(e) => {
|
||||
setReset(false);
|
||||
e.stopPropagation();
|
||||
setLogCron({ ...record, timestamp: Date.now() });
|
||||
}}
|
||||
@@ -346,64 +379,77 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
||||
const [logCron, setLogCron] = useState<any>();
|
||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||
const [pageConf, setPageConf] = useState<{
|
||||
page: number;
|
||||
size: number;
|
||||
sorter: any;
|
||||
filters: any;
|
||||
}>({} as any);
|
||||
const [viewConf, setViewConf] = useState<any>();
|
||||
const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
|
||||
const [detailCron, setDetailCron] = useState<any>();
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const [total, setTotal] = useState<number>();
|
||||
const [isCreateViewModalVisible, setIsCreateViewModalVisible] =
|
||||
useState(false);
|
||||
const [isViewManageModalVisible, setIsViewManageModalVisible] =
|
||||
useState(false);
|
||||
const [cronViews, setCronViews] = useState<any[]>([]);
|
||||
const [enabledCronViews, setEnabledCronViews] = useState<any[]>([]);
|
||||
const [moreMenuActive, setMoreMenuActive] = useState(false);
|
||||
const tableRef = useRef<any>();
|
||||
const tableScrollHeight = useTableScrollHeight(tableRef);
|
||||
const resetRef = useRef<boolean>(true);
|
||||
const setReset = (v) => {
|
||||
resetRef.current = v;
|
||||
};
|
||||
|
||||
const goToScriptManager = (record: any) => {
|
||||
const cmd = record.command.split(' ') as string[];
|
||||
if (cmd[0] === 'task') {
|
||||
if (cmd[1].startsWith('/ql/data/scripts')) {
|
||||
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
||||
}
|
||||
|
||||
let [p, s] = cmd[1].split('/');
|
||||
if (!s) {
|
||||
s = p;
|
||||
p = '';
|
||||
}
|
||||
const result = getCommandScript(record.command);
|
||||
if (Array.isArray(result)) {
|
||||
const [s, p] = result;
|
||||
history.push(`/script?p=${p}&s=${s}`);
|
||||
} else if (cmd[1] === 'repo') {
|
||||
location.href = cmd[2];
|
||||
} else if (result) {
|
||||
location.href = result;
|
||||
}
|
||||
};
|
||||
|
||||
const getCrons = () => {
|
||||
setLoading(true);
|
||||
const { page, size, sorter, filters } = pageConf;
|
||||
let url = `${
|
||||
config.apiPrefix
|
||||
}crons?searchValue=${searchText}&page=${page}&size=${size}&filters=${JSON.stringify(
|
||||
filters,
|
||||
)}`;
|
||||
if (sorter && sorter.column && sorter.order) {
|
||||
url += `&sorter=${JSON.stringify({
|
||||
field: sorter.column.key,
|
||||
type: sorter.order === 'ascend' ? 'ASC' : 'DESC',
|
||||
})}`;
|
||||
}
|
||||
if (viewConf) {
|
||||
url += `&queryString=${JSON.stringify({
|
||||
filters: viewConf.filters,
|
||||
sorts: viewConf.sorts,
|
||||
filterRelation: viewConf.filterRelation || 'and',
|
||||
})}`;
|
||||
}
|
||||
request
|
||||
.get(`${config.apiPrefix}crons?searchValue=${searchText}`)
|
||||
.then((data: any) => {
|
||||
.get(url)
|
||||
.then(({ code, data: _data }) => {
|
||||
if (code === 200) {
|
||||
const { data, total } = _data;
|
||||
setValue(
|
||||
data.data
|
||||
.sort((a: any, b: any) => {
|
||||
const sortA =
|
||||
a.isPinned && a.status !== 0
|
||||
? 5
|
||||
: a.isDisabled && a.status !== 0
|
||||
? 4
|
||||
: a.status;
|
||||
const sortB =
|
||||
b.isPinned && b.status !== 0
|
||||
? 5
|
||||
: b.isDisabled && b.status !== 0
|
||||
? 4
|
||||
: b.status;
|
||||
return CrontabSort[sortA] - CrontabSort[sortB];
|
||||
})
|
||||
.map((x) => {
|
||||
data.map((x) => {
|
||||
return {
|
||||
...x,
|
||||
nextRunTime: cron_parser
|
||||
.parseExpression(x.schedule)
|
||||
.next()
|
||||
.toDate(),
|
||||
nextRunTime: parseCrontab(x.schedule),
|
||||
};
|
||||
}),
|
||||
);
|
||||
setCurrentPage(1);
|
||||
setTotal(total);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -433,8 +479,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}crons`, { data: [record.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('删除成功');
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
@@ -442,8 +488,6 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
result.splice(i, 1);
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -468,8 +512,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/run`, { data: [record.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
@@ -479,8 +523,6 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -505,8 +547,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/stop`, { data: [record.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
@@ -517,8 +559,6 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -551,8 +591,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
data: [record.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const newStatus = record.isDisabled === 1 ? 0 : 1;
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
@@ -563,8 +603,6 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -597,8 +635,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
data: [record.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const newStatus = record.isPinned === 1 ? 0 : 1;
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
@@ -609,8 +647,6 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -646,15 +682,14 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
arrow={{ pointAtCenter: true }}
|
||||
placement="bottomRight"
|
||||
trigger={['click']}
|
||||
overlay={
|
||||
<Menu
|
||||
items={getMenuItems(record)}
|
||||
onClick={({ key, domEvent }) => {
|
||||
menu={{
|
||||
items: getMenuItems(record),
|
||||
onClick: ({ key, domEvent }) => {
|
||||
domEvent.stopPropagation();
|
||||
setReset(false);
|
||||
action(key, record, index);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<a onClick={(e) => e.stopPropagation()}>
|
||||
<EllipsisOutlined />
|
||||
@@ -681,73 +716,47 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = (cron?: any) => {
|
||||
const handleCancel = () => {
|
||||
setIsModalVisible(false);
|
||||
if (cron) {
|
||||
handleCrons(cron);
|
||||
}
|
||||
getCrons();
|
||||
};
|
||||
|
||||
const onSearch = (value: string) => {
|
||||
setReset(true);
|
||||
setSearchText(value.trim());
|
||||
};
|
||||
|
||||
const handleCrons = (cron: any) => {
|
||||
const index = value.findIndex((x) => x.id === cron.id);
|
||||
const result = [...value];
|
||||
cron.nextRunTime = cron_parser
|
||||
.parseExpression(cron.schedule)
|
||||
.next()
|
||||
.toDate();
|
||||
if (index === -1) {
|
||||
result.unshift(cron);
|
||||
} else {
|
||||
result.splice(index, 1, {
|
||||
...cron,
|
||||
});
|
||||
}
|
||||
setValue(result);
|
||||
};
|
||||
|
||||
const getCronDetail = (cron: any) => {
|
||||
request
|
||||
.get(`${config.apiPrefix}crons/${cron.id}`)
|
||||
.then((data: any) => {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const index = value.findIndex((x) => x.id === cron.id);
|
||||
const result = [...value];
|
||||
data.data.nextRunTime = cron_parser
|
||||
.parseExpression(data.data.schedule)
|
||||
.next()
|
||||
.toDate();
|
||||
data.nextRunTime = parseCrontab(data.schedule);
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1, {
|
||||
...cron,
|
||||
...data.data,
|
||||
...data,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const onSelectChange = (selectedIds: any[]) => {
|
||||
setSelectedRowIds(selectedIds);
|
||||
|
||||
setTimeout(() => {
|
||||
if (selectedRowIds.length === 0 || selectedIds.length === 0) {
|
||||
setTableScrollHeight(getTableScroll());
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setReset(false);
|
||||
}, [selectedRowIds]);
|
||||
|
||||
const rowSelection = {
|
||||
selectedRowIds,
|
||||
selectedRowKeys: selectedRowIds,
|
||||
onChange: onSelectChange,
|
||||
selections: [
|
||||
Table.SELECTION_ALL,
|
||||
Table.SELECTION_INVERT,
|
||||
Table.SELECTION_NONE,
|
||||
],
|
||||
};
|
||||
|
||||
const delCrons = () => {
|
||||
@@ -757,13 +766,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}crons`, { data: selectedRowIds })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('批量删除成功');
|
||||
setSelectedRowIds([]);
|
||||
getCrons();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -774,6 +781,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
};
|
||||
|
||||
const operateCrons = (operationStatus: number) => {
|
||||
setReset(false);
|
||||
Modal.confirm({
|
||||
title: `确认${OperationName[operationStatus]}`,
|
||||
content: <>确认{OperationName[operationStatus]}选中的定时任务吗</>,
|
||||
@@ -782,11 +790,9 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.put(`${config.apiPrefix}crons/${OperationPath[operationStatus]}`, {
|
||||
data: selectedRowIds,
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
getCrons();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -796,10 +802,20 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
};
|
||||
|
||||
const onPageChange = (page: number, pageSize: number | undefined) => {
|
||||
setCurrentPage(page);
|
||||
setPageSize(pageSize as number);
|
||||
localStorage.setItem('pageSize', pageSize + '');
|
||||
const onPageChange = (
|
||||
pagination: TablePaginationConfig,
|
||||
filters: Record<string, FilterValue | null>,
|
||||
sorter: SorterResult<any> | SorterResult<any>[],
|
||||
) => {
|
||||
const { current, pageSize } = pagination;
|
||||
setReset(true);
|
||||
setPageConf({
|
||||
page: current as number,
|
||||
size: pageSize as number,
|
||||
sorter,
|
||||
filters,
|
||||
});
|
||||
localStorage.setItem('pageSize', String(pageSize));
|
||||
};
|
||||
|
||||
const getRowClassName = (record: any, index: number) => {
|
||||
@@ -814,19 +830,118 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
}, [logCron]);
|
||||
|
||||
useEffect(() => {
|
||||
getCrons();
|
||||
setPageConf({ ...pageConf, page: 1 });
|
||||
}, [searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
setPageSize(parseInt(localStorage.getItem('pageSize') || '20'));
|
||||
setTimeout(() => {
|
||||
setTableScrollHeight(getTableScroll());
|
||||
if (pageConf.page && pageConf.size) {
|
||||
getCrons();
|
||||
}
|
||||
}, [pageConf, viewConf]);
|
||||
|
||||
useEffect(() => {
|
||||
if (viewConf && enabledCronViews && enabledCronViews.length > 0) {
|
||||
const view = enabledCronViews.slice(4).find((x) => x.id === viewConf.id);
|
||||
setMoreMenuActive(!!view);
|
||||
}
|
||||
}, [viewConf, enabledCronViews]);
|
||||
|
||||
useEffect(() => {
|
||||
setPageConf({
|
||||
page: 1,
|
||||
size: parseInt(localStorage.getItem('pageSize') || '20'),
|
||||
sorter: {},
|
||||
filters: {},
|
||||
});
|
||||
getCronViews();
|
||||
}, []);
|
||||
|
||||
const viewAction = (key: string) => {
|
||||
switch (key) {
|
||||
case 'new':
|
||||
setIsCreateViewModalVisible(true);
|
||||
break;
|
||||
case 'manage':
|
||||
setIsViewManageModalVisible(true);
|
||||
break;
|
||||
|
||||
default:
|
||||
tabClick(key);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const menu: MenuProps = {
|
||||
onClick: ({ key, domEvent }) => {
|
||||
domEvent.stopPropagation();
|
||||
viewAction(key);
|
||||
},
|
||||
items: [
|
||||
...[...enabledCronViews].slice(4).map((x) => ({
|
||||
label: (
|
||||
<Space style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>{x.name}</span>
|
||||
{viewConf?.id === x.id && (
|
||||
<CheckOutlined style={{ color: '#1890ff' }} />
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
key: x.id,
|
||||
icon: <UnorderedListOutlined />,
|
||||
})),
|
||||
{
|
||||
type: 'divider' as 'group',
|
||||
},
|
||||
{
|
||||
label: '新建视图',
|
||||
key: 'new',
|
||||
icon: <PlusOutlined />,
|
||||
},
|
||||
{
|
||||
label: '视图管理',
|
||||
key: 'manage',
|
||||
icon: <SettingOutlined />,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const getCronViews = () => {
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}crons/views`)
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setCronViews(data);
|
||||
setEnabledCronViews(data.filter((x) => !x.isDisabled));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
};
|
||||
|
||||
const tabClick = (key: string) => {
|
||||
const view = enabledCronViews.find((x) => x.id == key);
|
||||
setSelectedRowIds([]);
|
||||
setReset(true);
|
||||
setPageConf({ ...pageConf, page: 1 });
|
||||
setViewConf(view ? view : null);
|
||||
};
|
||||
|
||||
const vComponents = useMemo(() => {
|
||||
return VList({
|
||||
height: tableScrollHeight,
|
||||
reset: resetRef.current,
|
||||
rowHeight: 69,
|
||||
scrollTop: resetRef.current
|
||||
? 0
|
||||
: tableRef.current?.querySelector('.ant-table-body')?.scrollTop,
|
||||
});
|
||||
}, [tableScrollHeight, resetRef.current]);
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper crontab-wrapper"
|
||||
className="ql-container-wrapper crontab-wrapper ql-container-wrapper-has-tab"
|
||||
title="定时任务"
|
||||
extra={[
|
||||
<Search
|
||||
@@ -847,9 +962,42 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
style: headerStyle,
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
defaultActiveKey="all"
|
||||
size="small"
|
||||
tabPosition="top"
|
||||
className={`crontab-view ${moreMenuActive ? 'more-active' : ''}`}
|
||||
tabBarExtraContent={
|
||||
<Dropdown
|
||||
menu={menu}
|
||||
trigger={['click']}
|
||||
overlayStyle={{ minWidth: 200 }}
|
||||
>
|
||||
<div className={`view-more ${moreMenuActive ? 'active' : ''}`}>
|
||||
<Space>
|
||||
更多
|
||||
<DownOutlined />
|
||||
</Space>
|
||||
<div className="ant-tabs-ink-bar ant-tabs-ink-bar-animated"></div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
}
|
||||
onTabClick={tabClick}
|
||||
items={[
|
||||
...[...enabledCronViews].slice(0, 4).map((x) => ({
|
||||
key: x.id,
|
||||
label: x.name,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
<div ref={tableRef}>
|
||||
{selectedRowIds.length > 0 && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<Button type="primary" style={{ marginBottom: 5 }} onClick={delCrons}>
|
||||
<Button
|
||||
type="primary"
|
||||
style={{ marginBottom: 5 }}
|
||||
onClick={delCrons}
|
||||
>
|
||||
批量删除
|
||||
</Button>
|
||||
<Button
|
||||
@@ -906,23 +1054,16 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Table
|
||||
columns={columns}
|
||||
pagination={{
|
||||
current: currentPage,
|
||||
onChange: onPageChange,
|
||||
pageSize: pageSize,
|
||||
current: pageConf.page,
|
||||
pageSize: pageConf.size,
|
||||
showSizeChanger: true,
|
||||
simple: isPhone,
|
||||
defaultPageSize: 20,
|
||||
total,
|
||||
showTotal: (total: number, range: number[]) =>
|
||||
`第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
|
||||
pageSizeOptions: [20, 100, 500, 1000] as any,
|
||||
}}
|
||||
onRow={(record) => {
|
||||
return {
|
||||
onClick: (event) => {
|
||||
setDetailCron(record);
|
||||
setIsDetailModalVisible(true);
|
||||
},
|
||||
};
|
||||
pageSizeOptions: [10, 20, 50, 100, 200, 500, total || 10000].sort(
|
||||
(a, b) => a - b,
|
||||
),
|
||||
}}
|
||||
dataSource={value}
|
||||
rowKey="id"
|
||||
@@ -931,7 +1072,10 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
loading={loading}
|
||||
rowSelection={rowSelection}
|
||||
rowClassName={getRowClassName}
|
||||
onChange={onPageChange}
|
||||
components={vComponents}
|
||||
/>
|
||||
</div>
|
||||
<CronLogModal
|
||||
visible={isLogModalVisible}
|
||||
handleCancel={() => {
|
||||
@@ -964,6 +1108,29 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
theme={theme}
|
||||
isPhone={isPhone}
|
||||
/>
|
||||
<ViewCreateModal
|
||||
visible={isCreateViewModalVisible}
|
||||
handleCancel={(data) => {
|
||||
setIsCreateViewModalVisible(false);
|
||||
getCronViews();
|
||||
if (data && data.id === viewConf.id) {
|
||||
setViewConf({ ...viewConf, ...data });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<ViewManageModal
|
||||
cronViews={cronViews}
|
||||
visible={isViewManageModalVisible}
|
||||
handleCancel={() => {
|
||||
setIsViewManageModalVisible(false);
|
||||
}}
|
||||
cronViewChange={(data) => {
|
||||
getCronViews();
|
||||
if (data && data.id === viewConf.id) {
|
||||
setViewConf({ ...viewConf, ...data });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Modal, message, Input, Form, Statistic, Button } from 'antd';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
CheckCircleOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { PageLoading } from '@ant-design/pro-layout';
|
||||
import { logEnded } from '@/utils';
|
||||
|
||||
enum CrontabStatus {
|
||||
'running',
|
||||
@@ -33,7 +34,7 @@ const CronLogModal = ({
|
||||
const [loading, setLoading] = useState<any>(true);
|
||||
const [executing, setExecuting] = useState<any>(true);
|
||||
const [isPhone, setIsPhone] = useState(false);
|
||||
const [theme, setTheme] = useState<string>('');
|
||||
const scrollInfoRef = useRef({ value: 0, down: true });
|
||||
|
||||
const getCronLog = (isFirst?: boolean) => {
|
||||
if (isFirst) {
|
||||
@@ -41,14 +42,23 @@ const CronLogModal = ({
|
||||
}
|
||||
request
|
||||
.get(logUrl ? logUrl : `${config.apiPrefix}crons/${cron.id}/log`)
|
||||
.then((data: any) => {
|
||||
if (localStorage.getItem('logCron') === String(cron.id)) {
|
||||
const log = data.data as string;
|
||||
.then(({ code, data }) => {
|
||||
if (
|
||||
code === 200 &&
|
||||
localStorage.getItem('logCron') === String(cron.id) &&
|
||||
data !== value
|
||||
) {
|
||||
const log = data as string;
|
||||
setValue(log || '暂无日志');
|
||||
setExecuting(
|
||||
log && !log.includes('执行结束') && !log.includes('重启面板'),
|
||||
const hasNext = Boolean(
|
||||
log &&
|
||||
!logEnded(log) &&
|
||||
!log.includes('重启面板') &&
|
||||
!log.includes('任务未运行'),
|
||||
);
|
||||
if (log && !log.includes('执行结束') && !log.includes('重启面板')) {
|
||||
setExecuting(hasNext);
|
||||
autoScroll();
|
||||
if (hasNext) {
|
||||
setTimeout(() => {
|
||||
getCronLog();
|
||||
}, 2000);
|
||||
@@ -85,11 +95,33 @@ const CronLogModal = ({
|
||||
});
|
||||
};
|
||||
|
||||
const autoScroll = () => {
|
||||
if (!scrollInfoRef.current.down) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
document
|
||||
.querySelector('#log-flag')!
|
||||
.scrollIntoView({ behavior: 'smooth' });
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
localStorage.removeItem('logCron');
|
||||
handleCancel();
|
||||
};
|
||||
|
||||
const handleScroll = (e) => {
|
||||
const sTop = e.target.scrollTop;
|
||||
if (scrollInfoRef.current.down) {
|
||||
scrollInfoRef.current = {
|
||||
value: sTop,
|
||||
down: sTop > scrollInfoRef.current.value,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const titleElement = () => {
|
||||
return (
|
||||
<>
|
||||
@@ -119,7 +151,7 @@ const CronLogModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title={titleElement()}
|
||||
visible={visible}
|
||||
open={visible}
|
||||
centered
|
||||
className="log-modal"
|
||||
bodyStyle={{
|
||||
@@ -134,6 +166,7 @@ const CronLogModal = ({
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<div onScroll={handleScroll} className="log-container">
|
||||
{loading ? (
|
||||
<PageLoading />
|
||||
) : (
|
||||
@@ -151,6 +184,8 @@ const CronLogModal = ({
|
||||
{value}
|
||||
</pre>
|
||||
)}
|
||||
<div id="log-flag"></div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
+12
-10
@@ -28,13 +28,12 @@ const CronModal = ({
|
||||
const { code, data } = await request[method](`${config.apiPrefix}crons`, {
|
||||
data: payload,
|
||||
});
|
||||
|
||||
if (code === 200) {
|
||||
message.success(cron ? '更新Cron成功' : '新建Cron成功');
|
||||
} else {
|
||||
message.error(data);
|
||||
handleCancel(data);
|
||||
}
|
||||
setLoading(false);
|
||||
handleCancel(data);
|
||||
} catch (error: any) {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -47,7 +46,7 @@ const CronModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title={cron ? '编辑任务' : '新建任务'}
|
||||
visible={visible}
|
||||
open={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
@@ -75,13 +74,13 @@ const CronModal = ({
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="command"
|
||||
label="命令"
|
||||
label="命令/脚本"
|
||||
rules={[{ required: true, whitespace: true }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={4}
|
||||
autoSize={true}
|
||||
placeholder="请输入要执行的命令"
|
||||
placeholder="支持输入脚本路径/任意系统可执行命令/task 脚本路径"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
@@ -128,21 +127,24 @@ const CronLabelModal = ({
|
||||
.then(async (values) => {
|
||||
setLoading(true);
|
||||
const payload = { ids, labels: values.labels };
|
||||
try {
|
||||
const { code, data } = await request[action](
|
||||
`${config.apiPrefix}crons/labels`,
|
||||
{
|
||||
data: payload,
|
||||
},
|
||||
);
|
||||
|
||||
if (code === 200) {
|
||||
message.success(
|
||||
action === 'post' ? '添加Labels成功' : '删除Labels成功',
|
||||
);
|
||||
} else {
|
||||
message.error(data);
|
||||
handleCancel(true);
|
||||
}
|
||||
setLoading(false);
|
||||
handleCancel(true);
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch((info) => {
|
||||
console.log('Validate Failed:', info);
|
||||
@@ -166,7 +168,7 @@ const CronLabelModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title="批量修改标签"
|
||||
visible={visible}
|
||||
open={visible}
|
||||
footer={buttons}
|
||||
centered
|
||||
maskClosable={false}
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
message,
|
||||
Input,
|
||||
Form,
|
||||
Statistic,
|
||||
Button,
|
||||
Space,
|
||||
Select,
|
||||
} from 'antd';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import IconFont from '@/components/iconfont';
|
||||
import get from 'lodash/get';
|
||||
|
||||
const PROPERTIES = [
|
||||
{ name: '命令', value: 'command' },
|
||||
{ name: '名称', value: 'name' },
|
||||
{ name: '定时规则', value: 'schedule' },
|
||||
{ name: '状态', value: 'status' },
|
||||
{ name: '标签', value: 'labels' },
|
||||
];
|
||||
|
||||
const EOperation: any = {
|
||||
Reg: '',
|
||||
NotReg: '',
|
||||
In: 'select',
|
||||
Nin: 'select',
|
||||
};
|
||||
const OPERATIONS = [
|
||||
{ name: '包含', value: 'Reg' },
|
||||
{ name: '不包含', value: 'NotReg' },
|
||||
{ name: '属于', value: 'In', type: 'select' },
|
||||
{ name: '不属于', value: 'Nin', type: 'select' },
|
||||
// { name: '等于', value: 'Eq' },
|
||||
// { name: '不等于', value: 'Ne' },
|
||||
// { name: '为空', value: 'IsNull' },
|
||||
// { name: '不为空', value: 'NotNull' },
|
||||
];
|
||||
|
||||
const SORTTYPES = [
|
||||
{ name: '顺序', value: 'ASC' },
|
||||
{ name: '倒序', value: 'DESC' },
|
||||
];
|
||||
|
||||
const STATUS_MAP = {
|
||||
status: [
|
||||
{ name: '运行中', value: 0 },
|
||||
{ name: '空闲中', value: 1 },
|
||||
{ name: '已禁用', value: 2 },
|
||||
],
|
||||
};
|
||||
|
||||
enum ViewFilterRelation {
|
||||
'and' = '且',
|
||||
'or' = '或',
|
||||
}
|
||||
|
||||
const ViewCreateModal = ({
|
||||
view,
|
||||
handleCancel,
|
||||
visible,
|
||||
}: {
|
||||
view?: any;
|
||||
visible: boolean;
|
||||
handleCancel: (param?: any) => void;
|
||||
}) => {
|
||||
const [form] = Form.useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [filterRelation, setFilterRelation] = useState<'and' | 'or'>('and');
|
||||
|
||||
const handleOk = async (values: any) => {
|
||||
setLoading(true);
|
||||
values.filterRelation = filterRelation;
|
||||
const method = view ? 'put' : 'post';
|
||||
try {
|
||||
const { code, data } = await request[method](
|
||||
`${config.apiPrefix}crons/views`,
|
||||
{
|
||||
data: view ? { ...values, id: view.id } : values,
|
||||
},
|
||||
);
|
||||
|
||||
if (code === 200) {
|
||||
handleCancel(data);
|
||||
}
|
||||
setLoading(false);
|
||||
} catch (error: any) {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!view) {
|
||||
form.resetFields();
|
||||
}
|
||||
form.setFieldsValue(
|
||||
view || {
|
||||
filters: [{ property: 'command', operation: 'Reg' }],
|
||||
},
|
||||
);
|
||||
}, [view, visible]);
|
||||
|
||||
const operationElement = (
|
||||
<Select style={{ width: 80 }}>
|
||||
{OPERATIONS.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
|
||||
const propertyElement = (props: any, style: React.CSSProperties = {}) => {
|
||||
return (
|
||||
<Select style={style}>
|
||||
{props.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
};
|
||||
|
||||
const typeElement = (
|
||||
<Select>
|
||||
{SORTTYPES.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
|
||||
const statusElement = (property: keyof typeof STATUS_MAP) => {
|
||||
return (
|
||||
<Select mode="tags" allowClear placeholder="输入后回车增加自定义选项">
|
||||
{STATUS_MAP[property]?.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={view ? '编辑视图' : '新建视图'}
|
||||
open={visible}
|
||||
forceRender
|
||||
width={580}
|
||||
centered
|
||||
maskClosable={false}
|
||||
onOk={() => {
|
||||
form
|
||||
.validateFields()
|
||||
.then((values) => {
|
||||
handleOk(values);
|
||||
})
|
||||
.catch((info) => {
|
||||
console.log('Validate Failed:', info);
|
||||
});
|
||||
}}
|
||||
onCancel={() => handleCancel()}
|
||||
confirmLoading={loading}
|
||||
>
|
||||
<Form form={form} layout="vertical" name="env_modal">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="视图名称"
|
||||
rules={[{ required: true, message: '请输入视图名称' }]}
|
||||
>
|
||||
<Input placeholder="请输入视图名称" />
|
||||
</Form.Item>
|
||||
<Form.List name="filters">
|
||||
{(fields, { add, remove }) => (
|
||||
<div
|
||||
style={{ position: 'relative' }}
|
||||
className={`view-filters-container ${
|
||||
fields.length > 1 ? 'active' : ''
|
||||
}`}
|
||||
>
|
||||
{fields.length > 1 && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: 50,
|
||||
borderRadius: 10,
|
||||
border: '1px solid rgb(190, 220, 255)',
|
||||
borderRight: 'none',
|
||||
height: 56 * (fields.length - 1),
|
||||
top: 46,
|
||||
left: 15,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
translate: '-50% -50%',
|
||||
padding: '0 0 0 3px',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={() => {
|
||||
setFilterRelation(
|
||||
filterRelation === 'and' ? 'or' : 'and',
|
||||
);
|
||||
}}
|
||||
>
|
||||
<>
|
||||
<span>{ViewFilterRelation[filterRelation]}</span>
|
||||
<IconFont type="ql-icon-d-caret" />
|
||||
</>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
{fields.map(({ key, name, ...restField }, index) => (
|
||||
<Form.Item
|
||||
label={index === 0 ? '筛选条件' : ''}
|
||||
key={key}
|
||||
style={{ marginBottom: 0 }}
|
||||
required
|
||||
className="filter-item"
|
||||
>
|
||||
<Space
|
||||
className="view-create-modal-filters"
|
||||
align="baseline"
|
||||
style={
|
||||
fields.length > 1 ? { width: 'calc(100% - 40px)' } : {}
|
||||
}
|
||||
>
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'property']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{propertyElement(PROPERTIES, { width: 90 })}
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'operation']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{operationElement}
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prevValues, nextValues) => {
|
||||
const preOperation =
|
||||
EOperation[
|
||||
get(prevValues, ['filters', name, 'operation'])
|
||||
];
|
||||
const nextOperation =
|
||||
EOperation[
|
||||
get(nextValues, ['filters', name, 'operation'])
|
||||
];
|
||||
const flag = preOperation !== nextOperation;
|
||||
if (flag) {
|
||||
form.setFieldValue(
|
||||
['filters', name, 'value'],
|
||||
nextOperation === 'select' ? [] : '',
|
||||
);
|
||||
}
|
||||
return flag;
|
||||
}}
|
||||
>
|
||||
{() => {
|
||||
const property = form.getFieldValue([
|
||||
'filters',
|
||||
index,
|
||||
'property',
|
||||
]) as 'status';
|
||||
const operate = form.getFieldValue([
|
||||
'filters',
|
||||
name,
|
||||
'operation',
|
||||
]);
|
||||
return (
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'value']}
|
||||
rules={[
|
||||
{ required: true, message: '请输入内容' },
|
||||
]}
|
||||
>
|
||||
{EOperation[operate] === 'select' ? (
|
||||
statusElement(property)
|
||||
) : (
|
||||
<Input placeholder="请输入内容" />
|
||||
)}
|
||||
</Form.Item>
|
||||
);
|
||||
}}
|
||||
</Form.Item>
|
||||
{index !== 0 && (
|
||||
<MinusCircleOutlined onClick={() => remove(name)} />
|
||||
)}
|
||||
</Space>
|
||||
</Form.Item>
|
||||
))}
|
||||
<Form.Item>
|
||||
<a
|
||||
onClick={() =>
|
||||
add({ property: 'command', operation: 'Reg' })
|
||||
}
|
||||
>
|
||||
<PlusOutlined />
|
||||
新增筛选条件
|
||||
</a>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Form.List>
|
||||
<Form.List name="sorts">
|
||||
{(fields, { add, remove }) => (
|
||||
<>
|
||||
{fields.map(({ key, name, ...restField }, index) => (
|
||||
<Form.Item
|
||||
label={index === 0 ? '排序方式' : ''}
|
||||
key={key}
|
||||
style={{ marginBottom: 0 }}
|
||||
>
|
||||
<Space className="view-create-modal-sorts" align="baseline">
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'property']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{propertyElement(PROPERTIES, { width: 240 })}
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'type']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{typeElement}
|
||||
</Form.Item>
|
||||
<MinusCircleOutlined onClick={() => remove(name)} />
|
||||
</Space>
|
||||
</Form.Item>
|
||||
))}
|
||||
<Form.Item>
|
||||
<a onClick={() => add({ property: 'command', type: 'ASC' })}>
|
||||
<PlusOutlined />
|
||||
新增排序方式
|
||||
</a>
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ViewCreateModal;
|
||||
@@ -0,0 +1,270 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
message,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
Button,
|
||||
Switch,
|
||||
} from 'antd';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
|
||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||
import ViewCreateModal from './viewCreateModal';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const type = 'DragableBodyRow';
|
||||
|
||||
const DragableBodyRow = ({
|
||||
index,
|
||||
moveRow,
|
||||
className,
|
||||
style,
|
||||
...restProps
|
||||
}: any) => {
|
||||
const ref = useRef();
|
||||
const [{ isOver, dropClassName }, drop] = useDrop({
|
||||
accept: type,
|
||||
collect: (monitor) => {
|
||||
const { index: dragIndex } = (monitor.getItem() as any) || {};
|
||||
if (dragIndex === index) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
isOver: monitor.isOver(),
|
||||
dropClassName:
|
||||
dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
|
||||
};
|
||||
},
|
||||
drop: (item: any) => {
|
||||
moveRow(item.index, index);
|
||||
},
|
||||
});
|
||||
const [, drag] = useDrag({
|
||||
type,
|
||||
item: { index },
|
||||
collect: (monitor) => ({
|
||||
isDragging: monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
drop(drag(ref));
|
||||
|
||||
return (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={`${className}${isOver ? dropClassName : ''}`}
|
||||
style={{ cursor: 'move', ...style }}
|
||||
{...restProps}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const ViewManageModal = ({
|
||||
cronViews,
|
||||
handleCancel,
|
||||
visible,
|
||||
cronViewChange,
|
||||
}: {
|
||||
cronViews: any[];
|
||||
visible: boolean;
|
||||
handleCancel: () => void;
|
||||
cronViewChange: (data?: any) => void;
|
||||
}) => {
|
||||
const columns: any = [
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
dataIndex: 'type',
|
||||
key: 'type',
|
||||
render: (v) => (v === 1 ? '系统' : '个人'),
|
||||
},
|
||||
{
|
||||
title: '显示',
|
||||
key: 'isDisabled',
|
||||
dataIndex: 'isDisabled',
|
||||
width: 100,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return (
|
||||
<Switch
|
||||
checked={!record.isDisabled}
|
||||
onChange={(checked) => onShowChange(checked, record, index)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 100,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return record.type !== 1 ? (
|
||||
<Space size="middle">
|
||||
<a onClick={() => editView(record, index)}>
|
||||
<EditOutlined />
|
||||
</a>
|
||||
<a onClick={() => deleteView(record, index)}>
|
||||
<DeleteOutlined />
|
||||
</a>
|
||||
</Space>
|
||||
) : (
|
||||
'-'
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
const [list, setList] = useState<any[]>([]);
|
||||
const [isCreateViewModalVisible, setIsCreateViewModalVisible] =
|
||||
useState<boolean>(false);
|
||||
const [editedView, setEditedView] = useState<any>(null);
|
||||
|
||||
const editView = (record: any, index: number) => {
|
||||
setEditedView(record);
|
||||
setIsCreateViewModalVisible(true);
|
||||
};
|
||||
|
||||
const deleteView = (record: any, index: number) => {
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: (
|
||||
<>
|
||||
确认删除视图{' '}
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{record.name}
|
||||
</Text>{' '}
|
||||
吗
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}crons/views`, { data: [record.id] })
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('删除成功');
|
||||
cronViewChange();
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const onShowChange = (checked: boolean, record: any, index: number) => {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/views/${checked ? 'enable' : 'disable'}`, {
|
||||
data: [record.id],
|
||||
})
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const _list = [...list];
|
||||
_list.splice(index, 1, { ...list[index], isDisabled: !checked });
|
||||
setList(_list);
|
||||
cronViewChange();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const components = {
|
||||
body: {
|
||||
row: DragableBodyRow,
|
||||
},
|
||||
};
|
||||
|
||||
const moveRow = useCallback(
|
||||
(dragIndex, hoverIndex) => {
|
||||
if (dragIndex === hoverIndex) {
|
||||
return;
|
||||
}
|
||||
const dragRow = list[dragIndex];
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/views/move`, {
|
||||
data: { fromIndex: dragIndex, toIndex: hoverIndex, id: dragRow.id },
|
||||
})
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const newData = [...list];
|
||||
newData.splice(dragIndex, 1);
|
||||
newData.splice(hoverIndex, 0, { ...dragRow, ...data });
|
||||
setList(newData);
|
||||
cronViewChange();
|
||||
}
|
||||
});
|
||||
},
|
||||
[list],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setList(cronViews);
|
||||
}, [cronViews]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="视图管理"
|
||||
open={visible}
|
||||
centered
|
||||
width={620}
|
||||
onCancel={() => handleCancel()}
|
||||
className="view-manage-modal"
|
||||
forceRender
|
||||
footer={false}
|
||||
maskClosable={false}
|
||||
>
|
||||
<Space
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
marginBottom: 10,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
key="2"
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
setEditedView(null);
|
||||
setIsCreateViewModalVisible(true);
|
||||
}}
|
||||
>
|
||||
新建视图
|
||||
</Button>
|
||||
</Space>
|
||||
<DndProvider backend={HTML5Backend}>
|
||||
<Table
|
||||
bordered
|
||||
columns={columns}
|
||||
pagination={false}
|
||||
dataSource={list}
|
||||
rowKey="id"
|
||||
size="middle"
|
||||
style={{ marginBottom: 20 }}
|
||||
components={components}
|
||||
onRow={(record: any, index: number) => {
|
||||
return {
|
||||
index,
|
||||
moveRow,
|
||||
} as any;
|
||||
}}
|
||||
/>
|
||||
</DndProvider>
|
||||
<ViewCreateModal
|
||||
view={editedView}
|
||||
visible={isCreateViewModalVisible}
|
||||
handleCancel={(data) => {
|
||||
setIsCreateViewModalVisible(false);
|
||||
cronViewChange(data);
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ViewManageModal;
|
||||
+100
-86
@@ -27,8 +27,10 @@ import DependenceModal from './modal';
|
||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||
import './index.less';
|
||||
import { getTableScroll } from '@/utils/index';
|
||||
import DependenceLogModal from './logModal';
|
||||
import { useOutletContext } from '@umijs/max';
|
||||
import { SharedContext } from '@/layouts';
|
||||
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
||||
|
||||
const { Text } = Typography;
|
||||
const { Search } = Input;
|
||||
@@ -48,11 +50,12 @@ enum StatusColor {
|
||||
'error',
|
||||
}
|
||||
|
||||
const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
const Dependence = () => {
|
||||
const { headerStyle, isPhone, socketMessage } =
|
||||
useOutletContext<SharedContext>();
|
||||
const columns: any = [
|
||||
{
|
||||
title: '序号',
|
||||
align: 'center' as const,
|
||||
width: 50,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return <span style={{ cursor: 'text' }}>{index + 1} </span>;
|
||||
@@ -62,13 +65,11 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
align: 'center' as const,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: 'status',
|
||||
dataIndex: 'status',
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return (
|
||||
<Space size="middle" style={{ cursor: 'text' }}>
|
||||
@@ -86,13 +87,11 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
title: '备注',
|
||||
dataIndex: 'remark',
|
||||
key: 'remark',
|
||||
align: 'center' as const,
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
key: 'timestamp',
|
||||
dataIndex: 'timestamp',
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any) => {
|
||||
const language = navigator.language || navigator.languages[0];
|
||||
const time = record.createdAt || record.timestamp;
|
||||
@@ -115,7 +114,6 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
const isPc = !isPhone;
|
||||
return (
|
||||
@@ -160,10 +158,11 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
const [editedDependence, setEditedDependence] = useState();
|
||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||
const [logDependence, setLogDependence] = useState<any>();
|
||||
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
||||
const [type, setType] = useState('nodejs');
|
||||
const tableRef = useRef<any>();
|
||||
const tableScrollHeight = useTableScrollHeight(tableRef, 59);
|
||||
|
||||
const getDependencies = () => {
|
||||
setLoading(true);
|
||||
@@ -171,8 +170,10 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
.get(
|
||||
`${config.apiPrefix}dependencies?searchValue=${searchText}&type=${type}`,
|
||||
)
|
||||
.then((data: any) => {
|
||||
setValue(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setValue(data);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -208,9 +209,8 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
.delete(`${config.apiPrefix}dependencies${force ? '/force' : ''}`, {
|
||||
data: [record.id],
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
if (force) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200 && force) {
|
||||
const i = value.findIndex((x) => x.id === data.data[0].id);
|
||||
if (i !== -1) {
|
||||
const result = [...value];
|
||||
@@ -218,9 +218,6 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
setValue(result);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
@@ -246,11 +243,9 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
.put(`${config.apiPrefix}dependencies/reinstall`, {
|
||||
data: [record.id],
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
handleDependence(data.data[0]);
|
||||
} else {
|
||||
message.error(data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
handleDependence(data[0]);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -282,16 +277,10 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
|
||||
const onSelectChange = (selectedIds: any[]) => {
|
||||
setSelectedRowIds(selectedIds);
|
||||
|
||||
setTimeout(() => {
|
||||
if (selectedRowIds.length === 0 || selectedIds.length === 0) {
|
||||
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const rowSelection = {
|
||||
selectedRowIds,
|
||||
selectedRowKeys: selectedRowIds,
|
||||
onChange: onSelectChange,
|
||||
};
|
||||
|
||||
@@ -305,12 +294,32 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
.delete(`${config.apiPrefix}dependencies${forceUrl}`, {
|
||||
data: selectedRowIds,
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setSelectedRowIds([]);
|
||||
getDependencies();
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handlereInstallDependencies = () => {
|
||||
Modal.confirm({
|
||||
title: '确认重新安装',
|
||||
content: <>确认重新安装选中的依赖吗</>,
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}dependencies/reinstall`, {
|
||||
data: selectedRowIds,
|
||||
})
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setSelectedRowIds([]);
|
||||
getDependencies();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -323,16 +332,18 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
const getDependenceDetail = (dependence: any) => {
|
||||
request
|
||||
.get(`${config.apiPrefix}dependencies/${dependence.id}`)
|
||||
.then((data: any) => {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const index = value.findIndex((x) => x.id === dependence.id);
|
||||
const result = [...value];
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1, {
|
||||
...dependence,
|
||||
...data.data,
|
||||
...data,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -345,12 +356,6 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
getDependencies();
|
||||
}, [searchText, type]);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (logDependence) {
|
||||
localStorage.setItem('logDependence', logDependence.id);
|
||||
@@ -399,10 +404,61 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
}
|
||||
}, [socketMessage]);
|
||||
|
||||
const panelContent = () => (
|
||||
<>
|
||||
const onTabChange = (activeKey: string) => {
|
||||
setSelectedRowIds([]);
|
||||
setType(activeKey);
|
||||
};
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper dependence-wrapper ql-container-wrapper-has-tab"
|
||||
title="依赖管理"
|
||||
extra={[
|
||||
<Search
|
||||
placeholder="请输入名称"
|
||||
style={{ width: 'auto' }}
|
||||
enterButton
|
||||
loading={loading}
|
||||
onSearch={onSearch}
|
||||
/>,
|
||||
<Button key="2" type="primary" onClick={() => addDependence()}>
|
||||
新建依赖
|
||||
</Button>,
|
||||
]}
|
||||
header={{
|
||||
style: headerStyle,
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
defaultActiveKey="nodejs"
|
||||
size="small"
|
||||
tabPosition="top"
|
||||
onChange={onTabChange}
|
||||
items={[
|
||||
{
|
||||
key: 'nodejs',
|
||||
label: 'NodeJs',
|
||||
},
|
||||
{
|
||||
key: 'python3',
|
||||
label: 'Python3',
|
||||
},
|
||||
{
|
||||
key: 'linux',
|
||||
label: 'Linux',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<div ref={tableRef}>
|
||||
{selectedRowIds.length > 0 && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
style={{ marginBottom: 5, marginLeft: 8 }}
|
||||
onClick={() => handlereInstallDependencies()}
|
||||
>
|
||||
批量安装
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
style={{ marginBottom: 5, marginLeft: 8 }}
|
||||
@@ -435,49 +491,7 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
loading={loading}
|
||||
/>
|
||||
</DndProvider>
|
||||
</>
|
||||
);
|
||||
|
||||
const onTabChange = (activeKey: string) => {
|
||||
setType(activeKey);
|
||||
};
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper dependence-wrapper"
|
||||
title="依赖管理"
|
||||
extra={[
|
||||
<Search
|
||||
placeholder="请输入名称"
|
||||
style={{ width: 'auto' }}
|
||||
enterButton
|
||||
loading={loading}
|
||||
onSearch={onSearch}
|
||||
/>,
|
||||
<Button key="2" type="primary" onClick={() => addDependence()}>
|
||||
新建依赖
|
||||
</Button>,
|
||||
]}
|
||||
header={{
|
||||
style: headerStyle,
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
defaultActiveKey="nodejs"
|
||||
size="small"
|
||||
tabPosition="top"
|
||||
onChange={onTabChange}
|
||||
>
|
||||
<Tabs.TabPane tab="NodeJs" key="nodejs">
|
||||
{panelContent()}
|
||||
</Tabs.TabPane>
|
||||
<Tabs.TabPane tab="Python3" key="python3">
|
||||
{panelContent()}
|
||||
</Tabs.TabPane>
|
||||
<Tabs.TabPane tab="Linux" key="linux">
|
||||
{panelContent()}
|
||||
</Tabs.TabPane>
|
||||
</Tabs>
|
||||
</div>
|
||||
<DependenceModal
|
||||
visible={isModalVisible}
|
||||
handleCancel={handleCancel}
|
||||
|
||||
@@ -48,9 +48,12 @@ const DependenceLogModal = ({
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}dependencies/${dependence.id}`)
|
||||
.then((data: any) => {
|
||||
if (localStorage.getItem('logDependence') === String(dependence.id)) {
|
||||
const log = (data.data.log || []).join('') as string;
|
||||
.then(({ code, data }) => {
|
||||
if (
|
||||
code === 200 &&
|
||||
localStorage.getItem('logDependence') === String(dependence.id)
|
||||
) {
|
||||
const log = (data.log || []).join('') as string;
|
||||
setValue(log);
|
||||
setExecuting(!log.includes('结束时间'));
|
||||
setIsRemoveFailed(log.includes('删除失败'));
|
||||
@@ -67,8 +70,10 @@ const DependenceLogModal = ({
|
||||
.delete(`${config.apiPrefix}dependencies/force`, {
|
||||
data: [dependence.id],
|
||||
})
|
||||
.then((data: any) => {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
cancel(true);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
setRemoveLoading(false);
|
||||
@@ -112,7 +117,7 @@ const DependenceLogModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title={titleElement()}
|
||||
visible={visible}
|
||||
open={visible}
|
||||
centered
|
||||
className="log-modal"
|
||||
bodyStyle={{
|
||||
|
||||
@@ -52,11 +52,11 @@ const DependenceModal = ({
|
||||
data: payload,
|
||||
},
|
||||
);
|
||||
if (code !== 200) {
|
||||
message.error(data);
|
||||
|
||||
if (code === 200) {
|
||||
handleCancel(data);
|
||||
}
|
||||
setLoading(false);
|
||||
handleCancel(data);
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -69,7 +69,7 @@ const DependenceModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title={dependence ? '编辑依赖' : '新建依赖'}
|
||||
visible={visible}
|
||||
open={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
@@ -99,7 +99,9 @@ const DependenceModal = ({
|
||||
>
|
||||
<Select>
|
||||
{config.dependenceTypes.map((x, i) => (
|
||||
<Option value={i}>{x}</Option>
|
||||
<Option key={i} value={i}>
|
||||
{x}
|
||||
</Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
@@ -17,4 +17,8 @@
|
||||
.ant-form-item {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
+ section {
|
||||
height: calc(100% - 40px) !important;
|
||||
}
|
||||
}
|
||||
|
||||
+30
-11
@@ -6,10 +6,13 @@ import { request } from '@/utils/http';
|
||||
import './index.less';
|
||||
import { DiffEditor } from '@monaco-editor/react';
|
||||
import ReactDiffViewer from 'react-diff-viewer';
|
||||
import { useOutletContext } from '@umijs/max';
|
||||
import { SharedContext } from '@/layouts';
|
||||
|
||||
const { Option } = Select;
|
||||
|
||||
const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const Diff = () => {
|
||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
||||
const [origin, setOrigin] = useState('config.sample.sh');
|
||||
const [current, setCurrent] = useState('config.sh');
|
||||
const [originValue, setOriginValue] = useState('');
|
||||
@@ -19,14 +22,22 @@ const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const editorRef = useRef<any>(null);
|
||||
|
||||
const getConfig = () => {
|
||||
request.get(`${config.apiPrefix}configs/${current}`).then((data) => {
|
||||
setCurrentValue(data.data);
|
||||
request
|
||||
.get(`${config.apiPrefix}configs/${current}`)
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setCurrentValue(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const getSample = () => {
|
||||
request.get(`${config.apiPrefix}configs/${origin}`).then((data) => {
|
||||
setOriginValue(data.data);
|
||||
request
|
||||
.get(`${config.apiPrefix}configs/${origin}`)
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setOriginValue(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -39,8 +50,10 @@ const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.post(`${config.apiPrefix}configs/save`, {
|
||||
data: { content, name: current },
|
||||
})
|
||||
.then((data: any) => {
|
||||
message.success(data.message);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('保存成功');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -48,8 +61,10 @@ const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}configs/files`)
|
||||
.then((data: any) => {
|
||||
setFiles(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setFiles(data);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -95,7 +110,9 @@ const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Form.Item label="源文件">
|
||||
<Select value={origin} onChange={originFileChange}>
|
||||
{files.map((x) => (
|
||||
<Option value={x.value}>{x.title}</Option>
|
||||
<Option key={x.value} value={x.value}>
|
||||
{x.title}
|
||||
</Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
@@ -104,7 +121,9 @@ const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Form.Item label="当前文件">
|
||||
<Select value={current} onChange={currentFileChange}>
|
||||
{files.map((x) => (
|
||||
<Option value={x.value}>{x.title}</Option>
|
||||
<Option key={x.value} value={x.value}>
|
||||
{x.title}
|
||||
</Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
Vendored
+7
-4
@@ -17,19 +17,22 @@ const EditNameModal = ({
|
||||
|
||||
const handleOk = async (values: any) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { code, data } = await request.put(`${config.apiPrefix}envs/name`, {
|
||||
data: {
|
||||
ids,
|
||||
name: values.name,
|
||||
},
|
||||
});
|
||||
|
||||
if (code === 200) {
|
||||
message.success('更新环境变量名称成功');
|
||||
} else {
|
||||
message.error(data);
|
||||
handleCancel();
|
||||
}
|
||||
setLoading(false);
|
||||
handleCancel();
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -39,7 +42,7 @@ const EditNameModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title="修改环境变量名称"
|
||||
visible={visible}
|
||||
open={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
|
||||
Vendored
+6
@@ -5,3 +5,9 @@ tr.drop-over-downward td {
|
||||
tr.drop-over-upward td {
|
||||
border-top: 2px dashed #1890ff;
|
||||
}
|
||||
|
||||
.text-ellipsis {
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
Vendored
+164
-115
@@ -1,4 +1,10 @@
|
||||
import React, { useCallback, useRef, useState, useEffect } from 'react';
|
||||
import React, {
|
||||
useCallback,
|
||||
useRef,
|
||||
useState,
|
||||
useEffect,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import {
|
||||
Button,
|
||||
message,
|
||||
@@ -9,6 +15,8 @@ import {
|
||||
Typography,
|
||||
Tooltip,
|
||||
Input,
|
||||
UploadProps,
|
||||
Upload,
|
||||
} from 'antd';
|
||||
import {
|
||||
EditOutlined,
|
||||
@@ -16,6 +24,7 @@ import {
|
||||
SyncOutlined,
|
||||
CheckCircleOutlined,
|
||||
StopOutlined,
|
||||
UploadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import config from '@/utils/config';
|
||||
import { PageContainer } from '@ant-design/pro-layout';
|
||||
@@ -25,9 +34,14 @@ import EditNameModal from './editNameModal';
|
||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||
import './index.less';
|
||||
import { exportJson, getTableScroll } from '@/utils/index';
|
||||
import { exportJson } from '@/utils/index';
|
||||
import { useOutletContext } from '@umijs/max';
|
||||
import { SharedContext } from '@/layouts';
|
||||
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
||||
import Copy from '../../components/copy';
|
||||
import { VList } from '../../components/vlist';
|
||||
|
||||
const { Text, Paragraph } = Typography;
|
||||
const { Text } = Typography;
|
||||
const { Search } = Input;
|
||||
|
||||
enum Status {
|
||||
@@ -52,55 +66,11 @@ enum OperationPath {
|
||||
|
||||
const type = 'DragableBodyRow';
|
||||
|
||||
const DragableBodyRow = ({
|
||||
index,
|
||||
moveRow,
|
||||
className,
|
||||
style,
|
||||
...restProps
|
||||
}: any) => {
|
||||
const ref = useRef();
|
||||
const [{ isOver, dropClassName }, drop] = useDrop({
|
||||
accept: type,
|
||||
collect: (monitor) => {
|
||||
const { index: dragIndex } = (monitor.getItem() as any) || {};
|
||||
if (dragIndex === index) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
isOver: monitor.isOver(),
|
||||
dropClassName:
|
||||
dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
|
||||
};
|
||||
},
|
||||
drop: (item: any) => {
|
||||
moveRow(item.index, index);
|
||||
},
|
||||
});
|
||||
const [, drag] = useDrag({
|
||||
type,
|
||||
item: { index },
|
||||
collect: (monitor) => ({
|
||||
isDragging: monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
drop(drag(ref));
|
||||
|
||||
return (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={`${className}${isOver ? dropClassName : ''}`}
|
||||
style={{ cursor: 'move', ...style }}
|
||||
{...restProps}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const Env = () => {
|
||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
||||
const columns: any = [
|
||||
{
|
||||
title: '序号',
|
||||
align: 'center' as const,
|
||||
width: 60,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return <span style={{ cursor: 'text' }}>{index + 1} </span>;
|
||||
@@ -110,27 +80,21 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
align: 'center' as const,
|
||||
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
|
||||
},
|
||||
{
|
||||
title: '值',
|
||||
dataIndex: 'value',
|
||||
key: 'value',
|
||||
align: 'center' as const,
|
||||
width: '35%',
|
||||
render: (text: string, record: any) => {
|
||||
return (
|
||||
<Paragraph
|
||||
style={{
|
||||
wordBreak: 'break-all',
|
||||
marginBottom: 0,
|
||||
textAlign: 'left',
|
||||
}}
|
||||
ellipsis={{ tooltip: text, rows: 2 }}
|
||||
>
|
||||
{text}
|
||||
</Paragraph>
|
||||
<div style={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Tooltip title={text} placement="topLeft">
|
||||
<div className="text-ellipsis">{text}</div>
|
||||
</Tooltip>
|
||||
<Copy text={text} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -138,13 +102,18 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
title: '备注',
|
||||
dataIndex: 'remarks',
|
||||
key: 'remarks',
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any) => {
|
||||
return (
|
||||
<Tooltip title={text} placement="topLeft">
|
||||
<div className="text-ellipsis">{text}</div>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '更新时间',
|
||||
dataIndex: 'timestamp',
|
||||
key: 'timestamp',
|
||||
align: 'center' as const,
|
||||
width: 165,
|
||||
ellipsis: {
|
||||
showTitle: false,
|
||||
@@ -179,7 +148,6 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
title: '状态',
|
||||
key: 'status',
|
||||
dataIndex: 'status',
|
||||
align: 'center' as const,
|
||||
width: 70,
|
||||
filters: [
|
||||
{
|
||||
@@ -206,7 +174,6 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 120,
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
const isPc = !isPhone;
|
||||
return (
|
||||
@@ -246,19 +213,28 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const [editedEnv, setEditedEnv] = useState();
|
||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||
const [importLoading, setImportLoading] = useState(false);
|
||||
const tableRef = useRef<any>();
|
||||
const tableScrollHeight = useTableScrollHeight(tableRef, 59);
|
||||
const resetRef = useRef<boolean>(true);
|
||||
const setReset = (v) => {
|
||||
resetRef.current = v;
|
||||
};
|
||||
|
||||
const getEnvs = () => {
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}envs?searchValue=${searchText}`)
|
||||
.then((data: any) => {
|
||||
setValue(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setValue(data);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const enabledOrDisabledEnv = (record: any, index: number) => {
|
||||
setReset(false);
|
||||
Modal.confirm({
|
||||
title: `确认${record.status === Status.已禁用 ? '启用' : '禁用'}`,
|
||||
content: (
|
||||
@@ -281,8 +257,8 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
data: [record.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success(
|
||||
`${record.status === Status.已禁用 ? '启用' : '禁用'}成功`,
|
||||
);
|
||||
@@ -294,8 +270,6 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
status: newStatus,
|
||||
});
|
||||
setValue(result);
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -306,16 +280,19 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
};
|
||||
|
||||
const addEnv = () => {
|
||||
setReset(false);
|
||||
setEditedEnv(null as any);
|
||||
setIsModalVisible(true);
|
||||
};
|
||||
|
||||
const editEnv = (record: any, index: number) => {
|
||||
setReset(false);
|
||||
setEditedEnv(record);
|
||||
setIsModalVisible(true);
|
||||
};
|
||||
|
||||
const deleteEnv = (record: any, index: number) => {
|
||||
setReset(false);
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: (
|
||||
@@ -330,14 +307,12 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}envs`, { data: [record.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('删除成功');
|
||||
const result = [...value];
|
||||
result.splice(index, 1);
|
||||
setValue(result);
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -349,7 +324,7 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
|
||||
const handleCancel = (env?: any[]) => {
|
||||
setIsModalVisible(false);
|
||||
env && handleEnv(env);
|
||||
getEnvs();
|
||||
};
|
||||
|
||||
const handleEditNameCancel = (env?: any[]) => {
|
||||
@@ -357,28 +332,75 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
getEnvs();
|
||||
};
|
||||
|
||||
const handleEnv = (env: any) => {
|
||||
const result = [...value];
|
||||
const index = value.findIndex((x) => x.id === env.id);
|
||||
if (index === -1) {
|
||||
env = Array.isArray(env) ? env : [env];
|
||||
result.push(...env);
|
||||
} else {
|
||||
result.splice(index, 1, {
|
||||
...env,
|
||||
const vComponents = useMemo(() => {
|
||||
return VList({
|
||||
height: tableScrollHeight!,
|
||||
reset: resetRef.current,
|
||||
rowHeight: 48,
|
||||
scrollTop: resetRef.current
|
||||
? 0
|
||||
: tableRef.current?.querySelector('.ant-table-body')?.scrollTop,
|
||||
});
|
||||
}, [tableScrollHeight, resetRef.current]);
|
||||
|
||||
const DragableBodyRow = (props: any) => {
|
||||
const { index, moveRow, className, style, ...restProps } = props;
|
||||
const ref = useRef();
|
||||
const [{ isOver, dropClassName }, drop] = useDrop({
|
||||
accept: type,
|
||||
collect: (monitor) => {
|
||||
const { index: dragIndex } = (monitor.getItem() as any) || {};
|
||||
if (dragIndex === index) {
|
||||
return {};
|
||||
}
|
||||
setValue(result);
|
||||
return {
|
||||
isOver: monitor.isOver(),
|
||||
dropClassName:
|
||||
dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
|
||||
};
|
||||
},
|
||||
drop: (item: any) => {
|
||||
moveRow(item.index, index);
|
||||
},
|
||||
});
|
||||
const [, drag] = useDrag({
|
||||
type,
|
||||
item: { index },
|
||||
collect: (monitor) => ({
|
||||
isDragging: monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
drop(drag(ref));
|
||||
}, [drag, drop]);
|
||||
|
||||
const components = useMemo(() => vComponents.body.row, []);
|
||||
|
||||
const tempProps = useMemo(() => {
|
||||
return {
|
||||
ref: ref,
|
||||
className: `${className}${isOver ? dropClassName : ''}`,
|
||||
style: { cursor: 'move', ...style },
|
||||
...restProps,
|
||||
};
|
||||
}, [className, dropClassName, restProps, style, isOver]);
|
||||
|
||||
return <> {components(tempProps, ref)} </>;
|
||||
};
|
||||
|
||||
const components = {
|
||||
const components = useMemo(() => {
|
||||
return {
|
||||
...vComponents,
|
||||
body: {
|
||||
...vComponents.body,
|
||||
row: DragableBodyRow,
|
||||
},
|
||||
};
|
||||
}, [vComponents]);
|
||||
|
||||
const moveRow = useCallback(
|
||||
(dragIndex, hoverIndex) => {
|
||||
(dragIndex: number, hoverIndex: number) => {
|
||||
if (dragIndex === hoverIndex) {
|
||||
return;
|
||||
}
|
||||
@@ -387,14 +409,12 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.put(`${config.apiPrefix}envs/${dragRow.id}/move`, {
|
||||
data: { fromIndex: dragIndex, toIndex: hoverIndex },
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
const newData = [...value];
|
||||
newData.splice(dragIndex, 1);
|
||||
newData.splice(hoverIndex, 0, { ...dragRow, ...data.data });
|
||||
setValue([...newData]);
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -403,33 +423,30 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
|
||||
const onSelectChange = (selectedIds: any[]) => {
|
||||
setSelectedRowIds(selectedIds);
|
||||
|
||||
setTimeout(() => {
|
||||
if (selectedRowIds.length === 0 || selectedIds.length === 0) {
|
||||
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setReset(false);
|
||||
}, [selectedRowIds]);
|
||||
|
||||
const rowSelection = {
|
||||
selectedRowIds,
|
||||
selectedRowKeys: selectedRowIds,
|
||||
onChange: onSelectChange,
|
||||
};
|
||||
|
||||
const delEnvs = () => {
|
||||
setReset(false);
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: <>确认删除选中的变量吗</>,
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}envs`, { data: selectedRowIds })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
message.success('批量删除成功');
|
||||
setSelectedRowIds([]);
|
||||
getEnvs();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -440,6 +457,7 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
};
|
||||
|
||||
const operateEnvs = (operationStatus: number) => {
|
||||
setReset(false);
|
||||
Modal.confirm({
|
||||
title: `确认${OperationName[operationStatus]}`,
|
||||
content: <>确认{OperationName[operationStatus]}选中的变量吗</>,
|
||||
@@ -448,11 +466,9 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.put(`${config.apiPrefix}envs/${OperationPath[operationStatus]}`, {
|
||||
data: selectedRowIds,
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
getEnvs();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -474,19 +490,41 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
};
|
||||
|
||||
const onSearch = (value: string) => {
|
||||
setReset(true);
|
||||
setSearchText(value.trim());
|
||||
};
|
||||
|
||||
const uploadProps: UploadProps = {
|
||||
accept: 'application/json',
|
||||
beforeUpload: async (file) => {
|
||||
const formData = new FormData();
|
||||
formData.append('env', file);
|
||||
setImportLoading(true);
|
||||
try {
|
||||
const { code, data } = await request.post(
|
||||
`${config.apiPrefix}envs/upload`,
|
||||
{
|
||||
data: formData,
|
||||
},
|
||||
);
|
||||
|
||||
if (code === 200) {
|
||||
message.success(`成功上传${data.length}个环境变量`);
|
||||
getEnvs();
|
||||
}
|
||||
setImportLoading(false);
|
||||
} catch (error: any) {
|
||||
setImportLoading(false);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
fileList: [],
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getEnvs();
|
||||
}, [searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper env-wrapper"
|
||||
@@ -499,6 +537,15 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
loading={loading}
|
||||
onSearch={onSearch}
|
||||
/>,
|
||||
<Upload {...uploadProps}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<UploadOutlined />}
|
||||
loading={importLoading}
|
||||
>
|
||||
导入
|
||||
</Button>
|
||||
</Upload>,
|
||||
<Button key="2" type="primary" onClick={() => addEnv()}>
|
||||
新建变量
|
||||
</Button>,
|
||||
@@ -507,6 +554,7 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
style: headerStyle,
|
||||
}}
|
||||
>
|
||||
<div ref={tableRef}>
|
||||
{selectedRowIds.length > 0 && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<Button
|
||||
@@ -561,7 +609,7 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
scroll={{ x: 1000, y: tableScrollHeight }}
|
||||
components={components}
|
||||
loading={loading}
|
||||
onRow={(record: any, index: number) => {
|
||||
onRow={(record: any, index: number | undefined) => {
|
||||
return {
|
||||
index,
|
||||
moveRow,
|
||||
@@ -569,6 +617,7 @@ const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||
}}
|
||||
/>
|
||||
</DndProvider>
|
||||
</div>
|
||||
<EnvModal
|
||||
visible={isModalVisible}
|
||||
handleCancel={handleCancel}
|
||||
|
||||
Vendored
+3
-4
@@ -40,13 +40,12 @@ const EnvModal = ({
|
||||
const { code, data } = await request[method](`${config.apiPrefix}envs`, {
|
||||
data: payload,
|
||||
});
|
||||
|
||||
if (code === 200) {
|
||||
message.success(env ? '更新变量成功' : '新建变量成功');
|
||||
} else {
|
||||
message.error(data);
|
||||
handleCancel(data);
|
||||
}
|
||||
setLoading(false);
|
||||
handleCancel(data);
|
||||
} catch (error: any) {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -59,7 +58,7 @@ const EnvModal = ({
|
||||
return (
|
||||
<Modal
|
||||
title={env ? '编辑变量' : '新建变量'}
|
||||
visible={visible}
|
||||
open={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
|
||||
@@ -3,22 +3,43 @@ import config from '@/utils/config';
|
||||
import { request } from '@/utils/http';
|
||||
import Terminal, { ColorMode, LineType } from '../../components/terminal';
|
||||
import { PageLoading } from '@ant-design/pro-layout';
|
||||
import { history } from 'umi';
|
||||
import { history, useOutletContext } from '@umijs/max';
|
||||
import Ansi from 'ansi-to-react';
|
||||
import './index.less';
|
||||
import { SharedContext } from '@/layouts';
|
||||
|
||||
const Error = ({ user, theme }: any) => {
|
||||
const Error = () => {
|
||||
const { user, theme, reloadUser } = useOutletContext<SharedContext>();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [data, setData] = useState('暂无日志');
|
||||
|
||||
const getLog = () => {
|
||||
setLoading(true);
|
||||
const getTimes = () => {
|
||||
return parseInt(localStorage.getItem('error_retry_times') || '0', 10);
|
||||
};
|
||||
|
||||
let times = getTimes();
|
||||
|
||||
const getLog = (needLoading: boolean = true) => {
|
||||
needLoading && setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}public/panel/log`)
|
||||
.then((data: any) => {
|
||||
setData(data.data);
|
||||
.then(({ code, data }) => {
|
||||
if (code === 200) {
|
||||
setData(data);
|
||||
if (!data) {
|
||||
times = getTimes();
|
||||
if (times > 5) {
|
||||
return;
|
||||
}
|
||||
localStorage.setItem('error_retry_times', `${times + 1}`);
|
||||
setTimeout(() => {
|
||||
reloadUser();
|
||||
getLog(false);
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
.finally(() => needLoading && setLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -35,7 +56,7 @@ const Error = ({ user, theme }: any) => {
|
||||
<div className="error-wrapper">
|
||||
{loading ? (
|
||||
<PageLoading />
|
||||
) : (
|
||||
) : data ? (
|
||||
<Terminal
|
||||
name="服务错误"
|
||||
colorMode={theme === 'vs-dark' ? ColorMode.Dark : ColorMode.Light}
|
||||
@@ -51,6 +72,10 @@ const Error = ({ user, theme }: any) => {
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : times > 5 ? (
|
||||
<>服务启动超时,请手动进入容器执行 ql -l check 后刷新再试</>
|
||||
) : (
|
||||
<PageLoading tip="启动中,请稍后..." />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user