mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-12 03:10:48 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99d7eaeff0 | ||
|
|
c8f5eb7c2e | ||
|
|
109e16e8fb | ||
|
|
555f6e04e8 | ||
|
|
bcde0a54bf | ||
|
|
eee7f25bc3 | ||
|
|
b10157b09a | ||
|
|
a09a21fa5d | ||
|
|
ec2918b427 | ||
|
|
57bfc19ecf | ||
|
|
aa110d4187 | ||
|
|
9e8febfc11 | ||
|
|
5905c2ce25 | ||
|
|
b03ef0d494 | ||
|
|
585f77ed49 | ||
|
|
1c580ea2f9 | ||
|
|
b1af6575b9 | ||
|
|
b24c5fdee1 | ||
|
|
a256ada847 | ||
|
|
a8cdab629d | ||
|
|
09cca0a920 | ||
|
|
6a0aa6aae2 | ||
|
|
565cc06c27 | ||
|
|
29caa4b770 | ||
|
|
953cf4795a | ||
|
|
31bc8395aa | ||
|
|
eb94b39e40 | ||
|
|
c16bbe0f9a | ||
|
|
b60caa60d5 | ||
|
|
1ea97e9206 | ||
|
|
32970bca71 | ||
|
|
1fc9f87eaa | ||
|
|
b2f5960097 | ||
|
|
1cfcc66548 | ||
|
|
60152a313f | ||
|
|
d50ff20ff8 | ||
|
|
3aed5ef955 | ||
|
|
61e0e8dbe2 | ||
|
|
1ba5d52ee7 | ||
|
|
03bc5bb882 | ||
|
|
8011b4b793 | ||
|
|
deb124ae23 | ||
|
|
a3114e40d1 | ||
|
|
0b9ecfc3a5 | ||
|
|
c32bb4157b | ||
|
|
7f9c9f05b8 | ||
|
|
906a074634 | ||
|
|
286ec0e714 | ||
|
|
0f81414497 | ||
|
|
b451831db2 | ||
|
|
ae13185319 | ||
|
|
f2bcbaefd2 | ||
|
|
96ddcf49c5 | ||
|
|
322a4e2729 | ||
|
|
8e48960253 | ||
|
|
3b419a8e96 | ||
|
|
bf1685bf79 | ||
|
|
3ab84428f0 | ||
|
|
fdda732c4c | ||
|
|
f46b30498b | ||
|
|
d7ee2576f2 | ||
|
|
d2c03bc298 | ||
|
|
6283e23d29 | ||
|
|
dc9923ac13 | ||
|
|
62ac80257a | ||
|
|
868452f13c | ||
|
|
6c368f7ea7 | ||
|
|
732d63d588 | ||
|
|
ae40947801 | ||
|
|
079d4dfa06 | ||
|
|
67c50bf622 | ||
|
|
f1e494b1fc | ||
|
|
f4f275490e | ||
|
|
baad96106f | ||
|
|
15fa7754b5 | ||
|
|
8f175f8447 | ||
|
|
9c45cfd7ed | ||
|
|
f2426c3f66 | ||
|
|
36ae6e460d | ||
|
|
7ae93efe07 | ||
|
|
8b97d92d0a | ||
|
|
e5c06335ec | ||
|
|
2bd8e49302 | ||
|
|
c0d401e296 | ||
|
|
e07d2b6639 | ||
|
|
220a87627d | ||
|
|
87bca2ac4e | ||
|
|
c320906149 | ||
|
|
27958a1a90 | ||
|
|
82c7011522 | ||
|
|
fa6d57d809 | ||
|
|
1060fc7476 | ||
|
|
56bc38e9e7 | ||
|
|
18be65d6fe | ||
|
|
3409085195 | ||
|
|
17e17ac077 | ||
|
|
c655e1da38 | ||
|
|
0ea158724f | ||
|
|
fb521498ff | ||
|
|
399550ccad | ||
|
|
c7c30c86f2 | ||
|
|
5f6c0882d6 | ||
|
|
6e05a4f3a5 | ||
|
|
ea8aa6a231 | ||
|
|
ae2570c677 | ||
|
|
c76d952d41 | ||
|
|
cdf9fb24be | ||
|
|
2131e16781 | ||
|
|
b0c8425639 | ||
|
|
f0869567de | ||
|
|
be2a19949b | ||
|
|
8627cccb58 | ||
|
|
4a8eaebf17 | ||
|
|
e7edd0a5a4 | ||
|
|
9ccbea0a04 | ||
|
|
ab715ef840 | ||
|
|
117822fe7c | ||
|
|
da922678a1 | ||
|
|
133e9e0e1f | ||
|
|
7cc6081d15 | ||
|
|
5a24f62a62 | ||
|
|
be597355a7 | ||
|
|
51afcb6c5b | ||
|
|
92ebb70eaa | ||
|
|
ab19f30342 | ||
|
|
fc9bc7bea2 | ||
|
|
793da29f22 | ||
|
|
5afe4da607 | ||
|
|
a7a56c03ce | ||
|
|
7639b588d8 | ||
|
|
1d536cdd53 | ||
|
|
9f08245b6d | ||
|
|
ff9bf20e57 | ||
|
|
b201730100 | ||
|
|
6ca098f9e2 | ||
|
|
e0eef05f5c | ||
|
|
6398e5ec70 | ||
|
|
6f93219c44 | ||
|
|
9b957ac019 | ||
|
|
e0d1b127aa | ||
|
|
64072b3435 | ||
|
|
f81f7720f0 | ||
|
|
69fab610e6 | ||
|
|
d693e1f9ea | ||
|
|
2a9ca67355 | ||
|
|
3fb01860d4 | ||
|
|
d92a46d09c | ||
|
|
ec605bfba4 | ||
|
|
d2f999a5e2 | ||
|
|
627f541f17 | ||
|
|
c457dca555 | ||
|
|
ff3ec7395e | ||
|
|
fdaba146ca | ||
|
|
31a6d30c23 | ||
|
|
fa3b185fd5 | ||
|
|
101d4fb497 | ||
|
|
ccd308f5b0 | ||
|
|
999d9f8e01 | ||
|
|
313db0d74e | ||
|
|
634e9705a7 | ||
|
|
c959cec738 | ||
|
|
95330e04a3 | ||
|
|
a099d09af7 | ||
|
|
a0d0197ad7 | ||
|
|
d49e711a34 | ||
|
|
e3b8cd75b9 | ||
|
|
7a240eaabb | ||
|
|
01564e96d3 | ||
|
|
03f4b5c219 | ||
|
|
99e1d44f7d | ||
|
|
8c55659c18 | ||
|
|
3ea980b2f8 | ||
|
|
f5fc987b51 | ||
|
|
9cfa4af2b2 | ||
|
|
3efdf1fa87 | ||
|
|
25fc832605 | ||
|
|
a7e404c5d5 | ||
|
|
90b27f0564 | ||
|
|
632440965d | ||
|
|
aedfac446b | ||
|
|
3372b0025a | ||
|
|
0112b92e77 | ||
|
|
0caf53b147 | ||
|
|
4d1354d5f4 | ||
|
|
fc4562eca2 | ||
|
|
5b048a5510 | ||
|
|
d23049b2fe | ||
|
|
caac5607b9 | ||
|
|
fb2e69b12d | ||
|
|
fc1838ff39 | ||
|
|
25689cf40f | ||
|
|
c746a3d215 | ||
|
|
548d924fa0 | ||
|
|
18a6be3ecd | ||
|
|
afef0cb72f | ||
|
|
1221b47eca | ||
|
|
a356eeb5da | ||
|
|
25bb0972b9 | ||
|
|
0914075cf6 | ||
|
|
74b258e1b6 | ||
|
|
27eb0a21e4 | ||
|
|
d77c6d50d8 | ||
|
|
6a64c18a7b | ||
|
|
b97ff714ae | ||
|
|
1f23eea805 | ||
|
|
cb0cb7df21 | ||
|
|
f3e8628664 | ||
|
|
4758471f9f | ||
|
|
c10bd5a549 | ||
|
|
d53faf96eb | ||
|
|
2307b8ed1a | ||
|
|
711af8d4a5 | ||
|
|
458c9c456b | ||
|
|
29069df48c | ||
|
|
300e84ae2c | ||
|
|
bf11768b92 | ||
|
|
91bd1d9263 | ||
|
|
ac40f9ff12 | ||
|
|
f930837220 | ||
|
|
1d5e3acc93 | ||
|
|
2aec1f9846 | ||
|
|
b56a681b98 | ||
|
|
2713419b32 | ||
|
|
764a3492cc | ||
|
|
29fc471ac4 | ||
|
|
54a597aad3 | ||
|
|
778961d0b6 | ||
|
|
14b01ac761 | ||
|
|
f87848c05b | ||
|
|
153e5a806d | ||
|
|
ee1b8a906f | ||
|
|
734685d45a | ||
|
|
e3b540c212 | ||
|
|
201f578bbc | ||
|
|
ce9aa369d2 | ||
|
|
c5c41c0859 | ||
|
|
d3009f82dd | ||
|
|
0eb9a1fdb0 | ||
|
|
83f6d9926a | ||
|
|
14134842b0 | ||
|
|
4c094c4710 | ||
|
|
3ac41075fd | ||
|
|
fdc97773d1 | ||
|
|
917a739595 | ||
|
|
21475f81ae | ||
|
|
a2a9a0560c | ||
|
|
b879846cdb | ||
|
|
a24011cd72 | ||
|
|
410dd2ecdc | ||
|
|
96b111b894 | ||
|
|
630572c8f9 | ||
|
|
6a381a6366 | ||
|
|
fd04f12677 | ||
|
|
86b8cd17a4 | ||
|
|
bb8ee01693 | ||
|
|
5fb0bca3af | ||
|
|
1e4d1f373d | ||
|
|
87c78d0fcc | ||
|
|
041d2b7947 | ||
|
|
5e7b90d995 | ||
|
|
fadc3dcb55 | ||
|
|
4eea091944 | ||
|
|
9f8d46f395 | ||
|
|
2c54a057c9 | ||
|
|
e1e5cacc6d | ||
|
|
edf9066967 | ||
|
|
7097d12b87 | ||
|
|
08aaeb6372 | ||
|
|
4310f80ec0 | ||
|
|
01577f6494 | ||
|
|
9aa570b2c6 | ||
|
|
d611d7d698 | ||
|
|
f05549b06c | ||
|
|
8c4db8dd40 | ||
|
|
ddee69d291 | ||
|
|
28960c9fab | ||
|
|
449301e519 | ||
|
|
28dab3dc2f | ||
|
|
7995d98db5 | ||
|
|
1f319f3533 | ||
|
|
7d2dbaa62d | ||
|
|
ed5999526b | ||
|
|
2409f75491 | ||
|
|
0c840095d1 | ||
|
|
3eaf0b4856 | ||
|
|
394735a5d9 | ||
|
|
5bfa10bfe7 | ||
|
|
3f12d9cbd5 | ||
|
|
54d89754df | ||
|
|
9470524615 | ||
|
|
b5faa6eaaa | ||
|
|
eab476cfe8 | ||
|
|
b773def012 | ||
|
|
a9f8b23a7a | ||
|
|
61bb6535fb | ||
|
|
eb0bdffe06 | ||
|
|
e129485285 | ||
|
|
aac7de172e | ||
|
|
e19d2412fc | ||
|
|
7cba2cf76c | ||
|
|
55d7a49dbc | ||
|
|
f695864fd8 | ||
|
|
ae4883fbe7 | ||
|
|
836dfd2861 | ||
|
|
6e0523c6d7 | ||
|
|
cd9ba084ae | ||
|
|
c8a0c0de67 | ||
|
|
5dd8d9df91 | ||
|
|
2dbee94e85 | ||
|
|
9001797037 | ||
|
|
5e7104d5a3 | ||
|
|
7c33b22d63 | ||
|
|
b7cb1e379c | ||
|
|
274a6ce52e | ||
|
|
8079e4e7b8 | ||
|
|
920efb8fab | ||
|
|
92aeb2b9da | ||
|
|
ced76cf343 | ||
|
|
3750d6ecd5 | ||
|
|
7444f30384 | ||
|
|
b0fd5ba47f | ||
|
|
cc098bc2e5 | ||
|
|
1cfcf8d194 | ||
|
|
d1e9f741d0 | ||
|
|
0cde9d07ee | ||
|
|
a266425348 | ||
|
|
6dbe02e321 | ||
|
|
39979879c9 | ||
|
|
ba3f604a5c | ||
|
|
9572582401 | ||
|
|
2bcef0ba75 | ||
|
|
31cd7c4007 | ||
|
|
1c4c1799b0 | ||
|
|
2d558df15e | ||
|
|
7b769da4e2 | ||
|
|
4e95d62933 | ||
|
|
83255280b9 | ||
|
|
2546cebdea | ||
|
|
f14a3fe0f1 | ||
|
|
c3eb845be4 | ||
|
|
1eef77dca5 | ||
|
|
d7d9f47fe5 | ||
|
|
fce6a996d9 | ||
|
|
48a484d7de | ||
|
|
4b81d3c612 | ||
|
|
21b6edd7eb | ||
|
|
9a43e022e9 | ||
|
|
62bef3f13d | ||
|
|
c87f5fa004 | ||
|
|
8d99f3ffbb | ||
|
|
100ca7b54b | ||
|
|
4a2624f12a | ||
|
|
21b01a85a8 | ||
|
|
e039ae436e | ||
|
|
b13a1a45f8 | ||
|
|
667fe2bbba | ||
|
|
f083871ca0 | ||
|
|
782e1ba235 | ||
|
|
b92c6edc4e | ||
|
|
bdf4657c73 | ||
|
|
8559438611 | ||
|
|
04045fd410 | ||
|
|
1c71a9d8a8 | ||
|
|
9a9ae9782c | ||
|
|
da2569850b | ||
|
|
b475035415 | ||
|
|
7baee27585 | ||
|
|
2cb2f1ce0a | ||
|
|
8c1407e2a9 | ||
|
|
7bcb113085 | ||
|
|
42dc27addf | ||
|
|
aac30398c4 | ||
|
|
ceae888372 | ||
|
|
61df7050db | ||
|
|
af5561cbbf | ||
|
|
bce30f922d | ||
|
|
d6ed394557 | ||
|
|
7b512a1681 | ||
|
|
7af0597cd5 | ||
|
|
2f5cf6d93c | ||
|
|
d672d2d104 | ||
|
|
c0d1fb1ef4 | ||
|
|
3c882ad0ce | ||
|
|
58acd2eb68 | ||
|
|
590473e7d2 | ||
|
|
21139157c8 | ||
|
|
8f8296ab64 | ||
|
|
40bf07d2a4 | ||
|
|
fd2b4fb86d | ||
|
|
783e867ef6 | ||
|
|
3873d9f978 | ||
|
|
7dece938c8 | ||
|
|
0842d66c79 | ||
|
|
d071e50d62 | ||
|
|
337f01aff1 | ||
|
|
5614e41eb0 | ||
|
|
4f0fdbe453 | ||
|
|
49c068db78 | ||
|
|
fbba44d482 | ||
|
|
10c07b0a09 | ||
|
|
20893698ba | ||
|
|
31de659ed3 | ||
|
|
6c08a16c66 | ||
|
|
21e7178f48 | ||
|
|
aefd267eb2 | ||
|
|
fb1a3980d4 | ||
|
|
cfc467f8a5 | ||
|
|
48120f012d | ||
|
|
c907a78437 | ||
|
|
915c0d09a9 | ||
|
|
80638862cc | ||
|
|
a7350948cd | ||
|
|
1e1be013b5 | ||
|
|
4062584eae | ||
|
|
abedddffa6 | ||
|
|
38858ccdb2 | ||
|
|
d56e6359d0 | ||
|
|
5886991464 | ||
|
|
838326616b | ||
|
|
fcf80fe946 | ||
|
|
2e63a7056c | ||
|
|
7c807e3ec8 | ||
|
|
b558aa0934 | ||
|
|
38757758cb | ||
|
|
84dd3d8fd1 | ||
|
|
19423c2d30 | ||
|
|
98bba7d7fa | ||
|
|
dcaa9ce000 | ||
|
|
3cae44a136 | ||
|
|
df8a3d2692 | ||
|
|
56e43f1808 | ||
|
|
2f6b95cccf | ||
|
|
ad9f6b2b64 | ||
|
|
165c3dc976 | ||
|
|
cbe6390b41 | ||
|
|
026eaf6606 | ||
|
|
ee184f8e62 | ||
|
|
5745231dc9 | ||
|
|
cbdc3a9861 | ||
|
|
ba5c42ad6d | ||
|
|
b056a731a1 | ||
|
|
b4cd94f2d9 | ||
|
|
3b8cb43f02 | ||
|
|
82cb11c3c4 | ||
|
|
eb7522a90b | ||
|
|
3898201b1e | ||
|
|
bb6ab0c17b | ||
|
|
652c40ab1f | ||
|
|
ca0d6215a9 | ||
|
|
61d155257c | ||
|
|
91399f1a1f | ||
|
|
2e738c5977 | ||
|
|
c0bd51cf03 | ||
|
|
ca5afe04f8 | ||
|
|
47db0b9f4e | ||
|
|
27f17a377a | ||
|
|
ecaf731ecf | ||
|
|
9fba2a85f6 | ||
|
|
93f75be182 | ||
|
|
d537901f59 | ||
|
|
260c1ed4a4 | ||
|
|
ac2bd52463 | ||
|
|
16c6f8fee1 | ||
|
|
8a0db21f17 | ||
|
|
9ab08a71c0 | ||
|
|
381c32a3b4 | ||
|
|
350c0f10c4 | ||
|
|
d5b982f813 | ||
|
|
6587375ff2 | ||
|
|
f5ecb81bad | ||
|
|
0141cd81c4 | ||
|
|
ff412c7497 | ||
|
|
623f239f91 | ||
|
|
c7ba304c6a | ||
|
|
c8393604d1 | ||
|
|
c5d47a67aa | ||
|
|
3a1423cd59 | ||
|
|
d57f4cf6cd | ||
|
|
af420942c4 | ||
|
|
eac4e5e66f | ||
|
|
b8822a98f7 | ||
|
|
95322b42c0 | ||
|
|
33f5a06d32 | ||
|
|
a7e5126c92 | ||
|
|
c62f3e5b8e | ||
|
|
5d3f413a05 | ||
|
|
644154ca38 | ||
|
|
cccce5ff74 | ||
|
|
aa1fe98188 | ||
|
|
b6a78550d6 | ||
|
|
70b7f2c493 | ||
|
|
ea44e5f209 | ||
|
|
41ef87d9f8 | ||
|
|
c0b4a70aa0 | ||
|
|
955875cb7a | ||
|
|
827e8571aa | ||
|
|
aed08b0f59 | ||
|
|
3ddaf41e27 | ||
|
|
38a9cce6bf | ||
|
|
ae255ef381 | ||
|
|
4316bef01e | ||
|
|
8491c5706d | ||
|
|
7b7fab1f32 | ||
|
|
5a6fccdc2f | ||
|
|
23668be46d | ||
|
|
f92f2c1666 | ||
|
|
895740a3cb | ||
|
|
4c76c3231f | ||
|
|
ca9d3f9559 | ||
|
|
3ca3c5e75c | ||
|
|
c2c0b1dfdc | ||
|
|
c633774487 | ||
|
|
c2d86fc517 | ||
|
|
d7c8d150ca | ||
|
|
6b8a4e65f2 | ||
|
|
482e43dd1f | ||
|
|
1437babc6c | ||
|
|
5ed882943a | ||
|
|
e678b3fb3a | ||
|
|
a5770bc4e4 | ||
|
|
59821bb939 | ||
|
|
b58040be44 | ||
|
|
be3b8ad52e | ||
|
|
0fdaf97461 | ||
|
|
f5f036372f | ||
|
|
3fceb983e6 | ||
|
|
ae6a39196d | ||
|
|
2810ff2753 | ||
|
|
205c0cf8d3 | ||
|
|
d9c801a091 | ||
|
|
0833aa3b30 | ||
|
|
9c90bbc146 | ||
|
|
231b387076 | ||
|
|
3de432652f | ||
|
|
cad714493e | ||
|
|
6a690a6108 | ||
|
|
1b85c52557 | ||
|
|
b37be92ea9 | ||
|
|
f95979f445 | ||
|
|
09e07218ae | ||
|
|
085f5a9451 | ||
|
|
eb4e935554 | ||
|
|
57986cf425 | ||
|
|
7bf14b9acc | ||
|
|
3ba0be34d9 | ||
|
|
0f828a3c75 | ||
|
|
16a768a142 | ||
|
|
f380d20279 | ||
|
|
be908ab36c | ||
|
|
b545454537 | ||
|
|
a5ff8dd1d6 | ||
|
|
59f23e518b | ||
|
|
858b3f0176 | ||
|
|
89b8494ad0 | ||
|
|
64ecd75bd5 | ||
|
|
138eb3393d | ||
|
|
1ad51d2925 | ||
|
|
317e175bca | ||
|
|
0e287aa7d1 | ||
|
|
28018b705b | ||
|
|
46ec72d6be | ||
|
|
82494a87af | ||
|
|
95c19b447a | ||
|
|
9c6eae936a | ||
|
|
77605a9360 | ||
|
|
82880c3f06 | ||
|
|
11143c771b | ||
|
|
0968eaa5a8 | ||
|
|
0687f9d472 | ||
|
|
25f0f5951a | ||
|
|
eec0ce65ad | ||
|
|
be4e100168 | ||
|
|
59e4f1063c | ||
|
|
359e21f02b | ||
|
|
6894bd9c0e | ||
|
|
7040f02823 | ||
|
|
41408de337 | ||
|
|
72e243dce8 | ||
|
|
77d4840e2a | ||
|
|
0d5961821c | ||
|
|
f34980b173 | ||
|
|
5b21a6e529 | ||
|
|
6dbb737d4b | ||
|
|
76ecfbaaa2 | ||
|
|
d9aacbcb92 | ||
|
|
e088325d95 | ||
|
|
b29dd2c580 | ||
|
|
89e82fd5b0 | ||
|
|
9f0b671d42 | ||
|
|
7de7c724dc | ||
|
|
3525b1d92a | ||
|
|
30cea84886 | ||
|
|
0c2cc7f575 |
@@ -1,42 +0,0 @@
|
|||||||
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.
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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.
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
## 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
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
# 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! 🎉🎉🎉
|
|
||||||
@@ -57,10 +57,12 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
|
|
||||||
- name: Setup timezone
|
- name: Set time zone
|
||||||
uses: zcong1993/setup-timezone@master
|
uses: szenius/set-timezone@v1.0
|
||||||
with:
|
with:
|
||||||
timezone: Asia/Shanghai
|
timezoneLinux: "Asia/Shanghai"
|
||||||
|
timezoneMacos: "Asia/Shanghai"
|
||||||
|
timezoneWindows: "China Standard Time"
|
||||||
|
|
||||||
- name: Login to DockerHub
|
- name: Login to DockerHub
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v2
|
||||||
|
|||||||
@@ -1,2 +1 @@
|
|||||||
sentrycli_cdnurl=https://npmmirror.com/mirrors/sentry-cli/
|
sentrycli_cdnurl=https://cdn.npm.taobao.org/dist/sentry-cli
|
||||||
strict-peer-dependencies=false
|
|
||||||
@@ -1,15 +1,24 @@
|
|||||||
import { defineConfig } from '@umijs/max';
|
import { defineConfig } from 'umi';
|
||||||
const CompressionPlugin = require('compression-webpack-plugin');
|
const CompressionPlugin = require('compression-webpack-plugin');
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
hash: true,
|
hash: true,
|
||||||
antd: {},
|
layout: false,
|
||||||
outputPath: 'static/dist',
|
outputPath: 'static/dist',
|
||||||
fastRefresh: true,
|
nodeModulesTransform: {
|
||||||
favicons: ['/images/favicon.svg'],
|
type: 'none',
|
||||||
mfsu: {
|
|
||||||
strategy: 'eager',
|
|
||||||
},
|
},
|
||||||
|
fastRefresh: {},
|
||||||
|
// antd: {
|
||||||
|
// dark: true,
|
||||||
|
// },
|
||||||
|
mfsu: {},
|
||||||
|
esbuild: {},
|
||||||
|
webpack5: {},
|
||||||
|
dynamicImport: {
|
||||||
|
loading: '@/components/pageLoading',
|
||||||
|
},
|
||||||
|
favicon: '/images/g5.ico',
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api/public': {
|
'/api/public': {
|
||||||
target: 'http://127.0.0.1:5400/',
|
target: 'http://127.0.0.1:5400/',
|
||||||
@@ -21,7 +30,7 @@ export default defineConfig({
|
|||||||
ws: true,
|
ws: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
chainWebpack: ((config: any) => {
|
chainWebpack: (config) => {
|
||||||
config.plugin('compression-webpack-plugin').use(
|
config.plugin('compression-webpack-plugin').use(
|
||||||
new CompressionPlugin({
|
new CompressionPlugin({
|
||||||
algorithm: 'gzip',
|
algorithm: 'gzip',
|
||||||
@@ -30,13 +39,13 @@ export default defineConfig({
|
|||||||
minRatio: 0.6,
|
minRatio: 0.6,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}) as any,
|
},
|
||||||
externals: {
|
externals: {
|
||||||
react: 'window.React',
|
react: 'window.React',
|
||||||
'react-dom': 'window.ReactDOM',
|
'react-dom': 'window.ReactDOM',
|
||||||
},
|
},
|
||||||
headScripts: [
|
scripts: [
|
||||||
'https://gw.alipayobjects.com/os/lib/react/18.2.0/umd/react.production.min.js',
|
'https://gw.alipayobjects.com/os/lib/react/16.13.1/umd/react.production.min.js',
|
||||||
'https://gw.alipayobjects.com/os/lib/react-dom/18.2.0/umd/react-dom.production.min.js',
|
'https://gw.alipayobjects.com/os/lib/react-dom/16.13.1/umd/react-dom.production.min.js',
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
+5
-8
@@ -1,6 +1,6 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/whyour/qinglong">
|
<a href="https://github.com/whyour/qinglong">
|
||||||
<img width="150" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -57,10 +57,11 @@ https://podman.io/getting-started/installation
|
|||||||
```bash
|
```bash
|
||||||
podman run -dit \
|
podman run -dit \
|
||||||
--network bridge \
|
--network bridge \
|
||||||
-v $PWD/ql/data:/ql/data \
|
-v $PWD/ql:/ql/data \
|
||||||
-p 5700:5700 \
|
-p 5700:5700 \
|
||||||
--name qinglong \
|
--name qinglong \
|
||||||
--hostname qinglong \
|
--hostname qinglong \
|
||||||
|
--restart unless-stopped \
|
||||||
docker.io/whyour/qinglong:latest
|
docker.io/whyour/qinglong:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -95,7 +96,7 @@ systemctl restart docker
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run -dit \
|
docker run -dit \
|
||||||
-v $PWD/ql/data:/ql/data \
|
-v $PWD/ql:/ql/data \
|
||||||
-p 5700:5700 \
|
-p 5700:5700 \
|
||||||
--name qinglong \
|
--name qinglong \
|
||||||
--hostname qinglong \
|
--hostname qinglong \
|
||||||
@@ -123,10 +124,6 @@ docker-compose up -d
|
|||||||
docker-compose down
|
docker-compose down
|
||||||
```
|
```
|
||||||
|
|
||||||
3. access
|
|
||||||
|
|
||||||
Open your browser and visit http://{ip}:5700
|
|
||||||
|
|
||||||
## Use
|
## Use
|
||||||
|
|
||||||
1. built-in commands
|
1. built-in commands
|
||||||
@@ -182,7 +179,7 @@ task <file_path> desi <env_name> <account_number>
|
|||||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||||
- [Ant Design](https://ant.design)
|
- [Ant Design](https://ant.design)
|
||||||
- [Ant Design Pro](https://pro.ant.design/)
|
- [Ant Design Pro](https://pro.ant.design/)
|
||||||
- [Umijs](https://umijs.org)
|
- [Umijs3.0](https://umijs.org)
|
||||||
- [darkreader](https://github.com/darkreader/darkreader)
|
- [darkreader](https://github.com/darkreader/darkreader)
|
||||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/whyour/qinglong">
|
<a href="https://github.com/whyour/qinglong">
|
||||||
<img width="150" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -57,10 +57,11 @@ https://podman.io/getting-started/installation
|
|||||||
```bash
|
```bash
|
||||||
podman run -dit \
|
podman run -dit \
|
||||||
--network bridge \
|
--network bridge \
|
||||||
-v $PWD/ql/data:/ql/data \
|
-v $PWD/ql:/ql/data \
|
||||||
-p 5700:5700 \
|
-p 5700:5700 \
|
||||||
--name qinglong \
|
--name qinglong \
|
||||||
--hostname qinglong \
|
--hostname qinglong \
|
||||||
|
--restart unless-stopped \
|
||||||
docker.io/whyour/qinglong:latest
|
docker.io/whyour/qinglong:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -96,7 +97,7 @@ systemctl restart docker
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run -dit \
|
docker run -dit \
|
||||||
-v $PWD/ql/data:/ql/data \
|
-v $PWD/ql:/ql/data \
|
||||||
-p 5700:5700 \
|
-p 5700:5700 \
|
||||||
--name qinglong \
|
--name qinglong \
|
||||||
--hostname qinglong \
|
--hostname qinglong \
|
||||||
@@ -124,10 +125,6 @@ docker-compose up -d
|
|||||||
docker-compose down
|
docker-compose down
|
||||||
```
|
```
|
||||||
|
|
||||||
3. 访问
|
|
||||||
|
|
||||||
打开你的浏览器,访问 http://{ip}:5700
|
|
||||||
|
|
||||||
## 使用
|
## 使用
|
||||||
|
|
||||||
1. 内置命令
|
1. 内置命令
|
||||||
@@ -166,11 +163,11 @@ task <file_path> desi <env_name> <account_number>
|
|||||||
|
|
||||||
* file_url: 脚本地址
|
* file_url: 脚本地址
|
||||||
* repo_url: 仓库地址
|
* repo_url: 仓库地址
|
||||||
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串,多个竖线分割
|
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串
|
||||||
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串,多个竖线分割
|
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串
|
||||||
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响,多个竖线分割
|
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响
|
||||||
* extensions: 拉取仓库的文件后缀,多个竖线分割
|
|
||||||
* branch: 拉取仓库的分支
|
* branch: 拉取仓库的分支
|
||||||
|
* extensions: 拉取仓库的文件后缀
|
||||||
* days: 需要保留的日志的天数
|
* days: 需要保留的日志的天数
|
||||||
* file_path: 任务执行时的文件路径
|
* file_path: 任务执行时的文件路径
|
||||||
* env_name: 任务执行时需要并发或者指定时的环境变量名称
|
* env_name: 任务执行时需要并发或者指定时的环境变量名称
|
||||||
@@ -182,7 +179,7 @@ task <file_path> desi <env_name> <account_number>
|
|||||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||||
- [Ant Design](https://ant.design)
|
- [Ant Design](https://ant.design)
|
||||||
- [Ant Design Pro](https://pro.ant.design/)
|
- [Ant Design Pro](https://pro.ant.design/)
|
||||||
- [Umijs](https://umijs.org)
|
- [Umijs3.0](https://umijs.org)
|
||||||
- [darkreader](https://github.com/darkreader/darkreader)
|
- [darkreader](https://github.com/darkreader/darkreader)
|
||||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export default (app: Router) => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -50,6 +51,7 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -74,6 +76,7 @@ export default (app: Router) => {
|
|||||||
fs.writeFileSync(path, content);
|
fs.writeFileSync(path, content);
|
||||||
res.send({ code: 200, message: '保存成功' });
|
res.send({ code: 200, message: '保存成功' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+24
-133
@@ -2,7 +2,6 @@ import { Router, Request, Response, NextFunction } from 'express';
|
|||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import CronService from '../services/cron';
|
import CronService from '../services/cron';
|
||||||
import CronViewService from '../services/cronView';
|
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import cron_parser from 'cron-parser';
|
import cron_parser from 'cron-parser';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
@@ -10,135 +9,11 @@ const route = Router();
|
|||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/crons', route);
|
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(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
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(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
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) => {
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.crontabs(req.query as any);
|
const data = await cronService.crontabs(req.query.searchValue as string);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error('🔥 error: %o', e);
|
logger.error('🔥 error: %o', e);
|
||||||
@@ -167,6 +42,7 @@ export default (app: Router) => {
|
|||||||
return res.send({ code: 400, message: 'param schedule error' });
|
return res.send({ code: 400, message: 'param schedule error' });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -184,6 +60,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.run(req.body);
|
const data = await cronService.run(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -201,6 +78,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.stop(req.body);
|
const data = await cronService.stop(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -224,6 +102,7 @@ export default (app: Router) => {
|
|||||||
);
|
);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -244,6 +123,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.addLabels(req.body.ids, req.body.labels);
|
const data = await cronService.addLabels(req.body.ids, req.body.labels);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -261,6 +141,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.disabled(req.body);
|
const data = await cronService.disabled(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -278,6 +159,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.enabled(req.body);
|
const data = await cronService.enabled(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -297,6 +179,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.log(req.params.id);
|
const data = await cronService.log(req.params.id);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -307,9 +190,9 @@ export default (app: Router) => {
|
|||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
labels: Joi.array().optional().allow(null),
|
labels: Joi.array().optional().allow(null),
|
||||||
command: Joi.string().required(),
|
command: Joi.string().optional(),
|
||||||
schedule: Joi.string().required(),
|
schedule: Joi.string().optional(),
|
||||||
name: Joi.string().optional().allow(null),
|
name: Joi.string().optional(),
|
||||||
id: Joi.number().required(),
|
id: Joi.number().required(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -327,6 +210,7 @@ export default (app: Router) => {
|
|||||||
return res.send({ code: 400, message: 'param schedule error' });
|
return res.send({ code: 400, message: 'param schedule error' });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -344,6 +228,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.remove(req.body);
|
const data = await cronService.remove(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -361,6 +246,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.pin(req.body);
|
const data = await cronService.pin(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -378,6 +264,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.unPin(req.body);
|
const data = await cronService.unPin(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -392,6 +279,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.import_crontab();
|
const data = await cronService.import_crontab();
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -411,6 +299,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.getDb({ id: req.params.id });
|
const data = await cronService.getDb({ id: req.params.id });
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -422,10 +311,10 @@ export default (app: Router) => {
|
|||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
ids: Joi.array().items(Joi.number().required()),
|
ids: Joi.array().items(Joi.number().required()),
|
||||||
status: Joi.string().required(),
|
status: Joi.string().required(),
|
||||||
pid: Joi.string().optional().allow(null),
|
pid: Joi.string().optional(),
|
||||||
log_path: Joi.string().optional().allow(null),
|
log_path: Joi.string().optional(),
|
||||||
last_running_time: Joi.number().optional().allow(null),
|
last_running_time: Joi.number().optional(),
|
||||||
last_execution_time: Joi.number().optional().allow(null),
|
last_execution_time: Joi.number().optional(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
@@ -439,6 +328,7 @@ export default (app: Router) => {
|
|||||||
});
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -458,6 +348,7 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.logs(req.params.id);
|
const data = await cronService.logs(req.params.id);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ export default (app: Router) => {
|
|||||||
const data = await dependenceService.create(req.body);
|
const data = await dependenceService.create(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -60,6 +61,7 @@ export default (app: Router) => {
|
|||||||
const data = await dependenceService.update(req.body);
|
const data = await dependenceService.update(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -77,6 +79,7 @@ export default (app: Router) => {
|
|||||||
const data = await dependenceService.remove(req.body);
|
const data = await dependenceService.remove(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -94,6 +97,7 @@ export default (app: Router) => {
|
|||||||
const data = await dependenceService.remove(req.body, true);
|
const data = await dependenceService.remove(req.body, true);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -113,6 +117,7 @@ export default (app: Router) => {
|
|||||||
const data = await dependenceService.getDb({ id: req.params.id });
|
const data = await dependenceService.getDb({ id: req.params.id });
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -130,6 +135,7 @@ export default (app: Router) => {
|
|||||||
const data = await dependenceService.reInstall(req.body);
|
const data = await dependenceService.reInstall(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+11
-50
@@ -3,21 +3,8 @@ import { Container } from 'typedi';
|
|||||||
import EnvService from '../services/env';
|
import EnvService from '../services/env';
|
||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import multer from 'multer';
|
|
||||||
import config from '../config';
|
|
||||||
import fs from 'fs';
|
|
||||||
const route = Router();
|
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) => {
|
export default (app: Router) => {
|
||||||
app.use('/envs', route);
|
app.use('/envs', route);
|
||||||
|
|
||||||
@@ -39,9 +26,7 @@ export default (app: Router) => {
|
|||||||
body: Joi.array().items(
|
body: Joi.array().items(
|
||||||
Joi.object({
|
Joi.object({
|
||||||
value: Joi.string().required(),
|
value: Joi.string().required(),
|
||||||
name: Joi.string()
|
name: Joi.string().required(),
|
||||||
.required()
|
|
||||||
.pattern(/^[a-zA-Z_][0-9a-zA-Z_]*$/),
|
|
||||||
remarks: Joi.string().optional().allow(''),
|
remarks: Joi.string().optional().allow(''),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -53,6 +38,7 @@ export default (app: Router) => {
|
|||||||
const data = await envService.create(req.body);
|
const data = await envService.create(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -75,6 +61,7 @@ export default (app: Router) => {
|
|||||||
const data = await envService.update(req.body);
|
const data = await envService.update(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -92,6 +79,7 @@ export default (app: Router) => {
|
|||||||
const data = await envService.remove(req.body);
|
const data = await envService.remove(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -109,11 +97,13 @@ export default (app: Router) => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.move(req.params.id, req.body);
|
const data = await envService.move(req.params.id, req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -131,6 +121,7 @@ export default (app: Router) => {
|
|||||||
const data = await envService.disabled(req.body);
|
const data = await envService.disabled(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -148,6 +139,7 @@ export default (app: Router) => {
|
|||||||
const data = await envService.enabled(req.body);
|
const data = await envService.enabled(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -168,6 +160,7 @@ export default (app: Router) => {
|
|||||||
const data = await envService.updateNames(req.body);
|
const data = await envService.updateNames(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -184,42 +177,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.getDb({ id: req.params.id });
|
const data = await envService.getDb(req.params.id);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
logger.error('🔥 error: %o', e);
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
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);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+3
-37
@@ -3,11 +3,9 @@ import { Container } from 'typedi';
|
|||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { emptyDir, getFileContentByName, readDirs } from '../config/util';
|
import { getFileContentByName, readDirs } from '../config/util';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
|
||||||
const route = Router();
|
const route = Router();
|
||||||
const blacklist = ['.tmp'];
|
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/logs', route);
|
app.use('/logs', route);
|
||||||
@@ -15,7 +13,7 @@ export default (app: Router) => {
|
|||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const result = readDirs(config.logPath, config.logPath, blacklist);
|
const result = readDirs(config.logPath, config.logPath);
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
data: result,
|
data: result,
|
||||||
@@ -31,9 +29,6 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
if (blacklist.includes(req.path)) {
|
|
||||||
return res.send({ code: 403, message: '暂无权限' });
|
|
||||||
}
|
|
||||||
const filePath = join(
|
const filePath = join(
|
||||||
config.logPath,
|
config.logPath,
|
||||||
(req.query.path || '') as string,
|
(req.query.path || '') as string,
|
||||||
@@ -42,38 +37,9 @@ export default (app: Router) => {
|
|||||||
const content = getFileContentByName(filePath);
|
const content = getFileContentByName(filePath);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
+7
-1
@@ -16,6 +16,7 @@ export default (app: Router) => {
|
|||||||
const data = await openService.list();
|
const data = await openService.list();
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -25,7 +26,7 @@ export default (app: Router) => {
|
|||||||
'/apps',
|
'/apps',
|
||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
name: Joi.string().optional().allow('').disallow('system'),
|
name: Joi.string().optional().allow(''),
|
||||||
scopes: Joi.array().items(Joi.string().required()),
|
scopes: Joi.array().items(Joi.string().required()),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -36,6 +37,7 @@ export default (app: Router) => {
|
|||||||
const data = await openService.create(req.body);
|
const data = await openService.create(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -57,6 +59,7 @@ export default (app: Router) => {
|
|||||||
const data = await openService.update(req.body);
|
const data = await openService.update(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -74,6 +77,7 @@ export default (app: Router) => {
|
|||||||
const data = await openService.remove(req.body);
|
const data = await openService.remove(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -93,6 +97,7 @@ export default (app: Router) => {
|
|||||||
const data = await openService.resetSecret(req.params.id);
|
const data = await openService.resetSecret(req.params.id);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -113,6 +118,7 @@ export default (app: Router) => {
|
|||||||
const result = await openService.authToken(req.query as any);
|
const result = await openService.authToken(req.query as any);
|
||||||
return res.send(result);
|
return res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+35
-65
@@ -3,8 +3,6 @@ import {
|
|||||||
getFileContentByName,
|
getFileContentByName,
|
||||||
readDirs,
|
readDirs,
|
||||||
getLastModifyFilePath,
|
getLastModifyFilePath,
|
||||||
readDir,
|
|
||||||
emptyDir,
|
|
||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import { Router, Request, Response, NextFunction } from 'express';
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
@@ -12,38 +10,17 @@ import { Logger } from 'winston';
|
|||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import path, { join, parse } from 'path';
|
import path, { join } from 'path';
|
||||||
import ScriptService from '../services/script';
|
import ScriptService from '../services/script';
|
||||||
import multer from 'multer';
|
|
||||||
const route = Router();
|
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) => {
|
export default (app: Router) => {
|
||||||
app.use('/scripts', route);
|
app.use('/scripts', route);
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let result = [];
|
const result = readDirs(config.scriptPath, config.scriptPath);
|
||||||
const blacklist = ['node_modules', '.git'];
|
|
||||||
if (req.query.path) {
|
|
||||||
const targetPath = path.join(
|
|
||||||
config.scriptPath,
|
|
||||||
req.query.path as string,
|
|
||||||
);
|
|
||||||
result = readDir(targetPath, config.scriptPath, blacklist);
|
|
||||||
} else {
|
|
||||||
result = readDirs(config.scriptPath, config.scriptPath, blacklist);
|
|
||||||
}
|
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
data: result,
|
data: result,
|
||||||
@@ -67,6 +44,7 @@ export default (app: Router) => {
|
|||||||
const content = getFileContentByName(filePath);
|
const content = getFileContentByName(filePath);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -74,19 +52,23 @@ export default (app: Router) => {
|
|||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
'/',
|
'/',
|
||||||
upload.single('file'),
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
filename: Joi.string().required(),
|
||||||
|
path: Joi.string().optional().allow(''),
|
||||||
|
content: Joi.string().allow(''),
|
||||||
|
originFilename: Joi.string().allow(''),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let { filename, path, content, originFilename, directory } =
|
let { filename, path, content, originFilename } = req.body as {
|
||||||
req.body as {
|
|
||||||
filename: string;
|
filename: string;
|
||||||
path: string;
|
path: string;
|
||||||
content: string;
|
content: string;
|
||||||
originFilename: string;
|
originFilename: string;
|
||||||
directory: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!path) {
|
if (!path) {
|
||||||
path = config.scriptPath;
|
path = config.scriptPath;
|
||||||
}
|
}
|
||||||
@@ -102,26 +84,15 @@ export default (app: Router) => {
|
|||||||
message: '文件路径禁止访问',
|
message: '文件路径禁止访问',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.file) {
|
|
||||||
fs.renameSync(req.file.path, join(path, req.file.filename));
|
|
||||||
return res.send({ code: 200 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (directory) {
|
|
||||||
fs.mkdirSync(join(path, directory), { recursive: true });
|
|
||||||
return res.send({ code: 200 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!originFilename) {
|
if (!originFilename) {
|
||||||
originFilename = filename;
|
originFilename = filename;
|
||||||
}
|
}
|
||||||
const originFilePath = join(
|
const originFilePath = `${path}${originFilename.replace(/\//g, '')}`;
|
||||||
path,
|
const filePath = `${path}${filename.replace(/\//g, '')}`;
|
||||||
`${originFilename.replace(/\//g, '')}`,
|
|
||||||
);
|
|
||||||
const filePath = join(path, `${filename.replace(/\//g, '')}`);
|
|
||||||
if (fs.existsSync(originFilePath)) {
|
if (fs.existsSync(originFilePath)) {
|
||||||
|
if (!fs.existsSync(config.bakPath)) {
|
||||||
|
fs.mkdirSync(config.bakPath);
|
||||||
|
}
|
||||||
fs.copyFileSync(
|
fs.copyFileSync(
|
||||||
originFilePath,
|
originFilePath,
|
||||||
`${config.bakPath}${originFilename.replace(/\//g, '')}`,
|
`${config.bakPath}${originFilename.replace(/\//g, '')}`,
|
||||||
@@ -133,6 +104,7 @@ export default (app: Router) => {
|
|||||||
fs.writeFileSync(filePath, content);
|
fs.writeFileSync(filePath, content);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -144,7 +116,7 @@ export default (app: Router) => {
|
|||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
filename: Joi.string().required(),
|
filename: Joi.string().required(),
|
||||||
path: Joi.string().optional().allow(''),
|
path: Joi.string().optional().allow(''),
|
||||||
content: Joi.string().required().allow(''),
|
content: Joi.string().required(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
@@ -159,6 +131,7 @@ export default (app: Router) => {
|
|||||||
fs.writeFileSync(filePath, content);
|
fs.writeFileSync(filePath, content);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -170,25 +143,20 @@ export default (app: Router) => {
|
|||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
filename: Joi.string().required(),
|
filename: Joi.string().required(),
|
||||||
path: Joi.string().allow(''),
|
path: Joi.string().allow(''),
|
||||||
type: Joi.string().optional()
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let { filename, path, type } = req.body as {
|
let { filename, path } = req.body as {
|
||||||
filename: string;
|
filename: string;
|
||||||
path: string;
|
path: string;
|
||||||
type: string;
|
|
||||||
};
|
};
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
const filePath = join(config.scriptPath, path, filename);
|
||||||
if (type === 'directory') {
|
|
||||||
emptyDir(filePath);
|
|
||||||
} else {
|
|
||||||
fs.unlinkSync(filePath);
|
fs.unlinkSync(filePath);
|
||||||
}
|
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -219,6 +187,7 @@ export default (app: Router) => {
|
|||||||
return next(err);
|
return next(err);
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -229,22 +198,22 @@ export default (app: Router) => {
|
|||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
filename: Joi.string().required(),
|
filename: Joi.string().required(),
|
||||||
content: Joi.string().optional().allow(''),
|
|
||||||
path: Joi.string().optional().allow(''),
|
path: Joi.string().optional().allow(''),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let { filename, content, path } = req.body;
|
let { filename, path } = req.body as {
|
||||||
const { name, ext } = parse(filename);
|
filename: string;
|
||||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
path: string;
|
||||||
fs.writeFileSync(filePath, content || '', { encoding: 'utf8' });
|
};
|
||||||
|
const filePath = join(path, filename);
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const result = await scriptService.runScript(filePath);
|
const result = await scriptService.runScript(filePath);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -255,21 +224,22 @@ export default (app: Router) => {
|
|||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
filename: Joi.string().required(),
|
filename: Joi.string().required(),
|
||||||
content: Joi.string().optional().allow(''),
|
|
||||||
path: Joi.string().optional().allow(''),
|
path: Joi.string().optional().allow(''),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let { filename, content, path } = req.body;
|
let { filename, path } = req.body as {
|
||||||
const { name, ext } = parse(filename);
|
filename: string;
|
||||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
path: string;
|
||||||
|
};
|
||||||
|
const filePath = join(path, filename);
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const result = await scriptService.stopScript(filePath);
|
const result = await scriptService.stopScript(filePath);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -29,13 +29,7 @@ export default (app: Router) => {
|
|||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
type: Joi.string().required(),
|
type: Joi.string().required(),
|
||||||
schedule: Joi.string().optional().allow('').allow(null),
|
schedule: Joi.string().optional().allow('').allow(null),
|
||||||
interval_schedule: Joi.object({
|
interval_schedule: Joi.object().optional().allow('').allow(null),
|
||||||
type: Joi.string().required(),
|
|
||||||
value: Joi.number().min(1).required(),
|
|
||||||
})
|
|
||||||
.optional()
|
|
||||||
.allow('')
|
|
||||||
.allow(null),
|
|
||||||
name: Joi.string().optional().allow('').allow(null),
|
name: Joi.string().optional().allow('').allow(null),
|
||||||
url: Joi.string().required(),
|
url: Joi.string().required(),
|
||||||
whitelist: Joi.string().optional().allow('').allow(null),
|
whitelist: Joi.string().optional().allow('').allow(null),
|
||||||
@@ -65,6 +59,7 @@ export default (app: Router) => {
|
|||||||
return res.send({ code: 400, message: 'param schedule error' });
|
return res.send({ code: 400, message: 'param schedule error' });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -82,6 +77,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.run(req.body);
|
const data = await subscriptionService.run(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -99,6 +95,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.stop(req.body);
|
const data = await subscriptionService.stop(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -116,6 +113,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.disabled(req.body);
|
const data = await subscriptionService.disabled(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -133,6 +131,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.enabled(req.body);
|
const data = await subscriptionService.enabled(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -152,6 +151,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.log(req.params.id);
|
const data = await subscriptionService.log(req.params.id);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -195,6 +195,7 @@ export default (app: Router) => {
|
|||||||
return res.send({ code: 400, message: 'param schedule error' });
|
return res.send({ code: 400, message: 'param schedule error' });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -212,6 +213,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.remove(req.body);
|
const data = await subscriptionService.remove(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -231,6 +233,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.getDb({ id: req.params.id });
|
const data = await subscriptionService.getDb({ id: req.params.id });
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -257,6 +260,7 @@ export default (app: Router) => {
|
|||||||
});
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -276,6 +280,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.logs(req.params.id);
|
const data = await subscriptionService.logs(req.params.id);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+5
-14
@@ -7,8 +7,6 @@ import SystemService from '../services/system';
|
|||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import UserService from '../services/user';
|
import UserService from '../services/user';
|
||||||
import { EnvModel } from '../data/env';
|
import { EnvModel } from '../data/env';
|
||||||
import { promiseExec } from '../config/util';
|
|
||||||
|
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
@@ -24,15 +22,6 @@ export default (app: Router) => {
|
|||||||
|
|
||||||
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||||
const version = currentVersionFile.match(versionRegx)![1];
|
const version = currentVersionFile.match(versionRegx)![1];
|
||||||
const lastCommitTime = (
|
|
||||||
await promiseExec('git show -s --format=%ai')
|
|
||||||
).replace('\n', '');
|
|
||||||
const lastCommitId = (
|
|
||||||
await promiseExec('git rev-parse --short HEAD')
|
|
||||||
).replace('\n', '');
|
|
||||||
const branch = (
|
|
||||||
await promiseExec('git symbolic-ref --short HEAD')
|
|
||||||
).replace('\n', '');
|
|
||||||
|
|
||||||
let isInitialized = true;
|
let isInitialized = true;
|
||||||
if (
|
if (
|
||||||
@@ -48,9 +37,6 @@ export default (app: Router) => {
|
|||||||
data: {
|
data: {
|
||||||
isInitialized,
|
isInitialized,
|
||||||
version,
|
version,
|
||||||
lastCommitTime,
|
|
||||||
lastCommitId,
|
|
||||||
branch,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -68,6 +54,7 @@ export default (app: Router) => {
|
|||||||
const data = await systemService.getLogRemoveFrequency();
|
const data = await systemService.getLogRemoveFrequency();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -89,6 +76,7 @@ export default (app: Router) => {
|
|||||||
);
|
);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -103,6 +91,7 @@ export default (app: Router) => {
|
|||||||
const result = await systemService.checkUpdate();
|
const result = await systemService.checkUpdate();
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -117,6 +106,7 @@ export default (app: Router) => {
|
|||||||
const result = await systemService.updateSystem();
|
const result = await systemService.updateSystem();
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -137,6 +127,7 @@ export default (app: Router) => {
|
|||||||
const result = await systemService.notify(req.body);
|
const result = await systemService.notify(req.body);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.login({ ...req.body }, req);
|
const data = await userService.login({ ...req.body }, req);
|
||||||
return res.send(data);
|
return res.send(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -53,6 +54,7 @@ export default (app: Router) => {
|
|||||||
await userService.logout(req.platform);
|
await userService.logout(req.platform);
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -73,6 +75,7 @@ export default (app: Router) => {
|
|||||||
await userService.updateUsernameAndPassword(req.body);
|
await userService.updateUsernameAndPassword(req.body);
|
||||||
res.send({ code: 200, message: '更新成功' });
|
res.send({ code: 200, message: '更新成功' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -106,6 +109,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.initTwoFactor();
|
const data = await userService.initTwoFactor();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -125,6 +129,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.activeTwoFactor(req.body.code);
|
const data = await userService.activeTwoFactor(req.body.code);
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -139,6 +144,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.deactiveTwoFactor();
|
const data = await userService.deactiveTwoFactor();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -160,6 +166,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.twoFactorLogin(req.body, req);
|
const data = await userService.twoFactorLogin(req.body, req);
|
||||||
res.send(data);
|
res.send(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -174,6 +181,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.getLoginLog();
|
const data = await userService.getLoginLog();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -188,6 +196,7 @@ export default (app: Router) => {
|
|||||||
const data = await userService.getNotificationMode();
|
const data = await userService.getNotificationMode();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -202,6 +211,7 @@ export default (app: Router) => {
|
|||||||
const result = await userService.updateNotificationMode(req.body);
|
const result = await userService.updateNotificationMode(req.body);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -222,6 +232,7 @@ export default (app: Router) => {
|
|||||||
await userService.updateUsernameAndPassword(req.body);
|
await userService.updateUsernameAndPassword(req.body);
|
||||||
res.send({ code: 200, message: '更新成功' });
|
res.send({ code: 200, message: '更新成功' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -236,6 +247,7 @@ export default (app: Router) => {
|
|||||||
const result = await userService.updateNotificationMode(req.body);
|
const result = await userService.updateNotificationMode(req.body);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -251,6 +263,7 @@ export default (app: Router) => {
|
|||||||
const result = await userService.updateAvatar(req.file!.filename);
|
const result = await userService.updateAvatar(req.file!.filename);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+6
-4
@@ -1,23 +1,25 @@
|
|||||||
import 'reflect-metadata'; // We need this in order to use @Decorators
|
import 'reflect-metadata'; // We need this in order to use @Decorators
|
||||||
|
|
||||||
import config from './config';
|
import config from './config';
|
||||||
|
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
|
|
||||||
import Logger from './loaders/logger';
|
import Logger from './loaders/logger';
|
||||||
import path from 'path';
|
|
||||||
|
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
await require('./loaders/db').default();
|
|
||||||
|
|
||||||
await require('./loaders/initFile').default();
|
await require('./loaders/initFile').default();
|
||||||
|
|
||||||
await require('./loaders/sentry').default({ expressApp: app });
|
await require('./loaders/sentry').default({ expressApp: app });
|
||||||
|
|
||||||
|
await require('./loaders/db').default();
|
||||||
|
|
||||||
await require('./loaders/app').default({ expressApp: app });
|
await require('./loaders/app').default({ expressApp: app });
|
||||||
|
|
||||||
const server = app
|
const server = app
|
||||||
.listen(config.port, () => {
|
.listen(config.port, () => {
|
||||||
Logger.debug(`✌️ 后端服务启动成功!`);
|
Logger.debug(`✌️ Back server launched on port ${config.port}`);
|
||||||
})
|
})
|
||||||
.on('error', (err) => {
|
.on('error', (err) => {
|
||||||
Logger.error(err);
|
Logger.error(err);
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
export const LOG_END_SYMBOL = '\n ';
|
|
||||||
+3
-15
@@ -4,21 +4,10 @@ import { createRandomString } from './util';
|
|||||||
|
|
||||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||||
|
|
||||||
if (!process.env.QL_DIR) {
|
const lastVersionFile = `http://qn.whyour.cn/version.ts?v=${Date.now()}`;
|
||||||
// 声明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.ts`;
|
|
||||||
|
|
||||||
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 dataPath = path.join(rootPath, 'data/');
|
||||||
const samplePath = path.join(rootPath, 'sample/');
|
const samplePath = path.join(rootPath, 'sample/');
|
||||||
const configPath = path.join(dataPath, 'config/');
|
const configPath = path.join(dataPath, 'config/');
|
||||||
@@ -80,7 +69,6 @@ export default {
|
|||||||
'cookie.sh',
|
'cookie.sh',
|
||||||
'crontab.list',
|
'crontab.list',
|
||||||
'env.sh',
|
'env.sh',
|
||||||
'token.json',
|
|
||||||
],
|
],
|
||||||
writePathList: [configPath, scriptPath],
|
writePathList: [configPath, scriptPath],
|
||||||
bakPath,
|
bakPath,
|
||||||
|
|||||||
+6
-142
@@ -2,8 +2,6 @@ import * as fs from 'fs';
|
|||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import got from 'got';
|
import got from 'got';
|
||||||
import iconv from 'iconv-lite';
|
import iconv from 'iconv-lite';
|
||||||
import { exec } from 'child_process';
|
|
||||||
import FormData from 'form-data';
|
|
||||||
|
|
||||||
export function getFileContentByName(fileName: string) {
|
export function getFileContentByName(fileName: string) {
|
||||||
if (fs.existsSync(fileName)) {
|
if (fs.existsSync(fileName)) {
|
||||||
@@ -279,165 +277,31 @@ export async function concurrentRun(
|
|||||||
return replyList;
|
return replyList;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum FileType {
|
export function readDirs(dir: string, baseDir: string = '') {
|
||||||
'directory',
|
|
||||||
'file',
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readDirs(
|
|
||||||
dir: string,
|
|
||||||
baseDir: string = '',
|
|
||||||
blacklist: string[] = [],
|
|
||||||
) {
|
|
||||||
const relativePath = path.relative(baseDir, dir);
|
const relativePath = path.relative(baseDir, dir);
|
||||||
const files = fs.readdirSync(dir);
|
const files = fs.readdirSync(dir);
|
||||||
const result: any = files
|
const result: any = files.map((file: string) => {
|
||||||
.filter((x) => !blacklist.includes(x))
|
|
||||||
.map((file: string) => {
|
|
||||||
const subPath = path.join(dir, file);
|
const subPath = path.join(dir, file);
|
||||||
const stats = fs.statSync(subPath);
|
const stats = fs.statSync(subPath);
|
||||||
const key = path.join(relativePath, file);
|
const key = path.join(relativePath, file);
|
||||||
if (stats.isDirectory()) {
|
if (stats.isDirectory()) {
|
||||||
return {
|
return {
|
||||||
title: file,
|
title: file,
|
||||||
|
value: file,
|
||||||
key,
|
key,
|
||||||
type: 'directory',
|
type: 'directory',
|
||||||
|
disabled: true,
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
children: readDirs(subPath, baseDir).sort(
|
children: readDirs(subPath, baseDir),
|
||||||
(a: any, b: any) =>
|
|
||||||
(FileType as any)[a.type] - (FileType as any)[b.type],
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
title: file,
|
title: file,
|
||||||
|
value: file,
|
||||||
type: 'file',
|
type: 'file',
|
||||||
isLeaf: true,
|
|
||||||
key,
|
|
||||||
parent: relativePath,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
return result.sort(
|
|
||||||
(a: any, b: any) => (FileType as any)[a.type] - (FileType as any)[b.type],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readDir(
|
|
||||||
dir: string,
|
|
||||||
baseDir: string = '',
|
|
||||||
blacklist: string[] = [],
|
|
||||||
) {
|
|
||||||
const relativePath = path.relative(baseDir, dir);
|
|
||||||
const files = fs.readdirSync(dir);
|
|
||||||
const result: any = files
|
|
||||||
.filter((x) => !blacklist.includes(x))
|
|
||||||
.map((file: string) => {
|
|
||||||
const subPath = path.join(dir, file);
|
|
||||||
const stats = fs.statSync(subPath);
|
|
||||||
const key = path.join(relativePath, file);
|
|
||||||
return {
|
|
||||||
title: file,
|
|
||||||
type: stats.isDirectory() ? 'directory' : 'file',
|
|
||||||
key,
|
key,
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
return result;
|
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(
|
|
||||||
command,
|
|
||||||
{ maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' },
|
|
||||||
(err, stdout, stderr) => {
|
|
||||||
resolve(stdout || stderr || JSON.stringify(err));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
import { sequelize } from '.';
|
|
||||||
import { DataTypes, Model } from 'sequelize';
|
|
||||||
|
|
||||||
interface SortType {
|
|
||||||
type: 'ASC' | 'DESC';
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FilterType {
|
|
||||||
type: 'or' | 'and';
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CrontabView {
|
|
||||||
name?: string;
|
|
||||||
id?: number;
|
|
||||||
position?: number;
|
|
||||||
isDisabled?: 1 | 0;
|
|
||||||
filters?: FilterType[];
|
|
||||||
sorts?: SortType[];
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
+1
-4
@@ -26,10 +26,7 @@ export enum EnvStatus {
|
|||||||
'disabled',
|
'disabled',
|
||||||
}
|
}
|
||||||
|
|
||||||
export const maxPosition = 9000000000000000;
|
export const initEnvPosition = 9999999999;
|
||||||
export const initPosition = 4500000000000000;
|
|
||||||
export const stepPosition = 10000000;
|
|
||||||
export const minPosition = 100;
|
|
||||||
|
|
||||||
interface EnvInstance extends Model<Env, Env>, Env {}
|
interface EnvInstance extends Model<Env, Env>, Env {}
|
||||||
export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
||||||
|
|||||||
+3
-10
@@ -1,22 +1,15 @@
|
|||||||
import { Sequelize, Transaction } from 'sequelize';
|
import { Sequelize } from 'sequelize';
|
||||||
import config from '../config/index';
|
import config from '../config/index';
|
||||||
|
|
||||||
export const sequelize = new Sequelize({
|
export const sequelize = new Sequelize({
|
||||||
dialect: 'sqlite',
|
dialect: 'sqlite',
|
||||||
storage: `${config.dbPath}database.sqlite`,
|
storage: `${config.dbPath}database.sqlite`,
|
||||||
logging: false,
|
logging: false,
|
||||||
retry: {
|
|
||||||
max: 10,
|
|
||||||
match: ['SQLITE_BUSY: database is locked'],
|
|
||||||
},
|
|
||||||
pool: {
|
pool: {
|
||||||
max: 5,
|
max: 6,
|
||||||
min: 2,
|
min: 0,
|
||||||
idle: 30000,
|
idle: 30000,
|
||||||
acquire: 30000,
|
|
||||||
evict: 10000,
|
|
||||||
},
|
},
|
||||||
transactionType: Transaction.TYPES.IMMEDIATE,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export type ResponseType<T> = { code: number; data?: T; message?: string };
|
export type ResponseType<T> = { code: number; data?: T; message?: string };
|
||||||
|
|||||||
+2
-38
@@ -1,22 +1,16 @@
|
|||||||
import { IncomingHttpHeaders } from 'http';
|
|
||||||
|
|
||||||
export enum NotificationMode {
|
export enum NotificationMode {
|
||||||
'gotify' = 'gotify',
|
'gotify' = 'gotify',
|
||||||
'goCqHttpBot' = 'goCqHttpBot',
|
'goCqHttpBot' = 'goCqHttpBot',
|
||||||
'serverChan' = 'serverChan',
|
'serverChan' = 'serverChan',
|
||||||
'pushDeer' = 'pushDeer',
|
'pushDeer' = 'pushDeer',
|
||||||
'bark' = 'bark',
|
'bark' = 'bark',
|
||||||
'chat' = 'chat',
|
|
||||||
'telegramBot' = 'telegramBot',
|
'telegramBot' = 'telegramBot',
|
||||||
'dingtalkBot' = 'dingtalkBot',
|
'dingtalkBot' = 'dingtalkBot',
|
||||||
'weWorkBot' = 'weWorkBot',
|
'weWorkBot' = 'weWorkBot',
|
||||||
'weWorkApp' = 'weWorkApp',
|
'weWorkApp' = 'weWorkApp',
|
||||||
'aibotk' = 'aibotk',
|
|
||||||
'iGot' = 'iGot',
|
'iGot' = 'iGot',
|
||||||
'pushPlus' = 'pushPlus',
|
'pushPlus' = 'pushPlus',
|
||||||
'email' = 'email',
|
'email' = 'email',
|
||||||
'feishu' = 'feishu',
|
|
||||||
'webhook' = 'webhook',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class NotificationBaseInfo {
|
abstract class NotificationBaseInfo {
|
||||||
@@ -43,14 +37,9 @@ export class PushDeerNotification extends NotificationBaseInfo {
|
|||||||
public pushDeerKey = '';
|
public pushDeerKey = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ChatNotification extends NotificationBaseInfo {
|
|
||||||
public chatUrl = '';
|
|
||||||
public chatToken = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
export class BarkNotification extends NotificationBaseInfo {
|
export class BarkNotification extends NotificationBaseInfo {
|
||||||
public barkPush = '';
|
public barkPush = '';
|
||||||
public barkIcon = 'https://qn.whyour.cn/logo.png';
|
public barkIcon = 'http://qn.whyour.cn/logo.png';
|
||||||
public barkSound = '';
|
public barkSound = '';
|
||||||
public barkGroup = 'qinglong';
|
public barkGroup = 'qinglong';
|
||||||
}
|
}
|
||||||
@@ -77,12 +66,6 @@ export class WeWorkAppNotification extends NotificationBaseInfo {
|
|||||||
public weWorkAppKey = '';
|
public weWorkAppKey = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AibotkNotification extends NotificationBaseInfo {
|
|
||||||
public aibotkKey: string = '';
|
|
||||||
public aibotkType: 'room' | 'contact' = 'room';
|
|
||||||
public aibotkName: string = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
export class IGotNotification extends NotificationBaseInfo {
|
export class IGotNotification extends NotificationBaseInfo {
|
||||||
public iGotPushKey = '';
|
public iGotPushKey = '';
|
||||||
}
|
}
|
||||||
@@ -98,35 +81,16 @@ export class EmailNotification extends NotificationBaseInfo {
|
|||||||
public emailPass: string = '';
|
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
|
export interface NotificationInfo
|
||||||
extends GoCqHttpBotNotification,
|
extends GoCqHttpBotNotification,
|
||||||
GotifyNotification,
|
GotifyNotification,
|
||||||
ServerChanNotification,
|
ServerChanNotification,
|
||||||
PushDeerNotification,
|
PushDeerNotification,
|
||||||
ChatNotification,
|
|
||||||
BarkNotification,
|
BarkNotification,
|
||||||
TelegramBotNotification,
|
TelegramBotNotification,
|
||||||
DingtalkBotNotification,
|
DingtalkBotNotification,
|
||||||
WeWorkBotNotification,
|
WeWorkBotNotification,
|
||||||
WeWorkAppNotification,
|
WeWorkAppNotification,
|
||||||
AibotkNotification,
|
|
||||||
IGotNotification,
|
IGotNotification,
|
||||||
PushPlusNotification,
|
PushPlusNotification,
|
||||||
EmailNotification,
|
EmailNotification {}
|
||||||
WebhookNotification,
|
|
||||||
LarkNotification {}
|
|
||||||
|
|||||||
+4
-3
@@ -6,9 +6,9 @@ import { CrontabModel } from '../data/cron';
|
|||||||
import { DependenceModel } from '../data/dependence';
|
import { DependenceModel } from '../data/dependence';
|
||||||
import { AppModel } from '../data/open';
|
import { AppModel } from '../data/open';
|
||||||
import { AuthModel } from '../data/auth';
|
import { AuthModel } from '../data/auth';
|
||||||
|
import { sequelize } from '../data';
|
||||||
import { fileExist } from '../config/util';
|
import { fileExist } from '../config/util';
|
||||||
import { SubscriptionModel } from '../data/subscription';
|
import { SubscriptionModel } from '../data/subscription';
|
||||||
import { CrontabViewModel } from '../data/cronView';
|
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
@@ -18,8 +18,9 @@ export default async () => {
|
|||||||
await AppModel.sync();
|
await AppModel.sync();
|
||||||
await AuthModel.sync();
|
await AuthModel.sync();
|
||||||
await EnvModel.sync();
|
await EnvModel.sync();
|
||||||
await SubscriptionModel.sync();
|
await SubscriptionModel.sync({ alter: true });
|
||||||
await CrontabViewModel.sync();
|
|
||||||
|
await sequelize.sync();
|
||||||
|
|
||||||
// try {
|
// try {
|
||||||
// const queryInterface = sequelize.getQueryInterface();
|
// const queryInterface = sequelize.getQueryInterface();
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import path from 'path';
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import chokidar from 'chokidar';
|
import chokidar from 'chokidar';
|
||||||
import config from '../config/index';
|
import config from '../config/index';
|
||||||
import { promiseExec } from '../config/util';
|
|
||||||
|
|
||||||
function linkToNodeModule(src: string, dst?: string) {
|
function linkToNodeModule(src: string, dst?: string) {
|
||||||
const target = path.join(config.rootPath, 'node_modules', dst || src);
|
const target = path.join(config.rootPath, 'node_modules', dst || src);
|
||||||
@@ -17,32 +16,7 @@ function linkToNodeModule(src: string, dst?: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function linkCommand() {
|
|
||||||
const commandPath = await promiseExec('which node');
|
|
||||||
const commandDir = path.dirname(commandPath);
|
|
||||||
const linkShell = [
|
|
||||||
{
|
|
||||||
src: 'update.sh',
|
|
||||||
dest: 'ql',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
src: 'task.sh',
|
|
||||||
dest: 'task',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const link of linkShell) {
|
|
||||||
const source = path.join(config.rootPath, 'shell', link.src);
|
|
||||||
const target = path.join(commandDir, link.dest);
|
|
||||||
if (fs.existsSync(target)) {
|
|
||||||
fs.unlinkSync(target);
|
|
||||||
}
|
|
||||||
fs.symlink(source, target, (err) => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async (src: string = 'deps') => {
|
export default async (src: string = 'deps') => {
|
||||||
await linkCommand();
|
|
||||||
linkToNodeModule(src);
|
linkToNodeModule(src);
|
||||||
|
|
||||||
const source = path.join(config.rootPath, src);
|
const source = path.join(config.rootPath, src);
|
||||||
|
|||||||
+14
-41
@@ -3,7 +3,7 @@ import bodyParser from 'body-parser';
|
|||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
import routes from '../api';
|
import routes from '../api';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import jwt, { UnauthorizedError } from 'express-jwt';
|
import jwt from 'express-jwt';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { getPlatform, getToken } from '../config/util';
|
import { getPlatform, getToken } from '../config/util';
|
||||||
import Container from 'typedi';
|
import Container from 'typedi';
|
||||||
@@ -75,24 +75,29 @@ export default ({ app }: { app: Application }) => {
|
|||||||
if (
|
if (
|
||||||
!headerToken &&
|
!headerToken &&
|
||||||
originPath &&
|
originPath &&
|
||||||
config.apiWhiteList.includes(originPath)
|
config.apiWhiteList.includes(originPath) &&
|
||||||
|
originPath !== '/api/crons/status'
|
||||||
|
) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
const remoteAddress = req.socket.remoteAddress;
|
||||||
|
if (
|
||||||
|
remoteAddress === '::ffff:127.0.0.1' &&
|
||||||
|
originPath === '/api/crons/status'
|
||||||
) {
|
) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
||||||
if (data && headerToken) {
|
if (data) {
|
||||||
const { token = '', tokens = {} } = JSON.parse(data);
|
const { token = '', tokens = {} } = JSON.parse(data);
|
||||||
if (headerToken === token || tokens[req.platform] === headerToken) {
|
if (headerToken === token || tokens[req.platform] === headerToken) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const errorCode = headerToken ? 'invalid_token' : 'credentials_required';
|
const err: any = new Error('UnauthorizedError');
|
||||||
const errorMessage = headerToken
|
err.status = 401;
|
||||||
? 'jwt malformed'
|
|
||||||
: 'No authorization token was found';
|
|
||||||
const err = new UnauthorizedError(errorCode, { message: errorMessage });
|
|
||||||
next(err);
|
next(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -131,6 +136,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.use(errors());
|
app.use(errors());
|
||||||
|
app.use(Sentry.Handlers.errorHandler());
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
@@ -149,39 +155,6 @@ export default ({ app }: { app: Application }) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
app.use(
|
|
||||||
(
|
|
||||||
err: Error & { errors: any[] },
|
|
||||||
req: Request,
|
|
||||||
res: Response,
|
|
||||||
next: NextFunction,
|
|
||||||
) => {
|
|
||||||
if (err.name.includes('Sequelize')) {
|
|
||||||
return res
|
|
||||||
.status(500)
|
|
||||||
.send({
|
|
||||||
code: 400,
|
|
||||||
message: `${err.name} ${err.message}`,
|
|
||||||
validation: err.errors,
|
|
||||||
})
|
|
||||||
.end();
|
|
||||||
}
|
|
||||||
return next(err);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
app.use(
|
|
||||||
Sentry.Handlers.errorHandler({
|
|
||||||
shouldHandleError(error) {
|
|
||||||
// 排除 SequelizeUniqueConstraintError / NotFound
|
|
||||||
return (
|
|
||||||
!['SequelizeUniqueConstraintError'].includes(error.name) ||
|
|
||||||
!['Not Found'].includes(error.message)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
err: Error & { status: number },
|
err: Error & { status: number },
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { Container } from 'typedi';
|
|||||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||||
import CronService from '../services/cron';
|
import CronService from '../services/cron';
|
||||||
import EnvService from '../services/env';
|
import EnvService from '../services/env';
|
||||||
import groupBy from 'lodash/groupBy';
|
import _ from 'lodash';
|
||||||
import { DependenceModel } from '../data/dependence';
|
import { DependenceModel } from '../data/dependence';
|
||||||
import { Op } from 'sequelize';
|
import { Op } from 'sequelize';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
@@ -21,18 +21,15 @@ export default async () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
||||||
DependenceModel.findAll({
|
DependenceModel.findAll({ where: {}, raw: true }).then(async (docs) => {
|
||||||
where: {},
|
const groups = _.groupBy(docs, 'type');
|
||||||
order: [['type', 'DESC']],
|
for (const key in groups) {
|
||||||
raw: true,
|
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
||||||
}).then(async (docs) => {
|
|
||||||
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];
|
const group = groups[key];
|
||||||
const depIds = group.map((x) => x.id);
|
const depIds = group.map((x) => x.id);
|
||||||
await dependenceService.reInstall(depIds as number[]);
|
await dependenceService.reInstall(depIds as number[]);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 初始化时执行一次所有的ql repo 任务
|
// 初始化时执行一次所有的ql repo 任务
|
||||||
|
|||||||
@@ -5,13 +5,12 @@ import dotenv from 'dotenv';
|
|||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
import { fileExist } from '../config/util';
|
import { fileExist } from '../config/util';
|
||||||
|
|
||||||
const rootPath = process.env.QL_DIR as string;;
|
const rootPath = process.cwd();
|
||||||
const dataPath = path.join(rootPath, 'data/');
|
const dataPath = path.join(rootPath, 'data/');
|
||||||
const configPath = path.join(dataPath, 'config/');
|
const configPath = path.join(dataPath, 'config/');
|
||||||
const scriptPath = path.join(dataPath, 'scripts/');
|
const scriptPath = path.join(dataPath, 'scripts/');
|
||||||
const logPath = path.join(dataPath, 'log/');
|
const logPath = path.join(dataPath, 'log/');
|
||||||
const uploadPath = path.join(dataPath, 'upload/');
|
const uploadPath = path.join(dataPath, 'upload/');
|
||||||
const bakPath = path.join(dataPath, 'bak/');
|
|
||||||
const samplePath = path.join(rootPath, 'sample/');
|
const samplePath = path.join(rootPath, 'sample/');
|
||||||
const confFile = path.join(configPath, 'config.sh');
|
const confFile = path.join(configPath, 'config.sh');
|
||||||
const authConfigFile = path.join(configPath, 'auth.json');
|
const authConfigFile = path.join(configPath, 'auth.json');
|
||||||
@@ -28,7 +27,6 @@ export default async () => {
|
|||||||
const configDirExist = await fileExist(configPath);
|
const configDirExist = await fileExist(configPath);
|
||||||
const uploadDirExist = await fileExist(uploadPath);
|
const uploadDirExist = await fileExist(uploadPath);
|
||||||
const sshDirExist = await fileExist(sshPath);
|
const sshDirExist = await fileExist(sshPath);
|
||||||
const bakDirExist = await fileExist(bakPath);
|
|
||||||
|
|
||||||
if (!configDirExist) {
|
if (!configDirExist) {
|
||||||
fs.mkdirSync(configPath);
|
fs.mkdirSync(configPath);
|
||||||
@@ -58,10 +56,6 @@ export default async () => {
|
|||||||
fs.mkdirSync(sshPath);
|
fs.mkdirSync(sshPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!bakDirExist) {
|
|
||||||
fs.mkdirSync(bakPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
dotenv.config({ path: confFile });
|
dotenv.config({ path: confFile });
|
||||||
|
|
||||||
Logger.info('✌️ Init file down');
|
Logger.info('✌️ Init file down');
|
||||||
|
|||||||
@@ -1,30 +1,14 @@
|
|||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
|
import _ from 'lodash';
|
||||||
import SystemService from '../services/system';
|
import SystemService from '../services/system';
|
||||||
import ScheduleService from '../services/schedule';
|
import ScheduleService from '../services/schedule';
|
||||||
import SubscriptionService from '../services/subscription';
|
import SubscriptionService from '../services/subscription';
|
||||||
import config from '../config';
|
|
||||||
import { fileExist } from '../config/util';
|
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
const scheduleService = Container.get(ScheduleService);
|
const scheduleService = Container.get(ScheduleService);
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
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,
|
|
||||||
};
|
|
||||||
scheduleService.createIntervalTask(cron, {
|
|
||||||
days: 28,
|
|
||||||
});
|
|
||||||
|
|
||||||
// 运行删除日志任务
|
// 运行删除日志任务
|
||||||
const data = await systemService.getLogRemoveFrequency();
|
const data = await systemService.getLogRemoveFrequency();
|
||||||
if (data && data.info && data.info.frequency) {
|
if (data && data.info && data.info.frequency) {
|
||||||
@@ -33,19 +17,15 @@ export default async () => {
|
|||||||
name: '删除日志',
|
name: '删除日志',
|
||||||
command: `ql rmlog ${data.info.frequency}`,
|
command: `ql rmlog ${data.info.frequency}`,
|
||||||
};
|
};
|
||||||
scheduleService.createIntervalTask(cron, {
|
await scheduleService.createIntervalTask(cron, {
|
||||||
days: data.info.frequency,
|
days: data.info.frequency,
|
||||||
|
runImmediately: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 运行所有订阅
|
// 运行所有订阅
|
||||||
const subs = await subscriptionService.list();
|
const subs = await subscriptionService.list();
|
||||||
for (const sub of subs) {
|
for (const sub of subs) {
|
||||||
await subscriptionService.handleTask(
|
await subscriptionService.handleTask(sub, true, true, true);
|
||||||
sub,
|
|
||||||
!sub.is_disabled,
|
|
||||||
true,
|
|
||||||
!sub.is_disabled,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,23 +2,16 @@ import { Application } from 'express';
|
|||||||
import * as Sentry from '@sentry/node';
|
import * as Sentry from '@sentry/node';
|
||||||
import * as Tracing from '@sentry/tracing';
|
import * as Tracing from '@sentry/tracing';
|
||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
import config from '../config';
|
|
||||||
import fs from 'fs';
|
|
||||||
|
|
||||||
export default ({ expressApp }: { expressApp: Application }) => {
|
export default ({ expressApp }: { expressApp: Application }) => {
|
||||||
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
|
||||||
|
|
||||||
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
|
||||||
const currentVersion = currentVersionFile.match(versionRegx)![1];
|
|
||||||
|
|
||||||
Sentry.init({
|
Sentry.init({
|
||||||
dsn: 'https://f4b5b55fb3c645b29a5dc2d70a1a4ef4@o1098464.ingest.sentry.io/6122819',
|
dsn: 'https://f4b5b55fb3c645b29a5dc2d70a1a4ef4@o1098464.ingest.sentry.io/6122819',
|
||||||
integrations: [
|
integrations: [
|
||||||
new Sentry.Integrations.Http({ tracing: true }),
|
new Sentry.Integrations.Http({ tracing: true }),
|
||||||
new Tracing.Integrations.Express({ app: expressApp }),
|
new Tracing.Integrations.Express({ app: expressApp }),
|
||||||
],
|
],
|
||||||
tracesSampleRate: 0.1,
|
|
||||||
release: currentVersion,
|
tracesSampleRate: 1.0,
|
||||||
});
|
});
|
||||||
|
|
||||||
expressApp.use(Sentry.Handlers.requestHandler());
|
expressApp.use(Sentry.Handlers.requestHandler());
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@ app
|
|||||||
await require('./loaders/sentry').default({ expressApp: app });
|
await require('./loaders/sentry').default({ expressApp: app });
|
||||||
await require('./loaders/db').default();
|
await require('./loaders/db').default();
|
||||||
|
|
||||||
Logger.debug(`✌️ 公共服务启动成功!`);
|
Logger.debug(`✌️ Back server launched on port ${config.publicPort}`);
|
||||||
})
|
})
|
||||||
.on('error', (err) => {
|
.on('error', (err) => {
|
||||||
Logger.error(err);
|
Logger.error(err);
|
||||||
|
|||||||
+7
-4
@@ -18,15 +18,14 @@ const run = async () => {
|
|||||||
_schedule &&
|
_schedule &&
|
||||||
_schedule.length > 5 &&
|
_schedule.length > 5 &&
|
||||||
task.status !== CrontabStatus.disabled &&
|
task.status !== CrontabStatus.disabled &&
|
||||||
!task.isDisabled &&
|
!task.isDisabled
|
||||||
task.schedule
|
|
||||||
) {
|
) {
|
||||||
schedule.scheduleJob(task.schedule, function () {
|
schedule.scheduleJob(task.schedule, function () {
|
||||||
let command = task.command as string;
|
let command = task.command as string;
|
||||||
if (!command.includes('task ') && !command.includes('ql ')) {
|
if (!command.includes('task ') && !command.includes('ql ')) {
|
||||||
command = `task ${command}`;
|
command = `task ${command}`;
|
||||||
}
|
}
|
||||||
exec(`ID=${task.id} ${command}`);
|
exec(command);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -44,7 +43,11 @@ app
|
|||||||
await require('./loaders/db').default();
|
await require('./loaders/db').default();
|
||||||
|
|
||||||
await run();
|
await run();
|
||||||
Logger.debug('定时任务服务启动成功!');
|
Logger.info(`
|
||||||
|
################################################
|
||||||
|
🛡️ Schedule listening on port: ${config.cronPort} 🛡️
|
||||||
|
################################################
|
||||||
|
`);
|
||||||
})
|
})
|
||||||
.on('error', (err) => {
|
.on('error', (err) => {
|
||||||
Logger.error(err);
|
Logger.error(err);
|
||||||
|
|||||||
+28
-162
@@ -10,8 +10,6 @@ import { promises, existsSync } from 'fs';
|
|||||||
import { promisify } from 'util';
|
import { promisify } from 'util';
|
||||||
import { Op } from 'sequelize';
|
import { Op } from 'sequelize';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import dayjs from 'dayjs';
|
|
||||||
import { LOG_END_SYMBOL } from '../config/const';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class CronService {
|
export default class CronService {
|
||||||
@@ -114,69 +112,9 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private formatViewQuery(query: any, viewQuery: any) {
|
public async crontabs(searchText?: string): Promise<Crontab[]> {
|
||||||
if (viewQuery.filters && viewQuery.filters.length > 0) {
|
let query = {};
|
||||||
if (!query[Op.and]) {
|
|
||||||
query[Op.and] = [];
|
|
||||||
}
|
|
||||||
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] = {
|
|
||||||
[operate2]: [
|
|
||||||
{ [operate]: `%${value}%` },
|
|
||||||
{ [operate]: `%${encodeURIComponent(value)}%` },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
query[Op.and].push(q);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private formatSearchText(query: any, searchText: string | undefined) {
|
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
if (!query[Op.and]) {
|
|
||||||
query[Op.and] = [];
|
|
||||||
}
|
|
||||||
let q: any = {};
|
|
||||||
const textArray = searchText.split(':');
|
const textArray = searchText.split(':');
|
||||||
switch (textArray[0]) {
|
switch (textArray[0]) {
|
||||||
case 'name':
|
case 'name':
|
||||||
@@ -184,11 +122,13 @@ export default class CronService {
|
|||||||
case 'schedule':
|
case 'schedule':
|
||||||
case 'label':
|
case 'label':
|
||||||
const column = textArray[0] === 'label' ? 'labels' : textArray[0];
|
const column = textArray[0] === 'label' ? 'labels' : textArray[0];
|
||||||
q[column] = {
|
query = {
|
||||||
|
[column]: {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${textArray[1]}%` },
|
{ [Op.like]: `%${textArray[1]}%` },
|
||||||
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
||||||
],
|
],
|
||||||
|
},
|
||||||
};
|
};
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -198,7 +138,8 @@ export default class CronService {
|
|||||||
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
q[Op.or] = [
|
query = {
|
||||||
|
[Op.or]: [
|
||||||
{
|
{
|
||||||
name: reg,
|
name: reg,
|
||||||
},
|
},
|
||||||
@@ -211,83 +152,17 @@ export default class CronService {
|
|||||||
{
|
{
|
||||||
labels: reg,
|
labels: reg,
|
||||||
},
|
},
|
||||||
];
|
],
|
||||||
|
};
|
||||||
break;
|
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 (filterKeys[key]) {
|
|
||||||
q[key] = filterKeys[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 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 {
|
try {
|
||||||
const result = await CrontabModel.findAll(condition);
|
const result = await CrontabModel.findAll({
|
||||||
const count = await CrontabModel.count({ where: query });
|
where: query,
|
||||||
return { data: result, total: count };
|
order: [['createdAt', 'DESC']],
|
||||||
|
});
|
||||||
|
return result as any;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -322,21 +197,13 @@ export default class CronService {
|
|||||||
const err = await this.killTask(doc.command);
|
const err = await this.killTask(doc.command);
|
||||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
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) {
|
if (logFileExist) {
|
||||||
const str = err ? `\n${err}` : '';
|
const str = err ? `\n${err}` : '';
|
||||||
fs.appendFileSync(
|
fs.appendFileSync(
|
||||||
`${absolutePath}`,
|
`${absolutePath}`,
|
||||||
`${str}\n## 执行结束... ${endTime.format(
|
`${str}\n## 执行结束... ${new Date()
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
.toLocaleString('zh', { hour12: false })
|
||||||
)}${diffTimeStr}${LOG_END_SYMBOL}`,
|
.replace(' 24:', ' 00:')} `,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -361,7 +228,6 @@ export default class CronService {
|
|||||||
const killLogs = [];
|
const killLogs = [];
|
||||||
if (pids && pids.length > 0) {
|
if (pids && pids.length > 0) {
|
||||||
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
||||||
pids = pids.slice(0, 3);
|
|
||||||
for (const id of pids) {
|
for (const id of pids) {
|
||||||
const c = `kill -9 ${id.slice(1)}`;
|
const c = `kill -9 ${id.slice(1)}`;
|
||||||
try {
|
try {
|
||||||
@@ -403,17 +269,11 @@ export default class CronService {
|
|||||||
if (!cmdStr.includes('task ') && !cmdStr.includes('ql ')) {
|
if (!cmdStr.includes('task ') && !cmdStr.includes('ql ')) {
|
||||||
cmdStr = `task ${cmdStr}`;
|
cmdStr = `task ${cmdStr}`;
|
||||||
}
|
}
|
||||||
if (
|
if (cmdStr.endsWith('.js')) {
|
||||||
cmdStr.endsWith('.js') ||
|
|
||||||
cmdStr.endsWith('.py') ||
|
|
||||||
cmdStr.endsWith('.pyc') ||
|
|
||||||
cmdStr.endsWith('.sh') ||
|
|
||||||
cmdStr.endsWith('.ts')
|
|
||||||
) {
|
|
||||||
cmdStr = `${cmdStr} now`;
|
cmdStr = `${cmdStr} now`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const cp = spawn(`ID=${id} ${cmdStr}`, { shell: '/bin/bash' });
|
const cp = spawn(cmdStr, { shell: '/bin/bash' });
|
||||||
|
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{ status: CrontabStatus.running, pid: cp.pid },
|
{ status: CrontabStatus.running, pid: cp.pid },
|
||||||
@@ -421,7 +281,7 @@ export default class CronService {
|
|||||||
);
|
);
|
||||||
cp.stderr.on('data', (data) => {
|
cp.stderr.on('data', (data) => {
|
||||||
if (logFileExist) {
|
if (logFileExist) {
|
||||||
fs.appendFileSync(`${absolutePath}`, `${data.toString()}`);
|
fs.appendFileSync(`${absolutePath}`, `${data}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
cp.on('error', (err) => {
|
cp.on('error', (err) => {
|
||||||
@@ -432,10 +292,16 @@ export default class CronService {
|
|||||||
|
|
||||||
cp.on('exit', async (code, signal) => {
|
cp.on('exit', async (code, signal) => {
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`任务 ${command} 进程id: ${cp.pid} 退出,退出码 ${code}`,
|
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||||
);
|
);
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.idle, pid: undefined },
|
||||||
|
{ where: { id } },
|
||||||
|
);
|
||||||
|
resolve();
|
||||||
});
|
});
|
||||||
cp.on('close', async (code) => {
|
cp.on('close', async (code) => {
|
||||||
|
this.logger.info(`${command} pid: ${cp.pid} closed ${code}`);
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{ status: CrontabStatus.idle, pid: undefined },
|
{ status: CrontabStatus.idle, pid: undefined },
|
||||||
{ where: { id } },
|
{ where: { id } },
|
||||||
@@ -565,7 +431,7 @@ export default class CronService {
|
|||||||
private async set_crontab(needReloadSchedule: boolean = false) {
|
private async set_crontab(needReloadSchedule: boolean = false) {
|
||||||
const tabs = await this.crontabs();
|
const tabs = await this.crontabs();
|
||||||
var crontab_string = '';
|
var crontab_string = '';
|
||||||
tabs.data.forEach((tab) => {
|
tabs.forEach((tab) => {
|
||||||
const _schedule = tab.schedule && tab.schedule.split(/ +/);
|
const _schedule = tab.schedule && tab.schedule.split(/ +/);
|
||||||
if (tab.isDisabled === 1 || _schedule!.length !== 5) {
|
if (tab.isDisabled === 1 || _schedule!.length !== 5) {
|
||||||
crontab_string += '# ';
|
crontab_string += '# ';
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
|
||||||
import winston from 'winston';
|
|
||||||
import { CrontabView, CrontabViewModel } from '../data/cronView';
|
|
||||||
import { initPosition } 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);
|
|
||||||
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(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 } });
|
|
||||||
}
|
|
||||||
|
|
||||||
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: targetPosition,
|
|
||||||
});
|
|
||||||
return newDoc;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+23
-19
@@ -9,11 +9,11 @@ import {
|
|||||||
unInstallDependenceCommandTypes,
|
unInstallDependenceCommandTypes,
|
||||||
DependenceModel,
|
DependenceModel,
|
||||||
} from '../data/dependence';
|
} from '../data/dependence';
|
||||||
|
import _ from 'lodash';
|
||||||
import { spawn } from 'child_process';
|
import { spawn } from 'child_process';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import { Op } from 'sequelize';
|
import { Op } from 'sequelize';
|
||||||
import { concurrentRun } from '../config/util';
|
import { concurrentRun } from '../config/util';
|
||||||
import dayjs from 'dayjs';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class DependenceService {
|
export default class DependenceService {
|
||||||
@@ -124,11 +124,8 @@ export default class DependenceService {
|
|||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async find(query: any, sort: any = []): Promise<Dependence[]> {
|
private async find(query: any, sort?: any): Promise<Dependence[]> {
|
||||||
const docs = await DependenceModel.findAll({
|
const docs = await DependenceModel.findAll({ where: { ...query } });
|
||||||
where: { ...query },
|
|
||||||
order: [...sort, ['createdAt', 'DESC']],
|
|
||||||
});
|
|
||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,17 +161,20 @@ export default class DependenceService {
|
|||||||
)[dependencies[0].type as any];
|
)[dependencies[0].type as any];
|
||||||
const actionText = isInstall ? '安装' : '删除';
|
const actionText = isInstall ? '安装' : '删除';
|
||||||
const depIds = dependencies.map((x) => x.id) as number[];
|
const depIds = dependencies.map((x) => x.id) as number[];
|
||||||
const startTime = dayjs();
|
const startTime = Date.now();
|
||||||
|
|
||||||
const message = `开始${actionText}依赖 ${depNames},开始时间 ${startTime.format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
)}\n\n`;
|
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
type: socketMessageType,
|
type: socketMessageType,
|
||||||
message,
|
message: `开始${actionText}依赖 ${depNames},开始时间 ${new Date(
|
||||||
|
startTime,
|
||||||
|
).toLocaleString()}\n\n`,
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
await this.updateLog(depIds, message);
|
await this.updateLog(
|
||||||
|
depIds,
|
||||||
|
`开始${actionText}依赖 ${depNames},开始时间 ${new Date(
|
||||||
|
startTime,
|
||||||
|
).toLocaleString()}\n\n`,
|
||||||
|
);
|
||||||
|
|
||||||
const cp = spawn(`${depRunCommand} ${depNames}`, { shell: '/bin/bash' });
|
const cp = spawn(`${depRunCommand} ${depNames}`, { shell: '/bin/bash' });
|
||||||
|
|
||||||
@@ -207,19 +207,23 @@ export default class DependenceService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
cp.on('close', async (code) => {
|
cp.on('close', async (code) => {
|
||||||
const endTime = dayjs();
|
const endTime = Date.now();
|
||||||
const isSucceed = code === 0;
|
const isSucceed = code === 0;
|
||||||
const resultText = isSucceed ? '成功' : '失败';
|
const resultText = isSucceed ? '成功' : '失败';
|
||||||
|
|
||||||
const message = `\n依赖${actionText}${resultText},结束时间 ${endTime.format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
)},耗时 ${endTime.diff(startTime, 'second')} 秒`;
|
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
type: socketMessageType,
|
type: socketMessageType,
|
||||||
message,
|
message: `\n依赖${actionText}${resultText},结束时间 ${new Date(
|
||||||
|
endTime,
|
||||||
|
).toLocaleString()},耗时 ${(endTime - startTime) / 1000} 秒`,
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
await this.updateLog(depIds, message);
|
await this.updateLog(
|
||||||
|
depIds,
|
||||||
|
`\n依赖${actionText}${resultText},结束时间 ${new Date(
|
||||||
|
endTime,
|
||||||
|
).toLocaleString()},耗时 ${(endTime - startTime) / 1000} 秒`,
|
||||||
|
);
|
||||||
|
|
||||||
let status = null;
|
let status = null;
|
||||||
if (isSucceed) {
|
if (isSucceed) {
|
||||||
|
|||||||
+29
-58
@@ -1,17 +1,10 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
|
import { getFileContentByName } from '../config/util';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import {
|
import { Env, EnvModel, EnvStatus, initEnvPosition } from '../data/env';
|
||||||
Env,
|
import _ from 'lodash';
|
||||||
EnvModel,
|
|
||||||
EnvStatus,
|
|
||||||
initPosition,
|
|
||||||
maxPosition,
|
|
||||||
minPosition,
|
|
||||||
stepPosition,
|
|
||||||
} from '../data/env';
|
|
||||||
import groupBy from 'lodash/groupBy';
|
|
||||||
import { Op } from 'sequelize';
|
import { Op } from 'sequelize';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
@@ -20,22 +13,17 @@ export default class EnvService {
|
|||||||
|
|
||||||
public async create(payloads: Env[]): Promise<Env[]> {
|
public async create(payloads: Env[]): Promise<Env[]> {
|
||||||
const envs = await this.envs();
|
const envs = await this.envs();
|
||||||
let position = initPosition;
|
let position = initEnvPosition;
|
||||||
if (
|
if (envs && envs.length > 0 && envs[envs.length - 1].position) {
|
||||||
envs &&
|
position = envs[envs.length - 1].position as number;
|
||||||
envs.length > 0 &&
|
|
||||||
typeof envs[envs.length - 1].position === 'number'
|
|
||||||
) {
|
|
||||||
position = envs[envs.length - 1].position!;
|
|
||||||
}
|
}
|
||||||
const tabs = payloads.map((x) => {
|
const tabs = payloads.map((x) => {
|
||||||
position = position - stepPosition;
|
position = position / 2;
|
||||||
const tab = new Env({ ...x, position });
|
const tab = new Env({ ...x, position });
|
||||||
return tab;
|
return tab;
|
||||||
});
|
});
|
||||||
const docs = await this.insert(tabs);
|
const docs = await this.insert(tabs);
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
await this.checkPosition(tabs[tabs.length - 1].position!);
|
|
||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,40 +67,25 @@ export default class EnvService {
|
|||||||
const envs = await this.envs();
|
const envs = await this.envs();
|
||||||
if (toIndex === 0 || toIndex === envs.length - 1) {
|
if (toIndex === 0 || toIndex === envs.length - 1) {
|
||||||
targetPosition = isUpward
|
targetPosition = isUpward
|
||||||
? envs[0].position! + stepPosition
|
? envs[0].position * 2
|
||||||
: envs[toIndex].position! - stepPosition;
|
: envs[toIndex].position / 2;
|
||||||
} else {
|
} else {
|
||||||
targetPosition = isUpward
|
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({
|
const newDoc = await this.update({
|
||||||
id,
|
id,
|
||||||
position: this.getPrecisionPosition(targetPosition),
|
position: targetPosition,
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.checkPosition(targetPosition);
|
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async checkPosition(position: number) {
|
public async envs(
|
||||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
searchText: string = '',
|
||||||
if (precisionPosition < minPosition || precisionPosition > maxPosition) {
|
sort: any = { position: -1 },
|
||||||
const envs = await this.envs();
|
query: any = {},
|
||||||
let position = initPosition;
|
): Promise<Env[]> {
|
||||||
for (const env of envs) {
|
|
||||||
position = position - stepPosition;
|
|
||||||
await this.updateDb({ ...env, position });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getPrecisionPosition(position: number): number {
|
|
||||||
return parseFloat(position.toPrecision(16));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const encodeText = encodeURIComponent(searchText);
|
const encodeText = encodeURIComponent(searchText);
|
||||||
@@ -139,11 +112,7 @@ export default class EnvService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.find(condition, [
|
const result = await this.find(condition, [['position', 'DESC']]);
|
||||||
['status', 'ASC'],
|
|
||||||
['position', 'DESC'],
|
|
||||||
['createdAt', 'ASC'],
|
|
||||||
]);
|
|
||||||
return result as any;
|
return result as any;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
@@ -182,22 +151,24 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async set_envs() {
|
public async set_envs() {
|
||||||
const envs = await this.envs('', {
|
const envs = await this.envs(
|
||||||
name: { [Op.not]: null },
|
'',
|
||||||
status: EnvStatus.normal,
|
{ position: -1 },
|
||||||
});
|
{ name: { [Op.not]: null } },
|
||||||
const groups = groupBy(envs, 'name');
|
);
|
||||||
|
const groups = _.groupBy(envs, 'name');
|
||||||
let env_string = '';
|
let env_string = '';
|
||||||
for (const key in groups) {
|
for (const key in groups) {
|
||||||
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
||||||
const group = groups[key];
|
const group = groups[key];
|
||||||
|
|
||||||
// 忽略不符合bash要求的环境变量名称
|
// 忽略不符合bash要求的环境变量名称
|
||||||
if (/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(key)) {
|
if (/^[a-zA-Z_][0-9a-zA-Z_]+$/.test(key)) {
|
||||||
let value = group
|
let value = _(group)
|
||||||
.map((x) => x.value)
|
.filter((x) => x.status !== EnvStatus.disabled)
|
||||||
|
.map('value')
|
||||||
.join('&')
|
.join('&')
|
||||||
.replace(/(\\)[^n]/g, '\\\\')
|
.replace(/(\\)[^\n]/g, '\\\\')
|
||||||
.replace(/(\\$)/, '\\\\')
|
.replace(/(\\$)/, '\\\\')
|
||||||
.replace(/"/g, '\\"')
|
.replace(/"/g, '\\"')
|
||||||
.trim();
|
.trim();
|
||||||
|
|||||||
+27
-150
@@ -6,7 +6,6 @@ import got from 'got';
|
|||||||
import nodemailer from 'nodemailer';
|
import nodemailer from 'nodemailer';
|
||||||
import crypto from 'crypto';
|
import crypto from 'crypto';
|
||||||
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
||||||
import { parseBody, parseHeaders } from '../config/util';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class NotificationService {
|
export default class NotificationService {
|
||||||
@@ -18,27 +17,20 @@ export default class NotificationService {
|
|||||||
['goCqHttpBot', this.goCqHttpBot],
|
['goCqHttpBot', this.goCqHttpBot],
|
||||||
['serverChan', this.serverChan],
|
['serverChan', this.serverChan],
|
||||||
['pushDeer', this.pushDeer],
|
['pushDeer', this.pushDeer],
|
||||||
['chat', this.chat],
|
|
||||||
['bark', this.bark],
|
['bark', this.bark],
|
||||||
['telegramBot', this.telegramBot],
|
['telegramBot', this.telegramBot],
|
||||||
['dingtalkBot', this.dingtalkBot],
|
['dingtalkBot', this.dingtalkBot],
|
||||||
['weWorkBot', this.weWorkBot],
|
['weWorkBot', this.weWorkBot],
|
||||||
['weWorkApp', this.weWorkApp],
|
['weWorkApp', this.weWorkApp],
|
||||||
['aibotk', this.aibotk],
|
|
||||||
['iGot', this.iGot],
|
['iGot', this.iGot],
|
||||||
['pushPlus', this.pushPlus],
|
['pushPlus', this.pushPlus],
|
||||||
['email', this.email],
|
['email', this.email],
|
||||||
['webhook', this.webhook],
|
|
||||||
['lark', this.lark],
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
private timeout = 10000;
|
||||||
private title = '';
|
private title = '';
|
||||||
private content = '';
|
private content = '';
|
||||||
private params!: Omit<NotificationInfo, 'type'>;
|
private params!: Omit<NotificationInfo, 'type'>;
|
||||||
private gotOption = {
|
|
||||||
timeout: 30000,
|
|
||||||
retry: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
@@ -81,7 +73,8 @@ export default class NotificationService {
|
|||||||
const { gotifyUrl, gotifyToken, gotifyPriority } = this.params;
|
const { gotifyUrl, gotifyToken, gotifyPriority } = this.params;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(`${gotifyUrl}/message?token=${gotifyToken}`, {
|
.post(`${gotifyUrl}/message?token=${gotifyToken}`, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
body: `title=${encodeURIComponent(
|
body: `title=${encodeURIComponent(
|
||||||
this.title,
|
this.title,
|
||||||
)}&message=${encodeURIComponent(
|
)}&message=${encodeURIComponent(
|
||||||
@@ -99,7 +92,8 @@ export default class NotificationService {
|
|||||||
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, {
|
.post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
json: { message: `${this.title}\n${this.content}` },
|
json: { message: `${this.title}\n${this.content}` },
|
||||||
headers: { Authorization: 'Bearer ' + goCqHttpBotToken },
|
headers: { Authorization: 'Bearer ' + goCqHttpBotToken },
|
||||||
})
|
})
|
||||||
@@ -114,7 +108,8 @@ export default class NotificationService {
|
|||||||
: `https://sc.ftqq.com/${serverChanKey}.send`;
|
: `https://sc.ftqq.com/${serverChanKey}.send`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
body: `title=${this.title}&desp=${this.content}`,
|
body: `title=${this.title}&desp=${this.content}`,
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
})
|
})
|
||||||
@@ -127,7 +122,8 @@ export default class NotificationService {
|
|||||||
const url = `https://api2.pushdeer.com/message/push`;
|
const url = `https://api2.pushdeer.com/message/push`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
body: `pushkey=${pushDeerKey}&text=${encodeURIComponent(
|
body: `pushkey=${pushDeerKey}&text=${encodeURIComponent(
|
||||||
this.title,
|
this.title,
|
||||||
)}&desp=${encodeURIComponent(this.content)}&type=markdown`,
|
)}&desp=${encodeURIComponent(this.content)}&type=markdown`,
|
||||||
@@ -139,19 +135,6 @@ 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() {
|
private async bark() {
|
||||||
let { barkPush, barkIcon, barkSound, barkGroup } = this.params;
|
let { barkPush, barkIcon, barkSound, barkGroup } = this.params;
|
||||||
if (!barkPush.startsWith('http') && !barkPush.startsWith('https')) {
|
if (!barkPush.startsWith('http') && !barkPush.startsWith('https')) {
|
||||||
@@ -164,7 +147,8 @@ export default class NotificationService {
|
|||||||
)}?icon=${barkIcon}?sound=${barkSound}&group=${barkGroup}`;
|
)}?icon=${barkIcon}?sound=${barkSound}&group=${barkGroup}`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.get(url, {
|
.get(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
@@ -202,7 +186,8 @@ export default class NotificationService {
|
|||||||
}
|
}
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
body: `chat_id=${telegramBotUserId}&text=${this.title}\n\n${this.content}&disable_web_page_preview=true`,
|
body: `chat_id=${telegramBotUserId}&text=${this.title}\n\n${this.content}&disable_web_page_preview=true`,
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
agent,
|
agent,
|
||||||
@@ -224,7 +209,8 @@ export default class NotificationService {
|
|||||||
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
|
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
json: {
|
json: {
|
||||||
msgtype: 'text',
|
msgtype: 'text',
|
||||||
text: {
|
text: {
|
||||||
@@ -241,7 +227,8 @@ export default class NotificationService {
|
|||||||
const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${weWorkBotKey}`;
|
const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${weWorkBotKey}`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
json: {
|
json: {
|
||||||
msgtype: 'text',
|
msgtype: 'text',
|
||||||
text: {
|
text: {
|
||||||
@@ -258,9 +245,10 @@ export default class NotificationService {
|
|||||||
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
||||||
weWorkAppKey.split(',');
|
weWorkAppKey.split(',');
|
||||||
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken`;
|
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken`;
|
||||||
const tokenRes: any = await got
|
const { access_token } = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
json: {
|
json: {
|
||||||
corpid,
|
corpid,
|
||||||
corpsecret,
|
corpsecret,
|
||||||
@@ -308,9 +296,10 @@ export default class NotificationService {
|
|||||||
|
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(
|
.post(
|
||||||
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${tokenRes.access_token}`,
|
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`,
|
||||||
{
|
{
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
json: {
|
json: {
|
||||||
touser,
|
touser,
|
||||||
agentid,
|
agentid,
|
||||||
@@ -324,53 +313,13 @@ export default class NotificationService {
|
|||||||
return res.errcode === 0;
|
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() {
|
private async iGot() {
|
||||||
const { iGotPushKey } = this.params;
|
const { iGotPushKey } = this.params;
|
||||||
const url = `https://push.hellyw.com/${iGotPushKey.toLowerCase()}`;
|
const url = `https://push.hellyw.com/${iGotPushKey.toLowerCase()}`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
body: `title=${this.title}&content=${this.content}`,
|
body: `title=${this.title}&content=${this.content}`,
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
})
|
})
|
||||||
@@ -384,7 +333,8 @@ export default class NotificationService {
|
|||||||
const url = `https://www.pushplus.plus/send`;
|
const url = `https://www.pushplus.plus/send`;
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
timeout: this.timeout,
|
||||||
|
retry: 0,
|
||||||
json: {
|
json: {
|
||||||
token: `${pushPlusToken}`,
|
token: `${pushPlusToken}`,
|
||||||
title: `${this.title}`,
|
title: `${this.title}`,
|
||||||
@@ -397,21 +347,6 @@ export default class NotificationService {
|
|||||||
return res.code === 200;
|
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() {
|
private async email() {
|
||||||
const { emailPass, emailService, emailUser } = this.params;
|
const { emailPass, emailService, emailUser } = this.params;
|
||||||
const transporter = nodemailer.createTransport({
|
const transporter = nodemailer.createTransport({
|
||||||
@@ -433,62 +368,4 @@ export default class NotificationService {
|
|||||||
|
|
||||||
return !!info.messageId;
|
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),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-26
@@ -90,9 +90,7 @@ export default class OpenService {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.find(condition);
|
const result = await this.find(condition);
|
||||||
return result
|
return result.map((x) => ({ ...x, tokens: [] }));
|
||||||
.filter((x) => x.name !== 'system')
|
|
||||||
.map((x) => ({ ...x, tokens: [] }));
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -144,27 +142,4 @@ export default class OpenService {
|
|||||||
return { code: 400, message: 'client_id或client_seret有误' };
|
return { code: 400, message: 'client_id或client_seret有误' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async generateSystemToken(): Promise<{
|
|
||||||
value: string;
|
|
||||||
expiration: number;
|
|
||||||
}> {
|
|
||||||
let systemApp = (await AppModel.findOne({
|
|
||||||
where: { name: 'system' },
|
|
||||||
})) as App;
|
|
||||||
if (!systemApp) {
|
|
||||||
systemApp = await this.create({
|
|
||||||
name: 'system',
|
|
||||||
scopes: ['crons', 'system'],
|
|
||||||
} as App);
|
|
||||||
}
|
|
||||||
const { data } = await this.authToken({
|
|
||||||
client_id: systemApp.client_id,
|
|
||||||
client_secret: systemApp.client_secret,
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
...data,
|
|
||||||
value: data.token,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ interface ScheduleTaskType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface TaskCallbacks {
|
export interface TaskCallbacks {
|
||||||
onBefore?: (startTime: dayjs.Dayjs) => Promise<void>;
|
|
||||||
onStart?: (
|
onStart?: (
|
||||||
cp: ChildProcessWithoutNullStreams,
|
cp: ChildProcessWithoutNullStreams,
|
||||||
startTime: dayjs.Dayjs,
|
startTime: dayjs.Dayjs,
|
||||||
@@ -46,8 +45,6 @@ export default class ScheduleService {
|
|||||||
return new Promise(async (resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
const startTime = dayjs();
|
const startTime = dayjs();
|
||||||
await callbacks.onBefore?.(startTime);
|
|
||||||
|
|
||||||
const cp = spawn(command, { shell: '/bin/bash' });
|
const cp = spawn(command, { shell: '/bin/bash' });
|
||||||
|
|
||||||
// TODO:
|
// TODO:
|
||||||
@@ -79,12 +76,13 @@ export default class ScheduleService {
|
|||||||
|
|
||||||
cp.on('exit', async (code, signal) => {
|
cp.on('exit', async (code, signal) => {
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`任务 ${command} 进程id: ${cp.pid} 退出,退出码 ${code}`,
|
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.on('close', async (code) => {
|
cp.on('close', async (code) => {
|
||||||
const endTime = dayjs();
|
const endTime = dayjs();
|
||||||
|
this.logger.info(`${command} pid: ${cp.pid} closed ${code}`);
|
||||||
await callbacks.onEnd?.(
|
await callbacks.onEnd?.(
|
||||||
cp,
|
cp,
|
||||||
endTime,
|
endTime,
|
||||||
@@ -168,7 +166,7 @@ export default class ScheduleService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const job = new LongIntervalJob(
|
const job = new LongIntervalJob(
|
||||||
{ runImmediately: false, ...schedule },
|
{ ...schedule, runImmediately: false },
|
||||||
task,
|
task,
|
||||||
_id,
|
_id,
|
||||||
);
|
);
|
||||||
|
|||||||
+33
-36
@@ -1,12 +1,8 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import fs from 'fs';
|
import { spawn } from 'child_process';
|
||||||
import path from 'path';
|
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import CronService from './cron';
|
import CronService from './cron';
|
||||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
|
||||||
import config from '../config';
|
|
||||||
import { LOG_END_SYMBOL } from '../config/const';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class ScriptService {
|
export default class ScriptService {
|
||||||
@@ -14,49 +10,50 @@ export default class ScriptService {
|
|||||||
@Inject('logger') private logger: winston.Logger,
|
@Inject('logger') private logger: winston.Logger,
|
||||||
private sockService: SockService,
|
private sockService: SockService,
|
||||||
private cronService: CronService,
|
private cronService: CronService,
|
||||||
private scheduleService: ScheduleService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private taskCallbacks(filePath: string): TaskCallbacks {
|
public async runScript(path: string) {
|
||||||
return {
|
const cp = spawn(`task -l ${path} now`, { shell: '/bin/bash' });
|
||||||
onEnd: async (cp, endTime, diff) => {
|
|
||||||
try {
|
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
} catch (error) {}
|
|
||||||
},
|
|
||||||
onError: async (message: string) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: 'manuallyRunScript',
|
|
||||||
message,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onLog: async (message: string) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: 'manuallyRunScript',
|
|
||||||
message,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public async runScript(filePath: string) {
|
cp.stdout.on('data', (data) => {
|
||||||
const relativePath = path.relative(config.scriptPath, filePath);
|
this.sockService.sendMessage({
|
||||||
const command = `task -l ${relativePath} now`;
|
type: 'manuallyRunScript',
|
||||||
this.scheduleService.runTask(command, this.taskCallbacks(filePath));
|
message: data.toString(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.stderr.on('data', (data) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'manuallyRunScript',
|
||||||
|
message: data.toString(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('error', (err) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'manuallyRunScript',
|
||||||
|
message: JSON.stringify(err),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('close', (err) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'manuallyRunScript',
|
||||||
|
message: `执行结束`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
return { code: 200 };
|
return { code: 200 };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stopScript(filePath: string) {
|
public async stopScript(path: string) {
|
||||||
const relativePath = path.relative(config.scriptPath, filePath);
|
const err = await this.cronService.killTask(`task -l ${path} now`);
|
||||||
const err = await this.cronService.killTask(`task -l ${relativePath} now`);
|
|
||||||
|
|
||||||
const str = err ? `\n${err}` : '';
|
const str = err ? `\n${err}` : '';
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
type: 'manuallyRunScript',
|
type: 'manuallyRunScript',
|
||||||
message: `${str}\n## 执行结束... ${new Date()
|
message: `${str}\n## 执行结束... ${new Date()
|
||||||
.toLocaleString('zh', { hour12: false })
|
.toLocaleString('zh', { hour12: false })
|
||||||
.replace(' 24:', ' 00:')}${LOG_END_SYMBOL}`,
|
.replace(' 24:', ' 00:')} `,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { code: 200 };
|
return { code: 200 };
|
||||||
|
|||||||
+5
-13
@@ -23,13 +23,6 @@ export default class SshKeyService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private getConfigRegx(alias: string) {
|
|
||||||
return new RegExp(
|
|
||||||
`Host ${alias}\n.*[^StrictHostKeyChecking]*.*[\n]*.*StrictHostKeyChecking no`,
|
|
||||||
'g',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private removePrivateKeyFile(alias: string): void {
|
private removePrivateKeyFile(alias: string): void {
|
||||||
try {
|
try {
|
||||||
fs.unlinkSync(`${this.sshPath}/${alias}`);
|
fs.unlinkSync(`${this.sshPath}/${alias}`);
|
||||||
@@ -54,25 +47,24 @@ export default class SshKeyService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private removeSshConfig(alias: string) {
|
private removeSshConfig(config: string) {
|
||||||
try {
|
try {
|
||||||
const configRegx = this.getConfigRegx(alias);
|
|
||||||
const data = fs
|
const data = fs
|
||||||
.readFileSync(this.sshConfigFilePath, { encoding: 'utf8' })
|
.readFileSync(this.sshConfigFilePath, { encoding: 'utf8' })
|
||||||
.replace(configRegx, '')
|
.replace(config, '')
|
||||||
.replace(/\n[\n]+/g, '\n');
|
.replace(/\n\n+/, '\n\n');
|
||||||
fs.writeFileSync(this.sshConfigFilePath, data, {
|
fs.writeFileSync(this.sshConfigFilePath, data, {
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`删除ssh配置文件${alias}失败`, error);
|
this.logger.error(`删除ssh配置文件${config}失败`, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public addSSHKey(key: string, alias: string, host: string): void {
|
public addSSHKey(key: string, alias: string, host: string): void {
|
||||||
this.generatePrivateKeyFile(alias, key);
|
this.generatePrivateKeyFile(alias, key);
|
||||||
const config = this.generateSingleSshConfig(alias, host);
|
const config = this.generateSingleSshConfig(alias, host);
|
||||||
this.removeSshConfig(alias);
|
this.removeSshConfig(config);
|
||||||
this.generateSshConfig([config]);
|
this.generateSshConfig([config]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,8 +28,6 @@ import ScheduleService, { TaskCallbacks } from './schedule';
|
|||||||
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import SshKeyService from './sshKey';
|
import SshKeyService from './sshKey';
|
||||||
import dayjs from 'dayjs';
|
|
||||||
import { LOG_END_SYMBOL } from '../config/const';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class SubscriptionService {
|
export default class SubscriptionService {
|
||||||
@@ -43,6 +41,23 @@ export default class SubscriptionService {
|
|||||||
public async list(searchText?: string): Promise<Subscription[]> {
|
public async list(searchText?: string): Promise<Subscription[]> {
|
||||||
let query = {};
|
let query = {};
|
||||||
if (searchText) {
|
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 = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
@@ -55,18 +70,23 @@ export default class SubscriptionService {
|
|||||||
name: reg,
|
name: reg,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: reg,
|
command: reg,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
schedule: reg,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
labels: reg,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await SubscriptionModel.findAll({
|
const result = await SubscriptionModel.findAll({
|
||||||
where: query,
|
where: query,
|
||||||
order: [
|
order: [['createdAt', 'DESC']],
|
||||||
['is_disabled', 'ASC'],
|
|
||||||
['createdAt', 'DESC'],
|
|
||||||
],
|
|
||||||
});
|
});
|
||||||
return result as any;
|
return result as any;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -172,13 +192,14 @@ export default class SubscriptionService {
|
|||||||
|
|
||||||
private taskCallbacks(doc: Subscription): TaskCallbacks {
|
private taskCallbacks(doc: Subscription): TaskCallbacks {
|
||||||
return {
|
return {
|
||||||
onBefore: async (startTime) => {
|
onStart: async (cp: ChildProcessWithoutNullStreams, startTime) => {
|
||||||
const logTime = startTime.format('YYYY-MM-DD-HH-mm-ss');
|
const logTime = startTime.format('YYYY-MM-DD-HH-mm-ss');
|
||||||
const logPath = `${doc.alias}/${logTime}.log`;
|
const logPath = `${doc.alias}/${logTime}.log`;
|
||||||
await SubscriptionModel.update(
|
await SubscriptionModel.update(
|
||||||
{
|
{
|
||||||
status: SubscriptionStatus.running,
|
status: SubscriptionStatus.running,
|
||||||
log_path: logPath,
|
log_path: logPath,
|
||||||
|
pid: cp.pid,
|
||||||
},
|
},
|
||||||
{ where: { id: doc.id } },
|
{ where: { id: doc.id } },
|
||||||
);
|
);
|
||||||
@@ -199,17 +220,9 @@ export default class SubscriptionService {
|
|||||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||||
}
|
}
|
||||||
if (beforeStr) {
|
if (beforeStr) {
|
||||||
fs.appendFileSync(absolutePath, `${beforeStr}\n`);
|
fs.appendFileSync(absolutePath, `${beforeStr}\n\n`);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onStart: async (cp: ChildProcessWithoutNullStreams, startTime) => {
|
|
||||||
await SubscriptionModel.update(
|
|
||||||
{
|
|
||||||
pid: cp.pid,
|
|
||||||
},
|
|
||||||
{ where: { id: doc.id } },
|
|
||||||
);
|
|
||||||
},
|
|
||||||
onEnd: async (cp, endTime, diff) => {
|
onEnd: async (cp, endTime, diff) => {
|
||||||
const sub = await this.getDb({ id: doc.id });
|
const sub = await this.getDb({ id: doc.id });
|
||||||
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||||
@@ -218,7 +231,7 @@ export default class SubscriptionService {
|
|||||||
let afterStr = '';
|
let afterStr = '';
|
||||||
try {
|
try {
|
||||||
if (sub.sub_after) {
|
if (sub.sub_after) {
|
||||||
fs.appendFileSync(absolutePath, `\n\n## 执行after命令...\n\n`);
|
fs.appendFileSync(absolutePath, `\n\n## 执行after命令...\n`);
|
||||||
afterStr = await this.promiseExec(sub.sub_after);
|
afterStr = await this.promiseExec(sub.sub_after);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -233,7 +246,7 @@ export default class SubscriptionService {
|
|||||||
absolutePath,
|
absolutePath,
|
||||||
`\n## 执行结束... ${endTime.format(
|
`\n## 执行结束... ${endTime.format(
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
)} 耗时 ${diff} 秒${LOG_END_SYMBOL}`,
|
)} 耗时 ${diff} 秒`,
|
||||||
);
|
);
|
||||||
|
|
||||||
await SubscriptionModel.update(
|
await SubscriptionModel.update(
|
||||||
@@ -273,7 +286,7 @@ export default class SubscriptionService {
|
|||||||
|
|
||||||
public async update(payload: Subscription): Promise<Subscription> {
|
public async update(payload: Subscription): Promise<Subscription> {
|
||||||
const newDoc = await this.updateDb(payload);
|
const newDoc = await this.updateDb(payload);
|
||||||
await this.handleTask(newDoc, !newDoc.is_disabled);
|
await this.handleTask(newDoc);
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,14 +360,16 @@ export default class SubscriptionService {
|
|||||||
this.logger.silly(error);
|
this.logger.silly(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
await this.handleTask(doc, false);
|
||||||
const command = this.formatCommand(doc);
|
const command = this.formatCommand(doc);
|
||||||
const err = await this.killTask(command);
|
const err = await this.killTask(command);
|
||||||
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
||||||
const str = err ? `\n${err}` : '';
|
const str = err ? `\n${err}` : '';
|
||||||
|
|
||||||
fs.appendFileSync(
|
fs.appendFileSync(
|
||||||
`${absolutePath}`,
|
`${absolutePath}`,
|
||||||
`${str}\n## 执行结束... ${dayjs().format('YYYY-MM-DD HH:mm:ss')}${LOG_END_SYMBOL}`,
|
`${str}\n## 执行结束... ${new Date()
|
||||||
|
.toLocaleString('zh', { hour12: false })
|
||||||
|
.replace(' 24:', ' 00:')} `,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-5
@@ -2,6 +2,7 @@ import { Service, Inject } from 'typedi';
|
|||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
|
import _ from 'lodash';
|
||||||
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
import NotificationService from './notify';
|
import NotificationService from './notify';
|
||||||
@@ -9,7 +10,6 @@ import ScheduleService from './schedule';
|
|||||||
import { spawn } from 'child_process';
|
import { spawn } from 'child_process';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import got from 'got';
|
import got from 'got';
|
||||||
import { promiseExec } from '../config/util';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class SystemService {
|
export default class SystemService {
|
||||||
@@ -70,8 +70,9 @@ export default class SystemService {
|
|||||||
};
|
};
|
||||||
await this.scheduleService.cancelIntervalTask(cron);
|
await this.scheduleService.cancelIntervalTask(cron);
|
||||||
if (frequency > 0) {
|
if (frequency > 0) {
|
||||||
this.scheduleService.createIntervalTask(cron, {
|
await this.scheduleService.createIntervalTask(cron, {
|
||||||
days: frequency,
|
days: frequency,
|
||||||
|
runImmediately: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return { code: 200, data: { ...cron } };
|
return { code: 200, data: { ...cron } };
|
||||||
@@ -88,9 +89,11 @@ export default class SystemService {
|
|||||||
let lastVersion = '';
|
let lastVersion = '';
|
||||||
let lastLog = '';
|
let lastLog = '';
|
||||||
try {
|
try {
|
||||||
const lastVersionFileContent = await promiseExec(
|
const result = await got.get(config.lastVersionFile, {
|
||||||
`curl ${config.lastVersionFile}?t=${Date.now()}`,
|
timeout: 6000,
|
||||||
);
|
retry: 0,
|
||||||
|
});
|
||||||
|
const lastVersionFileContent = result.body;
|
||||||
lastVersion = lastVersionFileContent.match(versionRegx)![1];
|
lastVersion = lastVersionFileContent.match(versionRegx)![1];
|
||||||
lastLog = lastVersionFileContent.match(logRegx)
|
lastLog = lastVersionFileContent.match(logRegx)
|
||||||
? lastVersionFileContent.match(logRegx)![1]
|
? lastVersionFileContent.match(logRegx)![1]
|
||||||
@@ -135,6 +138,10 @@ export default class SystemService {
|
|||||||
public async updateSystem() {
|
public async updateSystem() {
|
||||||
const cp = spawn('ql -l update', { shell: '/bin/bash' });
|
const cp = spawn('ql -l update', { shell: '/bin/bash' });
|
||||||
|
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'updateSystemVersion',
|
||||||
|
message: `开始更新系统`,
|
||||||
|
});
|
||||||
cp.stdout.on('data', (data) => {
|
cp.stdout.on('data', (data) => {
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
type: 'updateSystemVersion',
|
type: 'updateSystemVersion',
|
||||||
|
|||||||
+22
-35
@@ -3,6 +3,7 @@ import winston from 'winston';
|
|||||||
import { createRandomString, getNetIp, getPlatform } from '../config/util';
|
import { createRandomString, getNetIp, getPlatform } from '../config/util';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
|
import _ from 'lodash';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
import { authenticator } from '@otplib/preset-default';
|
import { authenticator } from '@otplib/preset-default';
|
||||||
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
||||||
@@ -12,7 +13,7 @@ import { Request } from 'express';
|
|||||||
import ScheduleService from './schedule';
|
import ScheduleService from './schedule';
|
||||||
import { spawn } from 'child_process';
|
import { spawn } from 'child_process';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import dayjs from 'dayjs';
|
import got from 'got';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class UserService {
|
export default class UserService {
|
||||||
@@ -64,37 +65,32 @@ export default class UserService {
|
|||||||
return this.initAuthInfo();
|
return this.initAuthInfo();
|
||||||
}
|
}
|
||||||
|
|
||||||
const retriesTime = Math.pow(3, retries) * 1000;
|
if (retries > 2 && Date.now() - lastlogon < Math.pow(3, retries) * 1000) {
|
||||||
if (retries > 2 && timestamp - lastlogon < retriesTime) {
|
|
||||||
const waitTime = Math.ceil(
|
|
||||||
(retriesTime - (timestamp - lastlogon)) / 1000,
|
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
code: 410,
|
code: 410,
|
||||||
message: `失败次数过多,请${waitTime}秒后重试`,
|
message: `失败次数过多,请${Math.round(
|
||||||
data: waitTime,
|
(Math.pow(3, retries) * 1000 - Date.now() + lastlogon) / 1000,
|
||||||
};
|
)}秒后重试`,
|
||||||
}
|
data: Math.round(
|
||||||
|
(Math.pow(3, retries) * 1000 - Date.now() + lastlogon) / 1000,
|
||||||
if (
|
),
|
||||||
username === cUsername &&
|
|
||||||
password === cPassword &&
|
|
||||||
twoFactorActivated &&
|
|
||||||
needTwoFactor
|
|
||||||
) {
|
|
||||||
this.updateAuthInfo(content, {
|
|
||||||
isTwoFactorChecking: true,
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
code: 420,
|
|
||||||
message: '',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const { ip, address } = await getNetIp(req);
|
const { ip, address } = await getNetIp(req);
|
||||||
if (username === cUsername && password === cPassword) {
|
if (username === cUsername && password === cPassword) {
|
||||||
|
if (twoFactorActivated && needTwoFactor) {
|
||||||
|
this.updateAuthInfo(content, {
|
||||||
|
isTwoFactorChecking: true,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
code: 420,
|
||||||
|
message: '请输入两步验证token',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const data = createRandomString(50, 100);
|
const data = createRandomString(50, 100);
|
||||||
const expiration = twoFactorActivated ? 60 : 20;
|
const expiration = twoFactorActivated ? 30 : 3;
|
||||||
let token = jwt.sign({ data }, config.secret as any, {
|
let token = jwt.sign({ data }, config.secret as any, {
|
||||||
expiresIn: 60 * 60 * 24 * expiration,
|
expiresIn: 60 * 60 * 24 * expiration,
|
||||||
algorithm: 'HS384',
|
algorithm: 'HS384',
|
||||||
@@ -115,7 +111,7 @@ export default class UserService {
|
|||||||
});
|
});
|
||||||
await this.notificationService.notify(
|
await this.notificationService.notify(
|
||||||
'登录通知',
|
'登录通知',
|
||||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
`你于${new Date(timestamp).toLocaleString()}在 ${address} ${
|
||||||
req.platform
|
req.platform
|
||||||
}端 登录成功,ip地址 ${ip}`,
|
}端 登录成功,ip地址 ${ip}`,
|
||||||
);
|
);
|
||||||
@@ -144,7 +140,7 @@ export default class UserService {
|
|||||||
});
|
});
|
||||||
await this.notificationService.notify(
|
await this.notificationService.notify(
|
||||||
'登录通知',
|
'登录通知',
|
||||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
`你于${new Date(timestamp).toLocaleString()}在 ${address} ${
|
||||||
req.platform
|
req.platform
|
||||||
}端 登录失败,ip地址 ${ip}`,
|
}端 登录失败,ip地址 ${ip}`,
|
||||||
);
|
);
|
||||||
@@ -159,17 +155,8 @@ export default class UserService {
|
|||||||
status: LoginStatus.fail,
|
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 };
|
return { code: 400, message: config.authError };
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
return this.initAuthInfo();
|
return this.initAuthInfo();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
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';
|
|
||||||
|
|
||||||
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), { encoding: 'utf8' }, () => {
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
getToken();
|
|
||||||
+7
-8
@@ -1,12 +1,11 @@
|
|||||||
FROM python:alpine
|
FROM node:alpine
|
||||||
|
|
||||||
ARG QL_MAINTAINER="whyour"
|
ARG QL_MAINTAINER="whyour"
|
||||||
LABEL maintainer="${QL_MAINTAINER}"
|
LABEL maintainer="${QL_MAINTAINER}"
|
||||||
ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
||||||
ARG QL_BRANCH=develop
|
ARG QL_BRANCH=master
|
||||||
|
|
||||||
ENV PNPM_HOME=/root/.local/share/pnpm \
|
ENV 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 \
|
||||||
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 \
|
|
||||||
LANG=zh_CN.UTF-8 \
|
LANG=zh_CN.UTF-8 \
|
||||||
SHELL=/bin/bash \
|
SHELL=/bin/bash \
|
||||||
PS1="\u@\h:\w \$ " \
|
PS1="\u@\h:\w \$ " \
|
||||||
@@ -29,18 +28,18 @@ RUN set -x \
|
|||||||
perl \
|
perl \
|
||||||
openssl \
|
openssl \
|
||||||
nginx \
|
nginx \
|
||||||
nodejs \
|
python3 \
|
||||||
jq \
|
jq \
|
||||||
openssh \
|
openssh \
|
||||||
npm \
|
py3-pip \
|
||||||
&& rm -rf /var/cache/apk/* \
|
&& rm -rf /var/cache/apk/* \
|
||||||
&& apk update \
|
|
||||||
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||||
&& echo "Asia/Shanghai" > /etc/timezone \
|
&& echo "Asia/Shanghai" > /etc/timezone \
|
||||||
&& git config --global user.email "qinglong@@users.noreply.github.com" \
|
&& git config --global user.email "qinglong@@users.noreply.github.com" \
|
||||||
&& git config --global user.name "qinglong" \
|
&& git config --global user.name "qinglong" \
|
||||||
&& git config --global http.postBuffer 524288000 \
|
|
||||||
&& npm install -g pnpm \
|
&& npm install -g pnpm \
|
||||||
|
&& pnpm setup \
|
||||||
|
&& source ~/.bashrc \
|
||||||
&& pnpm add -g pm2 ts-node typescript tslib \
|
&& pnpm add -g pm2 ts-node typescript tslib \
|
||||||
&& git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
&& git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||||
&& cd ${QL_DIR} \
|
&& cd ${QL_DIR} \
|
||||||
|
|||||||
@@ -4,17 +4,12 @@ dir_shell=/ql/shell
|
|||||||
. $dir_shell/share.sh
|
. $dir_shell/share.sh
|
||||||
link_shell
|
link_shell
|
||||||
|
|
||||||
export isFirstStartServer=true
|
|
||||||
|
|
||||||
echo -e "======================1. 检测配置文件========================\n"
|
echo -e "======================1. 检测配置文件========================\n"
|
||||||
make_dir /etc/nginx/conf.d
|
make_dir /etc/nginx/conf.d
|
||||||
make_dir /run/nginx
|
make_dir /run/nginx
|
||||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.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
|
pm2 l &>/dev/null
|
||||||
|
|
||||||
patch_version &>/dev/null
|
|
||||||
echo
|
echo
|
||||||
|
|
||||||
echo -e "======================2. 安装依赖========================\n"
|
echo -e "======================2. 安装依赖========================\n"
|
||||||
@@ -42,13 +37,13 @@ echo -e "定时任务启动成功...\n"
|
|||||||
|
|
||||||
if [[ $AutoStartBot == true ]]; then
|
if [[ $AutoStartBot == true ]]; then
|
||||||
echo -e "======================7. 启动bot========================\n"
|
echo -e "======================7. 启动bot========================\n"
|
||||||
nohup ql bot >$dir_log/bot.log 2>&1 &
|
nohup ql bot >>$dir_log/start.log 2>&1 &
|
||||||
echo -e "bot后台启动中...\n"
|
echo -e "bot后台启动中...\n"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ $EnableExtraShell == true ]]; then
|
if [[ $EnableExtraShell == true ]]; then
|
||||||
echo -e "======================8. 执行自定义脚本========================\n"
|
echo -e "======================8. 执行自定义脚本========================\n"
|
||||||
nohup ql extra >$dir_log/extra.log 2>&1 &
|
nohup ql extra >>$dir_log/start.log 2>&1 &
|
||||||
echo -e "自定义脚本后台执行中...\n"
|
echo -e "自定义脚本后台执行中...\n"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
+10
-10
@@ -1,8 +1,8 @@
|
|||||||
upstream baseApi {
|
upstream api {
|
||||||
server 0.0.0.0:5600;
|
server 0.0.0.0:5600;
|
||||||
}
|
}
|
||||||
|
|
||||||
upstream publicApi {
|
upstream public {
|
||||||
server 0.0.0.0:5400;
|
server 0.0.0.0:5400;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -16,28 +16,28 @@ server {
|
|||||||
root /ql/static/dist;
|
root /ql/static/dist;
|
||||||
ssl_session_timeout 5m;
|
ssl_session_timeout 5m;
|
||||||
|
|
||||||
location QL_BASE_URL/api/public/ {
|
location /api/public {
|
||||||
proxy_set_header Host $http_host;
|
proxy_set_header Host $http_host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_pass http://publicApi/api/public/;
|
proxy_pass http://public;
|
||||||
}
|
}
|
||||||
|
|
||||||
location QL_BASE_URL/api/ {
|
location /api {
|
||||||
proxy_set_header Host $http_host;
|
proxy_set_header Host $http_host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_pass http://baseApi/api/;
|
proxy_pass http://api;
|
||||||
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection $connection_upgrade;
|
proxy_set_header Connection $connection_upgrade;
|
||||||
}
|
}
|
||||||
|
|
||||||
location QL_BASE_URL/open/ {
|
location /open {
|
||||||
proxy_set_header Host $http_host;
|
proxy_set_header Host $http_host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_pass http://baseApi/open/;
|
proxy_pass http://api;
|
||||||
}
|
}
|
||||||
|
|
||||||
gzip on;
|
gzip on;
|
||||||
@@ -49,9 +49,9 @@ server {
|
|||||||
gzip_buffers 16 8k;
|
gzip_buffers 16 8k;
|
||||||
gzip_http_version 1.0;
|
gzip_http_version 1.0;
|
||||||
|
|
||||||
location QL_BASE_URL/ {
|
location / {
|
||||||
index index.html index.htm;
|
index index.html index.htm;
|
||||||
try_files $uri $uri/ QL_BASE_URL/index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ~ .*\.(html)$ {
|
location ~ .*\.(html)$ {
|
||||||
|
|||||||
+26
-40
@@ -2,16 +2,16 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "concurrently -n w: npm:start:*",
|
"start": "concurrently -n w: npm:start:*",
|
||||||
"start:front": "max dev",
|
"start:front": "umi dev",
|
||||||
"start:back": "nodemon",
|
"start:back": "nodemon",
|
||||||
"start:public": "ts-node back/public.ts",
|
"start:public": "ts-node back/public.ts",
|
||||||
"build:front": "max build",
|
"build:front": "umi build",
|
||||||
"build:back": "tsc -p tsconfig.back.json",
|
"build:back": "tsc -p tsconfig.back.json",
|
||||||
"panel": "npm run build:back && node static/build/app.js",
|
"panel": "npm run build:back && node static/build/app.js",
|
||||||
"schedule": "npm run build:back && node static/build/schedule.js",
|
"schedule": "npm run build:back && node static/build/schedule.js",
|
||||||
"public": "npm run build:back && node static/build/public.js",
|
"public": "npm run build:back && node static/build/public.js",
|
||||||
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
||||||
"postinstall": "max setup 2>/dev/null || true",
|
"postinstall": "umi generate tmp 2>/dev/null || true",
|
||||||
"test": "umi-test",
|
"test": "umi-test",
|
||||||
"test:coverage": "umi-test --coverage"
|
"test:coverage": "umi-test --coverage"
|
||||||
},
|
},
|
||||||
@@ -28,33 +28,20 @@
|
|||||||
},
|
},
|
||||||
"pnpm": {
|
"pnpm": {
|
||||||
"peerDependencyRules": {
|
"peerDependencyRules": {
|
||||||
"ignoreMissing": [
|
|
||||||
"react",
|
|
||||||
"react-dom",
|
|
||||||
"antd",
|
|
||||||
"dva",
|
|
||||||
"postcss",
|
|
||||||
"webpack",
|
|
||||||
"eslint",
|
|
||||||
"stylelint",
|
|
||||||
"redux",
|
|
||||||
"@babel/core",
|
|
||||||
"monaco-editor",
|
|
||||||
"rc-field-form",
|
|
||||||
"@types/lodash.merge",
|
|
||||||
"rollup"
|
|
||||||
],
|
|
||||||
"allowedVersions": {
|
"allowedVersions": {
|
||||||
"react": "18",
|
"react": "17",
|
||||||
"react-dom": "18",
|
"react-dom": "17"
|
||||||
"dva-core": "2"
|
},
|
||||||
}
|
"ignoreMissing": [
|
||||||
|
"monaco-editor",
|
||||||
|
"react-router"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@otplib/preset-default": "^12.0.1",
|
"@otplib/preset-default": "^12.0.1",
|
||||||
"@sentry/node": "^7.12.1",
|
"@sentry/node": "^6.18.1",
|
||||||
"@sentry/tracing": "^7.12.1",
|
"@sentry/tracing": "^6.18.1",
|
||||||
"body-parser": "^1.19.2",
|
"body-parser": "^1.19.2",
|
||||||
"celebrate": "^15.0.1",
|
"celebrate": "^15.0.1",
|
||||||
"chokidar": "^3.5.3",
|
"chokidar": "^3.5.3",
|
||||||
@@ -65,7 +52,6 @@
|
|||||||
"express": "^4.17.3",
|
"express": "^4.17.3",
|
||||||
"express-jwt": "^6.1.1",
|
"express-jwt": "^6.1.1",
|
||||||
"express-urlrewrite": "^1.4.0",
|
"express-urlrewrite": "^1.4.0",
|
||||||
"form-data": "^4.0.0",
|
|
||||||
"got": "^11.8.2",
|
"got": "^11.8.2",
|
||||||
"hpagent": "^0.1.2",
|
"hpagent": "^0.1.2",
|
||||||
"iconv-lite": "^0.6.3",
|
"iconv-lite": "^0.6.3",
|
||||||
@@ -77,10 +63,10 @@
|
|||||||
"nodemailer": "^6.7.2",
|
"nodemailer": "^6.7.2",
|
||||||
"p-queue": "7.2.0",
|
"p-queue": "7.2.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"sequelize": "^6.25.3",
|
"sequelize": "^6.17.0",
|
||||||
"serve-handler": "^6.1.3",
|
"serve-handler": "^6.1.3",
|
||||||
"sockjs": "^0.3.24",
|
"sockjs": "^0.3.24",
|
||||||
"sqlite3": "npm:@louislam/sqlite3@^15.0.6",
|
"sqlite3": "npm:@louislam/sqlite3@^15.0.3",
|
||||||
"toad-scheduler": "^1.6.0",
|
"toad-scheduler": "^1.6.0",
|
||||||
"typedi": "^0.10.0",
|
"typedi": "^0.10.0",
|
||||||
"uuid": "^8.3.2",
|
"uuid": "^8.3.2",
|
||||||
@@ -90,31 +76,32 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ant-design/icons": "^4.7.0",
|
"@ant-design/icons": "^4.7.0",
|
||||||
"@ant-design/pro-layout": "^6.33.1",
|
"@ant-design/pro-layout": "^6.33.1",
|
||||||
"@monaco-editor/react": "4.2.1",
|
"@monaco-editor/react": "^4.3.1",
|
||||||
"@react-hook/resize-observer": "^1.2.6",
|
"@sentry/react": "^6.18.1",
|
||||||
"@sentry/react": "^7.12.1",
|
|
||||||
"@types/body-parser": "^1.19.2",
|
"@types/body-parser": "^1.19.2",
|
||||||
"@types/cors": "^2.8.12",
|
"@types/cors": "^2.8.12",
|
||||||
"@types/express": "^4.17.13",
|
"@types/express": "^4.17.13",
|
||||||
"@types/express-jwt": "^6.0.4",
|
"@types/express-jwt": "^6.0.4",
|
||||||
"@types/jsonwebtoken": "^8.5.8",
|
"@types/jsonwebtoken": "^8.5.8",
|
||||||
"@types/lodash": "^4.14.185",
|
"@types/lodash": "^4.14.179",
|
||||||
"@types/multer": "^1.4.7",
|
"@types/multer": "^1.4.7",
|
||||||
"@types/nedb": "^1.8.12",
|
"@types/nedb": "^1.8.12",
|
||||||
"@types/node": "^17.0.21",
|
"@types/node": "^17.0.21",
|
||||||
"@types/node-schedule": "^1.3.2",
|
"@types/node-schedule": "^1.3.2",
|
||||||
"@types/nodemailer": "^6.4.4",
|
"@types/nodemailer": "^6.4.4",
|
||||||
"@types/qrcode.react": "^1.0.2",
|
"@types/qrcode.react": "^1.0.2",
|
||||||
"@types/react": "^18.0.20",
|
"@types/react": "^17.0.39",
|
||||||
"@types/react-dom": "^18.0.6",
|
"@types/react-dom": "^17.0.13",
|
||||||
"@types/serve-handler": "^6.1.1",
|
"@types/serve-handler": "^6.1.1",
|
||||||
"@types/sockjs": "^0.3.33",
|
"@types/sockjs": "^0.3.33",
|
||||||
"@types/sockjs-client": "^1.5.1",
|
"@types/sockjs-client": "^1.5.1",
|
||||||
"@types/uuid": "^8.3.4",
|
"@types/uuid": "^8.3.4",
|
||||||
"@umijs/max": "^4.0.21",
|
"@umijs/plugin-antd": "^0.15.0",
|
||||||
|
"@umijs/plugin-esbuild": "^1.4.1",
|
||||||
"@umijs/ssr-darkreader": "^4.9.45",
|
"@umijs/ssr-darkreader": "^4.9.45",
|
||||||
|
"@umijs/test": "^3.5.21",
|
||||||
"ansi-to-react": "^6.1.6",
|
"ansi-to-react": "^6.1.6",
|
||||||
"antd": "^4.23.0",
|
"antd": "^4.20.5",
|
||||||
"antd-img-crop": "^4.2.3",
|
"antd-img-crop": "^4.2.3",
|
||||||
"codemirror": "^5.65.2",
|
"codemirror": "^5.65.2",
|
||||||
"compression-webpack-plugin": "9.2.0",
|
"compression-webpack-plugin": "9.2.0",
|
||||||
@@ -124,19 +111,18 @@
|
|||||||
"prettier": "^2.5.1",
|
"prettier": "^2.5.1",
|
||||||
"qiniu": "^7.4.0",
|
"qiniu": "^7.4.0",
|
||||||
"qrcode.react": "^1.0.1",
|
"qrcode.react": "^1.0.1",
|
||||||
"query-string": "^7.1.1",
|
|
||||||
"rc-tween-one": "^3.0.6",
|
"rc-tween-one": "^3.0.6",
|
||||||
"react": "18.2.0",
|
"react": "17.x",
|
||||||
"react-codemirror2": "^7.2.1",
|
"react-codemirror2": "^7.2.1",
|
||||||
"react-diff-viewer": "^3.1.1",
|
"react-diff-viewer": "^3.1.1",
|
||||||
"react-dnd": "^14.0.2",
|
"react-dnd": "^14.0.2",
|
||||||
"react-dnd-html5-backend": "^14.0.0",
|
"react-dnd-html5-backend": "^14.0.0",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "17.x",
|
||||||
"react-split-pane": "^0.1.92",
|
"react-split-pane": "^0.1.92",
|
||||||
"sockjs-client": "^1.6.0",
|
"sockjs-client": "^1.6.0",
|
||||||
"ts-node": "^10.6.0",
|
"ts-node": "^10.6.0",
|
||||||
"tslib": "^2.4.0",
|
|
||||||
"typescript": "^4.6.2",
|
"typescript": "^4.6.2",
|
||||||
|
"umi": "^3.5.21",
|
||||||
"umi-request": "^1.4.0",
|
"umi-request": "^1.4.0",
|
||||||
"vh-check": "^2.0.5",
|
"vh-check": "^2.0.5",
|
||||||
"webpack": "^5.70.0",
|
"webpack": "^5.70.0",
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
+3
-34
@@ -19,11 +19,6 @@ RepoFileExtensions="js py"
|
|||||||
## 代理地址,支持http/https/socks,例如 http://127.0.0.1:7890
|
## 代理地址,支持http/https/socks,例如 http://127.0.0.1:7890
|
||||||
ProxyUrl=""
|
ProxyUrl=""
|
||||||
|
|
||||||
## 资源告警阙值,默认CPU 80%、内存80%、磁盘90%
|
|
||||||
CpuWarn=80
|
|
||||||
MemoryWarn=80
|
|
||||||
DiskWarn=90
|
|
||||||
|
|
||||||
## 设置定时任务执行的超时时间,默认1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
## 设置定时任务执行的超时时间,默认1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
||||||
CommandTimeoutTime="1h"
|
CommandTimeoutTime="1h"
|
||||||
|
|
||||||
@@ -34,14 +29,6 @@ MaxConcurrentNum="5"
|
|||||||
## 默认给javascript任务加随机延迟,如 RandomDelay="300" ,表示任务将在 1-300 秒内随机延迟一个秒数,然后再运行,取消延迟赋值为空
|
## 默认给javascript任务加随机延迟,如 RandomDelay="300" ,表示任务将在 1-300 秒内随机延迟一个秒数,然后再运行,取消延迟赋值为空
|
||||||
RandomDelay="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
|
## 如果你自己会写shell脚本,并且希望在每次运行 ql update 命令时,额外运行你的 shell 脚本,请赋值为 "true",默认为true
|
||||||
EnableExtraShell="true"
|
EnableExtraShell="true"
|
||||||
|
|
||||||
@@ -51,11 +38,8 @@ AutoStartBot=""
|
|||||||
## 是否使用第三方bot,默认不使用,使用时填入仓库地址,存到ql/repo目录下,文件夹命名为diybot
|
## 是否使用第三方bot,默认不使用,使用时填入仓库地址,存到ql/repo目录下,文件夹命名为diybot
|
||||||
BotRepoUrl=""
|
BotRepoUrl=""
|
||||||
|
|
||||||
## 安装python依赖时指定pip源
|
## 安装bot依赖时指定pip源,默认使用清华源,如不需要源,设置此参数为空
|
||||||
PipMirror="https://pypi.doubanio.com/simple/"
|
PipMirror="https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||||
|
|
||||||
## 安装node依赖时指定npm源
|
|
||||||
NpmMirror="https://registry.npmmirror.com"
|
|
||||||
|
|
||||||
## 通知环境变量
|
## 通知环境变量
|
||||||
## 1. Server酱
|
## 1. Server酱
|
||||||
@@ -67,7 +51,7 @@ export PUSH_KEY=""
|
|||||||
## 下方填写app提供的设备码,例如:https://api.day.app/123 那么此处的设备码就是123
|
## 下方填写app提供的设备码,例如:https://api.day.app/123 那么此处的设备码就是123
|
||||||
export BARK_PUSH=""
|
export BARK_PUSH=""
|
||||||
## 下方填写推送图标设置,自定义推送图标(需iOS15或以上)
|
## 下方填写推送图标设置,自定义推送图标(需iOS15或以上)
|
||||||
export BARK_ICON="https://qn.whyour.cn/logo.png"
|
export BARK_ICON="http://qn.whyour.cn/logo.png"
|
||||||
## 下方填写推送声音设置,例如choo,具体值请在bark-推送铃声-查看所有铃声
|
## 下方填写推送声音设置,例如choo,具体值请在bark-推送铃声-查看所有铃声
|
||||||
export BARK_SOUND=""
|
export BARK_SOUND=""
|
||||||
## 下方填写推送消息分组,默认为"QingLong"
|
## 下方填写推送消息分组,默认为"QingLong"
|
||||||
@@ -145,19 +129,4 @@ export GOTIFY_PRIORITY=0
|
|||||||
## deer_key 填写PushDeer的key
|
## deer_key 填写PushDeer的key
|
||||||
export DEER_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=""
|
|
||||||
|
|
||||||
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
||||||
|
|||||||
+75
-172
@@ -39,17 +39,11 @@ let SCKEY = '';
|
|||||||
//(环境变量名 DEER_KEY)
|
//(环境变量名 DEER_KEY)
|
||||||
let PUSHDEER_KEY = '';
|
let PUSHDEER_KEY = '';
|
||||||
|
|
||||||
// =======================================Synology Chat通知设置区域===========================================
|
|
||||||
//此处填你申请的CHAT_URL与CHAT_TOKEN
|
|
||||||
//(环境变量名 CHAT_URL CHAT_TOKEN)
|
|
||||||
let CHAT_URL = '';
|
|
||||||
let CHAT_TOKEN = '';
|
|
||||||
|
|
||||||
// =======================================Bark App通知设置区域===========================================
|
// =======================================Bark App通知设置区域===========================================
|
||||||
//此处填你BarkAPP的信息(IP/设备码,例如:https://api.day.app/XXXXXXXX)
|
//此处填你BarkAPP的信息(IP/设备码,例如:https://api.day.app/XXXXXXXX)
|
||||||
let BARK_PUSH = '';
|
let BARK_PUSH = '';
|
||||||
//BARK app推送图标,自定义推送图标(需iOS15或以上)
|
//BARK app推送图标,自定义推送图标(需iOS15或以上)
|
||||||
let BARK_ICON = 'https://qn.whyour.cn/logo.png';
|
let BARK_ICON = 'http://qn.whyour.cn/logo.png';
|
||||||
//BARK app推送铃声,铃声列表去APP查看复制填写
|
//BARK app推送铃声,铃声列表去APP查看复制填写
|
||||||
let BARK_SOUND = '';
|
let BARK_SOUND = '';
|
||||||
//BARK app推送消息的分组, 默认为"QingLong"
|
//BARK app推送消息的分组, 默认为"QingLong"
|
||||||
@@ -103,27 +97,6 @@ let IGOT_PUSH_KEY = '';
|
|||||||
let PUSH_PLUS_TOKEN = '';
|
let PUSH_PLUS_TOKEN = '';
|
||||||
let PUSH_PLUS_USER = '';
|
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 = '';
|
|
||||||
|
|
||||||
//==========================云端环境变量的判断与接收=========================
|
//==========================云端环境变量的判断与接收=========================
|
||||||
if (process.env.GOTIFY_URL) {
|
if (process.env.GOTIFY_URL) {
|
||||||
GOTIFY_URL = process.env.GOTIFY_URL;
|
GOTIFY_URL = process.env.GOTIFY_URL;
|
||||||
@@ -153,14 +126,6 @@ if (process.env.DEER_KEY) {
|
|||||||
PUSHDEER_KEY = process.env.DEER_KEY;
|
PUSHDEER_KEY = process.env.DEER_KEY;
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
if (process.env.QQ_SKEY) {
|
||||||
QQ_SKEY = process.env.QQ_SKEY;
|
QQ_SKEY = process.env.QQ_SKEY;
|
||||||
}
|
}
|
||||||
@@ -234,20 +199,6 @@ if (process.env.PUSH_PLUS_TOKEN) {
|
|||||||
if (process.env.PUSH_PLUS_USER) {
|
if (process.env.PUSH_PLUS_USER) {
|
||||||
PUSH_PLUS_USER = 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;
|
|
||||||
}
|
|
||||||
//==========================云端环境变量的判断与接收=========================
|
//==========================云端环境变量的判断与接收=========================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -281,10 +232,6 @@ async function sendNotify(
|
|||||||
iGotNotify(text, desp, params), //iGot
|
iGotNotify(text, desp, params), //iGot
|
||||||
gobotNotify(text, desp), //go-cqhttp
|
gobotNotify(text, desp), //go-cqhttp
|
||||||
gotifyNotify(text, desp), //gotify
|
gotifyNotify(text, desp), //gotify
|
||||||
ChatNotify(text, desp), //synolog chat
|
|
||||||
PushDeerNotify(text, desp), //PushDeer
|
|
||||||
aibotkNotify(text, desp), //智能微秘书
|
|
||||||
fsBotNotify(text, desp), //飞书机器人
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +272,7 @@ function gotifyNotify(text, desp) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function gobotNotify(text, desp) {
|
function gobotNotify(text, desp, time = 2100) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
if (GOBOT_URL) {
|
if (GOBOT_URL) {
|
||||||
const options = {
|
const options = {
|
||||||
@@ -336,6 +283,7 @@ function gobotNotify(text, desp) {
|
|||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
};
|
};
|
||||||
|
setTimeout(() => {
|
||||||
$.post(options, (err, resp, data) => {
|
$.post(options, (err, resp, data) => {
|
||||||
try {
|
try {
|
||||||
if (err) {
|
if (err) {
|
||||||
@@ -348,7 +296,9 @@ function gobotNotify(text, desp) {
|
|||||||
} else if (data.retcode === 100) {
|
} else if (data.retcode === 100) {
|
||||||
console.log(`go-cqhttp发送通知消息异常: ${data.errmsg}\n`);
|
console.log(`go-cqhttp发送通知消息异常: ${data.errmsg}\n`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`go-cqhttp发送通知消息异常\n${JSON.stringify(data)}`);
|
console.log(
|
||||||
|
`go-cqhttp发送通知消息异常\n${JSON.stringify(data)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -357,13 +307,14 @@ function gobotNotify(text, desp) {
|
|||||||
resolve(data);
|
resolve(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}, time);
|
||||||
} else {
|
} else {
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function serverNotify(text, desp) {
|
function serverNotify(text, desp, time = 2100) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
if (SCKEY) {
|
if (SCKEY) {
|
||||||
//微信server酱推送通知一个\n不会换行,需要两个\n才能换行,故做此替换
|
//微信server酱推送通知一个\n不会换行,需要两个\n才能换行,故做此替换
|
||||||
@@ -378,6 +329,7 @@ function serverNotify(text, desp) {
|
|||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
};
|
};
|
||||||
|
setTimeout(() => {
|
||||||
$.post(options, (err, resp, data) => {
|
$.post(options, (err, resp, data) => {
|
||||||
try {
|
try {
|
||||||
if (err) {
|
if (err) {
|
||||||
@@ -392,7 +344,9 @@ function serverNotify(text, desp) {
|
|||||||
// 一分钟内发送相同的内容会触发
|
// 一分钟内发送相同的内容会触发
|
||||||
console.log(`server酱发送通知消息异常: ${data.errmsg}\n`);
|
console.log(`server酱发送通知消息异常: ${data.errmsg}\n`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`server酱发送通知消息异常\n${JSON.stringify(data)}`);
|
console.log(
|
||||||
|
`server酱发送通知消息异常\n${JSON.stringify(data)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -401,13 +355,14 @@ function serverNotify(text, desp) {
|
|||||||
resolve(data);
|
resolve(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}, time);
|
||||||
} else {
|
} else {
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function PushDeerNotify(text, desp) {
|
function PushDeerNotify(text, desp, time = 2100) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
if (PUSHDEER_KEY) {
|
if (PUSHDEER_KEY) {
|
||||||
// PushDeer 建议对消息内容进行 urlencode
|
// PushDeer 建议对消息内容进行 urlencode
|
||||||
@@ -420,6 +375,7 @@ function PushDeerNotify(text, desp) {
|
|||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
};
|
};
|
||||||
|
setTimeout(() => {
|
||||||
$.post(options, (err, resp, data) => {
|
$.post(options, (err, resp, data) => {
|
||||||
try {
|
try {
|
||||||
if (err) {
|
if (err) {
|
||||||
@@ -434,7 +390,9 @@ function PushDeerNotify(text, desp) {
|
|||||||
) {
|
) {
|
||||||
console.log('PushDeer发送通知消息成功🎉\n');
|
console.log('PushDeer发送通知消息成功🎉\n');
|
||||||
} else {
|
} else {
|
||||||
console.log(`PushDeer发送通知消息异常\n${JSON.stringify(data)}`);
|
console.log(
|
||||||
|
`PushDeer发送通知消息异常\n${JSON.stringify(data)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -443,39 +401,80 @@ function PushDeerNotify(text, desp) {
|
|||||||
resolve(data);
|
resolve(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}, time);
|
||||||
} else {
|
} else {
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function ChatNotify(text, desp) {
|
function CoolPush(text, desp) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
if (CHAT_URL && CHAT_TOKEN) {
|
if (QQ_SKEY) {
|
||||||
// 对消息内容进行 urlencode
|
let options = {
|
||||||
desp = encodeURI(desp);
|
url: `https://push.xuthus.cc/${QQ_MODE}/${QQ_SKEY}`,
|
||||||
const options = {
|
|
||||||
url: `${CHAT_URL}${CHAT_TOKEN}`,
|
|
||||||
body: `payload={"text":"${text}\n${desp}"}`,
|
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 已知敏感词
|
||||||
|
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) => {
|
$.post(options, (err, resp, data) => {
|
||||||
try {
|
try {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log('发送通知调用API失败!!\n');
|
console.log(`发送${pushMode(QQ_MODE)}通知调用API失败!!\n`);
|
||||||
console.log(err);
|
console.log(err);
|
||||||
} else {
|
} else {
|
||||||
data = JSON.parse(data);
|
data = JSON.parse(data);
|
||||||
if (data.success) {
|
if (data.code === 200) {
|
||||||
console.log('Chat发送通知消息成功🎉\n');
|
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`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`Chat发送通知消息异常\n${JSON.stringify(data)}`);
|
console.log(`酷推推送异常: ${JSON.stringify(data)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
$.logErr(e);
|
$.logErr(e, resp);
|
||||||
} finally {
|
} finally {
|
||||||
resolve(data);
|
resolve(data);
|
||||||
}
|
}
|
||||||
@@ -724,9 +723,9 @@ function qywxamNotify(text, desp) {
|
|||||||
timeout,
|
timeout,
|
||||||
};
|
};
|
||||||
$.post(options_accesstoken, (err, resp, data) => {
|
$.post(options_accesstoken, (err, resp, data) => {
|
||||||
let html = desp.replace(/\n/g, '<br/>');
|
html = desp.replace(/\n/g, '<br/>');
|
||||||
let json = JSON.parse(data);
|
var json = JSON.parse(data);
|
||||||
let accesstoken = json.access_token;
|
accesstoken = json.access_token;
|
||||||
let options;
|
let options;
|
||||||
|
|
||||||
switch (QYWX_AM_AY[4]) {
|
switch (QYWX_AM_AY[4]) {
|
||||||
@@ -922,102 +921,6 @@ 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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
sendNotify,
|
sendNotify,
|
||||||
BARK_PUSH,
|
BARK_PUSH,
|
||||||
|
|||||||
@@ -62,9 +62,6 @@ push_config = {
|
|||||||
|
|
||||||
'DEER_KEY': '', # PushDeer 的 PUSHDEER_KEY
|
'DEER_KEY': '', # PushDeer 的 PUSHDEER_KEY
|
||||||
|
|
||||||
'CHAT_URL': '', # synology chat url
|
|
||||||
'CHAT_TOKEN': '', # synology chat token
|
|
||||||
|
|
||||||
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
||||||
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
||||||
|
|
||||||
@@ -81,10 +78,6 @@ push_config = {
|
|||||||
'TG_PROXY_AUTH': '', # tg 代理认证参数
|
'TG_PROXY_AUTH': '', # tg 代理认证参数
|
||||||
'TG_PROXY_HOST': '', # tg 机器人的 TG_PROXY_HOST
|
'TG_PROXY_HOST': '', # tg 机器人的 TG_PROXY_HOST
|
||||||
'TG_PROXY_PORT': '', # tg 机器人的 TG_PROXY_PORT
|
'TG_PROXY_PORT': '', # tg 机器人的 TG_PROXY_PORT
|
||||||
|
|
||||||
'AIBOTK_KEY': '', # 智能微秘书 个人中心的apikey 文档地址:http://wechat.aibotk.com/docs/about
|
|
||||||
'AIBOTK_TYPE': '', # 智能微秘书 发送目标 room 或 contact
|
|
||||||
'AIBOTK_NAME': '', # 智能微秘书 发送群名 或者好友昵称和type要对应好
|
|
||||||
}
|
}
|
||||||
notify_function = []
|
notify_function = []
|
||||||
# fmt: on
|
# fmt: on
|
||||||
@@ -288,25 +281,6 @@ def pushdeer(title: str, content: str) -> None:
|
|||||||
print("PushDeer 推送失败!错误信息:", response)
|
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:
|
def pushplus_bot(title: str, content: str) -> None:
|
||||||
"""
|
"""
|
||||||
通过 push+ 推送消息。
|
通过 push+ 推送消息。
|
||||||
@@ -525,39 +499,6 @@ def telegram_bot(title: str, content: str) -> None:
|
|||||||
print("tg 推送失败!")
|
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 one() -> str:
|
def one() -> str:
|
||||||
"""
|
"""
|
||||||
获取一条一言。
|
获取一条一言。
|
||||||
@@ -586,8 +527,6 @@ if push_config.get("PUSH_KEY"):
|
|||||||
notify_function.append(serverJ)
|
notify_function.append(serverJ)
|
||||||
if push_config.get("DEER_KEY"):
|
if push_config.get("DEER_KEY"):
|
||||||
notify_function.append(pushdeer)
|
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"):
|
if push_config.get("PUSH_PLUS_TOKEN"):
|
||||||
notify_function.append(pushplus_bot)
|
notify_function.append(pushplus_bot)
|
||||||
if push_config.get("QMSG_KEY") and push_config.get("QMSG_TYPE"):
|
if push_config.get("QMSG_KEY") and push_config.get("QMSG_TYPE"):
|
||||||
@@ -598,8 +537,6 @@ if push_config.get("QYWX_KEY"):
|
|||||||
notify_function.append(wecom_bot)
|
notify_function.append(wecom_bot)
|
||||||
if push_config.get("TG_BOT_TOKEN") and push_config.get("TG_USER_ID"):
|
if push_config.get("TG_BOT_TOKEN") and push_config.get("TG_USER_ID"):
|
||||||
notify_function.append(telegram_bot)
|
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)
|
|
||||||
|
|
||||||
|
|
||||||
def send(title: str, content: str) -> None:
|
def send(title: str, content: str) -> None:
|
||||||
|
|||||||
+26
-8
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
get_token() {
|
get_token() {
|
||||||
token=$(cat $file_auth_token | jq -r .value)
|
token=$(cat $file_auth_user | jq -r .token)
|
||||||
}
|
}
|
||||||
|
|
||||||
add_cron_api() {
|
add_cron_api() {
|
||||||
@@ -17,7 +17,7 @@ add_cron_api() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||||
-H "Accept: application/json" \
|
-H "Accept: application/json" \
|
||||||
-H "Authorization: Bearer $token" \
|
-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 "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" \
|
||||||
@@ -52,7 +52,7 @@ update_cron_api() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
-H "Accept: application/json" \
|
||||||
-H "Authorization: Bearer $token" \
|
-H "Authorization: Bearer $token" \
|
||||||
@@ -84,7 +84,7 @@ update_cron_command_api() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
-H "Accept: application/json" \
|
||||||
-H "Authorization: Bearer $token" \
|
-H "Authorization: Bearer $token" \
|
||||||
@@ -109,7 +109,7 @@ del_cron_api() {
|
|||||||
local ids=$1
|
local ids=$1
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||||
-X 'DELETE' \
|
-X 'DELETE' \
|
||||||
-H "Accept: application/json" \
|
-H "Accept: application/json" \
|
||||||
-H "Authorization: Bearer $token" \
|
-H "Authorization: Bearer $token" \
|
||||||
@@ -130,6 +130,24 @@ del_cron_api() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get_user_info() {
|
||||||
|
local currentTimeStamp=$(date +%s)
|
||||||
|
local api=$(
|
||||||
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/user?t=$currentTimeStamp" \
|
||||||
|
-H 'Accept: */*' \
|
||||||
|
-H "Authorization: Bearer $token" \
|
||||||
|
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \
|
||||||
|
-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
|
||||||
|
)
|
||||||
|
code=$(echo $api | jq -r .code)
|
||||||
|
if [[ $code != 200 ]]; then
|
||||||
|
echo -e "请先登录!"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
update_cron() {
|
update_cron() {
|
||||||
local ids="$1"
|
local ids="$1"
|
||||||
local status="$2"
|
local status="$2"
|
||||||
@@ -139,7 +157,7 @@ update_cron() {
|
|||||||
local runningTime="${6:-0}"
|
local runningTime="${6:-0}"
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/status?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons/status?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
-H "Accept: application/json" \
|
||||||
-H "Authorization: Bearer $token" \
|
-H "Authorization: Bearer $token" \
|
||||||
@@ -154,7 +172,7 @@ update_cron() {
|
|||||||
code=$(echo $api | jq -r .code)
|
code=$(echo $api | jq -r .code)
|
||||||
message=$(echo $api | jq -r .message)
|
message=$(echo $api | jq -r .message)
|
||||||
if [[ $code != 200 ]]; then
|
if [[ $code != 200 ]]; then
|
||||||
echo -e "\n## 更新任务状态失败(${message})\n" >>$dir_log/$log_path
|
echo -e "\n## 更新任务状态失败(${message})\n" >> $log_path
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,7 +181,7 @@ notify_api() {
|
|||||||
local content=$2
|
local content=$2
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/system/notify?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/system/notify?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
-H "Accept: application/json" \
|
||||||
-H "Authorization: Bearer $token" \
|
-H "Authorization: Bearer $token" \
|
||||||
|
|||||||
+2
-1
@@ -35,7 +35,8 @@ fi
|
|||||||
cp -f "$repo_path/jbot/requirements.txt" "$dir_data"
|
cp -f "$repo_path/jbot/requirements.txt" "$dir_data"
|
||||||
|
|
||||||
cd $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
|
if [[ ! $(pip3 show "${LREAD%%=*}" 2>/dev/null) ]]; then
|
||||||
pip3 --default-timeout=100 install ${LREAD}
|
pip3 --default-timeout=100 install ${LREAD}
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ copy_dep() {
|
|||||||
echo -e "---> 2. 复制nginx配置文件\n"
|
echo -e "---> 2. 复制nginx配置文件\n"
|
||||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.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"
|
echo -e "---> 配置文件复制完成\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,10 +88,6 @@ check_pm2() {
|
|||||||
|
|
||||||
main() {
|
main() {
|
||||||
echo -e "=====> 开始检测"
|
echo -e "=====> 开始检测"
|
||||||
npm i -g pnpm
|
|
||||||
pnpm setup &>/dev/null
|
|
||||||
source ~/.bashrc
|
|
||||||
pnpm install -g &>/dev/null
|
|
||||||
pnpm add -g pm2
|
pnpm add -g pm2
|
||||||
copy_dep
|
copy_dep
|
||||||
check_ql
|
check_ql
|
||||||
|
|||||||
-272
@@ -1,272 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
## 导入通用变量与函数
|
|
||||||
dir_shell=$QL_DIR/shell
|
|
||||||
. $dir_shell/share.sh
|
|
||||||
. $dir_shell/api.sh
|
|
||||||
|
|
||||||
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 秒后再执行任务,如需立即终止,请按 CTRL+C...\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() {
|
|
||||||
cpu_use=$(top -b -n 1 | 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 ]] || [[ $mem_free -lt $mem_warn ]] || [[ $disk_use -gt $disk_warn ]]; then
|
|
||||||
local resource=$(top -b -n 1 | 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
|
|
||||||
}
|
|
||||||
|
|
||||||
handle_task_before() {
|
|
||||||
begin_time=$(format_time "$time_format" "$time")
|
|
||||||
begin_timestamp=$(format_timestamp "$time_format" "$time")
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
|
||||||
. $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))
|
|
||||||
|
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
|
||||||
echo -e "\n\n## 执行结束... $end_time 耗时 $diff_time 秒"
|
|
||||||
echo -e "\n "
|
|
||||||
}
|
|
||||||
|
|
||||||
## 正常运行单个脚本,$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.%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"
|
|
||||||
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 "$@"
|
|
||||||
+12
-112
@@ -14,6 +14,7 @@ dir_log=$dir_data/log
|
|||||||
dir_db=$dir_data/db
|
dir_db=$dir_data/db
|
||||||
dir_dep=$dir_data/deps
|
dir_dep=$dir_data/deps
|
||||||
dir_list_tmp=$dir_log/.tmp
|
dir_list_tmp=$dir_log/.tmp
|
||||||
|
dir_code=$dir_log/code
|
||||||
dir_update_log=$dir_log/update
|
dir_update_log=$dir_log/update
|
||||||
ql_static_repo=$dir_repo/static
|
ql_static_repo=$dir_repo/static
|
||||||
|
|
||||||
@@ -24,7 +25,6 @@ file_sharecode=$dir_config/sharecode.sh
|
|||||||
file_config_user=$dir_config/config.sh
|
file_config_user=$dir_config/config.sh
|
||||||
file_auth_sample=$dir_sample/auth.sample.json
|
file_auth_sample=$dir_sample/auth.sample.json
|
||||||
file_auth_user=$dir_config/auth.json
|
file_auth_user=$dir_config/auth.json
|
||||||
file_auth_token=$dir_config/token.json
|
|
||||||
file_extra_shell=$dir_config/extra.sh
|
file_extra_shell=$dir_config/extra.sh
|
||||||
file_task_before=$dir_config/task_before.sh
|
file_task_before=$dir_config/task_before.sh
|
||||||
file_task_after=$dir_config/task_after.sh
|
file_task_after=$dir_config/task_after.sh
|
||||||
@@ -52,10 +52,12 @@ list_own_drop=$dir_list_tmp/own_drop.list
|
|||||||
link_name=(
|
link_name=(
|
||||||
task
|
task
|
||||||
ql
|
ql
|
||||||
|
notify
|
||||||
)
|
)
|
||||||
original_name=(
|
original_name=(
|
||||||
task.sh
|
task.sh
|
||||||
update.sh
|
update.sh
|
||||||
|
notify.sh
|
||||||
)
|
)
|
||||||
|
|
||||||
init_env() {
|
init_env() {
|
||||||
@@ -67,7 +69,6 @@ import_config() {
|
|||||||
[[ -f $file_config_user ]] && . $file_config_user
|
[[ -f $file_config_user ]] && . $file_config_user
|
||||||
[[ -f $file_env ]] && . $file_env
|
[[ -f $file_env ]] && . $file_env
|
||||||
|
|
||||||
ql_base_url=${QlBaseUrl:-""}
|
|
||||||
command_timeout_time=${CommandTimeoutTime:-"1h"}
|
command_timeout_time=${CommandTimeoutTime:-"1h"}
|
||||||
proxy_url=${ProxyUrl:-""}
|
proxy_url=${ProxyUrl:-""}
|
||||||
file_extensions=${RepoFileExtensions:-"js py"}
|
file_extensions=${RepoFileExtensions:-"js py"}
|
||||||
@@ -78,10 +79,6 @@ import_config() {
|
|||||||
else
|
else
|
||||||
default_cron="$(random_range 0 59) $(random_range 0 23) * * *"
|
default_cron="$(random_range 0 59) $(random_range 0 23) * * *"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cpu_warn=${CpuWarn:-80}
|
|
||||||
mem_warn=${MemoryWarn:-80}
|
|
||||||
disk_warn=${DiskWarn:-90}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
set_proxy() {
|
set_proxy() {
|
||||||
@@ -104,7 +101,7 @@ make_dir() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
detect_termux() {
|
detect_termux() {
|
||||||
if [[ $PATH == *com.termux* ]]; then
|
if [[ ${ANDROID_RUNTIME_ROOT}${ANDROID_ROOT} ]] || [[ $PATH == *com.termux* ]]; then
|
||||||
is_termux=1
|
is_termux=1
|
||||||
else
|
else
|
||||||
is_termux=0
|
is_termux=0
|
||||||
@@ -249,13 +246,15 @@ fix_config() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
npm_install_sub() {
|
npm_install_sub() {
|
||||||
|
set_proxy
|
||||||
if [ $is_termux -eq 1 ]; then
|
if [ $is_termux -eq 1 ]; then
|
||||||
npm install --production --no-bin-links
|
npm install --production --no-bin-links --registry=https://registry.npm.taobao.org || npm install --production --no-bin-links
|
||||||
elif ! type pnpm &>/dev/null; then
|
elif ! type pnpm &>/dev/null; then
|
||||||
npm install --production
|
npm install --production --registry=https://registry.npm.taobao.org || npm install --production
|
||||||
else
|
else
|
||||||
pnpm install --loglevel error --production
|
pnpm install --loglevel error --production --registry=https://registry.npm.taobao.org || pnpm install --production --loglevel error
|
||||||
fi
|
fi
|
||||||
|
unset_proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
npm_install_1() {
|
npm_install_1() {
|
||||||
@@ -353,8 +352,8 @@ reset_branch() {
|
|||||||
local branch="$1"
|
local branch="$1"
|
||||||
if [[ $branch ]]; then
|
if [[ $branch ]]; then
|
||||||
part_cmd="origin/${branch}"
|
part_cmd="origin/${branch}"
|
||||||
git checkout -B "$branch" &>/dev/null
|
git checkout -B "$branch"
|
||||||
git branch --set-upstream-to=$part_cmd $branch &>/dev/null
|
git branch --set-upstream-to=$part_cmd $branch
|
||||||
fi
|
fi
|
||||||
git reset --hard $part_cmd &>/dev/null
|
git reset --hard $part_cmd &>/dev/null
|
||||||
}
|
}
|
||||||
@@ -381,109 +380,10 @@ reload_pm2() {
|
|||||||
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
|
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
|
||||||
}
|
}
|
||||||
|
|
||||||
diff_time() {
|
|
||||||
local format="$1"
|
|
||||||
local begin_time="$2"
|
|
||||||
local end_time="$3"
|
|
||||||
|
|
||||||
if [[ $is_macos -eq 1 ]]; then
|
|
||||||
diff_time=$(($(date -j -f "$format" "$end_time" +%s) - $(date -j -f "$format" "$begin_time" +%s)))
|
|
||||||
else
|
|
||||||
diff_time=$(($(date +%s -d "$end_time") - $(date +%s -d "$begin_time")))
|
|
||||||
fi
|
|
||||||
echo "$diff_time"
|
|
||||||
}
|
|
||||||
|
|
||||||
format_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")
|
|
||||||
else
|
|
||||||
echo $(date -d "$time" "+%Y-%m-%d %H:%M:%S")
|
|
||||||
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")
|
|
||||||
else
|
|
||||||
echo $(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
format_timestamp() {
|
|
||||||
local format="$1"
|
|
||||||
local time="$2"
|
|
||||||
|
|
||||||
if [[ $is_macos -eq 1 ]]; then
|
|
||||||
echo $(date -j -f "$format" "$time" "+%s")
|
|
||||||
else
|
|
||||||
echo $(date -d "$time" "+%s")
|
|
||||||
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
|
|
||||||
|
|
||||||
if ! type ts-node &>/dev/null; then
|
|
||||||
pnpm add -g ts-node typescript tslib
|
|
||||||
fi
|
|
||||||
|
|
||||||
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
|
init_env
|
||||||
detect_termux
|
detect_termux
|
||||||
detect_macos
|
detect_macos
|
||||||
define_cmd
|
define_cmd
|
||||||
fix_config
|
fix_config
|
||||||
|
|
||||||
import_config $1 2>$task_error_log_path
|
import_config $1 >$task_error_log_path 2>&1
|
||||||
|
|||||||
+328
-25
@@ -21,19 +21,71 @@ define_program() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
handle_log_path() {
|
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() {
|
||||||
local file_param=$1
|
local file_param=$1
|
||||||
|
define_program "$file_param"
|
||||||
if [[ -z $file_param ]];then
|
if [[ $file_param == *.js ]]; then
|
||||||
file_param="task"
|
if [[ $# -eq 1 ]]; then
|
||||||
|
random_delay
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local suffix=""
|
local time=$(date)
|
||||||
if [[ ! -z $ID ]]; then
|
log_time=$(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||||
suffix="_${ID}"
|
|
||||||
fi
|
|
||||||
time=$(date "+$time_format")
|
|
||||||
log_time=$(format_log_time "$time_format" "$time")
|
|
||||||
log_dir_tmp="${file_param##*/}"
|
log_dir_tmp="${file_param##*/}"
|
||||||
if [[ $file_param =~ "/" ]]; then
|
if [[ $file_param =~ "/" ]]; then
|
||||||
if [[ $file_param == /* ]]; then
|
if [[ $file_param == /* ]]; then
|
||||||
@@ -45,24 +97,249 @@ handle_log_path() {
|
|||||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||||
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_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||||
log_dir="${log_dir_tmp%.*}${suffix}"
|
log_dir="${log_dir_tmp%.*}"
|
||||||
log_path="$log_dir/$log_time.log"
|
log_path="$log_dir/$log_time.log"
|
||||||
cmd=">> $dir_log/$log_path 2>&1"
|
cmd="&>> $dir_log/$log_path"
|
||||||
[[ "$show_log" == "true" ]] && cmd=""
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
make_dir "$dir_log/$log_dir"
|
make_dir "$dir_log/$log_dir"
|
||||||
}
|
|
||||||
|
|
||||||
format_params() {
|
local begin_time=$(date -d "$time" "+%Y-%m-%d %H:%M:%S")
|
||||||
time_format="%Y-%m-%d %H:%M:%S"
|
local begin_timestamp=$(date -d "$time" "+%s")
|
||||||
timeoutCmd=""
|
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||||
if type timeout &>/dev/null; then
|
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||||
timeoutCmd="timeout -k 10s $command_timeout_time "
|
|
||||||
|
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
|
fi
|
||||||
params=$(echo "$@" | sed -E 's/([^ ])&([^ ])/\1\\\&\2/g')
|
eval timeout -k 10s $command_timeout_time $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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
## 并发执行时,设定的 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)
|
||||||
|
log_time=$(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||||
|
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"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(date -d "$time" "+%Y-%m-%d %H:%M:%S")
|
||||||
|
local begin_timestamp=$(date -d "$time" "+%s")
|
||||||
|
|
||||||
|
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"
|
||||||
|
timeout -k 10s $command_timeout_time $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
|
||||||
|
fi
|
||||||
|
|
||||||
|
define_program "$file_param"
|
||||||
|
local time=$(date)
|
||||||
|
log_time=$(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||||
|
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"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(date -d "$time" "+%Y-%m-%d %H:%M:%S")
|
||||||
|
local begin_timestamp=$(date -d "$time" "+%s")
|
||||||
|
|
||||||
|
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 timeout -k 10s $command_timeout_time $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
|
||||||
|
}
|
||||||
|
|
||||||
|
## 运行其他命令
|
||||||
|
run_else() {
|
||||||
|
local file_param="$1"
|
||||||
|
define_program "$file_param"
|
||||||
|
local time=$(date)
|
||||||
|
log_time=$(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||||
|
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"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(date -d "$time" "+%Y-%m-%d %H:%M:%S")
|
||||||
|
local begin_timestamp=$(date -d "$time" "+%s")
|
||||||
|
|
||||||
|
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 timeout -k 10s $command_timeout_time $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"
|
show_log="false"
|
||||||
while getopts ":l" opt; do
|
while getopts ":l" opt
|
||||||
|
do
|
||||||
case $opt in
|
case $opt in
|
||||||
l)
|
l)
|
||||||
show_log="true"
|
show_log="true"
|
||||||
@@ -71,11 +348,37 @@ while getopts ":l" opt; do
|
|||||||
done
|
done
|
||||||
[[ "$show_log" == "true" ]] && shift $(($OPTIND - 1))
|
[[ "$show_log" == "true" ]] && shift $(($OPTIND - 1))
|
||||||
|
|
||||||
format_params "$@"
|
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||||
define_program "$@"
|
case $# in
|
||||||
handle_log_path "$@"
|
1)
|
||||||
|
run_normal "$1"
|
||||||
eval . $dir_shell/otask.sh "$params" "$cmd"
|
;;
|
||||||
|
*)
|
||||||
|
case $2 in
|
||||||
|
now)
|
||||||
|
run_normal "$1" "$2"
|
||||||
|
;;
|
||||||
|
conc)
|
||||||
|
run_concurrent "$1" "$3" "$*"
|
||||||
|
;;
|
||||||
|
desi)
|
||||||
|
run_designated "$1" "$3" "$*"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
run_else "$@"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
esac
|
||||||
[[ -f "$dir_log/$log_path" ]] && cat "$dir_log/$log_path"
|
[[ -f "$dir_log/$log_path" ]] && cat "$dir_log/$log_path"
|
||||||
|
elif [[ $# -eq 0 ]]; then
|
||||||
|
echo
|
||||||
|
usage
|
||||||
|
else
|
||||||
|
run_else "$@"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
|
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
+95
-73
@@ -12,16 +12,14 @@ diff_cron() {
|
|||||||
local list_task="$2"
|
local list_task="$2"
|
||||||
local list_add="$3"
|
local list_add="$3"
|
||||||
local list_drop="$4"
|
local list_drop="$4"
|
||||||
if [[ -s $list_task ]] && [[ -s $list_scripts ]]; then
|
if [[ -s $list_task ]]; then
|
||||||
grep -vwf $list_task $list_scripts >$list_add
|
grep -vwf $list_task $list_scripts >$list_add
|
||||||
grep -vwf $list_scripts $list_task >$list_drop
|
elif [[ ! -s $list_task ]] && [[ -s $list_scripts ]]; then
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -s $list_task ]] && [[ -s $list_scripts ]]; then
|
|
||||||
cp -f $list_scripts $list_add
|
cp -f $list_scripts $list_add
|
||||||
fi
|
fi
|
||||||
|
if [[ -s $list_scripts ]]; then
|
||||||
if [[ ! -s $list_scripts ]] && [[ -s $list_task ]]; then
|
grep -vwf $list_scripts $list_task >$list_drop
|
||||||
|
else
|
||||||
cp -f $list_task $list_drop
|
cp -f $list_task $list_drop
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -230,7 +228,7 @@ run_extra_shell() {
|
|||||||
|
|
||||||
## 脚本用法
|
## 脚本用法
|
||||||
usage() {
|
usage() {
|
||||||
echo -e "ql命令使用方法:"
|
echo -e "本脚本用法:"
|
||||||
echo -e "1. $cmd_update update # 更新并重启青龙"
|
echo -e "1. $cmd_update update # 更新并重启青龙"
|
||||||
echo -e "2. $cmd_update extra # 运行自定义脚本"
|
echo -e "2. $cmd_update extra # 运行自定义脚本"
|
||||||
echo -e "3. $cmd_update raw <fileurl> # 更新单个脚本文件"
|
echo -e "3. $cmd_update raw <fileurl> # 更新单个脚本文件"
|
||||||
@@ -244,10 +242,9 @@ usage() {
|
|||||||
|
|
||||||
## 更新qinglong
|
## 更新qinglong
|
||||||
update_qinglong() {
|
update_qinglong() {
|
||||||
patch_version &>/dev/null
|
patch_version
|
||||||
|
|
||||||
export isFirstStartServer=false
|
|
||||||
|
|
||||||
|
local no_restart="$1"
|
||||||
local all_branch=$(git branch -a)
|
local all_branch=$(git branch -a)
|
||||||
local primary_branch="master"
|
local primary_branch="master"
|
||||||
if [[ "${all_branch}" =~ "${current_branch}" ]]; then
|
if [[ "${all_branch}" =~ "${current_branch}" ]]; then
|
||||||
@@ -265,16 +262,10 @@ update_qinglong() {
|
|||||||
|
|
||||||
[[ -f $dir_root/package.json ]] && ql_depend_new=$(cat $dir_root/package.json)
|
[[ -f $dir_root/package.json ]] && ql_depend_new=$(cat $dir_root/package.json)
|
||||||
[[ "$ql_depend_old" != "$ql_depend_new" ]] && npm_install_2 $dir_root
|
[[ "$ql_depend_old" != "$ql_depend_new" ]] && npm_install_2 $dir_root
|
||||||
|
|
||||||
update_qinglong_static "$1" "$primary_branch"
|
|
||||||
else
|
else
|
||||||
echo -e "\n更新青龙源文件失败,请检查网络...\n"
|
echo -e "\n更新青龙源文件失败,请检查原因...\n"
|
||||||
fi
|
fi
|
||||||
}
|
|
||||||
|
|
||||||
update_qinglong_static() {
|
|
||||||
local no_restart="$1"
|
|
||||||
local primary_branch="$2"
|
|
||||||
local url="https://github.com/whyour/qinglong-static.git"
|
local url="https://github.com/whyour/qinglong-static.git"
|
||||||
if [[ -d ${ql_static_repo}/.git ]]; then
|
if [[ -d ${ql_static_repo}/.git ]]; then
|
||||||
reset_romote_url ${ql_static_repo} ${url} ${primary_branch}
|
reset_romote_url ${ql_static_repo} ${url} ${primary_branch}
|
||||||
@@ -296,8 +287,56 @@ update_qinglong_static() {
|
|||||||
reload_pm2
|
reload_pm2
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
echo -e "\n更新青龙静态资源失败,请检查网络...\n"
|
echo -e "\n更新青龙静态资源失败,请检查原因...\n"
|
||||||
fi
|
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
|
||||||
|
npm i -g pnpm
|
||||||
|
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
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
## 对比脚本
|
## 对比脚本
|
||||||
@@ -348,9 +387,6 @@ gen_list_repo() {
|
|||||||
local index=0
|
local index=0
|
||||||
if [[ $6 ]]; then
|
if [[ $6 ]]; then
|
||||||
file_extensions="$6"
|
file_extensions="$6"
|
||||||
if [[ $file_extensions =~ "|" ]]; then
|
|
||||||
file_extensions=$(echo $file_extensions | sed 's/|/ /g')
|
|
||||||
fi
|
|
||||||
fi
|
fi
|
||||||
for extension in $file_extensions; do
|
for extension in $file_extensions; do
|
||||||
if [[ $index -eq 0 ]]; then
|
if [[ $index -eq 0 ]]; then
|
||||||
@@ -416,7 +452,8 @@ get_uniq_path() {
|
|||||||
main() {
|
main() {
|
||||||
## for ql update
|
## for ql update
|
||||||
show_log="false"
|
show_log="false"
|
||||||
while getopts ":l" opt; do
|
while getopts ":l" opt
|
||||||
|
do
|
||||||
case $opt in
|
case $opt in
|
||||||
l)
|
l)
|
||||||
show_log="true"
|
show_log="true"
|
||||||
@@ -432,95 +469,80 @@ main() {
|
|||||||
local p5=$5
|
local p5=$5
|
||||||
local p6=$6
|
local p6=$6
|
||||||
local p7=$7
|
local p7=$7
|
||||||
local log_dir="${p1}"
|
|
||||||
make_dir "$dir_log/$log_dir"
|
|
||||||
local log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
local log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||||
local log_path="${log_dir}/${log_time}.log"
|
local log_path="$dir_log/update/${log_time}_$p1.log"
|
||||||
local file_path="$dir_log/$log_path"
|
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||||
|
|
||||||
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")
|
|
||||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
|
||||||
|
|
||||||
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
|
case $p1 in
|
||||||
update)
|
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
|
eval update_qinglong "$2" $cmd
|
||||||
;;
|
;;
|
||||||
extra)
|
extra)
|
||||||
eval run_extra_shell $cmd
|
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||||
|
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||||
|
run_extra_shell >>$log_path
|
||||||
;;
|
;;
|
||||||
repo)
|
repo)
|
||||||
|
get_user_info
|
||||||
get_uniq_path "$p2" "$p6"
|
get_uniq_path "$p2" "$p6"
|
||||||
if [[ -n $p2 ]]; then
|
if [[ -n $p2 ]]; then
|
||||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7"
|
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7"
|
||||||
else
|
else
|
||||||
eval echo -e "命令输入错误...\\\n" $cmd
|
echo -e "命令输入错误...\n"
|
||||||
eval usage $cmd
|
usage
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
raw)
|
raw)
|
||||||
|
get_user_info
|
||||||
get_uniq_path "$p2"
|
get_uniq_path "$p2"
|
||||||
if [[ -n $p2 ]]; then
|
if [[ -n $p2 ]]; then
|
||||||
update_raw "$p2"
|
update_raw "$p2"
|
||||||
else
|
else
|
||||||
eval echo -e "命令输入错误...\\\n" $cmd
|
echo -e "命令输入错误...\n"
|
||||||
eval usage $cmd
|
usage
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
rmlog)
|
rmlog)
|
||||||
eval . $dir_shell/rmlog.sh "$p2" $cmd
|
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
|
||||||
;;
|
;;
|
||||||
bot)
|
bot)
|
||||||
eval . $dir_shell/bot.sh $cmd
|
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
|
||||||
;;
|
;;
|
||||||
check)
|
check)
|
||||||
eval . $dir_shell/check.sh $cmd
|
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
|
||||||
;;
|
;;
|
||||||
resetlet)
|
resetlet)
|
||||||
|
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||||
auth_value=$(cat $file_auth_user | jq '.retries =0' -c)
|
auth_value=$(cat $file_auth_user | jq '.retries =0' -c)
|
||||||
|
echo -e "重置登录错误次数成功 \n $auth_value" >>$log_path
|
||||||
echo "$auth_value" >$file_auth_user
|
echo "$auth_value" >$file_auth_user
|
||||||
echo -e "重置登录错误次数成功" $cmd
|
|
||||||
;;
|
;;
|
||||||
resettfa)
|
resettfa)
|
||||||
|
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||||
auth_value=$(cat $file_auth_user | jq '.twoFactorActivated =false' | jq '.twoFactorActived =false' -c)
|
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
|
echo "$auth_value" >$file_auth_user
|
||||||
eval echo -e "禁用两步验证成功" $cmd
|
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
eval echo -e "命令输入错误...\\\n" $cmd
|
echo -e "命令输入错误...\n"
|
||||||
eval usage $cmd
|
usage
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||||
local etime=$(date "+$time_format")
|
local diff_time=$(($(date +%s -d "$end_time") - $(date +%s -d "$begin_time")))
|
||||||
local end_time=$(format_time "$time_format" "$etime")
|
if [[ $p1 != "repo" ]] && [[ $p1 != "raw" ]]; then
|
||||||
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
echo -e "\n## 执行结束... $end_time 耗时 $diff_time 秒" >>$log_path
|
||||||
local diff_time=$(($end_timestamp - $begin_timestamp))
|
cat $log_path
|
||||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
|
||||||
|
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
|
||||||
eval echo -e "\\\n " $cmd
|
|
||||||
|
|
||||||
if [[ -f $file_path ]]; then
|
|
||||||
cat $file_path
|
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ const EditableTagGroup = ({
|
|||||||
{tag}
|
{tag}
|
||||||
</Tag>
|
</Tag>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span key={tag} style={{ display: 'inline-block', marginBottom: 8 }}>
|
<span key={tag} style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||||
{tagElem}
|
{tagElem}
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
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]);
|
|
||||||
};
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
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>()
|
|
||||||
|
|
||||||
useResizeObserver(target, (entry) => {
|
|
||||||
let _targe = entry.target as any
|
|
||||||
if (!_targe.classList.contains('ant-table-wrapper')) {
|
|
||||||
_targe = entry.target.querySelector('.ant-table-wrapper')
|
|
||||||
}
|
|
||||||
setHeight(getTableScroll({ extraHeight, target: _targe as HTMLElement }))
|
|
||||||
})
|
|
||||||
return height
|
|
||||||
}
|
|
||||||
@@ -68,18 +68,18 @@ export default {
|
|||||||
icon: <IconFont type="ql-icon-dependence" />,
|
icon: <IconFont type="ql-icon-dependence" />,
|
||||||
component: '@/pages/dependence/index',
|
component: '@/pages/dependence/index',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: '/log',
|
|
||||||
name: '日志管理',
|
|
||||||
icon: <IconFont type="ql-icon-log" />,
|
|
||||||
component: '@/pages/log/index',
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: '/diff',
|
path: '/diff',
|
||||||
name: '对比工具',
|
name: '对比工具',
|
||||||
icon: <IconFont type="ql-icon-diff" />,
|
icon: <IconFont type="ql-icon-diff" />,
|
||||||
component: '@/pages/diff/index',
|
component: '@/pages/diff/index',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/log',
|
||||||
|
name: '任务日志',
|
||||||
|
icon: <IconFont type="ql-icon-log" />,
|
||||||
|
component: '@/pages/log/index',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/setting',
|
path: '/setting',
|
||||||
name: '系统设置',
|
name: '系统设置',
|
||||||
|
|||||||
+15
-31
@@ -56,13 +56,7 @@
|
|||||||
overflow: auto;
|
overflow: auto;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background-color: @component-background;
|
background-color: @component-background;
|
||||||
padding: 12px;
|
padding: 16px;
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.ql-container-wrapper-has-tab {
|
|
||||||
.ant-pro-grid-content.wide .ant-pro-page-container-children-content {
|
|
||||||
padding-top: 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +136,7 @@
|
|||||||
flex: 1;
|
flex: 1;
|
||||||
|
|
||||||
.ant-pro-grid-content-children {
|
.ant-pro-grid-content-children {
|
||||||
height: 100%;
|
height: calc(100% - 36px);
|
||||||
|
|
||||||
> div,
|
> div,
|
||||||
.log-container,
|
.log-container,
|
||||||
@@ -161,7 +155,7 @@
|
|||||||
&.env-wrapper,
|
&.env-wrapper,
|
||||||
&.config-wrapper {
|
&.config-wrapper {
|
||||||
.CodeMirror {
|
.CodeMirror {
|
||||||
width: calc(100vw - 24px);
|
width: calc(100vw - 80px);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,8 +173,8 @@
|
|||||||
|
|
||||||
.Resizer {
|
.Resizer {
|
||||||
background: @component-background;
|
background: @component-background;
|
||||||
opacity: 0.8;
|
opacity: 0.2;
|
||||||
z-index: 100;
|
z-index: 1;
|
||||||
-moz-box-sizing: border-box;
|
-moz-box-sizing: border-box;
|
||||||
-webkit-box-sizing: border-box;
|
-webkit-box-sizing: border-box;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
@@ -243,6 +237,7 @@
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[data-dark='true'] {
|
||||||
/* Change autocomplete styles in WebKit */
|
/* Change autocomplete styles in WebKit */
|
||||||
input:-webkit-autofill,
|
input:-webkit-autofill,
|
||||||
input:-webkit-autofill:hover,
|
input:-webkit-autofill:hover,
|
||||||
@@ -253,10 +248,11 @@ textarea:-webkit-autofill:focus,
|
|||||||
select:-webkit-autofill,
|
select:-webkit-autofill,
|
||||||
select:-webkit-autofill:hover,
|
select:-webkit-autofill:hover,
|
||||||
select:-webkit-autofill:focus {
|
select:-webkit-autofill:focus {
|
||||||
border: none;
|
border: 1px solid @border-color-base;
|
||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
transition: background-color 5000s ease-in-out 0s;
|
transition: background-color 5000s ease-in-out 0s;
|
||||||
-webkit-text-fill-color: @text-color;
|
-webkit-text-fill-color: @text-color;
|
||||||
|
caret-color: #e8e6f3 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
::placeholder {
|
::placeholder {
|
||||||
@@ -266,25 +262,18 @@ select:-webkit-autofill:focus {
|
|||||||
.ant-select-selection-placeholder {
|
.ant-select-selection-placeholder {
|
||||||
opacity: 0.5 !important;
|
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 {
|
.ant-pro-page-container-children-content {
|
||||||
margin: 0;
|
margin: 18px 18px 18px;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.ant-pro-global-header {
|
.ant-pro-basicLayout-content {
|
||||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.03);
|
margin: 18px;
|
||||||
|
|
||||||
|
.ant-pro-page-container {
|
||||||
|
margin: -18px -18px -18px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.ant-menu-item.ant-pro-sider-collapsed-button {
|
.ant-menu-item.ant-pro-sider-collapsed-button {
|
||||||
@@ -342,8 +331,3 @@ select:-webkit-autofill:focus {
|
|||||||
width: auto !important;
|
width: auto !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pre {
|
|
||||||
word-break: break-all !important;
|
|
||||||
white-space: break-spaces !important;
|
|
||||||
}
|
|
||||||
|
|||||||
+37
-78
@@ -2,7 +2,7 @@ import React, { useEffect, useState, useRef } from 'react';
|
|||||||
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
|
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
|
||||||
import * as DarkReader from '@umijs/ssr-darkreader';
|
import * as DarkReader from '@umijs/ssr-darkreader';
|
||||||
import defaultProps from './defaultProps';
|
import defaultProps from './defaultProps';
|
||||||
import { Link, history, Outlet, useLocation } from '@umijs/max';
|
import { Link, history } from 'umi';
|
||||||
import {
|
import {
|
||||||
LogoutOutlined,
|
LogoutOutlined,
|
||||||
MenuFoldOutlined,
|
MenuFoldOutlined,
|
||||||
@@ -15,56 +15,21 @@ import './index.less';
|
|||||||
import vhCheck from 'vh-check';
|
import vhCheck from 'vh-check';
|
||||||
import { version, changeLogLink, changeLog } from '../version';
|
import { version, changeLogLink, changeLog } from '../version';
|
||||||
import { useCtx, useTheme } from '@/utils/hooks';
|
import { useCtx, useTheme } from '@/utils/hooks';
|
||||||
import {
|
import { message, Badge, Modal, Avatar, Dropdown, Menu, Image } from 'antd';
|
||||||
message,
|
|
||||||
Badge,
|
|
||||||
Modal,
|
|
||||||
Avatar,
|
|
||||||
Dropdown,
|
|
||||||
Menu,
|
|
||||||
Image,
|
|
||||||
Popover,
|
|
||||||
Descriptions,
|
|
||||||
Tooltip,
|
|
||||||
} from 'antd';
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import SockJS from 'sockjs-client';
|
import SockJS from 'sockjs-client';
|
||||||
import * as Sentry from '@sentry/react';
|
import * as Sentry from '@sentry/react';
|
||||||
import { init } from '../utils/init';
|
import { init } from '../utils/init';
|
||||||
import 'codemirror/mode/javascript/javascript';
|
|
||||||
import 'codemirror/mode/python/python';
|
|
||||||
import 'codemirror/mode/shell/shell';
|
|
||||||
|
|
||||||
export interface SharedContext {
|
export default function (props: any) {
|
||||||
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: string;
|
|
||||||
version: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function () {
|
|
||||||
const location = useLocation();
|
|
||||||
const ctx = useCtx();
|
const ctx = useCtx();
|
||||||
const { theme, reloadTheme } = useTheme();
|
const { theme, reloadTheme } = useTheme();
|
||||||
const [user, setUser] = useState<any>({});
|
const [user, setUser] = useState<any>({});
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
const [systemInfo, setSystemInfo] = useState<TSystemInfo>();
|
const [systemInfo, setSystemInfo] = useState<{ isInitialized: boolean }>();
|
||||||
const ws = useRef<any>(null);
|
const ws = useRef<any>(null);
|
||||||
const [socketMessage, setSocketMessage] = useState<any>();
|
const [socketMessage, setSocketMessage] = useState<any>();
|
||||||
const [collapsed, setCollapsed] = useState(false);
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
const [initLoading, setInitLoading] = useState<boolean>(true);
|
|
||||||
const {
|
const {
|
||||||
enable: enableDarkMode,
|
enable: enableDarkMode,
|
||||||
disable: disableDarkMode,
|
disable: disableDarkMode,
|
||||||
@@ -88,15 +53,17 @@ export default function () {
|
|||||||
setSystemInfo(data);
|
setSystemInfo(data);
|
||||||
if (!data.isInitialized) {
|
if (!data.isInitialized) {
|
||||||
history.push('/initialization');
|
history.push('/initialization');
|
||||||
|
setLoading(false);
|
||||||
} else {
|
} else {
|
||||||
getUser();
|
getUser();
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
})
|
});
|
||||||
.finally(() => setInitLoading(false));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getUser = (needLoading = true) => {
|
const getUser = (needLoading = true) => {
|
||||||
@@ -106,9 +73,11 @@ export default function () {
|
|||||||
.then(({ code, data }) => {
|
.then(({ code, data }) => {
|
||||||
if (code === 200 && data.username) {
|
if (code === 200 && data.username) {
|
||||||
setUser(data);
|
setUser(data);
|
||||||
if (location.pathname === '/') {
|
if (props.location.pathname === '/') {
|
||||||
history.push('/crontab');
|
history.push('/crontab');
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
needLoading && setLoading(false);
|
needLoading && setLoading(false);
|
||||||
})
|
})
|
||||||
@@ -125,7 +94,7 @@ export default function () {
|
|||||||
if (systemInfo && systemInfo.isInitialized && !user) {
|
if (systemInfo && systemInfo.isInitialized && !user) {
|
||||||
getUser();
|
getUser();
|
||||||
}
|
}
|
||||||
}, [location.pathname]);
|
}, [props.location.pathname]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!systemInfo) {
|
if (!systemInfo) {
|
||||||
@@ -167,11 +136,9 @@ export default function () {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user || !user.username) return;
|
if (!user) return;
|
||||||
ws.current = new SockJS(
|
ws.current = new SockJS(
|
||||||
`${window.location.origin}/api/ws?token=${localStorage.getItem(
|
`${location.origin}/api/ws?token=${localStorage.getItem(config.authKey)}`,
|
||||||
config.authKey,
|
|
||||||
)}`,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
ws.current.onmessage = (e: any) => {
|
ws.current.onmessage = (e: any) => {
|
||||||
@@ -179,9 +146,9 @@ export default function () {
|
|||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (data.type === 'ping') {
|
if (data.type === 'ping') {
|
||||||
if (data && data.message === 'hanhh') {
|
if (data && data.message === 'hanhh') {
|
||||||
console.log('WS connection succeeded !!!');
|
console.log('websocket连接成功', e);
|
||||||
} else {
|
} else {
|
||||||
console.log('WS connection Failed !!!', e);
|
console.log('websocket连接失败', e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setSocketMessage(data);
|
setSocketMessage(data);
|
||||||
@@ -216,31 +183,30 @@ export default function () {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (initLoading) {
|
if (
|
||||||
return <PageLoading />;
|
['/login', '/initialization', '/error'].includes(props.location.pathname)
|
||||||
}
|
) {
|
||||||
|
|
||||||
if (['/login', '/initialization', '/error'].includes(location.pathname)) {
|
|
||||||
document.title = `${
|
document.title = `${
|
||||||
(config.documentTitleMap as any)[location.pathname]
|
(config.documentTitleMap as any)[props.location.pathname]
|
||||||
} - 控制面板`;
|
} - 控制面板`;
|
||||||
if (systemInfo?.isInitialized && location.pathname === '/initialization') {
|
if (
|
||||||
|
systemInfo?.isInitialized &&
|
||||||
|
props.location.pathname === '/initialization'
|
||||||
|
) {
|
||||||
history.push('/crontab');
|
history.push('/crontab');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (systemInfo || location.pathname === '/error') {
|
if (systemInfo || props.location.pathname === '/error') {
|
||||||
return (
|
return React.Children.map(props.children, (child) => {
|
||||||
<Outlet
|
return React.cloneElement(child, {
|
||||||
context={{
|
|
||||||
...ctx,
|
...ctx,
|
||||||
theme,
|
theme,
|
||||||
user,
|
user,
|
||||||
reloadUser,
|
reloadUser,
|
||||||
reloadTheme,
|
reloadTheme,
|
||||||
ws: ws.current,
|
ws: ws.current,
|
||||||
}}
|
});
|
||||||
/>
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,10 +227,10 @@ export default function () {
|
|||||||
<PageLoading />
|
<PageLoading />
|
||||||
) : (
|
) : (
|
||||||
<ProLayout
|
<ProLayout
|
||||||
selectedKeys={[location.pathname]}
|
selectedKeys={[props.location.pathname]}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
ErrorBoundary={Sentry.ErrorBoundary}
|
ErrorBoundary={Sentry.ErrorBoundary}
|
||||||
logo={<Image preview={false} src="https://qn.whyour.cn/logo.png" />}
|
logo={<Image preview={false} src="http://qn.whyour.cn/logo.png" />}
|
||||||
title={
|
title={
|
||||||
<>
|
<>
|
||||||
<span style={{ fontSize: 16 }}>控制面板</span>
|
<span style={{ fontSize: 16 }}>控制面板</span>
|
||||||
@@ -276,10 +242,6 @@ export default function () {
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Tooltip
|
|
||||||
title={systemInfo?.branch === 'develop' ? '开发版' : '正式版'}
|
|
||||||
>
|
|
||||||
<Badge size="small" dot={systemInfo?.branch === 'develop'}>
|
|
||||||
<span
|
<span
|
||||||
style={{
|
style={{
|
||||||
fontSize: isFirefox ? 9 : 12,
|
fontSize: isFirefox ? 9 : 12,
|
||||||
@@ -291,8 +253,6 @@ export default function () {
|
|||||||
>
|
>
|
||||||
v{version}
|
v{version}
|
||||||
</span>
|
</span>
|
||||||
</Badge>
|
|
||||||
</Tooltip>
|
|
||||||
</a>
|
</a>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
@@ -322,7 +282,7 @@ export default function () {
|
|||||||
shape="square"
|
shape="square"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<UserOutlined />}
|
icon={<UserOutlined />}
|
||||||
src={user.avatar ? `/api/static/${user.avatar}` : ''}
|
src={`/api/static/${user.avatar}`}
|
||||||
/>
|
/>
|
||||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||||
</span>
|
</span>
|
||||||
@@ -344,7 +304,7 @@ export default function () {
|
|||||||
shape="square"
|
shape="square"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<UserOutlined />}
|
icon={<UserOutlined />}
|
||||||
src={user.avatar ? `/api/static/${user.avatar}` : ''}
|
src={`/api/static/${user.avatar}`}
|
||||||
/>
|
/>
|
||||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||||
</span>
|
</span>
|
||||||
@@ -360,17 +320,16 @@ export default function () {
|
|||||||
)}
|
)}
|
||||||
{...defaultProps}
|
{...defaultProps}
|
||||||
>
|
>
|
||||||
<Outlet
|
{React.Children.map(props.children, (child) => {
|
||||||
context={{
|
return React.cloneElement(child, {
|
||||||
...ctx,
|
...ctx,
|
||||||
theme,
|
theme,
|
||||||
user,
|
user,
|
||||||
reloadUser,
|
reloadUser,
|
||||||
reloadTheme,
|
reloadTheme,
|
||||||
socketMessage,
|
socketMessage,
|
||||||
systemInfo,
|
});
|
||||||
}}
|
})}
|
||||||
/>
|
|
||||||
</ProLayout>
|
</ProLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,11 +11,8 @@ import { PageContainer } from '@ant-design/pro-layout';
|
|||||||
import { request } from '@/utils/http';
|
import { request } from '@/utils/http';
|
||||||
import Editor from '@monaco-editor/react';
|
import Editor from '@monaco-editor/react';
|
||||||
import { Controlled as CodeMirror } from 'react-codemirror2';
|
import { Controlled as CodeMirror } from 'react-codemirror2';
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
|
|
||||||
const Config = () => {
|
const Config = ({ headerStyle, isPhone, theme }: any) => {
|
||||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
|
||||||
const [value, setValue] = useState('');
|
const [value, setValue] = useState('');
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [title, setTitle] = useState('config.sh');
|
const [title, setTitle] = useState('config.sh');
|
||||||
@@ -25,10 +22,8 @@ const Config = () => {
|
|||||||
const [confirmLoading, setConfirmLoading] = useState(false);
|
const [confirmLoading, setConfirmLoading] = useState(false);
|
||||||
|
|
||||||
const getConfig = (name: string) => {
|
const getConfig = (name: string) => {
|
||||||
request.get(`${config.apiPrefix}configs/${name}`).then(({ code, data }) => {
|
request.get(`${config.apiPrefix}configs/${name}`).then((data: any) => {
|
||||||
if (code === 200) {
|
setValue(data.data);
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -36,10 +31,8 @@ const Config = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}configs/files`)
|
.get(`${config.apiPrefix}configs/files`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
setData(data.data);
|
||||||
setData(data);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
@@ -54,10 +47,8 @@ const Config = () => {
|
|||||||
.post(`${config.apiPrefix}configs/save`, {
|
.post(`${config.apiPrefix}configs/save`, {
|
||||||
data: { content, name: select },
|
data: { content, name: select },
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
message.success(data.message);
|
||||||
message.success('保存成功');
|
|
||||||
}
|
|
||||||
setConfirmLoading(false);
|
setConfirmLoading(false);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -80,7 +71,6 @@ const Config = () => {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
extra={[
|
extra={[
|
||||||
<TreeSelect
|
<TreeSelect
|
||||||
treeExpandAction="click"
|
|
||||||
className="config-select"
|
className="config-select"
|
||||||
value={select}
|
value={select}
|
||||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ import {
|
|||||||
FileOutlined,
|
FileOutlined,
|
||||||
PlayCircleOutlined,
|
PlayCircleOutlined,
|
||||||
PauseCircleOutlined,
|
PauseCircleOutlined,
|
||||||
FullscreenOutlined,
|
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { CrontabStatus } from './index';
|
import { CrontabStatus } from './index';
|
||||||
import { diffTime } from '@/utils/date';
|
import { diffTime } from '@/utils/date';
|
||||||
@@ -103,10 +102,11 @@ const CronDetailModal = ({
|
|||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
lineNumbersMinChars: 3,
|
lineNumbersMinChars: 3,
|
||||||
fontFamily: 'Source Code Pro',
|
fontFamily: 'Source Code Pro',
|
||||||
|
folding: false,
|
||||||
glyphMargin: false,
|
glyphMargin: false,
|
||||||
wordWrap: 'on',
|
wordWrap: 'on',
|
||||||
}}
|
}}
|
||||||
onMount={(editor, monaco) => {
|
onMount={(editor) => {
|
||||||
editorRef.current = editor;
|
editorRef.current = editor;
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -122,11 +122,9 @@ const CronDetailModal = ({
|
|||||||
.get(
|
.get(
|
||||||
`${config.apiPrefix}logs/${item.filename}?path=${item.directory || ''}`,
|
`${config.apiPrefix}logs/${item.filename}?path=${item.directory || ''}`,
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
setLog(data.data);
|
||||||
setLog(data);
|
|
||||||
setIsLogModalVisible(true);
|
setIsLogModalVisible(true);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -138,9 +136,9 @@ const CronDetailModal = ({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}crons/${cron.id}/logs`)
|
.get(`${config.apiPrefix}crons/${cron.id}/logs`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
setLogs(data);
|
setLogs(data.data);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
@@ -154,22 +152,16 @@ const CronDetailModal = ({
|
|||||||
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
||||||
}
|
}
|
||||||
|
|
||||||
let p: string, s: string;
|
let [p, s] = cmd[1].split('/');
|
||||||
let index = cmd[1].lastIndexOf('/');
|
if (!s) {
|
||||||
if (index >= 0) {
|
s = p;
|
||||||
s = cmd[1].slice(index + 1);
|
|
||||||
p = cmd[1].slice(0, index);
|
|
||||||
} else {
|
|
||||||
s = cmd[1];
|
|
||||||
p = '';
|
p = '';
|
||||||
}
|
}
|
||||||
setScriptInfo({ parent: p, filename: s });
|
setScriptInfo({ parent: p, filename: s });
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}scripts/${s}?path=${p || ''}`)
|
.get(`${config.apiPrefix}scripts/${s}?path=${p || ''}`)
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
setValue(data.data);
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
setValidTabs([validTabs[0]]);
|
setValidTabs([validTabs[0]]);
|
||||||
@@ -201,10 +193,12 @@ const CronDetailModal = ({
|
|||||||
content,
|
content,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((_data: any) => {
|
||||||
if (code === 200) {
|
if (_data.code === 200) {
|
||||||
setValue(content);
|
setValue(content);
|
||||||
message.success(`保存成功`);
|
message.success(`保存成功`);
|
||||||
|
} else {
|
||||||
|
message.error(_data);
|
||||||
}
|
}
|
||||||
resolve(null);
|
resolve(null);
|
||||||
})
|
})
|
||||||
@@ -232,12 +226,14 @@ const CronDetailModal = ({
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}crons/run`, { data: [currentCron.id] })
|
.put(`${config.apiPrefix}crons/run`, { data: [currentCron.id] })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
setCurrentCron({ ...currentCron, status: CrontabStatus.running });
|
setCurrentCron({ ...currentCron, status: CrontabStatus.running });
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
getLogs();
|
getLogs();
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -262,9 +258,11 @@ const CronDetailModal = ({
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}crons/stop`, { data: [currentCron.id] })
|
.put(`${config.apiPrefix}crons/stop`, { data: [currentCron.id] })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
setCurrentCron({ ...currentCron, status: CrontabStatus.idle });
|
setCurrentCron({ ...currentCron, status: CrontabStatus.idle });
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -297,12 +295,14 @@ const CronDetailModal = ({
|
|||||||
data: [currentCron.id],
|
data: [currentCron.id],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
setCurrentCron({
|
setCurrentCron({
|
||||||
...currentCron,
|
...currentCron,
|
||||||
isDisabled: currentCron.isDisabled === 1 ? 0 : 1,
|
isDisabled: currentCron.isDisabled === 1 ? 0 : 1,
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -335,12 +335,14 @@ const CronDetailModal = ({
|
|||||||
data: [currentCron.id],
|
data: [currentCron.id],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
setCurrentCron({
|
setCurrentCron({
|
||||||
...currentCron,
|
...currentCron,
|
||||||
isPinned: currentCron.isPinned === 1 ? 0 : 1,
|
isPinned: currentCron.isPinned === 1 ? 0 : 1,
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -350,11 +352,6 @@ const CronDetailModal = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const fullscreen = () => {
|
|
||||||
const editorElement = editorRef.current._domElement as HTMLElement;
|
|
||||||
editorElement.parentElement?.requestFullscreen();
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (cron && cron.id) {
|
if (cron && cron.id) {
|
||||||
setCurrentCron(cron);
|
setCurrentCron(cron);
|
||||||
@@ -375,7 +372,7 @@ const CronDetailModal = ({
|
|||||||
{currentCron.labels?.length > 0 &&
|
{currentCron.labels?.length > 0 &&
|
||||||
currentCron.labels[0] !== '' &&
|
currentCron.labels[0] !== '' &&
|
||||||
currentCron.labels?.map((label: string, i: number) => (
|
currentCron.labels?.map((label: string, i: number) => (
|
||||||
<Tag key={label} color="blue" style={{ marginRight: 5 }}>
|
<Tag color="blue" style={{ marginRight: 5 }}>
|
||||||
{label}
|
{label}
|
||||||
</Tag>
|
</Tag>
|
||||||
))}
|
))}
|
||||||
@@ -438,7 +435,7 @@ const CronDetailModal = ({
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
centered
|
centered
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
footer={false}
|
footer={false}
|
||||||
onCancel={() => handleCancel()}
|
onCancel={() => handleCancel()}
|
||||||
@@ -532,7 +529,6 @@ const CronDetailModal = ({
|
|||||||
}}
|
}}
|
||||||
tabBarExtraContent={
|
tabBarExtraContent={
|
||||||
activeTabKey === 'script' && (
|
activeTabKey === 'script' && (
|
||||||
<>
|
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
style={{ marginRight: 8 }}
|
style={{ marginRight: 8 }}
|
||||||
@@ -540,12 +536,6 @@ const CronDetailModal = ({
|
|||||||
>
|
>
|
||||||
保存
|
保存
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
icon={<FullscreenOutlined />}
|
|
||||||
onClick={fullscreen}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -2,6 +2,12 @@
|
|||||||
margin-bottom: 0 !important;
|
margin-bottom: 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cron {
|
||||||
|
&:hover {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.crontab-detail {
|
.crontab-detail {
|
||||||
.card-wrapper {
|
.card-wrapper {
|
||||||
height: 80vh;
|
height: 80vh;
|
||||||
@@ -95,84 +101,3 @@
|
|||||||
background: #fafafa;
|
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+107
-275
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { PureComponent, Fragment, useState, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
message,
|
message,
|
||||||
@@ -12,8 +12,6 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
Input,
|
Input,
|
||||||
Popover,
|
Popover,
|
||||||
Tabs,
|
|
||||||
TablePaginationConfig,
|
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import {
|
||||||
ClockCircleOutlined,
|
ClockCircleOutlined,
|
||||||
@@ -29,11 +27,6 @@ import {
|
|||||||
PauseCircleOutlined,
|
PauseCircleOutlined,
|
||||||
FieldTimeOutlined,
|
FieldTimeOutlined,
|
||||||
PushpinOutlined,
|
PushpinOutlined,
|
||||||
DownOutlined,
|
|
||||||
SettingOutlined,
|
|
||||||
PlusOutlined,
|
|
||||||
UnorderedListOutlined,
|
|
||||||
CheckOutlined,
|
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { PageContainer } from '@ant-design/pro-layout';
|
import { PageContainer } from '@ant-design/pro-layout';
|
||||||
@@ -43,13 +36,9 @@ import CronLogModal from './logModal';
|
|||||||
import CronDetailModal from './detail';
|
import CronDetailModal from './detail';
|
||||||
import cron_parser from 'cron-parser';
|
import cron_parser from 'cron-parser';
|
||||||
import { diffTime } from '@/utils/date';
|
import { diffTime } from '@/utils/date';
|
||||||
import { history, useOutletContext } from '@umijs/max';
|
import { getTableScroll } from '@/utils/index';
|
||||||
|
import { history } from 'umi';
|
||||||
import './index.less';
|
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';
|
|
||||||
|
|
||||||
const { Text, Paragraph } = Typography;
|
const { Text, Paragraph } = Typography;
|
||||||
const { Search } = Input;
|
const { Search } = Input;
|
||||||
@@ -81,8 +70,7 @@ enum OperationPath {
|
|||||||
'unpin',
|
'unpin',
|
||||||
}
|
}
|
||||||
|
|
||||||
const Crontab = () => {
|
const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
|
||||||
const columns: any = [
|
const columns: any = [
|
||||||
{
|
{
|
||||||
title: '名称',
|
title: '名称',
|
||||||
@@ -94,11 +82,10 @@ const Crontab = () => {
|
|||||||
<>
|
<>
|
||||||
<a
|
<a
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setDetailCron(record);
|
goToScriptManager(record);
|
||||||
setIsDetailModalVisible(true);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{record.labels?.length > 0 && record.labels[0] !== '' && false ? (
|
{record.labels?.length > 0 && record.labels[0] !== '' ? (
|
||||||
<Popover
|
<Popover
|
||||||
placement="right"
|
placement="right"
|
||||||
trigger={isPhone ? 'click' : 'hover'}
|
trigger={isPhone ? 'click' : 'hover'}
|
||||||
@@ -107,12 +94,10 @@ const Crontab = () => {
|
|||||||
{record.labels?.map((label: string) => (
|
{record.labels?.map((label: string) => (
|
||||||
<Tag
|
<Tag
|
||||||
color="blue"
|
color="blue"
|
||||||
key={label}
|
|
||||||
style={{ cursor: 'point' }}
|
style={{ cursor: 'point' }}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setSearchValue(`label:${label}`);
|
setSearchValue(`label:${label}`);
|
||||||
setSearchText(`label:${label}`);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<a>{label}</a>
|
<a>{label}</a>
|
||||||
@@ -137,14 +122,15 @@ const Crontab = () => {
|
|||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
sorter: {
|
sorter: {
|
||||||
compare: (a: any, b: any) => a?.name?.localeCompare(b?.name),
|
compare: (a: any, b: any) => a.name.localeCompare(b.name),
|
||||||
|
multiple: 2,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '命令',
|
title: '命令',
|
||||||
dataIndex: 'command',
|
dataIndex: 'command',
|
||||||
key: 'command',
|
key: 'command',
|
||||||
width: 300,
|
width: 250,
|
||||||
align: 'center' as const,
|
align: 'center' as const,
|
||||||
render: (text: string, record: any) => {
|
render: (text: string, record: any) => {
|
||||||
return (
|
return (
|
||||||
@@ -155,19 +141,14 @@ const Crontab = () => {
|
|||||||
textAlign: 'left',
|
textAlign: 'left',
|
||||||
}}
|
}}
|
||||||
ellipsis={{ tooltip: text, rows: 2 }}
|
ellipsis={{ tooltip: text, rows: 2 }}
|
||||||
>
|
|
||||||
<a
|
|
||||||
onClick={() => {
|
|
||||||
goToScriptManager(record);
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{text}
|
{text}
|
||||||
</a>
|
|
||||||
</Paragraph>
|
</Paragraph>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
sorter: {
|
sorter: {
|
||||||
compare: (a: any, b: any) => a.command.localeCompare(b.command),
|
compare: (a: any, b: any) => a.command.localeCompare(b.command),
|
||||||
|
multiple: 3,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -178,13 +159,12 @@ const Crontab = () => {
|
|||||||
align: 'center' as const,
|
align: 'center' as const,
|
||||||
sorter: {
|
sorter: {
|
||||||
compare: (a: any, b: any) => a.schedule.localeCompare(b.schedule),
|
compare: (a: any, b: any) => a.schedule.localeCompare(b.schedule),
|
||||||
|
multiple: 1,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '最后运行时间',
|
title: '最后运行时间',
|
||||||
align: 'center' as const,
|
align: 'center' as const,
|
||||||
dataIndex: 'last_execution_time',
|
|
||||||
key: 'last_execution_time',
|
|
||||||
width: 150,
|
width: 150,
|
||||||
sorter: {
|
sorter: {
|
||||||
compare: (a: any, b: any) => {
|
compare: (a: any, b: any) => {
|
||||||
@@ -214,8 +194,6 @@ const Crontab = () => {
|
|||||||
title: '最后运行时长',
|
title: '最后运行时长',
|
||||||
align: 'center' as const,
|
align: 'center' as const,
|
||||||
width: 120,
|
width: 120,
|
||||||
dataIndex: 'last_running_time',
|
|
||||||
key: 'last_running_time',
|
|
||||||
sorter: {
|
sorter: {
|
||||||
compare: (a: any, b: any) => {
|
compare: (a: any, b: any) => {
|
||||||
return a.last_running_time - b.last_running_time;
|
return a.last_running_time - b.last_running_time;
|
||||||
@@ -368,26 +346,12 @@ const Crontab = () => {
|
|||||||
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
||||||
const [logCron, setLogCron] = useState<any>();
|
const [logCron, setLogCron] = useState<any>();
|
||||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||||
const [pageConf, setPageConf] = useState<{
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
page: number;
|
const [pageSize, setPageSize] = useState(20);
|
||||||
size: number;
|
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||||
sorter: any;
|
|
||||||
filters: any;
|
|
||||||
}>({} as any);
|
|
||||||
const [viewConf, setViewConf] = useState<any>();
|
|
||||||
const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
|
const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
|
||||||
const [detailCron, setDetailCron] = useState<any>();
|
const [detailCron, setDetailCron] = useState<any>();
|
||||||
const [searchValue, setSearchValue] = useState('');
|
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 goToScriptManager = (record: any) => {
|
const goToScriptManager = (record: any) => {
|
||||||
const cmd = record.command.split(' ') as string[];
|
const cmd = record.command.split(' ') as string[];
|
||||||
@@ -396,13 +360,9 @@ const Crontab = () => {
|
|||||||
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
||||||
}
|
}
|
||||||
|
|
||||||
let p: string, s: string;
|
let [p, s] = cmd[1].split('/');
|
||||||
let index = cmd[1].lastIndexOf('/');
|
if (!s) {
|
||||||
if (index >= 0) {
|
s = p;
|
||||||
s = cmd[1].slice(index + 1);
|
|
||||||
p = cmd[1].slice(0, index);
|
|
||||||
} else {
|
|
||||||
s = cmd[1];
|
|
||||||
p = '';
|
p = '';
|
||||||
}
|
}
|
||||||
history.push(`/script?p=${p}&s=${s}`);
|
history.push(`/script?p=${p}&s=${s}`);
|
||||||
@@ -413,30 +373,27 @@ const Crontab = () => {
|
|||||||
|
|
||||||
const getCrons = () => {
|
const getCrons = () => {
|
||||||
setLoading(true);
|
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.field) {
|
|
||||||
url += `&sorter=${JSON.stringify({
|
|
||||||
field: sorter.field,
|
|
||||||
type: sorter.order === 'ascend' ? 'ASC' : 'DESC',
|
|
||||||
})}`;
|
|
||||||
}
|
|
||||||
if (viewConf) {
|
|
||||||
url += `&queryString=${JSON.stringify({
|
|
||||||
filters: viewConf.filters,
|
|
||||||
sorts: viewConf.sorts,
|
|
||||||
})}`;
|
|
||||||
}
|
|
||||||
request
|
request
|
||||||
.get(url)
|
.get(`${config.apiPrefix}crons?searchValue=${searchText}`)
|
||||||
.then(({ code, data: _data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
|
||||||
const { data, total } = _data;
|
|
||||||
setValue(
|
setValue(
|
||||||
data.map((x) => {
|
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) => {
|
||||||
return {
|
return {
|
||||||
...x,
|
...x,
|
||||||
nextRunTime: cron_parser
|
nextRunTime: cron_parser
|
||||||
@@ -446,8 +403,7 @@ const Crontab = () => {
|
|||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
setTotal(total);
|
setCurrentPage(1);
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
@@ -477,8 +433,8 @@ const Crontab = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.delete(`${config.apiPrefix}crons`, { data: [record.id] })
|
.delete(`${config.apiPrefix}crons`, { data: [record.id] })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
message.success('删除成功');
|
message.success('删除成功');
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
const i = result.findIndex((x) => x.id === record.id);
|
const i = result.findIndex((x) => x.id === record.id);
|
||||||
@@ -486,6 +442,8 @@ const Crontab = () => {
|
|||||||
result.splice(i, 1);
|
result.splice(i, 1);
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -510,8 +468,8 @@ const Crontab = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}crons/run`, { data: [record.id] })
|
.put(`${config.apiPrefix}crons/run`, { data: [record.id] })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
const i = result.findIndex((x) => x.id === record.id);
|
const i = result.findIndex((x) => x.id === record.id);
|
||||||
if (i !== -1) {
|
if (i !== -1) {
|
||||||
@@ -521,6 +479,8 @@ const Crontab = () => {
|
|||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -545,8 +505,8 @@ const Crontab = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}crons/stop`, { data: [record.id] })
|
.put(`${config.apiPrefix}crons/stop`, { data: [record.id] })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
const i = result.findIndex((x) => x.id === record.id);
|
const i = result.findIndex((x) => x.id === record.id);
|
||||||
if (i !== -1) {
|
if (i !== -1) {
|
||||||
@@ -557,6 +517,8 @@ const Crontab = () => {
|
|||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -582,14 +544,15 @@ const Crontab = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(
|
.put(
|
||||||
`${config.apiPrefix}crons/${record.isDisabled === 1 ? 'enable' : 'disable'
|
`${config.apiPrefix}crons/${
|
||||||
|
record.isDisabled === 1 ? 'enable' : 'disable'
|
||||||
}`,
|
}`,
|
||||||
{
|
{
|
||||||
data: [record.id],
|
data: [record.id],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
const newStatus = record.isDisabled === 1 ? 0 : 1;
|
const newStatus = record.isDisabled === 1 ? 0 : 1;
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
const i = result.findIndex((x) => x.id === record.id);
|
const i = result.findIndex((x) => x.id === record.id);
|
||||||
@@ -600,6 +563,8 @@ const Crontab = () => {
|
|||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -625,14 +590,15 @@ const Crontab = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(
|
.put(
|
||||||
`${config.apiPrefix}crons/${record.isPinned === 1 ? 'unpin' : 'pin'
|
`${config.apiPrefix}crons/${
|
||||||
|
record.isPinned === 1 ? 'unpin' : 'pin'
|
||||||
}`,
|
}`,
|
||||||
{
|
{
|
||||||
data: [record.id],
|
data: [record.id],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
const newStatus = record.isPinned === 1 ? 0 : 1;
|
const newStatus = record.isPinned === 1 ? 0 : 1;
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
const i = result.findIndex((x) => x.id === record.id);
|
const i = result.findIndex((x) => x.id === record.id);
|
||||||
@@ -643,6 +609,8 @@ const Crontab = () => {
|
|||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -744,33 +712,42 @@ const Crontab = () => {
|
|||||||
const getCronDetail = (cron: any) => {
|
const getCronDetail = (cron: any) => {
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}crons/${cron.id}`)
|
.get(`${config.apiPrefix}crons/${cron.id}`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
|
||||||
const index = value.findIndex((x) => x.id === cron.id);
|
const index = value.findIndex((x) => x.id === cron.id);
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
data.nextRunTime = cron_parser
|
data.data.nextRunTime = cron_parser
|
||||||
.parseExpression(data.schedule)
|
.parseExpression(data.data.schedule)
|
||||||
.next()
|
.next()
|
||||||
.toDate();
|
.toDate();
|
||||||
if (index !== -1) {
|
if (index !== -1) {
|
||||||
result.splice(index, 1, {
|
result.splice(index, 1, {
|
||||||
...cron,
|
...cron,
|
||||||
...data,
|
...data.data,
|
||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
const onSelectChange = (selectedIds: any[]) => {
|
const onSelectChange = (selectedIds: any[]) => {
|
||||||
setSelectedRowIds(selectedIds);
|
setSelectedRowIds(selectedIds);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (selectedRowIds.length === 0 || selectedIds.length === 0) {
|
||||||
|
setTableScrollHeight(getTableScroll());
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const rowSelection = {
|
const rowSelection = {
|
||||||
selectedRowKeys: selectedRowIds,
|
selectedRowIds,
|
||||||
onChange: onSelectChange,
|
onChange: onSelectChange,
|
||||||
|
selections: [
|
||||||
|
Table.SELECTION_ALL,
|
||||||
|
Table.SELECTION_INVERT,
|
||||||
|
Table.SELECTION_NONE,
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const delCrons = () => {
|
const delCrons = () => {
|
||||||
@@ -780,11 +757,13 @@ const Crontab = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.delete(`${config.apiPrefix}crons`, { data: selectedRowIds })
|
.delete(`${config.apiPrefix}crons`, { data: selectedRowIds })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
message.success('批量删除成功');
|
message.success('批量删除成功');
|
||||||
setSelectedRowIds([]);
|
setSelectedRowIds([]);
|
||||||
getCrons();
|
getCrons();
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -803,9 +782,11 @@ const Crontab = () => {
|
|||||||
.put(`${config.apiPrefix}crons/${OperationPath[operationStatus]}`, {
|
.put(`${config.apiPrefix}crons/${OperationPath[operationStatus]}`, {
|
||||||
data: selectedRowIds,
|
data: selectedRowIds,
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
getCrons();
|
getCrons();
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -815,19 +796,10 @@ const Crontab = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onPageChange = (
|
const onPageChange = (page: number, pageSize: number | undefined) => {
|
||||||
pagination: TablePaginationConfig,
|
setCurrentPage(page);
|
||||||
filters: Record<string, FilterValue | null>,
|
setPageSize(pageSize as number);
|
||||||
sorter: SorterResult<any> | SorterResult<any>[],
|
localStorage.setItem('pageSize', pageSize + '');
|
||||||
) => {
|
|
||||||
const { current, pageSize } = pagination;
|
|
||||||
setPageConf({
|
|
||||||
page: current as number,
|
|
||||||
size: pageSize as number,
|
|
||||||
sorter,
|
|
||||||
filters,
|
|
||||||
});
|
|
||||||
localStorage.setItem('pageSize', String(pageSize));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getRowClassName = (record: any, index: number) => {
|
const getRowClassName = (record: any, index: number) => {
|
||||||
@@ -842,108 +814,19 @@ const Crontab = () => {
|
|||||||
}, [logCron]);
|
}, [logCron]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPageConf({ ...pageConf, page: 1 });
|
getCrons();
|
||||||
}, [searchText]);
|
}, [searchText]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (pageConf.page && pageConf.size) {
|
setPageSize(parseInt(localStorage.getItem('pageSize') || '20'));
|
||||||
getCrons();
|
setTimeout(() => {
|
||||||
}
|
setTableScrollHeight(getTableScroll());
|
||||||
}, [pageConf, viewConf]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (viewConf && enabledCronViews && enabledCronViews.length > 0) {
|
|
||||||
const view = enabledCronViews.slice(2).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 = (
|
|
||||||
<Menu
|
|
||||||
onClick={({ key, domEvent }) => {
|
|
||||||
domEvent.stopPropagation();
|
|
||||||
viewAction(key);
|
|
||||||
}}
|
|
||||||
items={[
|
|
||||||
...[...enabledCronViews].slice(2).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',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
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([]);
|
|
||||||
setPageConf({ ...pageConf, page: 1 });
|
|
||||||
setViewConf(view ? view : null);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer
|
<PageContainer
|
||||||
className="ql-container-wrapper crontab-wrapper ql-container-wrapper-has-tab"
|
className="ql-container-wrapper crontab-wrapper"
|
||||||
title="定时任务"
|
title="定时任务"
|
||||||
extra={[
|
extra={[
|
||||||
<Search
|
<Search
|
||||||
@@ -964,39 +847,6 @@ const Crontab = () => {
|
|||||||
style: headerStyle,
|
style: headerStyle,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Tabs
|
|
||||||
defaultActiveKey="all"
|
|
||||||
size="small"
|
|
||||||
tabPosition="top"
|
|
||||||
className={`crontab-view ${moreMenuActive ? 'more-active' : ''}`}
|
|
||||||
tabBarExtraContent={
|
|
||||||
<Dropdown
|
|
||||||
overlay={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={[
|
|
||||||
{
|
|
||||||
key: 'all',
|
|
||||||
label: '全部任务',
|
|
||||||
},
|
|
||||||
...[...enabledCronViews].slice(0, 2).map((x) => ({
|
|
||||||
key: x.id,
|
|
||||||
label: x.name,
|
|
||||||
})),
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
<div ref={tableRef}>
|
|
||||||
{selectedRowIds.length > 0 && (
|
{selectedRowIds.length > 0 && (
|
||||||
<div style={{ marginBottom: 16 }}>
|
<div style={{ marginBottom: 16 }}>
|
||||||
<Button type="primary" style={{ marginBottom: 5 }} onClick={delCrons}>
|
<Button type="primary" style={{ marginBottom: 5 }} onClick={delCrons}>
|
||||||
@@ -1056,16 +906,23 @@ const Crontab = () => {
|
|||||||
<Table
|
<Table
|
||||||
columns={columns}
|
columns={columns}
|
||||||
pagination={{
|
pagination={{
|
||||||
current: pageConf.page,
|
current: currentPage,
|
||||||
pageSize: pageConf.size,
|
onChange: onPageChange,
|
||||||
|
pageSize: pageSize,
|
||||||
showSizeChanger: true,
|
showSizeChanger: true,
|
||||||
simple: isPhone,
|
simple: isPhone,
|
||||||
total,
|
defaultPageSize: 20,
|
||||||
showTotal: (total: number, range: number[]) =>
|
showTotal: (total: number, range: number[]) =>
|
||||||
`第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
|
`第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
|
||||||
pageSizeOptions: [10, 20, 50, 100, 200, 500, total || 10000].sort(
|
pageSizeOptions: [20, 100, 500, 1000] as any,
|
||||||
(a, b) => a - b,
|
}}
|
||||||
),
|
onRow={(record) => {
|
||||||
|
return {
|
||||||
|
onClick: (event) => {
|
||||||
|
setDetailCron(record);
|
||||||
|
setIsDetailModalVisible(true);
|
||||||
|
},
|
||||||
|
};
|
||||||
}}
|
}}
|
||||||
dataSource={value}
|
dataSource={value}
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
@@ -1074,9 +931,7 @@ const Crontab = () => {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
rowSelection={rowSelection}
|
rowSelection={rowSelection}
|
||||||
rowClassName={getRowClassName}
|
rowClassName={getRowClassName}
|
||||||
onChange={onPageChange}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
<CronLogModal
|
<CronLogModal
|
||||||
visible={isLogModalVisible}
|
visible={isLogModalVisible}
|
||||||
handleCancel={() => {
|
handleCancel={() => {
|
||||||
@@ -1109,29 +964,6 @@ const Crontab = () => {
|
|||||||
theme={theme}
|
theme={theme}
|
||||||
isPhone={isPhone}
|
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>
|
</PageContainer>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { PageLoading } from '@ant-design/pro-layout';
|
import { PageLoading } from '@ant-design/pro-layout';
|
||||||
import { logEnded } from '@/utils';
|
|
||||||
|
|
||||||
enum CrontabStatus {
|
enum CrontabStatus {
|
||||||
'running',
|
'running',
|
||||||
@@ -42,17 +41,14 @@ const CronLogModal = ({
|
|||||||
}
|
}
|
||||||
request
|
request
|
||||||
.get(logUrl ? logUrl : `${config.apiPrefix}crons/${cron.id}/log`)
|
.get(logUrl ? logUrl : `${config.apiPrefix}crons/${cron.id}/log`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (
|
if (localStorage.getItem('logCron') === String(cron.id)) {
|
||||||
code === 200 &&
|
const log = data.data as string;
|
||||||
localStorage.getItem('logCron') === String(cron.id)
|
|
||||||
) {
|
|
||||||
const log = data as string;
|
|
||||||
setValue(log || '暂无日志');
|
setValue(log || '暂无日志');
|
||||||
setExecuting(
|
setExecuting(
|
||||||
log && !logEnded(log) && !log.includes('重启面板'),
|
log && !log.includes('执行结束') && !log.includes('重启面板'),
|
||||||
);
|
);
|
||||||
if (log && !logEnded(log) && !log.includes('重启面板')) {
|
if (log && !log.includes('执行结束') && !log.includes('重启面板')) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
getCronLog();
|
getCronLog();
|
||||||
}, 2000);
|
}, 2000);
|
||||||
@@ -123,7 +119,7 @@ const CronLogModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={titleElement()}
|
title={titleElement()}
|
||||||
open={visible}
|
visible={visible}
|
||||||
centered
|
centered
|
||||||
className="log-modal"
|
className="log-modal"
|
||||||
bodyStyle={{
|
bodyStyle={{
|
||||||
|
|||||||
@@ -28,12 +28,13 @@ const CronModal = ({
|
|||||||
const { code, data } = await request[method](`${config.apiPrefix}crons`, {
|
const { code, data } = await request[method](`${config.apiPrefix}crons`, {
|
||||||
data: payload,
|
data: payload,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success(cron ? '更新Cron成功' : '新建Cron成功');
|
message.success(cron ? '更新Cron成功' : '新建Cron成功');
|
||||||
handleCancel(data);
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
handleCancel(data);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -46,7 +47,7 @@ const CronModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={cron ? '编辑任务' : '新建任务'}
|
title={cron ? '编辑任务' : '新建任务'}
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
@@ -127,24 +128,21 @@ const CronLabelModal = ({
|
|||||||
.then(async (values) => {
|
.then(async (values) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const payload = { ids, labels: values.labels };
|
const payload = { ids, labels: values.labels };
|
||||||
try {
|
|
||||||
const { code, data } = await request[action](
|
const { code, data } = await request[action](
|
||||||
`${config.apiPrefix}crons/labels`,
|
`${config.apiPrefix}crons/labels`,
|
||||||
{
|
{
|
||||||
data: payload,
|
data: payload,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success(
|
message.success(
|
||||||
action === 'post' ? '添加Labels成功' : '删除Labels成功',
|
action === 'post' ? '添加Labels成功' : '删除Labels成功',
|
||||||
);
|
);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
handleCancel(true);
|
handleCancel(true);
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
} catch (error) {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.catch((info) => {
|
.catch((info) => {
|
||||||
console.log('Validate Failed:', info);
|
console.log('Validate Failed:', info);
|
||||||
@@ -168,7 +166,7 @@ const CronLabelModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="批量修改标签"
|
title="批量修改标签"
|
||||||
open={visible}
|
visible={visible}
|
||||||
footer={buttons}
|
footer={buttons}
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -1,262 +0,0 @@
|
|||||||
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';
|
|
||||||
|
|
||||||
const PROPERTIES = [
|
|
||||||
{ name: '命令', value: 'command' },
|
|
||||||
{ name: '名称', value: 'name' },
|
|
||||||
{ name: '定时规则', value: 'schedule' },
|
|
||||||
{ name: '状态', value: 'status' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const OPERATIONS = [
|
|
||||||
{ name: '包含', value: 'Reg' },
|
|
||||||
{ name: '不包含', value: 'NotReg' },
|
|
||||||
{ name: '属于', value: 'In' },
|
|
||||||
{ name: '不属于', value: 'Nin' },
|
|
||||||
// { name: '等于', value: 'Eq' },
|
|
||||||
// { name: '不等于', value: 'Ne' },
|
|
||||||
// { name: '为空', value: 'IsNull' },
|
|
||||||
// { name: '不为空', value: 'NotNull' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const SORTTYPES = [
|
|
||||||
{ name: '顺序', value: 'ASC' },
|
|
||||||
{ name: '倒序', value: 'DESC' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const STATUS = [
|
|
||||||
{ name: '运行中', value: 0 },
|
|
||||||
{ name: '空闲中', value: 1 },
|
|
||||||
{ name: '已禁用', value: 2 },
|
|
||||||
];
|
|
||||||
|
|
||||||
const ViewCreateModal = ({
|
|
||||||
view,
|
|
||||||
handleCancel,
|
|
||||||
visible,
|
|
||||||
}: {
|
|
||||||
view?: any;
|
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (param?: any) => void;
|
|
||||||
}) => {
|
|
||||||
const [form] = Form.useForm();
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [operationMap, setOperationMap] = useState<any>();
|
|
||||||
|
|
||||||
const handleOk = async (values: any) => {
|
|
||||||
setLoading(true);
|
|
||||||
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: 100 }}
|
|
||||||
onChange={() => {
|
|
||||||
setOperationMap({});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{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 = (
|
|
||||||
<Select mode="multiple" allowClear placeholder="请选择状态">
|
|
||||||
{STATUS.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 }) => (
|
|
||||||
<>
|
|
||||||
{fields.map(({ key, name, ...restField }, index) => (
|
|
||||||
<Form.Item
|
|
||||||
label={index === 0 ? '筛选条件' : ''}
|
|
||||||
key={key}
|
|
||||||
style={{ marginBottom: 0 }}
|
|
||||||
required
|
|
||||||
>
|
|
||||||
<Space className="view-create-modal-filters" align="baseline">
|
|
||||||
<Form.Item
|
|
||||||
{...restField}
|
|
||||||
name={[name, 'property']}
|
|
||||||
rules={[{ required: true }]}
|
|
||||||
>
|
|
||||||
{propertyElement(PROPERTIES, { width: 120 })}
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
{...restField}
|
|
||||||
name={[name, 'operation']}
|
|
||||||
rules={[{ required: true }]}
|
|
||||||
>
|
|
||||||
{operationElement}
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
{...restField}
|
|
||||||
name={[name, 'value']}
|
|
||||||
rules={[{ required: true, message: '请输入内容' }]}
|
|
||||||
>
|
|
||||||
{['In', 'Nin'].includes(
|
|
||||||
form.getFieldValue(['filters', index, 'operation']),
|
|
||||||
) ? (
|
|
||||||
statusElement
|
|
||||||
) : (
|
|
||||||
<Input placeholder="请输入内容" />
|
|
||||||
)}
|
|
||||||
</Form.Item>
|
|
||||||
{index !== 0 && (
|
|
||||||
<MinusCircleOutlined onClick={() => remove(name)} />
|
|
||||||
)}
|
|
||||||
</Space>
|
|
||||||
</Form.Item>
|
|
||||||
))}
|
|
||||||
<Form.Item>
|
|
||||||
<a
|
|
||||||
onClick={() => add({ property: 'command', operation: 'Reg' })}
|
|
||||||
>
|
|
||||||
<PlusOutlined />
|
|
||||||
新增筛选条件
|
|
||||||
</a>
|
|
||||||
</Form.Item>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</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;
|
|
||||||
@@ -1,266 +0,0 @@
|
|||||||
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',
|
|
||||||
align: 'center' as const,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '显示',
|
|
||||||
key: 'isDisabled',
|
|
||||||
dataIndex: 'isDisabled',
|
|
||||||
align: 'center' as const,
|
|
||||||
width: 100,
|
|
||||||
render: (text: string, record: any, index: number) => {
|
|
||||||
return (
|
|
||||||
<Switch
|
|
||||||
checked={!record.isDisabled}
|
|
||||||
onChange={(checked) => onShowChange(checked, record, index)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '操作',
|
|
||||||
key: 'action',
|
|
||||||
width: 140,
|
|
||||||
align: 'center' as const,
|
|
||||||
render: (text: string, record: any, index: number) => {
|
|
||||||
return (
|
|
||||||
<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) => {
|
|
||||||
console.log(checked);
|
|
||||||
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;
|
|
||||||
+80
-101
@@ -27,11 +27,8 @@ import DependenceModal from './modal';
|
|||||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||||
import './index.less';
|
import './index.less';
|
||||||
|
import { getTableScroll } from '@/utils/index';
|
||||||
import DependenceLogModal from './logModal';
|
import DependenceLogModal from './logModal';
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
|
||||||
|
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
const { Search } = Input;
|
const { Search } = Input;
|
||||||
@@ -51,9 +48,7 @@ enum StatusColor {
|
|||||||
'error',
|
'error',
|
||||||
}
|
}
|
||||||
|
|
||||||
const Dependence = () => {
|
const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||||
const { headerStyle, isPhone, socketMessage } =
|
|
||||||
useOutletContext<SharedContext>();
|
|
||||||
const columns: any = [
|
const columns: any = [
|
||||||
{
|
{
|
||||||
title: '序号',
|
title: '序号',
|
||||||
@@ -165,11 +160,10 @@ const Dependence = () => {
|
|||||||
const [editedDependence, setEditedDependence] = useState();
|
const [editedDependence, setEditedDependence] = useState();
|
||||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||||
const [searchText, setSearchText] = useState('');
|
const [searchText, setSearchText] = useState('');
|
||||||
|
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||||
const [logDependence, setLogDependence] = useState<any>();
|
const [logDependence, setLogDependence] = useState<any>();
|
||||||
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
||||||
const [type, setType] = useState('nodejs');
|
const [type, setType] = useState('nodejs');
|
||||||
const tableRef = useRef<any>();
|
|
||||||
const tableScrollHeight = useTableScrollHeight(tableRef, 59)
|
|
||||||
|
|
||||||
const getDependencies = () => {
|
const getDependencies = () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -177,10 +171,8 @@ const Dependence = () => {
|
|||||||
.get(
|
.get(
|
||||||
`${config.apiPrefix}dependencies?searchValue=${searchText}&type=${type}`,
|
`${config.apiPrefix}dependencies?searchValue=${searchText}&type=${type}`,
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
setValue(data.data);
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
@@ -216,8 +208,9 @@ const Dependence = () => {
|
|||||||
.delete(`${config.apiPrefix}dependencies${force ? '/force' : ''}`, {
|
.delete(`${config.apiPrefix}dependencies${force ? '/force' : ''}`, {
|
||||||
data: [record.id],
|
data: [record.id],
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200 && force) {
|
if (data.code === 200) {
|
||||||
|
if (force) {
|
||||||
const i = value.findIndex((x) => x.id === data.data[0].id);
|
const i = value.findIndex((x) => x.id === data.data[0].id);
|
||||||
if (i !== -1) {
|
if (i !== -1) {
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
@@ -225,6 +218,9 @@ const Dependence = () => {
|
|||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onCancel() {
|
onCancel() {
|
||||||
@@ -250,9 +246,11 @@ const Dependence = () => {
|
|||||||
.put(`${config.apiPrefix}dependencies/reinstall`, {
|
.put(`${config.apiPrefix}dependencies/reinstall`, {
|
||||||
data: [record.id],
|
data: [record.id],
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
handleDependence(data[0]);
|
handleDependence(data.data[0]);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -284,10 +282,16 @@ const Dependence = () => {
|
|||||||
|
|
||||||
const onSelectChange = (selectedIds: any[]) => {
|
const onSelectChange = (selectedIds: any[]) => {
|
||||||
setSelectedRowIds(selectedIds);
|
setSelectedRowIds(selectedIds);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (selectedRowIds.length === 0 || selectedIds.length === 0) {
|
||||||
|
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const rowSelection = {
|
const rowSelection = {
|
||||||
selectedRowKeys: selectedRowIds,
|
selectedRowIds,
|
||||||
onChange: onSelectChange,
|
onChange: onSelectChange,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -301,32 +305,12 @@ const Dependence = () => {
|
|||||||
.delete(`${config.apiPrefix}dependencies${forceUrl}`, {
|
.delete(`${config.apiPrefix}dependencies${forceUrl}`, {
|
||||||
data: selectedRowIds,
|
data: selectedRowIds,
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.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([]);
|
setSelectedRowIds([]);
|
||||||
getDependencies();
|
getDependencies();
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -339,18 +323,16 @@ const Dependence = () => {
|
|||||||
const getDependenceDetail = (dependence: any) => {
|
const getDependenceDetail = (dependence: any) => {
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}dependencies/${dependence.id}`)
|
.get(`${config.apiPrefix}dependencies/${dependence.id}`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
|
||||||
const index = value.findIndex((x) => x.id === dependence.id);
|
const index = value.findIndex((x) => x.id === dependence.id);
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
if (index !== -1) {
|
if (index !== -1) {
|
||||||
result.splice(index, 1, {
|
result.splice(index, 1, {
|
||||||
...dependence,
|
...dependence,
|
||||||
...data,
|
...data.data,
|
||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
@@ -363,6 +345,12 @@ const Dependence = () => {
|
|||||||
getDependencies();
|
getDependencies();
|
||||||
}, [searchText, type]);
|
}, [searchText, type]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setTimeout(() => {
|
||||||
|
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (logDependence) {
|
if (logDependence) {
|
||||||
localStorage.setItem('logDependence', logDependence.id);
|
localStorage.setItem('logDependence', logDependence.id);
|
||||||
@@ -411,61 +399,10 @@ const Dependence = () => {
|
|||||||
}
|
}
|
||||||
}, [socketMessage]);
|
}, [socketMessage]);
|
||||||
|
|
||||||
const onTabChange = (activeKey: string) => {
|
const panelContent = () => (
|
||||||
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 && (
|
{selectedRowIds.length > 0 && (
|
||||||
<div style={{ marginBottom: 16 }}>
|
<div style={{ marginBottom: 16 }}>
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
style={{ marginBottom: 5, marginLeft: 8 }}
|
|
||||||
onClick={() => handlereInstallDependencies()}
|
|
||||||
>
|
|
||||||
批量安装
|
|
||||||
</Button>
|
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
style={{ marginBottom: 5, marginLeft: 8 }}
|
style={{ marginBottom: 5, marginLeft: 8 }}
|
||||||
@@ -498,7 +435,49 @@ const Dependence = () => {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
/>
|
/>
|
||||||
</DndProvider>
|
</DndProvider>
|
||||||
</div>
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
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>
|
||||||
<DependenceModal
|
<DependenceModal
|
||||||
visible={isModalVisible}
|
visible={isModalVisible}
|
||||||
handleCancel={handleCancel}
|
handleCancel={handleCancel}
|
||||||
|
|||||||
@@ -48,12 +48,9 @@ const DependenceLogModal = ({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}dependencies/${dependence.id}`)
|
.get(`${config.apiPrefix}dependencies/${dependence.id}`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (
|
if (localStorage.getItem('logDependence') === String(dependence.id)) {
|
||||||
code === 200 &&
|
const log = (data.data.log || []).join('') as string;
|
||||||
localStorage.getItem('logDependence') === String(dependence.id)
|
|
||||||
) {
|
|
||||||
const log = (data.log || []).join('') as string;
|
|
||||||
setValue(log);
|
setValue(log);
|
||||||
setExecuting(!log.includes('结束时间'));
|
setExecuting(!log.includes('结束时间'));
|
||||||
setIsRemoveFailed(log.includes('删除失败'));
|
setIsRemoveFailed(log.includes('删除失败'));
|
||||||
@@ -70,10 +67,8 @@ const DependenceLogModal = ({
|
|||||||
.delete(`${config.apiPrefix}dependencies/force`, {
|
.delete(`${config.apiPrefix}dependencies/force`, {
|
||||||
data: [dependence.id],
|
data: [dependence.id],
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
|
||||||
cancel(true);
|
cancel(true);
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
setRemoveLoading(false);
|
setRemoveLoading(false);
|
||||||
@@ -117,7 +112,7 @@ const DependenceLogModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={titleElement()}
|
title={titleElement()}
|
||||||
open={visible}
|
visible={visible}
|
||||||
centered
|
centered
|
||||||
className="log-modal"
|
className="log-modal"
|
||||||
bodyStyle={{
|
bodyStyle={{
|
||||||
|
|||||||
@@ -52,11 +52,11 @@ const DependenceModal = ({
|
|||||||
data: payload,
|
data: payload,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
if (code !== 200) {
|
||||||
if (code === 200) {
|
message.error(data);
|
||||||
handleCancel(data);
|
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
handleCancel(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -69,7 +69,7 @@ const DependenceModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={dependence ? '编辑依赖' : '新建依赖'}
|
title={dependence ? '编辑依赖' : '新建依赖'}
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
@@ -99,9 +99,7 @@ const DependenceModal = ({
|
|||||||
>
|
>
|
||||||
<Select>
|
<Select>
|
||||||
{config.dependenceTypes.map((x, i) => (
|
{config.dependenceTypes.map((x, i) => (
|
||||||
<Option key={i} value={i}>
|
<Option value={i}>{x}</Option>
|
||||||
{x}
|
|
||||||
</Option>
|
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|||||||
@@ -17,8 +17,4 @@
|
|||||||
.ant-form-item {
|
.ant-form-item {
|
||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
+ section {
|
|
||||||
height: calc(100% - 40px) !important;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-30
@@ -6,13 +6,10 @@ import { request } from '@/utils/http';
|
|||||||
import './index.less';
|
import './index.less';
|
||||||
import { DiffEditor } from '@monaco-editor/react';
|
import { DiffEditor } from '@monaco-editor/react';
|
||||||
import ReactDiffViewer from 'react-diff-viewer';
|
import ReactDiffViewer from 'react-diff-viewer';
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
|
|
||||||
const { Option } = Select;
|
const { Option } = Select;
|
||||||
|
|
||||||
const Diff = () => {
|
const Diff = ({ headerStyle, isPhone, theme }: any) => {
|
||||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
|
||||||
const [origin, setOrigin] = useState('config.sample.sh');
|
const [origin, setOrigin] = useState('config.sample.sh');
|
||||||
const [current, setCurrent] = useState('config.sh');
|
const [current, setCurrent] = useState('config.sh');
|
||||||
const [originValue, setOriginValue] = useState('');
|
const [originValue, setOriginValue] = useState('');
|
||||||
@@ -22,22 +19,14 @@ const Diff = () => {
|
|||||||
const editorRef = useRef<any>(null);
|
const editorRef = useRef<any>(null);
|
||||||
|
|
||||||
const getConfig = () => {
|
const getConfig = () => {
|
||||||
request
|
request.get(`${config.apiPrefix}configs/${current}`).then((data) => {
|
||||||
.get(`${config.apiPrefix}configs/${current}`)
|
setCurrentValue(data.data);
|
||||||
.then(({ code, data }) => {
|
|
||||||
if (code === 200) {
|
|
||||||
setCurrentValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const getSample = () => {
|
const getSample = () => {
|
||||||
request
|
request.get(`${config.apiPrefix}configs/${origin}`).then((data) => {
|
||||||
.get(`${config.apiPrefix}configs/${origin}`)
|
setOriginValue(data.data);
|
||||||
.then(({ code, data }) => {
|
|
||||||
if (code === 200) {
|
|
||||||
setOriginValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -50,10 +39,8 @@ const Diff = () => {
|
|||||||
.post(`${config.apiPrefix}configs/save`, {
|
.post(`${config.apiPrefix}configs/save`, {
|
||||||
data: { content, name: current },
|
data: { content, name: current },
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
message.success(data.message);
|
||||||
message.success('保存成功');
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,10 +48,8 @@ const Diff = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}configs/files`)
|
.get(`${config.apiPrefix}configs/files`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
setFiles(data.data);
|
||||||
setFiles(data);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
@@ -110,9 +95,7 @@ const Diff = () => {
|
|||||||
<Form.Item label="源文件">
|
<Form.Item label="源文件">
|
||||||
<Select value={origin} onChange={originFileChange}>
|
<Select value={origin} onChange={originFileChange}>
|
||||||
{files.map((x) => (
|
{files.map((x) => (
|
||||||
<Option key={x.value} value={x.value}>
|
<Option value={x.value}>{x.title}</Option>
|
||||||
{x.title}
|
|
||||||
</Option>
|
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -121,9 +104,7 @@ const Diff = () => {
|
|||||||
<Form.Item label="当前文件">
|
<Form.Item label="当前文件">
|
||||||
<Select value={current} onChange={currentFileChange}>
|
<Select value={current} onChange={currentFileChange}>
|
||||||
{files.map((x) => (
|
{files.map((x) => (
|
||||||
<Option key={x.value} value={x.value}>
|
<Option value={x.value}>{x.title}</Option>
|
||||||
{x.title}
|
|
||||||
</Option>
|
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|||||||
Vendored
+5
-8
@@ -17,22 +17,19 @@ const EditNameModal = ({
|
|||||||
|
|
||||||
const handleOk = async (values: any) => {
|
const handleOk = async (values: any) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
|
||||||
const { code, data } = await request.put(`${config.apiPrefix}envs/name`, {
|
const { code, data } = await request.put(`${config.apiPrefix}envs/name`, {
|
||||||
data: {
|
data: {
|
||||||
ids,
|
ids,
|
||||||
name: values.name,
|
name: values.name,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success('更新环境变量名称成功');
|
message.success('更新环境变量名称成功');
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
handleCancel();
|
handleCancel();
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
} catch (error) {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,7 +39,7 @@ const EditNameModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="修改环境变量名称"
|
title="修改环境变量名称"
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
Vendored
+41
-81
@@ -9,8 +9,6 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Input,
|
Input,
|
||||||
UploadProps,
|
|
||||||
Upload,
|
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import {
|
||||||
EditOutlined,
|
EditOutlined,
|
||||||
@@ -18,7 +16,6 @@ import {
|
|||||||
SyncOutlined,
|
SyncOutlined,
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
StopOutlined,
|
StopOutlined,
|
||||||
UploadOutlined,
|
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { PageContainer } from '@ant-design/pro-layout';
|
import { PageContainer } from '@ant-design/pro-layout';
|
||||||
@@ -28,10 +25,7 @@ import EditNameModal from './editNameModal';
|
|||||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||||
import './index.less';
|
import './index.less';
|
||||||
import { exportJson } from '@/utils/index';
|
import { getTableScroll } from '@/utils/index';
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
|
||||||
|
|
||||||
const { Text, Paragraph } = Typography;
|
const { Text, Paragraph } = Typography;
|
||||||
const { Search } = Input;
|
const { Search } = Input;
|
||||||
@@ -102,8 +96,7 @@ const DragableBodyRow = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const Env = () => {
|
const Env = ({ headerStyle, isPhone, theme }: any) => {
|
||||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
|
||||||
const columns: any = [
|
const columns: any = [
|
||||||
{
|
{
|
||||||
title: '序号',
|
title: '序号',
|
||||||
@@ -135,7 +128,6 @@ const Env = () => {
|
|||||||
textAlign: 'left',
|
textAlign: 'left',
|
||||||
}}
|
}}
|
||||||
ellipsis={{ tooltip: text, rows: 2 }}
|
ellipsis={{ tooltip: text, rows: 2 }}
|
||||||
copyable
|
|
||||||
>
|
>
|
||||||
{text}
|
{text}
|
||||||
</Paragraph>
|
</Paragraph>
|
||||||
@@ -254,18 +246,14 @@ const Env = () => {
|
|||||||
const [editedEnv, setEditedEnv] = useState();
|
const [editedEnv, setEditedEnv] = useState();
|
||||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||||
const [searchText, setSearchText] = useState('');
|
const [searchText, setSearchText] = useState('');
|
||||||
const [importLoading, setImportLoading] = useState(false);
|
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||||
const tableRef = useRef<any>();
|
|
||||||
const tableScrollHeight = useTableScrollHeight(tableRef, 59)
|
|
||||||
|
|
||||||
const getEnvs = () => {
|
const getEnvs = () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}envs?searchValue=${searchText}`)
|
.get(`${config.apiPrefix}envs?searchValue=${searchText}`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
setValue(data.data);
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
@@ -286,14 +274,15 @@ const Env = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.put(
|
.put(
|
||||||
`${config.apiPrefix}envs/${record.status === Status.已禁用 ? 'enable' : 'disable'
|
`${config.apiPrefix}envs/${
|
||||||
|
record.status === Status.已禁用 ? 'enable' : 'disable'
|
||||||
}`,
|
}`,
|
||||||
{
|
{
|
||||||
data: [record.id],
|
data: [record.id],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
message.success(
|
message.success(
|
||||||
`${record.status === Status.已禁用 ? '启用' : '禁用'}成功`,
|
`${record.status === Status.已禁用 ? '启用' : '禁用'}成功`,
|
||||||
);
|
);
|
||||||
@@ -305,6 +294,8 @@ const Env = () => {
|
|||||||
status: newStatus,
|
status: newStatus,
|
||||||
});
|
});
|
||||||
setValue(result);
|
setValue(result);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -339,12 +330,14 @@ const Env = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.delete(`${config.apiPrefix}envs`, { data: [record.id] })
|
.delete(`${config.apiPrefix}envs`, { data: [record.id] })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
message.success('删除成功');
|
message.success('删除成功');
|
||||||
const result = [...value];
|
const result = [...value];
|
||||||
result.splice(index, 1);
|
result.splice(index, 1);
|
||||||
setValue(result);
|
setValue(result);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -394,12 +387,14 @@ const Env = () => {
|
|||||||
.put(`${config.apiPrefix}envs/${dragRow.id}/move`, {
|
.put(`${config.apiPrefix}envs/${dragRow.id}/move`, {
|
||||||
data: { fromIndex: dragIndex, toIndex: hoverIndex },
|
data: { fromIndex: dragIndex, toIndex: hoverIndex },
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
const newData = [...value];
|
const newData = [...value];
|
||||||
newData.splice(dragIndex, 1);
|
newData.splice(dragIndex, 1);
|
||||||
newData.splice(hoverIndex, 0, { ...dragRow, ...data.data });
|
newData.splice(hoverIndex, 0, { ...dragRow, ...data.data });
|
||||||
setValue([...newData]);
|
setValue([...newData]);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -408,10 +403,16 @@ const Env = () => {
|
|||||||
|
|
||||||
const onSelectChange = (selectedIds: any[]) => {
|
const onSelectChange = (selectedIds: any[]) => {
|
||||||
setSelectedRowIds(selectedIds);
|
setSelectedRowIds(selectedIds);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (selectedRowIds.length === 0 || selectedIds.length === 0) {
|
||||||
|
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const rowSelection = {
|
const rowSelection = {
|
||||||
selectedRowKeys: selectedRowIds,
|
selectedRowIds,
|
||||||
onChange: onSelectChange,
|
onChange: onSelectChange,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -422,11 +423,13 @@ const Env = () => {
|
|||||||
onOk() {
|
onOk() {
|
||||||
request
|
request
|
||||||
.delete(`${config.apiPrefix}envs`, { data: selectedRowIds })
|
.delete(`${config.apiPrefix}envs`, { data: selectedRowIds })
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
message.success('批量删除成功');
|
message.success('批量删除成功');
|
||||||
setSelectedRowIds([]);
|
setSelectedRowIds([]);
|
||||||
getEnvs();
|
getEnvs();
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -445,9 +448,11 @@ const Env = () => {
|
|||||||
.put(`${config.apiPrefix}envs/${OperationPath[operationStatus]}`, {
|
.put(`${config.apiPrefix}envs/${OperationPath[operationStatus]}`, {
|
||||||
data: selectedRowIds,
|
data: selectedRowIds,
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
getEnvs();
|
getEnvs();
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -457,13 +462,6 @@ const Env = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const exportEnvs = () => {
|
|
||||||
const envs = value
|
|
||||||
.filter((x) => selectedRowIds.includes(x.id))
|
|
||||||
.map((x) => ({ value: x.value, name: x.name, remarks: x.remarks }));
|
|
||||||
exportJson('env.json', JSON.stringify(envs));
|
|
||||||
};
|
|
||||||
|
|
||||||
const modifyName = () => {
|
const modifyName = () => {
|
||||||
setIsEditNameModalVisible(true);
|
setIsEditNameModalVisible(true);
|
||||||
};
|
};
|
||||||
@@ -472,37 +470,16 @@ const Env = () => {
|
|||||||
setSearchText(value.trim());
|
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(() => {
|
useEffect(() => {
|
||||||
getEnvs();
|
getEnvs();
|
||||||
}, [searchText]);
|
}, [searchText]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setTimeout(() => {
|
||||||
|
setTableScrollHeight(getTableScroll({ extraHeight: 87 }));
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer
|
<PageContainer
|
||||||
className="ql-container-wrapper env-wrapper"
|
className="ql-container-wrapper env-wrapper"
|
||||||
@@ -515,15 +492,6 @@ const Env = () => {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
onSearch={onSearch}
|
onSearch={onSearch}
|
||||||
/>,
|
/>,
|
||||||
<Upload {...uploadProps}>
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
icon={<UploadOutlined />}
|
|
||||||
loading={importLoading}
|
|
||||||
>
|
|
||||||
导入
|
|
||||||
</Button>
|
|
||||||
</Upload>,
|
|
||||||
<Button key="2" type="primary" onClick={() => addEnv()}>
|
<Button key="2" type="primary" onClick={() => addEnv()}>
|
||||||
新建变量
|
新建变量
|
||||||
</Button>,
|
</Button>,
|
||||||
@@ -548,13 +516,6 @@ const Env = () => {
|
|||||||
>
|
>
|
||||||
批量删除
|
批量删除
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
onClick={() => exportEnvs()}
|
|
||||||
style={{ marginLeft: 8, marginRight: 8 }}
|
|
||||||
>
|
|
||||||
批量导出
|
|
||||||
</Button>
|
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
onClick={() => operateEnvs(0)}
|
onClick={() => operateEnvs(0)}
|
||||||
@@ -577,7 +538,6 @@ const Env = () => {
|
|||||||
)}
|
)}
|
||||||
<DndProvider backend={HTML5Backend}>
|
<DndProvider backend={HTML5Backend}>
|
||||||
<Table
|
<Table
|
||||||
ref={tableRef}
|
|
||||||
columns={columns}
|
columns={columns}
|
||||||
rowSelection={rowSelection}
|
rowSelection={rowSelection}
|
||||||
pagination={false}
|
pagination={false}
|
||||||
@@ -587,7 +547,7 @@ const Env = () => {
|
|||||||
scroll={{ x: 1000, y: tableScrollHeight }}
|
scroll={{ x: 1000, y: tableScrollHeight }}
|
||||||
components={components}
|
components={components}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
onRow={(record: any, index: number | undefined) => {
|
onRow={(record: any, index: number) => {
|
||||||
return {
|
return {
|
||||||
index,
|
index,
|
||||||
moveRow,
|
moveRow,
|
||||||
|
|||||||
Vendored
+4
-3
@@ -40,12 +40,13 @@ const EnvModal = ({
|
|||||||
const { code, data } = await request[method](`${config.apiPrefix}envs`, {
|
const { code, data } = await request[method](`${config.apiPrefix}envs`, {
|
||||||
data: payload,
|
data: payload,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success(env ? '更新变量成功' : '新建变量成功');
|
message.success(env ? '更新变量成功' : '新建变量成功');
|
||||||
handleCancel(data);
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
handleCancel(data);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -58,7 +59,7 @@ const EnvModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={env ? '编辑变量' : '新建变量'}
|
title={env ? '编辑变量' : '新建变量'}
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -3,13 +3,11 @@ import config from '@/utils/config';
|
|||||||
import { request } from '@/utils/http';
|
import { request } from '@/utils/http';
|
||||||
import Terminal, { ColorMode, LineType } from '../../components/terminal';
|
import Terminal, { ColorMode, LineType } from '../../components/terminal';
|
||||||
import { PageLoading } from '@ant-design/pro-layout';
|
import { PageLoading } from '@ant-design/pro-layout';
|
||||||
import { history, useOutletContext } from '@umijs/max';
|
import { history } from 'umi';
|
||||||
import Ansi from 'ansi-to-react';
|
import Ansi from 'ansi-to-react';
|
||||||
import './index.less';
|
import './index.less';
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
|
|
||||||
const Error = () => {
|
const Error = ({ user, theme }: any) => {
|
||||||
const { user, theme } = useOutletContext<SharedContext>();
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [data, setData] = useState('暂无日志');
|
const [data, setData] = useState('暂无日志');
|
||||||
|
|
||||||
@@ -17,10 +15,8 @@ const Error = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}public/panel/log`)
|
.get(`${config.apiPrefix}public/panel/log`)
|
||||||
.then(({ code, data }) => {
|
.then((data: any) => {
|
||||||
if (code === 200) {
|
setData(data.data);
|
||||||
setData(data);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { history } from '@umijs/max';
|
import { history } from 'umi';
|
||||||
import styles from './index.less';
|
import styles from './index.less';
|
||||||
import { request } from '@/utils/http';
|
import { request } from '@/utils/http';
|
||||||
|
|
||||||
@@ -41,9 +41,11 @@ const Initialization = () => {
|
|||||||
password: values.password,
|
password: values.password,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
if (data.code === 200) {
|
||||||
next();
|
next();
|
||||||
|
} else {
|
||||||
|
message.error(data.message);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
@@ -57,9 +59,11 @@ const Initialization = () => {
|
|||||||
...values,
|
...values,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((_data: any) => {
|
||||||
if (code === 200) {
|
if (_data && _data.code === 200) {
|
||||||
next();
|
next();
|
||||||
|
} else {
|
||||||
|
message.error(_data.message);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
@@ -112,15 +116,12 @@ const Initialization = () => {
|
|||||||
{config.notificationModes
|
{config.notificationModes
|
||||||
.filter((x) => x.value !== 'closed')
|
.filter((x) => x.value !== 'closed')
|
||||||
.map((x) => (
|
.map((x) => (
|
||||||
<Option key={x.value} value={x.value}>
|
<Option value={x.value}>{x.label}</Option>
|
||||||
{x.label}
|
|
||||||
</Option>
|
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
{fields.map((x) => (
|
{fields.map((x) => (
|
||||||
<Form.Item
|
<Form.Item
|
||||||
key={x.label}
|
|
||||||
label={x.label}
|
label={x.label}
|
||||||
name={x.label}
|
name={x.label}
|
||||||
extra={x.tip}
|
extra={x.tip}
|
||||||
@@ -232,7 +233,7 @@ const Initialization = () => {
|
|||||||
<img
|
<img
|
||||||
alt="logo"
|
alt="logo"
|
||||||
className={styles.logo}
|
className={styles.logo}
|
||||||
src="https://qn.whyour.cn/logo.png"
|
src="http://qn.whyour.cn/logo.png"
|
||||||
/>
|
/>
|
||||||
<span className={styles.title}>初始化配置</span>
|
<span className={styles.title}>初始化配置</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
position: relative;
|
position: relative;
|
||||||
background-color: @component-background;
|
background-color: @component-background;
|
||||||
height: 100%;
|
height: calc(100vh - 128px);
|
||||||
|
height: calc(100vh - var(--vh-offset, 0px) - 128px);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-145
@@ -1,15 +1,5 @@
|
|||||||
import { useState, useEffect, useCallback, Key, useRef } from 'react';
|
import { useState, useEffect, useCallback, Key, useRef } from 'react';
|
||||||
import {
|
import { TreeSelect, Tree, Input, Empty } from 'antd';
|
||||||
TreeSelect,
|
|
||||||
Tree,
|
|
||||||
Input,
|
|
||||||
Empty,
|
|
||||||
Button,
|
|
||||||
message,
|
|
||||||
Modal,
|
|
||||||
Tooltip,
|
|
||||||
Typography,
|
|
||||||
} from 'antd';
|
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { PageContainer } from '@ant-design/pro-layout';
|
import { PageContainer } from '@ant-design/pro-layout';
|
||||||
import Editor from '@monaco-editor/react';
|
import Editor from '@monaco-editor/react';
|
||||||
@@ -17,64 +7,72 @@ import { request } from '@/utils/http';
|
|||||||
import styles from './index.module.less';
|
import styles from './index.module.less';
|
||||||
import { Controlled as CodeMirror } from 'react-codemirror2';
|
import { Controlled as CodeMirror } from 'react-codemirror2';
|
||||||
import SplitPane from 'react-split-pane';
|
import SplitPane from 'react-split-pane';
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
import { DeleteOutlined } from '@ant-design/icons';
|
|
||||||
import { depthFirstSearch } from '@/utils';
|
|
||||||
import debounce from 'lodash/groupBy';
|
|
||||||
import uniq from 'lodash/uniq';
|
|
||||||
import useFilterTreeData from '@/hooks/useFilterTreeData';
|
|
||||||
|
|
||||||
const { Text } = Typography;
|
function getFilterData(keyword: string, data: any) {
|
||||||
|
const expandedKeys: string[] = [];
|
||||||
|
if (keyword) {
|
||||||
|
const tree: any = [];
|
||||||
|
data.forEach((item: any) => {
|
||||||
|
if (item.title.toLocaleLowerCase().includes(keyword)) {
|
||||||
|
tree.push(item);
|
||||||
|
} else {
|
||||||
|
const children: any[] = [];
|
||||||
|
(item.children || []).forEach((subItem: any) => {
|
||||||
|
if (subItem.title.toLocaleLowerCase().includes(keyword)) {
|
||||||
|
children.push(subItem);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (children.length > 0) {
|
||||||
|
tree.push({
|
||||||
|
...item,
|
||||||
|
children,
|
||||||
|
});
|
||||||
|
expandedKeys.push(item.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { tree, expandedKeys };
|
||||||
|
}
|
||||||
|
return { tree: data, expandedKeys };
|
||||||
|
}
|
||||||
|
|
||||||
const Log = () => {
|
const Log = ({ headerStyle, isPhone, theme }: any) => {
|
||||||
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
|
const [title, setTitle] = useState('请选择日志文件');
|
||||||
const [value, setValue] = useState('请选择日志文件');
|
const [value, setValue] = useState('请选择日志文件');
|
||||||
const [select, setSelect] = useState<string>('');
|
const [select, setSelect] = useState<any>();
|
||||||
const [data, setData] = useState<any[]>([]);
|
const [data, setData] = useState<any[]>([]);
|
||||||
|
const [filterData, setFilterData] = useState<any[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [height, setHeight] = useState<number>();
|
const [height, setHeight] = useState<number>();
|
||||||
const treeDom = useRef<any>();
|
const treeDom = useRef<any>();
|
||||||
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
|
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
|
||||||
const [currentNode, setCurrentNode] = useState<any>();
|
|
||||||
const [searchValue, setSearchValue] = useState('');
|
|
||||||
|
|
||||||
const getLogs = () => {
|
const getLogs = () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}logs`)
|
.get(`${config.apiPrefix}logs`)
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
setData(data.data);
|
||||||
setData(data);
|
setFilterData(data.data);
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLog = (node: any) => {
|
const getLog = (node: any) => {
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}logs/${node.title}?path=${node.parent || ''}`)
|
.get(`${config.apiPrefix}logs/${node.value}?path=${node.parent || ''}`)
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
setValue(data.data);
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onSelect = (value: any, node: any) => {
|
const onSelect = (value: any, node: any) => {
|
||||||
setCurrentNode(node);
|
|
||||||
setSelect(value);
|
|
||||||
|
|
||||||
if (node.key === select || !value) {
|
if (node.key === select || !value) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.type === 'directory') {
|
|
||||||
setValue('请选择日志文件');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setValue('加载中...');
|
setValue('加载中...');
|
||||||
|
setSelect(value);
|
||||||
|
setTitle(node.key);
|
||||||
getLog(node);
|
getLog(node);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -85,130 +83,40 @@ const Log = () => {
|
|||||||
const onSearch = useCallback(
|
const onSearch = useCallback(
|
||||||
(e) => {
|
(e) => {
|
||||||
const keyword = e.target.value;
|
const keyword = e.target.value;
|
||||||
debounceSearch(keyword);
|
const { tree, expandedKeys } = getFilterData(
|
||||||
},
|
keyword.toLocaleLowerCase(),
|
||||||
[data],
|
|
||||||
);
|
|
||||||
|
|
||||||
const debounceSearch = useCallback(
|
|
||||||
debounce((keyword) => {
|
|
||||||
setSearchValue(keyword);
|
|
||||||
}, 300),
|
|
||||||
[data],
|
|
||||||
);
|
|
||||||
|
|
||||||
const { treeData: filterData, keys: searchExpandedKeys } = useFilterTreeData(
|
|
||||||
data,
|
data,
|
||||||
searchValue,
|
|
||||||
{ treeNodeFilterProp: 'title' },
|
|
||||||
);
|
);
|
||||||
|
setFilterData(tree);
|
||||||
useEffect(() => {
|
setExpandedKeys(expandedKeys);
|
||||||
setExpandedKeys(uniq([...expandedKeys, ...searchExpandedKeys]));
|
|
||||||
}, [searchExpandedKeys]);
|
|
||||||
|
|
||||||
const deleteFile = () => {
|
|
||||||
Modal.confirm({
|
|
||||||
title: `确认删除`,
|
|
||||||
content: (
|
|
||||||
<>
|
|
||||||
确认删除
|
|
||||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
|
||||||
{select}
|
|
||||||
</Text>
|
|
||||||
文件{currentNode.type === 'directory' ? '夹下所以日志' : ''}
|
|
||||||
,删除后不可恢复
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
onOk() {
|
|
||||||
request
|
|
||||||
.delete(`${config.apiPrefix}logs`, {
|
|
||||||
data: {
|
|
||||||
filename: currentNode.title,
|
|
||||||
path: currentNode.parent || '',
|
|
||||||
type: currentNode.type,
|
|
||||||
},
|
},
|
||||||
})
|
[data, setFilterData],
|
||||||
.then(({ code }) => {
|
|
||||||
if (code === 200) {
|
|
||||||
message.success(`删除成功`);
|
|
||||||
let newData = [...data];
|
|
||||||
if (currentNode.parent) {
|
|
||||||
newData = depthFirstSearch(
|
|
||||||
newData,
|
|
||||||
(c) => c.key === currentNode.key,
|
|
||||||
);
|
);
|
||||||
} else {
|
|
||||||
const index = newData.findIndex(
|
|
||||||
(x) => x.key === currentNode.key,
|
|
||||||
);
|
|
||||||
if (index !== -1) {
|
|
||||||
newData.splice(index, 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setData(newData);
|
|
||||||
initState();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onCancel() {
|
|
||||||
console.log('Cancel');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const initState = () => {
|
|
||||||
setSelect('');
|
|
||||||
setCurrentNode(null);
|
|
||||||
setValue('请选择脚本文件');
|
|
||||||
};
|
|
||||||
|
|
||||||
const onExpand = (expKeys: any) => {
|
|
||||||
setExpandedKeys(expKeys);
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getLogs();
|
getLogs();
|
||||||
}, []);
|
if (treeDom && treeDom.current) {
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (treeDom.current) {
|
|
||||||
setHeight(treeDom.current.clientHeight);
|
setHeight(treeDom.current.clientHeight);
|
||||||
}
|
}
|
||||||
}, [treeDom.current, data]);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer
|
<PageContainer
|
||||||
className="ql-container-wrapper log-wrapper"
|
className="ql-container-wrapper log-wrapper"
|
||||||
title={select}
|
title={title}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
extra={
|
extra={
|
||||||
isPhone
|
isPhone && [
|
||||||
? [
|
|
||||||
<TreeSelect
|
<TreeSelect
|
||||||
treeExpandAction="click"
|
|
||||||
className="log-select"
|
className="log-select"
|
||||||
value={select}
|
value={select}
|
||||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||||
treeData={data}
|
treeData={data}
|
||||||
placeholder="请选择日志"
|
placeholder="请选择日志"
|
||||||
fieldNames={{ value: 'key' }}
|
|
||||||
treeNodeFilterProp="title"
|
|
||||||
showSearch
|
showSearch
|
||||||
allowClear
|
|
||||||
onSelect={onSelect}
|
onSelect={onSelect}
|
||||||
/>,
|
/>,
|
||||||
]
|
]
|
||||||
: [
|
|
||||||
<Tooltip title="删除">
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
disabled={!select}
|
|
||||||
onClick={deleteFile}
|
|
||||||
icon={<DeleteOutlined />}
|
|
||||||
/>
|
|
||||||
</Tooltip>,
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
header={{
|
header={{
|
||||||
style: headerStyle,
|
style: headerStyle,
|
||||||
@@ -216,7 +124,6 @@ const Log = () => {
|
|||||||
>
|
>
|
||||||
<div className={`${styles['log-container']} log-container`}>
|
<div className={`${styles['log-container']} log-container`}>
|
||||||
{!isPhone && (
|
{!isPhone && (
|
||||||
/*// @ts-ignore*/
|
|
||||||
<SplitPane split="vertical" size={200} maxSize={-100}>
|
<SplitPane split="vertical" size={200} maxSize={-100}>
|
||||||
<div className={styles['left-tree-container']}>
|
<div className={styles['left-tree-container']}>
|
||||||
{data.length > 0 ? (
|
{data.length > 0 ? (
|
||||||
@@ -229,7 +136,6 @@ const Log = () => {
|
|||||||
></Input.Search>
|
></Input.Search>
|
||||||
<div className={styles['left-tree-scroller']} ref={treeDom}>
|
<div className={styles['left-tree-scroller']} ref={treeDom}>
|
||||||
<Tree
|
<Tree
|
||||||
expandAction="click"
|
|
||||||
className={styles['left-tree']}
|
className={styles['left-tree']}
|
||||||
treeData={filterData}
|
treeData={filterData}
|
||||||
showIcon={true}
|
showIcon={true}
|
||||||
@@ -237,8 +143,6 @@ const Log = () => {
|
|||||||
selectedKeys={[select]}
|
selectedKeys={[select]}
|
||||||
showLine={{ showLeafIcon: true }}
|
showLine={{ showLeafIcon: true }}
|
||||||
onSelect={onTreeSelect}
|
onSelect={onTreeSelect}
|
||||||
expandedKeys={expandedKeys}
|
|
||||||
onExpand={onExpand}
|
|
||||||
></Tree>
|
></Tree>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
+26
-21
@@ -9,18 +9,16 @@ import {
|
|||||||
Statistic,
|
Statistic,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { history, useOutletContext } from '@umijs/max';
|
import { history, Link } from 'umi';
|
||||||
import styles from './index.less';
|
import styles from './index.less';
|
||||||
import { request } from '@/utils/http';
|
import { request } from '@/utils/http';
|
||||||
import { useTheme } from '@/utils/hooks';
|
import { useTheme } from '@/utils/hooks';
|
||||||
import { MobileOutlined } from '@ant-design/icons';
|
import { MobileOutlined } from '@ant-design/icons';
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
|
|
||||||
const FormItem = Form.Item;
|
const FormItem = Form.Item;
|
||||||
const { Countdown } = Statistic;
|
const { Countdown } = Statistic;
|
||||||
|
|
||||||
const Login = () => {
|
const Login = ({ reloadUser }: any) => {
|
||||||
const { reloadUser } = useOutletContext<SharedContext>();
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [waitTime, setWaitTime] = useState<any>();
|
const [waitTime, setWaitTime] = useState<any>();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
@@ -40,7 +38,15 @@ const Login = () => {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
checkResponse(data, values);
|
if (data.code === 420) {
|
||||||
|
setLoginInfo({
|
||||||
|
username: values.username,
|
||||||
|
password: values.password,
|
||||||
|
});
|
||||||
|
setTwoFactor(true);
|
||||||
|
} else {
|
||||||
|
checkResponse(data);
|
||||||
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
@@ -56,7 +62,11 @@ const Login = () => {
|
|||||||
data: { ...loginInfo, code: values.code },
|
data: { ...loginInfo, code: values.code },
|
||||||
})
|
})
|
||||||
.then((data: any) => {
|
.then((data: any) => {
|
||||||
|
if (data.code === 430) {
|
||||||
|
message.error(data.message);
|
||||||
|
} else {
|
||||||
checkResponse(data);
|
checkResponse(data);
|
||||||
|
}
|
||||||
setVerifying(false);
|
setVerifying(false);
|
||||||
})
|
})
|
||||||
.catch((error: any) => {
|
.catch((error: any) => {
|
||||||
@@ -65,11 +75,8 @@ const Login = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const checkResponse = (
|
const checkResponse = (data: any) => {
|
||||||
{ code, data, message: _message }: any,
|
if (data.code === 200) {
|
||||||
values?: any,
|
|
||||||
) => {
|
|
||||||
if (code === 200) {
|
|
||||||
const {
|
const {
|
||||||
token,
|
token,
|
||||||
lastip,
|
lastip,
|
||||||
@@ -77,7 +84,7 @@ const Login = () => {
|
|||||||
lastlogon,
|
lastlogon,
|
||||||
retries = 0,
|
retries = 0,
|
||||||
platform,
|
platform,
|
||||||
} = data;
|
} = data.data;
|
||||||
localStorage.setItem(config.authKey, token);
|
localStorage.setItem(config.authKey, token);
|
||||||
notification.success({
|
notification.success({
|
||||||
message: '登录成功!',
|
message: '登录成功!',
|
||||||
@@ -96,14 +103,13 @@ const Login = () => {
|
|||||||
});
|
});
|
||||||
reloadUser(true);
|
reloadUser(true);
|
||||||
history.push('/crontab');
|
history.push('/crontab');
|
||||||
} else if (code === 410) {
|
} else if (data.code === 100) {
|
||||||
setWaitTime(data);
|
message.warn(data.message);
|
||||||
} else if (code === 420) {
|
} else if (data.code === 410) {
|
||||||
setLoginInfo({
|
message.error(data.message);
|
||||||
username: values.username,
|
setWaitTime(data.data);
|
||||||
password: values.password,
|
} else {
|
||||||
});
|
message.error(data.message);
|
||||||
setTwoFactor(true);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -129,7 +135,7 @@ const Login = () => {
|
|||||||
<img
|
<img
|
||||||
alt="logo"
|
alt="logo"
|
||||||
className={styles.logo}
|
className={styles.logo}
|
||||||
src="https://qn.whyour.cn/logo.png"
|
src="http://qn.whyour.cn/logo.png"
|
||||||
/>
|
/>
|
||||||
<span className={styles.title}>
|
<span className={styles.title}>
|
||||||
{twoFactor ? '两步验证' : config.siteName}
|
{twoFactor ? '两步验证' : config.siteName}
|
||||||
@@ -148,7 +154,6 @@ const Login = () => {
|
|||||||
message: '验证码为6位数字',
|
message: '验证码为6位数字',
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
validateTrigger="onBlur"
|
|
||||||
>
|
>
|
||||||
<Input
|
<Input
|
||||||
placeholder="6位数字"
|
placeholder="6位数字"
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import Editor from '@monaco-editor/react';
|
|||||||
import SaveModal from './saveModal';
|
import SaveModal from './saveModal';
|
||||||
import SettingModal from './setting';
|
import SettingModal from './setting';
|
||||||
import { useTheme } from '@/utils/hooks';
|
import { useTheme } from '@/utils/hooks';
|
||||||
import { logEnded } from '@/utils';
|
|
||||||
|
|
||||||
const { Option } = Select;
|
const { Option } = Select;
|
||||||
const LangMap: any = {
|
const LangMap: any = {
|
||||||
@@ -58,11 +57,6 @@ const EditModal = ({
|
|||||||
if (node.key === selectedKey || !value) {
|
if (node.key === selectedKey || !value) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.type === 'directory') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newMode = LangMap[value.slice(-3)] || '';
|
const newMode = LangMap[value.slice(-3)] || '';
|
||||||
setCNode(node);
|
setCNode(node);
|
||||||
setLanguage(newMode);
|
setLanguage(newMode);
|
||||||
@@ -72,49 +66,39 @@ const EditModal = ({
|
|||||||
|
|
||||||
const getDetail = (node: any) => {
|
const getDetail = (node: any) => {
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}scripts/${node.title}?path=${node.parent || ''}`)
|
.get(`${config.apiPrefix}scripts/${node.value}?path=${node.parent || ''}`)
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
setValue(data.data);
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const run = () => {
|
const run = () => {
|
||||||
setLog('');
|
setLog('');
|
||||||
const content = editorRef.current.getValue().replace(/\r\n/g, '\n');
|
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}scripts/run`, {
|
.put(`${config.apiPrefix}scripts/run`, {
|
||||||
data: {
|
data: {
|
||||||
filename: cNode.title,
|
filename: cNode.value,
|
||||||
path: cNode.parent || '',
|
path: cNode.parent || '',
|
||||||
content,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
|
||||||
setIsRunning(true);
|
setIsRunning(true);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const stop = () => {
|
const stop = () => {
|
||||||
if (!cNode || !cNode.title) {
|
if (!cNode || !cNode.value) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const content = editorRef.current.getValue().replace(/\r\n/g, '\n');
|
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}scripts/stop`, {
|
.put(`${config.apiPrefix}scripts/stop`, {
|
||||||
data: {
|
data: {
|
||||||
filename: cNode.title,
|
filename: cNode.value,
|
||||||
path: cNode.parent || '',
|
path: cNode.parent || '',
|
||||||
content,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
|
||||||
setIsRunning(false);
|
setIsRunning(false);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -129,7 +113,8 @@ const EditModal = ({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (logEnded(_message)) {
|
if (_message === '执行结束') {
|
||||||
|
_message = '';
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setIsRunning(false);
|
setIsRunning(false);
|
||||||
}, 300);
|
}, 300);
|
||||||
@@ -142,13 +127,10 @@ const EditModal = ({
|
|||||||
}, [socketMessage]);
|
}, [socketMessage]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setLog('');
|
|
||||||
if (currentNode) {
|
if (currentNode) {
|
||||||
setCNode(currentNode);
|
setCNode(currentNode);
|
||||||
setValue(content as string);
|
setValue(content as string);
|
||||||
setSelectedKey(currentNode.key);
|
setSelectedKey(currentNode.key);
|
||||||
const newMode = LangMap[currentNode.title.slice(-3)] || '';
|
|
||||||
setLanguage(newMode);
|
|
||||||
}
|
}
|
||||||
}, [content, currentNode]);
|
}, [content, currentNode]);
|
||||||
|
|
||||||
@@ -159,13 +141,11 @@ const EditModal = ({
|
|||||||
title={
|
title={
|
||||||
<>
|
<>
|
||||||
<TreeSelect
|
<TreeSelect
|
||||||
treeExpandAction="click"
|
|
||||||
style={{ marginRight: 8, width: 150 }}
|
style={{ marginRight: 8, width: 150 }}
|
||||||
value={selectedKey}
|
value={selectedKey}
|
||||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||||
treeData={treeData}
|
treeData={treeData}
|
||||||
placeholder="请选择脚本文件"
|
placeholder="请选择脚本文件"
|
||||||
fieldNames={{ value: 'key', label: 'title' }}
|
|
||||||
showSearch
|
showSearch
|
||||||
onSelect={onSelect}
|
onSelect={onSelect}
|
||||||
/>
|
/>
|
||||||
@@ -230,9 +210,8 @@ const EditModal = ({
|
|||||||
width={'100%'}
|
width={'100%'}
|
||||||
headerStyle={{ padding: '11px 24px' }}
|
headerStyle={{ padding: '11px 24px' }}
|
||||||
onClose={cancel}
|
onClose={cancel}
|
||||||
open={visible}
|
visible={visible}
|
||||||
>
|
>
|
||||||
{/* @ts-ignore */}
|
|
||||||
<SplitPane
|
<SplitPane
|
||||||
split="vertical"
|
split="vertical"
|
||||||
minSize={200}
|
minSize={200}
|
||||||
@@ -253,14 +232,7 @@ const EditModal = ({
|
|||||||
editorRef.current = editor;
|
editorRef.current = editor;
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<pre
|
<pre style={{ height: '100%', whiteSpace: 'break-spaces' }}>{log}</pre>
|
||||||
style={{
|
|
||||||
height: '100%',
|
|
||||||
padding: '0 15px',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{log}
|
|
||||||
</pre>
|
|
||||||
</SplitPane>
|
</SplitPane>
|
||||||
<SaveModal
|
<SaveModal
|
||||||
visible={saveModalVisible}
|
visible={saveModalVisible}
|
||||||
@@ -271,7 +243,7 @@ const EditModal = ({
|
|||||||
content:
|
content:
|
||||||
editorRef.current &&
|
editorRef.current &&
|
||||||
editorRef.current.getValue().replace(/\r\n/g, '\n'),
|
editorRef.current.getValue().replace(/\r\n/g, '\n'),
|
||||||
filename: cNode?.title,
|
filename: cNode?.value,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<SettingModal
|
<SettingModal
|
||||||
|
|||||||
@@ -1,17 +1,7 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import {
|
import { Modal, message, Input, Form, Select } from 'antd';
|
||||||
Modal,
|
|
||||||
message,
|
|
||||||
Input,
|
|
||||||
Form,
|
|
||||||
Select,
|
|
||||||
Upload,
|
|
||||||
Radio,
|
|
||||||
TreeSelect,
|
|
||||||
} from 'antd';
|
|
||||||
import { request } from '@/utils/http';
|
import { request } from '@/utils/http';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { UploadOutlined } from '@ant-design/icons';
|
|
||||||
|
|
||||||
const { Option } = Select;
|
const { Option } = Select;
|
||||||
|
|
||||||
@@ -31,75 +21,40 @@ const EditScriptNameModal = ({
|
|||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [dirs, setDirs] = useState<any[]>([]);
|
const [dirs, setDirs] = useState<any[]>([]);
|
||||||
const [file, setFile] = useState<File>();
|
|
||||||
const [type, setType] = useState<'blank' | 'upload' | 'directory'>('blank');
|
|
||||||
|
|
||||||
const handleOk = async (values: any) => {
|
const handleOk = async (values: any) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const { path = '', filename: inputFilename, directory = '' } = values;
|
values.path = values.path || '';
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('file', file as any);
|
|
||||||
formData.append('filename', inputFilename);
|
|
||||||
formData.append('path', path);
|
|
||||||
formData.append('content', '');
|
|
||||||
formData.append('directory', directory);
|
|
||||||
request
|
request
|
||||||
.post(`${config.apiPrefix}scripts`, {
|
.post(`${config.apiPrefix}scripts`, {
|
||||||
data: formData,
|
data: { filename: values.filename, path: values.path, content: '' },
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then(({ code, data }) => {
|
||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success(directory ? '新建文件夹成功' : '新建文件成功');
|
message.success('保存文件成功');
|
||||||
const key = path ? `${path}/` : '';
|
|
||||||
const filename = file ? file.name : inputFilename;
|
|
||||||
handleCancel({
|
handleCancel({
|
||||||
filename,
|
filename: values.filename,
|
||||||
path,
|
path: values.path,
|
||||||
key: `${key}${filename}`,
|
key: `${values.path}-${values.filename}`,
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
const beforeUpload = (file: File) => {
|
|
||||||
setFile(file);
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
const typeChange = (e) => {
|
|
||||||
setType(e.target.value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getDirs = (data) => {
|
|
||||||
for (const item of data) {
|
|
||||||
if (item.children && item.children.length > 0) {
|
|
||||||
item.children = item.children
|
|
||||||
.filter((x) => x.type === 'directory')
|
|
||||||
.map((x) => ({ ...x, disabled: false }));
|
|
||||||
getDirs(item.children);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const originDirs = treeData
|
|
||||||
.filter((x) => x.type === 'directory')
|
|
||||||
.map((x) => ({ ...x, disabled: false }));
|
|
||||||
const dirs = getDirs(originDirs);
|
|
||||||
setDirs(dirs);
|
|
||||||
}, [treeData]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
|
const originDirs = treeData.filter((x) => x.disabled);
|
||||||
|
setDirs([{ key: '' }, ...originDirs]);
|
||||||
}, [visible]);
|
}, [visible]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="新建"
|
title="新建文件"
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
@@ -117,63 +72,24 @@ const EditScriptNameModal = ({
|
|||||||
confirmLoading={loading}
|
confirmLoading={loading}
|
||||||
>
|
>
|
||||||
<Form form={form} layout="vertical" name="edit_name_modal">
|
<Form form={form} layout="vertical" name="edit_name_modal">
|
||||||
<Form.Item
|
|
||||||
name="type"
|
|
||||||
label="类型"
|
|
||||||
rules={[{ required: true }]}
|
|
||||||
initialValue={'blank'}
|
|
||||||
>
|
|
||||||
<Radio.Group onChange={typeChange}>
|
|
||||||
<Radio value="blank">空文件</Radio>
|
|
||||||
<Radio value="upload">本地文件</Radio>
|
|
||||||
<Radio value="directory">文件夹</Radio>
|
|
||||||
</Radio.Group>
|
|
||||||
</Form.Item>
|
|
||||||
{type === 'blank' && (
|
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="filename"
|
name="filename"
|
||||||
label="文件名"
|
label="文件名"
|
||||||
rules={[
|
rules={[{ required: true, message: '请输入文件名' }]}
|
||||||
{ required: true, message: '请输入文件名' },
|
|
||||||
{
|
|
||||||
validator: (_, value) =>
|
|
||||||
value.includes('/')
|
|
||||||
? Promise.reject(new Error('文件名不能包含斜杠'))
|
|
||||||
: Promise.resolve(),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
>
|
>
|
||||||
<Input placeholder="请输入文件名" />
|
<Input placeholder="请输入文件名" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
)}
|
|
||||||
{type === 'directory' && (
|
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="directory"
|
label="父目录"
|
||||||
label="文件夹名"
|
name="path"
|
||||||
rules={[{ required: true, message: '请输入文件夹名' }]}
|
initialValue={dirs && dirs.length > 0 ? dirs[0].key : ''}
|
||||||
>
|
>
|
||||||
<Input placeholder="请输入文件夹名" />
|
<Select placeholder="请选择父目录">
|
||||||
|
{dirs.map((x) => (
|
||||||
|
<Option value={x.key}>{x.key || '根'}</Option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
)}
|
|
||||||
<Form.Item label="父目录" name="path">
|
|
||||||
<TreeSelect
|
|
||||||
allowClear
|
|
||||||
treeData={dirs}
|
|
||||||
fieldNames={{ value: 'key', label: 'title' }}
|
|
||||||
placeholder="请选择父目录"
|
|
||||||
treeDefaultExpandAll
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
{type === 'upload' && (
|
|
||||||
<Form.Item label="文件" name="file">
|
|
||||||
<Upload.Dragger beforeUpload={beforeUpload} maxCount={1}>
|
|
||||||
<p className="ant-upload-drag-icon">
|
|
||||||
<UploadOutlined />
|
|
||||||
</p>
|
|
||||||
<p className="ant-upload-text">点击或者拖拽文件到此区域上传</p>
|
|
||||||
</Upload.Dragger>
|
|
||||||
</Form.Item>
|
|
||||||
)}
|
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
position: relative;
|
position: relative;
|
||||||
background-color: @component-background;
|
background-color: @component-background;
|
||||||
height: 100%;
|
height: calc(100vh - 128px);
|
||||||
|
height: calc(100vh - var(--vh-offset, 0px) - 128px);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|||||||
+107
-96
@@ -33,15 +33,38 @@ import {
|
|||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import EditScriptNameModal from './editNameModal';
|
import EditScriptNameModal from './editNameModal';
|
||||||
import debounce from 'lodash/debounce';
|
import debounce from 'lodash/debounce';
|
||||||
import { history, useOutletContext, useLocation } from '@umijs/max';
|
import { history } from 'umi';
|
||||||
import { parse } from 'query-string';
|
|
||||||
import { depthFirstSearch } from '@/utils';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
import useFilterTreeData from '@/hooks/useFilterTreeData';
|
|
||||||
import uniq from 'lodash/uniq';
|
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
function getFilterData(keyword: string, data: any) {
|
||||||
|
const expandedKeys: string[] = [];
|
||||||
|
if (keyword) {
|
||||||
|
const tree: any = [];
|
||||||
|
data.forEach((item: any) => {
|
||||||
|
if (item.title.toLocaleLowerCase().includes(keyword)) {
|
||||||
|
tree.push(item);
|
||||||
|
} else {
|
||||||
|
const children: any[] = [];
|
||||||
|
(item.children || []).forEach((subItem: any) => {
|
||||||
|
if (subItem.title.toLocaleLowerCase().includes(keyword)) {
|
||||||
|
children.push(subItem);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (children.length > 0) {
|
||||||
|
tree.push({
|
||||||
|
...item,
|
||||||
|
children,
|
||||||
|
});
|
||||||
|
expandedKeys.push(item.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { tree, expandedKeys };
|
||||||
|
}
|
||||||
|
return { tree: data, expandedKeys };
|
||||||
|
}
|
||||||
|
|
||||||
const LangMap: any = {
|
const LangMap: any = {
|
||||||
'.py': 'python',
|
'.py': 'python',
|
||||||
'.js': 'javascript',
|
'.js': 'javascript',
|
||||||
@@ -49,12 +72,12 @@ const LangMap: any = {
|
|||||||
'.ts': 'typescript',
|
'.ts': 'typescript',
|
||||||
};
|
};
|
||||||
|
|
||||||
const Script = () => {
|
const Script = ({ headerStyle, isPhone, theme, socketMessage }: any) => {
|
||||||
const { headerStyle, isPhone, theme, socketMessage } =
|
const [title, setTitle] = useState('请选择脚本文件');
|
||||||
useOutletContext<SharedContext>();
|
|
||||||
const [value, setValue] = useState('请选择脚本文件');
|
const [value, setValue] = useState('请选择脚本文件');
|
||||||
const [select, setSelect] = useState<string>('');
|
const [select, setSelect] = useState<any>();
|
||||||
const [data, setData] = useState<any[]>([]);
|
const [data, setData] = useState<any[]>([]);
|
||||||
|
const [filterData, setFilterData] = useState<any[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [mode, setMode] = useState('');
|
const [mode, setMode] = useState('');
|
||||||
const [height, setHeight] = useState<number>();
|
const [height, setHeight] = useState<number>();
|
||||||
@@ -71,36 +94,30 @@ const Script = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
request
|
request
|
||||||
.get(`${config.apiPrefix}scripts`)
|
.get(`${config.apiPrefix}scripts`)
|
||||||
.then(({ code, data }) => {
|
.then((data) => {
|
||||||
if (code === 200) {
|
setData(data.data);
|
||||||
setData(data);
|
setFilterData(data.data);
|
||||||
initGetScript();
|
initGetScript();
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
const getDetail = (node: any) => {
|
const getDetail = (node: any) => {
|
||||||
request
|
request
|
||||||
.get(
|
.get(`${config.apiPrefix}scripts/${node.value}?path=${node.parent || ''}`)
|
||||||
`${config.apiPrefix}scripts/${encodeURIComponent(node.title)}?path=${
|
.then((data) => {
|
||||||
node.parent || ''
|
setValue(data.data);
|
||||||
}`,
|
|
||||||
)
|
|
||||||
.then(({ code, data }) => {
|
|
||||||
if (code === 200) {
|
|
||||||
setValue(data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const initGetScript = () => {
|
const initGetScript = () => {
|
||||||
const { p, s } = parse(history.location.search);
|
const { p, s } = history.location.query as any;
|
||||||
if (s) {
|
if (s) {
|
||||||
const vkey = `${p}/${s}`;
|
const vkey = `${p}/${s}`;
|
||||||
const obj = {
|
const obj = {
|
||||||
node: {
|
node: {
|
||||||
title: s,
|
title: s,
|
||||||
|
value: s,
|
||||||
key: p ? vkey : s,
|
key: p ? vkey : s,
|
||||||
parent: p,
|
parent: p,
|
||||||
},
|
},
|
||||||
@@ -111,24 +128,22 @@ const Script = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onSelect = (value: any, node: any) => {
|
const onSelect = (value: any, node: any) => {
|
||||||
setSelect(node.key);
|
|
||||||
setCurrentNode(node);
|
|
||||||
|
|
||||||
if (node.key === select || !value) {
|
if (node.key === select || !value) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setValue('加载中...');
|
||||||
if (node.type === 'directory') {
|
|
||||||
setValue('请选择脚本文件');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newMode = value ? LangMap[value.slice(-3)] : '';
|
const newMode = value ? LangMap[value.slice(-3)] : '';
|
||||||
setMode(isPhone && newMode === 'typescript' ? 'javascript' : newMode);
|
setMode(isPhone && newMode === 'typescript' ? 'javascript' : newMode);
|
||||||
setValue('加载中...');
|
setSelect(node.key);
|
||||||
|
setTitle(node.key);
|
||||||
|
setCurrentNode(node);
|
||||||
getDetail(node);
|
getDetail(node);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onExpand = (expKeys: any) => {
|
||||||
|
setExpandedKeys(expKeys);
|
||||||
|
};
|
||||||
|
|
||||||
const onTreeSelect = useCallback(
|
const onTreeSelect = useCallback(
|
||||||
(keys: Key[], e: any) => {
|
(keys: Key[], e: any) => {
|
||||||
const content = editorRef.current
|
const content = editorRef.current
|
||||||
@@ -159,29 +174,21 @@ const Script = () => {
|
|||||||
const keyword = e.target.value;
|
const keyword = e.target.value;
|
||||||
debounceSearch(keyword);
|
debounceSearch(keyword);
|
||||||
},
|
},
|
||||||
[data],
|
[data, setFilterData],
|
||||||
);
|
);
|
||||||
|
|
||||||
const debounceSearch = useCallback(
|
const debounceSearch = useCallback(
|
||||||
debounce((keyword) => {
|
debounce((keyword) => {
|
||||||
setSearchValue(keyword);
|
setSearchValue(keyword);
|
||||||
}, 300),
|
const { tree, expandedKeys } = getFilterData(
|
||||||
[data],
|
keyword.toLocaleLowerCase(),
|
||||||
);
|
|
||||||
|
|
||||||
const { treeData: filterData, keys: searchExpandedKeys } = useFilterTreeData(
|
|
||||||
data,
|
data,
|
||||||
searchValue,
|
|
||||||
{ treeNodeFilterProp: 'title' },
|
|
||||||
);
|
);
|
||||||
|
setExpandedKeys(expandedKeys);
|
||||||
useEffect(() => {
|
setFilterData(tree);
|
||||||
setExpandedKeys(uniq([...expandedKeys, ...searchExpandedKeys]));
|
}, 300),
|
||||||
}, [searchExpandedKeys]);
|
[data, setFilterData],
|
||||||
|
);
|
||||||
const onExpand = (expKeys: any) => {
|
|
||||||
setExpandedKeys(expKeys);
|
|
||||||
};
|
|
||||||
|
|
||||||
const editFile = () => {
|
const editFile = () => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -202,7 +209,7 @@ const Script = () => {
|
|||||||
<>
|
<>
|
||||||
确认保存文件
|
确认保存文件
|
||||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||||
{currentNode.title}
|
{currentNode.value}
|
||||||
</Text>{' '}
|
</Text>{' '}
|
||||||
,保存后不可恢复
|
,保存后不可恢复
|
||||||
</>
|
</>
|
||||||
@@ -215,16 +222,18 @@ const Script = () => {
|
|||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}scripts`, {
|
.put(`${config.apiPrefix}scripts`, {
|
||||||
data: {
|
data: {
|
||||||
filename: currentNode.title,
|
filename: currentNode.value,
|
||||||
path: currentNode.parent || '',
|
path: currentNode.parent || '',
|
||||||
content,
|
content,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((_data: any) => {
|
||||||
if (code === 200) {
|
if (_data.code === 200) {
|
||||||
message.success(`保存成功`);
|
message.success(`保存成功`);
|
||||||
setValue(content);
|
setValue(content);
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
|
} else {
|
||||||
|
message.error(_data);
|
||||||
}
|
}
|
||||||
resolve(null);
|
resolve(null);
|
||||||
})
|
})
|
||||||
@@ -242,11 +251,10 @@ const Script = () => {
|
|||||||
title: `确认删除`,
|
title: `确认删除`,
|
||||||
content: (
|
content: (
|
||||||
<>
|
<>
|
||||||
确认删除
|
确认删除文件
|
||||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||||
{select}
|
{select}
|
||||||
</Text>
|
</Text>{' '}
|
||||||
文件{currentNode.type === 'directory' ? '夹及其子文件' : ''}
|
|
||||||
,删除后不可恢复
|
,删除后不可恢复
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
@@ -254,20 +262,26 @@ const Script = () => {
|
|||||||
request
|
request
|
||||||
.delete(`${config.apiPrefix}scripts`, {
|
.delete(`${config.apiPrefix}scripts`, {
|
||||||
data: {
|
data: {
|
||||||
filename: currentNode.title,
|
filename: currentNode.value,
|
||||||
path: currentNode.parent || '',
|
path: currentNode.parent || '',
|
||||||
type: currentNode.type,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code }) => {
|
.then((_data: any) => {
|
||||||
if (code === 200) {
|
if (_data.code === 200) {
|
||||||
message.success(`删除成功`);
|
message.success(`删除成功`);
|
||||||
let newData = [...data];
|
let newData = [...data];
|
||||||
if (currentNode.parent) {
|
if (currentNode.parent) {
|
||||||
newData = depthFirstSearch(
|
const parentNodeIndex = newData.findIndex(
|
||||||
newData,
|
(x) => x.key === currentNode.parent,
|
||||||
(c) => c.key === currentNode.key,
|
|
||||||
);
|
);
|
||||||
|
const parentNode = newData[parentNodeIndex];
|
||||||
|
const index = parentNode.children.findIndex(
|
||||||
|
(y) => y.key === currentNode.key,
|
||||||
|
);
|
||||||
|
if (index !== -1 && parentNodeIndex !== -1) {
|
||||||
|
parentNode.children.splice(index, 1);
|
||||||
|
newData.splice(parentNodeIndex, 1, { ...parentNode });
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const index = newData.findIndex(
|
const index = newData.findIndex(
|
||||||
(x) => x.key === currentNode.key,
|
(x) => x.key === currentNode.key,
|
||||||
@@ -277,7 +291,8 @@ const Script = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
setData(newData);
|
setData(newData);
|
||||||
initState();
|
} else {
|
||||||
|
message.error(_data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -299,22 +314,24 @@ const Script = () => {
|
|||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
if (filename) {
|
if (filename) {
|
||||||
let newData = [...data];
|
const newData = [...data];
|
||||||
const _file = { title: filename, key, parent: path };
|
const _file = { title: filename, key, value: filename, parent: path };
|
||||||
if (path) {
|
if (path) {
|
||||||
newData = depthFirstSearch(newData, (c) => c.key === path, _file);
|
const parentNodeIndex = newData.findIndex((x) => x.key === path);
|
||||||
const keys = path.split('/');
|
if (parentNodeIndex !== -1) {
|
||||||
const sKeys: string[] = [];
|
const parentNode = newData[parentNodeIndex];
|
||||||
keys.reduce((p, c) => {
|
if (parentNode.children && parentNode.children.length > 0) {
|
||||||
sKeys.push(p);
|
parentNode.children.unshift(_file);
|
||||||
return `${p}/${c}`;
|
} else {
|
||||||
});
|
parentNode.children = [_file];
|
||||||
setExpandedKeys([...expandedKeys, ...sKeys, path]);
|
}
|
||||||
|
newData.splice(parentNodeIndex, 1, { ...parentNode });
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
newData.unshift(_file);
|
newData.unshift(_file);
|
||||||
}
|
}
|
||||||
setData(newData);
|
setData(newData);
|
||||||
onSelect(_file.title, _file);
|
onSelect(_file.value, _file);
|
||||||
setIsEditing(true);
|
setIsEditing(true);
|
||||||
}
|
}
|
||||||
setIsAddFileModalVisible(false);
|
setIsAddFileModalVisible(false);
|
||||||
@@ -324,38 +341,37 @@ const Script = () => {
|
|||||||
request
|
request
|
||||||
.post(`${config.apiPrefix}scripts/download`, {
|
.post(`${config.apiPrefix}scripts/download`, {
|
||||||
data: {
|
data: {
|
||||||
filename: currentNode.title,
|
filename: currentNode.value,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(({ code, data }) => {
|
.then((_data: any) => {
|
||||||
if (code === 200) {
|
const blob = new Blob([_data], { type: 'application/json' });
|
||||||
const blob = new Blob([data], { type: 'application/json' });
|
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = currentNode.title;
|
a.download = currentNode.value;
|
||||||
document.documentElement.appendChild(a);
|
document.documentElement.appendChild(a);
|
||||||
a.click();
|
a.click();
|
||||||
document.documentElement.removeChild(a);
|
document.documentElement.removeChild(a);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const initState = () => {
|
useEffect(() => {
|
||||||
|
const word = searchValue || '';
|
||||||
|
const { tree } = getFilterData(word.toLocaleLowerCase(), data);
|
||||||
|
setFilterData(tree);
|
||||||
setSelect('');
|
setSelect('');
|
||||||
setCurrentNode(null);
|
setCurrentNode(null);
|
||||||
|
setTitle('请选择脚本文件');
|
||||||
setValue('请选择脚本文件');
|
setValue('请选择脚本文件');
|
||||||
};
|
}, [data]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getScripts();
|
getScripts();
|
||||||
}, []);
|
if (treeDom && treeDom.current) {
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (treeDom.current) {
|
|
||||||
setHeight(treeDom.current.clientHeight);
|
setHeight(treeDom.current.clientHeight);
|
||||||
}
|
}
|
||||||
}, [treeDom.current, data]);
|
}, []);
|
||||||
|
|
||||||
const action = (key: string | number) => {
|
const action = (key: string | number) => {
|
||||||
switch (key) {
|
switch (key) {
|
||||||
@@ -424,22 +440,18 @@ const Script = () => {
|
|||||||
return (
|
return (
|
||||||
<PageContainer
|
<PageContainer
|
||||||
className="ql-container-wrapper log-wrapper"
|
className="ql-container-wrapper log-wrapper"
|
||||||
title={select}
|
title={title}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
extra={
|
extra={
|
||||||
isPhone
|
isPhone
|
||||||
? [
|
? [
|
||||||
<TreeSelect
|
<TreeSelect
|
||||||
treeExpandAction="click"
|
|
||||||
className="log-select"
|
className="log-select"
|
||||||
value={select}
|
value={select}
|
||||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||||
treeData={data}
|
treeData={data}
|
||||||
placeholder="请选择脚本"
|
placeholder="请选择脚本"
|
||||||
fieldNames={{ value: 'key' }}
|
|
||||||
treeNodeFilterProp="title"
|
|
||||||
showSearch
|
showSearch
|
||||||
allowClear
|
|
||||||
onSelect={onSelect}
|
onSelect={onSelect}
|
||||||
/>,
|
/>,
|
||||||
<Dropdown overlay={menu} trigger={['click']}>
|
<Dropdown overlay={menu} trigger={['click']}>
|
||||||
@@ -495,7 +507,6 @@ const Script = () => {
|
|||||||
>
|
>
|
||||||
<div className={`${styles['log-container']} log-container`}>
|
<div className={`${styles['log-container']} log-container`}>
|
||||||
{!isPhone && (
|
{!isPhone && (
|
||||||
/*// @ts-ignore*/
|
|
||||||
<SplitPane split="vertical" size={200} maxSize={-100}>
|
<SplitPane split="vertical" size={200} maxSize={-100}>
|
||||||
<div className={styles['left-tree-container']}>
|
<div className={styles['left-tree-container']}>
|
||||||
{data.length > 0 ? (
|
{data.length > 0 ? (
|
||||||
@@ -508,7 +519,6 @@ const Script = () => {
|
|||||||
></Input.Search>
|
></Input.Search>
|
||||||
<div className={styles['left-tree-scroller']} ref={treeDom}>
|
<div className={styles['left-tree-scroller']} ref={treeDom}>
|
||||||
<Tree
|
<Tree
|
||||||
expandAction="click"
|
|
||||||
className={styles['left-tree']}
|
className={styles['left-tree']}
|
||||||
treeData={filterData}
|
treeData={filterData}
|
||||||
showIcon={true}
|
showIcon={true}
|
||||||
@@ -545,6 +555,7 @@ const Script = () => {
|
|||||||
readOnly: !isEditing,
|
readOnly: !isEditing,
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
lineNumbersMinChars: 3,
|
lineNumbersMinChars: 3,
|
||||||
|
folding: false,
|
||||||
glyphMargin: false,
|
glyphMargin: false,
|
||||||
}}
|
}}
|
||||||
onMount={(editor) => {
|
onMount={(editor) => {
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ const SaveModal = ({
|
|||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success('保存文件成功');
|
message.success('保存文件成功');
|
||||||
handleCancel(data);
|
handleCancel(data);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
});
|
});
|
||||||
@@ -39,7 +41,7 @@ const SaveModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="保存文件"
|
title="保存文件"
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ const SettingModal = ({
|
|||||||
if (code === 200) {
|
if (code === 200) {
|
||||||
message.success('保存文件成功');
|
message.success('保存文件成功');
|
||||||
handleCancel(data);
|
handleCancel(data);
|
||||||
|
} else {
|
||||||
|
message.error(data);
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
});
|
});
|
||||||
@@ -39,7 +41,7 @@ const SettingModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="运行设置"
|
title="运行设置"
|
||||||
open={visible}
|
visible={visible}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
onCancel={() => handleCancel()}
|
onCancel={() => handleCancel()}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user