mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0977f9e37 | ||
|
|
e9b85347f4 | ||
|
|
325482cbb1 | ||
|
|
45e02a55c3 | ||
|
|
6b8ef75b51 | ||
|
|
f2535ece76 | ||
|
|
b2afa65cb1 | ||
|
|
3a62cc37ff | ||
|
|
93c69826ad | ||
|
|
70727d0e26 | ||
|
|
2578aae0ba | ||
|
|
616e56ea95 | ||
|
|
96ae20de68 | ||
|
|
6975ff4aa1 | ||
|
|
1d8a1e9c4a | ||
|
|
2719280cdc | ||
|
|
575e41172f | ||
|
|
bd50b1e976 | ||
|
|
dfb2572b4f | ||
|
|
7746b18023 | ||
|
|
05c738c7c6 | ||
|
|
e561e12356 | ||
|
|
595b28ba62 | ||
|
|
366caed74e | ||
|
|
2e26a8c24e | ||
|
|
c09c375066 | ||
|
|
4f93905507 | ||
|
|
f152136f0b | ||
|
|
c24d3d6e2f | ||
|
|
33d820acdb | ||
|
|
78ef75bbfe | ||
|
|
31541fb87e | ||
|
|
0c169e3f6c | ||
|
|
73c15cb3bc | ||
|
|
4373a2df49 | ||
|
|
cb004cfbf5 | ||
|
|
7f2d6d159c | ||
|
|
4bba024e4a | ||
|
|
acb43f3ad8 | ||
|
|
b160f914ad | ||
|
|
6116aa6d12 | ||
|
|
d43cee53c9 | ||
|
|
defea8ff9b | ||
|
|
b290b60d46 | ||
|
|
706b5e8108 | ||
|
|
b55c7d5747 | ||
|
|
6b8fd94f0c | ||
|
|
e18710a30a | ||
|
|
c0f0da4e96 | ||
|
|
49ef5cd61f | ||
|
|
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 |
@@ -10,4 +10,3 @@ SECRET='whyour'
|
|||||||
QINIU_AK=''
|
QINIU_AK=''
|
||||||
QINIU_SK=''
|
QINIU_SK=''
|
||||||
QINIU_SCOPE=''
|
QINIU_SCOPE=''
|
||||||
TEMP=''
|
|
||||||
|
|||||||
@@ -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! 🎉🎉🎉
|
|
||||||
@@ -5,54 +5,28 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- 'master'
|
- 'master'
|
||||||
- 'develop'
|
- 'develop'
|
||||||
|
# Sequence of patterns matched against refs/tags
|
||||||
tags:
|
tags:
|
||||||
- 'v*'
|
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '00 20 * * *'
|
# 参考 https://jasonet.co/posts/scheduled-actions/
|
||||||
|
# note: 这里是GMT时间,北京时间减去八小时即可。如北京时间 22:30 => GMT 14:30
|
||||||
|
# minute hour day month dayOfWeek
|
||||||
|
- cron: '00 14 * * *' # GMT 14:00 => 北京时间 22:00
|
||||||
|
#- cron: '30 16 * * *' # GMT 16:30(前一天) => 北京时间 00:30
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
to_gitlab:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- uses: pixta-dev/repository-mirroring-action@v1
|
|
||||||
with:
|
|
||||||
target_repo_url:
|
|
||||||
git@gitlab.com:whyour/qinglong.git
|
|
||||||
ssh_private_key:
|
|
||||||
${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
|
|
||||||
to_gitee:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- uses: pixta-dev/repository-mirroring-action@v1
|
|
||||||
with:
|
|
||||||
target_repo_url:
|
|
||||||
git@gitee.com:whyour/qinglong.git
|
|
||||||
ssh_private_key:
|
|
||||||
${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
|
|
||||||
build-static:
|
build-static:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: pnpm/action-setup@v2
|
|
||||||
with:
|
|
||||||
version: '8.3.1'
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
|
||||||
cache: 'pnpm'
|
|
||||||
|
|
||||||
- name: build front and back
|
- name: build front and back
|
||||||
run: |
|
run: |
|
||||||
pnpm install --frozen-lockfile
|
npm i -g pnpm
|
||||||
|
pnpm install
|
||||||
pnpm build:front
|
pnpm build:front
|
||||||
pnpm build:back
|
pnpm build:back
|
||||||
|
|
||||||
@@ -60,9 +34,6 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
||||||
GITHUB_BRANCH: ${{ github.ref_name }}
|
GITHUB_BRANCH: ${{ github.ref_name }}
|
||||||
REPO_GITEE: git@gitee.com:whyour/qinglong-static.git
|
|
||||||
REPO_GITLAB: git@gitlab.com:whyour/qinglong-static.git
|
|
||||||
PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
run: |
|
run: |
|
||||||
mkdir -p tmp
|
mkdir -p tmp
|
||||||
cd ./tmp
|
cd ./tmp
|
||||||
@@ -73,48 +44,34 @@ jobs:
|
|||||||
git commit --allow-empty -m "copy static at $(date +'%Y-%m-%d %H:%M:%S')"
|
git commit --allow-empty -m "copy static at $(date +'%Y-%m-%d %H:%M:%S')"
|
||||||
git push --force --quiet "https://${{ secrets.API_TOKEN }}@${GITHUB_REPO}.git" ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
git push --force --quiet "https://${{ secrets.API_TOKEN }}@${GITHUB_REPO}.git" ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
||||||
|
|
||||||
mkdir -p ~/.ssh
|
|
||||||
echo "${PRIVATE_KEY}" > ~/.ssh/id_rsa
|
|
||||||
chmod 600 ~/.ssh/id_rsa
|
|
||||||
|
|
||||||
export GIT_SSH_COMMAND="ssh -v -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no -l git"
|
|
||||||
git remote add gitee "${REPO_GITEE}"
|
|
||||||
git remote add gitlab "${REPO_GITLAB}"
|
|
||||||
git push --force --quiet gitee ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
|
||||||
git push --force --quiet gitlab ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
|
||||||
|
|
||||||
build:
|
build:
|
||||||
needs: build-static
|
needs: build-static
|
||||||
|
|
||||||
# 由于 ubuntu-latest 中使用 linux6.x 内核 linux/s390x npm 无法使用
|
runs-on: ubuntu-latest
|
||||||
runs-on: ubuntu-20.04
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
packages: write
|
packages: write
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3
|
||||||
- uses: pnpm/action-setup@v2
|
|
||||||
with:
|
|
||||||
version: '8.3.1'
|
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
|
||||||
cache: 'pnpm'
|
|
||||||
|
|
||||||
- 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@v3
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
@@ -122,48 +79,38 @@ jobs:
|
|||||||
|
|
||||||
- name: Extract metadata (tags, labels) for Docker
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v5
|
uses: docker/metadata-action@v4
|
||||||
with:
|
with:
|
||||||
images: |
|
images: |
|
||||||
${{ github.repository }}
|
${{ github.repository }}
|
||||||
ghcr.io/${{ github.repository }}
|
ghcr.io/${{ github.repository }}
|
||||||
# generate Docker tags based on the following events/attributes
|
# generate Docker tags based on the following events/attributes
|
||||||
# nightly, master, pr-2, 1.2.3, 1.2, 1
|
# nightly, master, pr-2, 1.2.3, 1.2, 1
|
||||||
flavor: |
|
|
||||||
latest=false
|
|
||||||
tags: |
|
tags: |
|
||||||
type=schedule,pattern=nightly
|
type=schedule,pattern=nightly
|
||||||
type=edge
|
type=edge
|
||||||
|
type=ref,event=branch
|
||||||
type=ref,event=pr
|
type=ref,event=pr
|
||||||
type=ref,event=branch,enable=${{ github.ref != format('refs/heads/{0}', 'master') }}
|
|
||||||
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'master') }}
|
|
||||||
type=semver,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
type=semver,pattern={{major}}
|
type=semver,pattern={{major}}
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3
|
uses: docker/setup-qemu-action@v2
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
id: docker_build
|
id: docker_build
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v3
|
||||||
with:
|
with:
|
||||||
build-args: |
|
build-args: |
|
||||||
MAINTAINER=${{ github.repository_owner }}
|
MAINTAINER=${{ github.repository_owner }}
|
||||||
QL_BRANCH=${{ github.ref_name }}
|
QL_BRANCH=${{ github.ref_name }}
|
||||||
SOURCE_COMMIT=${{ github.sha }}
|
|
||||||
network: host
|
network: host
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
context: .
|
context: docker/
|
||||||
file: ./docker/Dockerfile
|
|
||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
cache-from: type=registry,ref=whyour/qinglong:cache
|
|
||||||
cache-to: type=registry,ref=whyour/qinglong:cache,mode=max
|
|
||||||
|
|
||||||
- name: Image digest
|
|
||||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
|
||||||
|
|||||||
+1
-1
@@ -5,6 +5,7 @@
|
|||||||
/npm-debug.log*
|
/npm-debug.log*
|
||||||
/yarn-error.log
|
/yarn-error.log
|
||||||
/yarn.lock
|
/yarn.lock
|
||||||
|
/pnpm-lock.yaml
|
||||||
/package-lock.json
|
/package-lock.json
|
||||||
|
|
||||||
# production
|
# production
|
||||||
@@ -29,4 +30,3 @@
|
|||||||
/manual_log
|
/manual_log
|
||||||
/scripts
|
/scripts
|
||||||
/bak
|
/bak
|
||||||
/.tmp
|
|
||||||
@@ -6,27 +6,3 @@ package.json
|
|||||||
.umi
|
.umi
|
||||||
.umi-production
|
.umi-production
|
||||||
.umi-test
|
.umi-test
|
||||||
.history
|
|
||||||
.tmp
|
|
||||||
node_modules
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-error.log
|
|
||||||
yarn.lock
|
|
||||||
package-lock.json
|
|
||||||
static
|
|
||||||
data
|
|
||||||
DS_Store
|
|
||||||
src/.umi
|
|
||||||
src/.umi-production
|
|
||||||
src/.umi-test
|
|
||||||
.env.local
|
|
||||||
.env
|
|
||||||
history
|
|
||||||
version.ts
|
|
||||||
config
|
|
||||||
log
|
|
||||||
db
|
|
||||||
manual_log
|
|
||||||
scripts
|
|
||||||
bak
|
|
||||||
.tmp
|
|
||||||
@@ -1,34 +1,32 @@
|
|||||||
import { defineConfig } from '@umijs/max';
|
import { defineConfig } from 'umi';
|
||||||
const CompressionPlugin = require('compression-webpack-plugin');
|
const CompressionPlugin = require('compression-webpack-plugin');
|
||||||
|
|
||||||
const baseUrl = process.env.QlBaseUrl || '/';
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
hash: true,
|
hash: true,
|
||||||
jsMinifier: 'terser',
|
layout: false,
|
||||||
antd: {},
|
|
||||||
locale: {
|
|
||||||
antd: true,
|
|
||||||
title: true,
|
|
||||||
baseNavigator: true,
|
|
||||||
},
|
|
||||||
outputPath: 'static/dist',
|
outputPath: 'static/dist',
|
||||||
fastRefresh: true,
|
nodeModulesTransform: {
|
||||||
favicons: [`https://qn.whyour.cn/favicon.svg`],
|
type: 'none',
|
||||||
publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
|
},
|
||||||
|
fastRefresh: {},
|
||||||
|
esbuild: {},
|
||||||
|
webpack5: {},
|
||||||
|
dynamicImport: {
|
||||||
|
loading: '@/components/pageLoading',
|
||||||
|
},
|
||||||
|
favicon: '/images/g5.ico',
|
||||||
proxy: {
|
proxy: {
|
||||||
[`${baseUrl}api/public`]: {
|
'/api/public': {
|
||||||
target: 'http://127.0.0.1:5400/',
|
target: 'http://127.0.0.1:5400/',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
pathRewrite: { [`^${baseUrl}api/public`]: '/api' },
|
|
||||||
},
|
},
|
||||||
[`${baseUrl}api`]: {
|
'/api': {
|
||||||
target: 'http://127.0.0.1:5600/',
|
target: 'http://127.0.0.1:5600/',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
ws: true,
|
ws: true,
|
||||||
pathRewrite: { [`^${baseUrl}api`]: '/api' },
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
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',
|
||||||
@@ -37,14 +35,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: [
|
||||||
`./api/env.js`,
|
'https://gw.alipayobjects.com/os/lib/react/16.13.1/umd/react.production.min.js',
|
||||||
'https://gw.alipayobjects.com/os/lib/react/18.2.0/umd/react.production.min.js',
|
'https://gw.alipayobjects.com/os/lib/react-dom/16.13.1/umd/react-dom.production.min.js',
|
||||||
'https://gw.alipayobjects.com/os/lib/react-dom/18.2.0/umd/react-dom.production.min.js',
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
+126
-128
@@ -1,29 +1,30 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/whyour/qinglong">
|
||||||
|
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h1 align="center">Green Dragon</h1>
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<img width="100" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
|
||||||
|
|
||||||
<h1 align="center">Qinglong</h1>
|
Timed task management panel with python3, javaScript, shell, typescript support
|
||||||
|
|
||||||
[简体中文](./README.md) | English
|
[![docker version][docker-version-image]][docker-version-url] [![docker pulls][docker-pulls-image]][docker-pulls-url] [![docker stars][docker-stars-image]][docker-stars-url] [![docker image size][docker-image-size-image]][docker-image-size-url]
|
||||||
|
|
||||||
Timed task management platform supporting Python3, JavaScript, Shell, Typescript
|
|
||||||
|
|
||||||
[![npm version][npm-version-image]][npm-version-url] [![docker pulls][docker-pulls-image]][docker-pulls-url] [![docker stars][docker-stars-image]][docker-stars-url] [![docker image size][docker-image-size-image]][docker-image-size-url]
|
|
||||||
|
|
||||||
[npm-version-image]: https://img.shields.io/npm/v/@whyour/qinglong?style=flat
|
|
||||||
[npm-version-url]: https://www.npmjs.com/package/@whyour/qinglong?activeTab=readme
|
|
||||||
[docker-pulls-image]: https://img.shields.io/docker/pulls/whyour/qinglong?style=flat
|
[docker-pulls-image]: https://img.shields.io/docker/pulls/whyour/qinglong?style=flat
|
||||||
[docker-pulls-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-pulls-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
|
[docker-version-image]: https://img.shields.io/docker/v/whyour/qinglong?style=flat
|
||||||
|
[docker-version-url]: https://hub.docker.com/r/whyour/qinglong/tags?page=1&ordering=last_updated
|
||||||
[docker-stars-image]: https://img.shields.io/docker/stars/whyour/qinglong?style=flat
|
[docker-stars-image]: https://img.shields.io/docker/stars/whyour/qinglong?style=flat
|
||||||
[docker-stars-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-stars-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
||||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
|
|
||||||
[Demo](http://demo.dlww.cc:4433/) / [Issues](https://github.com/whyour/qinglong/issues) / [Telegram Channel](https://t.me/jiao_long) / [Buy Me a Coffee](https://www.buymeacoffee.com/qinglong)
|
|
||||||
|
|
||||||
[演示](http://demo.dlww.cc:4433/) / [反馈](https://github.com/whyour/qinglong/issues) / [Telegram 频道](https://t.me/jiao_long) / [打赏开发者](https://user-images.githubusercontent.com/22700758/244744295-29cd0cd1-c8bb-4ea1-adf6-29bd390ad4dd.jpg)
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||

|
[](https://whyour.cn)
|
||||||
|
|
||||||
|
[简体中文](./README.md) | English
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@@ -35,49 +36,97 @@ Timed task management platform supporting Python3, JavaScript, Shell, Typescript
|
|||||||
- Support dark mode
|
- Support dark mode
|
||||||
- Support cell phone operation
|
- Support cell phone operation
|
||||||
|
|
||||||
## Version
|
## Deployment
|
||||||
|
|
||||||
### docker
|
### Local Deployment
|
||||||
|
|
||||||
The `latest` image is built on `alpine` and the `debian` image is built on `debian-slim`. If you need to use a dependency that is not supported by `alpine`, it is recommended that you use the `debian` image.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker pull whyour/qinglong:latest
|
# To be completed
|
||||||
docker pull whyour/qinglong:debian
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### npm
|
### Podman Deployment
|
||||||
|
|
||||||
The npm version supports `debian/ubuntu/centos/alpine` systems and requires `node/python3` to be installed.
|
1. podman installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i @whyour/qinglong
|
https://podman.io/getting-started/installation
|
||||||
```
|
```
|
||||||
|
|
||||||
## Built-in commands
|
2. start the container
|
||||||
|
|
||||||
1. task
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Execute in sequence, if a random delay is set, it will be randomly delayed by a certain number of seconds
|
podman run -dit \
|
||||||
task <file_path>
|
--network bridge \
|
||||||
# Execute in sequence, regardless of whether a random delay is set, all run immediately,
|
-v $PWD/ql:/ql/data \
|
||||||
# and the foreground will output the day, while recorded in the log file
|
-p 5700:5700 \
|
||||||
task <file_path> now
|
--name qinglong \
|
||||||
# Concurrent execution, regardless of whether a random delay is set, are run immediately,
|
--hostname qinglong \
|
||||||
# the foreground does not generate the day, directly recorded in the log file, and can be specified account execution
|
--restart unless-stopped \
|
||||||
task <file_path> conc <env_name> <account_number>(Optional)
|
docker.io/whyour/qinglong:latest
|
||||||
# Specify the account to execute and run immediately regardless of whether a random delay is set
|
|
||||||
task <file_path> desi <env_name> <account_number>
|
|
||||||
# Set task timeout
|
|
||||||
task -m <max_time> <file_path>
|
|
||||||
# Print task log in real time, no need to carry this parameter when creating timed tasks
|
|
||||||
task -l <file_path>
|
|
||||||
# Use -- to split, -- followed by a parameter that is passed to the script, as in the following example, the script receives the parameter -u whyour -p password
|
|
||||||
task <file_path> -- -u whyour -p password
|
|
||||||
```
|
```
|
||||||
|
|
||||||
1. ql
|
### Docker Deployment
|
||||||
|
|
||||||
|
1. docker installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo curl -sSL get.docker.com | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
2. configure domestic mirror sources
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p /etc/docker
|
||||||
|
tee /etc/docker/daemon.json <<-'EOF'
|
||||||
|
{
|
||||||
|
"registry-mirrors": [
|
||||||
|
"https://0b27f0a81a00f3560fbdc00ddd2f99e0.mirror.swr.myhuaweicloud.com",
|
||||||
|
"https://ypzju6vq.mirror.aliyuncs.com",
|
||||||
|
"https://registry.docker-cn.com",
|
||||||
|
"http://hub-mirror.c.163.com",
|
||||||
|
"https://docker.mirrors.ustc.edu.cn"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl restart docker
|
||||||
|
```
|
||||||
|
|
||||||
|
3. start the container
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -dit \
|
||||||
|
-v $PWD/ql:/ql/data \
|
||||||
|
-p 5700:5700 \
|
||||||
|
--name qinglong \
|
||||||
|
--hostname qinglong \
|
||||||
|
--restart unless-stopped \
|
||||||
|
whyour/qinglong:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker-compose Deployment
|
||||||
|
|
||||||
|
1. docker-compose installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
||||||
|
```
|
||||||
|
|
||||||
|
2. start the container
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir qinglong
|
||||||
|
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
||||||
|
|
||||||
|
# start
|
||||||
|
docker-compose up -d
|
||||||
|
# stop
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
## Use
|
||||||
|
|
||||||
|
1. built-in commands
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Update and restart Green Dragon
|
# Update and restart Green Dragon
|
||||||
@@ -98,86 +147,41 @@ ql check
|
|||||||
ql resetlet
|
ql resetlet
|
||||||
# Disable two-step login
|
# Disable two-step login
|
||||||
ql resettfa
|
ql resettfa
|
||||||
|
|
||||||
|
# Execute in sequence, if a random delay is set, it will be randomly delayed by a certain number of seconds
|
||||||
|
task <file_path>
|
||||||
|
# Execute in sequence, regardless of whether a random delay is set, all run immediately,
|
||||||
|
# and the foreground will output the day, while recorded in the log file
|
||||||
|
task <file_path> now
|
||||||
|
# Concurrent execution, regardless of whether a random delay is set, are run immediately,
|
||||||
|
# the foreground does not generate the day, directly recorded in the log file, and can be specified account execution
|
||||||
|
task <file_path> conc <env_name> <account_number>(Optional)
|
||||||
|
# Specify the account to execute and run immediately regardless of whether a random delay is set
|
||||||
|
task <file_path> desi <env_name> <account_number>
|
||||||
```
|
```
|
||||||
|
|
||||||
1. parameter description
|
2. parameter description
|
||||||
|
|
||||||
- file_url: Script address
|
* file_url: Script address
|
||||||
- repo_url: Repository address
|
* repo_url: Repository address
|
||||||
- whitelist: The whitelist when pulling the repository, i.e., the string contained in the path of the script to be pulled
|
* whitelist: The whitelist when pulling the repository, i.e., the string contained in the path of the script to be pulled
|
||||||
- blacklist: Blacklisting when pulling repositories, i.e. strings that are not included in the path of the script to be pulled
|
* blacklist: Blacklisting when pulling repositories, i.e. strings that are not included in the path of the script to be pulled
|
||||||
- dependence: Pulling the dependencies needed for the repository will be copied directly from the repository to the repository directory under scripts, regardless of the blacklist
|
* dependence: Pulling the dependencies needed for the repository will be copied directly from the repository to the repository directory under scripts, regardless of the blacklist
|
||||||
- branch: Pull the branch of the repository
|
* branch: Pull the branch of the repository
|
||||||
- days: Number of days of logs to be kept
|
* days: Number of days of logs to be kept
|
||||||
- file_path: File path for task execution
|
* file_path: File path for task execution
|
||||||
- env_name: The name of the environment variable that needs to be concurrent or specified at the time of task execution
|
* env_name: The name of the environment variable that needs to be concurrent or specified at the time of task execution
|
||||||
- account_number: Specify the account number of an environment variable to be executed when the task is executed
|
* account_number: Specify the account number of an environment variable to be executed when the task is executed
|
||||||
- max_time: Timeout, suffix "s" for seconds (default), "m" for minutes, "h" for hours, "d" for days
|
|
||||||
|
|
||||||
## Deployment
|
## Links
|
||||||
|
|
||||||
### Docker (Recommended)
|
- [nevinee](https://gitee.com/evine)
|
||||||
|
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||||
```bash
|
- [Ant Design](https://ant.design)
|
||||||
# curl -sSL get.docker.com | sh
|
- [Ant Design Pro](https://pro.ant.design/)
|
||||||
docker run -dit \
|
- [Umijs3.0](https://umijs.org)
|
||||||
-v $PWD/ql/data:/ql/data \
|
- [darkreader](https://github.com/darkreader/darkreader)
|
||||||
# The 5700 after the colon is the default port, if QlPort is set, it needs to be the same as QlPort.
|
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||||
-p 5700:5700 \
|
|
||||||
# Deployment paths are not required, e.g. /test.
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# Deployment port is not required, when using host mode, you can set the port after service startup, default 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
--restart unless-stopped \
|
|
||||||
whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Docker-compose (Recommended)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
|
||||||
mkdir qinglong
|
|
||||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
|
||||||
|
|
||||||
# start
|
|
||||||
docker-compose up -d
|
|
||||||
# stop
|
|
||||||
docker-compose down
|
|
||||||
```
|
|
||||||
|
|
||||||
### Podman (Recommended)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# https://podman.io/getting-started/installation
|
|
||||||
podman run -dit \
|
|
||||||
--network bridge \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
# The 5700 after the colon is the default port, if QlPort is set, it needs to be the same as QlPort.
|
|
||||||
-p 5700:5700 \
|
|
||||||
# Deployment paths are not required, e.g. /test.
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# Deployment port is not required, when using host mode, you can set the port after service startup, default 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
docker.io/whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Local
|
|
||||||
|
|
||||||
It is recommended to use a pure system installation to avoid losing the original system data, you need to install node/npm/python3/pip3 yourself
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install -g @whyour/qinglong
|
|
||||||
qinglong
|
|
||||||
# Add the environment variables QL_DIR and QL_DATA_DIR when prompted
|
|
||||||
export QL_DIR=""
|
|
||||||
export QL_DATA_DIR=""
|
|
||||||
# Run again
|
|
||||||
qinglong
|
|
||||||
```
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
@@ -186,22 +190,16 @@ $ git clone git@github.com:whyour/qinglong.git
|
|||||||
$ cd qinglong
|
$ cd qinglong
|
||||||
$ cp .env.example .env
|
$ cp .env.example .env
|
||||||
# Recommended use pnpm https://pnpm.io/zh/installation
|
# Recommended use pnpm https://pnpm.io/zh/installation
|
||||||
$ npm install -g pnpm@8.3.1
|
$ npm install -g pnpm
|
||||||
$ pnpm install
|
$ pnpm install
|
||||||
$ pnpm start
|
$ pnpm start
|
||||||
```
|
```
|
||||||
|
|
||||||
Open your browser and visit <http://127.0.0.1:5700>
|
Open your browser and visit http://127.0.0.1:5700
|
||||||
|
|
||||||
## Links
|
## Communication
|
||||||
|
|
||||||
- [nevinee](https://gitee.com/evine)
|
[telegram channel](https://t.me/jiao_long)
|
||||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
|
||||||
- [Ant Design](https://ant.design)
|
|
||||||
- [Ant Design Pro](https://pro.ant.design/)
|
|
||||||
- [Umijs](https://umijs.org)
|
|
||||||
- [darkreader](https://github.com/darkreader/darkreader)
|
|
||||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
|
||||||
|
|
||||||
## Name Origin
|
## Name Origin
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +1,30 @@
|
|||||||
<div align="center">
|
<p align="center">
|
||||||
<img width="100" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
<a href="https://github.com/whyour/qinglong">
|
||||||
|
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
<h1 align="center">青龙</h1>
|
<h1 align="center">青龙</h1>
|
||||||
|
|
||||||
简体中文 | [English](./README-en.md)
|
<div align="center">
|
||||||
|
|
||||||
支持 Python3、JavaScript、Shell、Typescript 的定时任务管理平台
|
支持python3、javaScript、shell、typescript 的定时任务管理面板
|
||||||
|
|
||||||
Timed task management platform supporting Python3, JavaScript, Shell, Typescript
|
[![docker version][docker-version-image]][docker-version-url] [![docker pulls][docker-pulls-image]][docker-pulls-url] [![docker stars][docker-stars-image]][docker-stars-url] [![docker image size][docker-image-size-image]][docker-image-size-url]
|
||||||
|
|
||||||
[![npm version][npm-version-image]][npm-version-url] [![docker pulls][docker-pulls-image]][docker-pulls-url] [![docker stars][docker-stars-image]][docker-stars-url] [![docker image size][docker-image-size-image]][docker-image-size-url]
|
|
||||||
|
|
||||||
[npm-version-image]: https://img.shields.io/npm/v/@whyour/qinglong?style=flat
|
|
||||||
[npm-version-url]: https://www.npmjs.com/package/@whyour/qinglong?activeTab=readme
|
|
||||||
[docker-pulls-image]: https://img.shields.io/docker/pulls/whyour/qinglong?style=flat
|
[docker-pulls-image]: https://img.shields.io/docker/pulls/whyour/qinglong?style=flat
|
||||||
[docker-pulls-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-pulls-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
|
[docker-version-image]: https://img.shields.io/docker/v/whyour/qinglong?style=flat
|
||||||
|
[docker-version-url]: https://hub.docker.com/r/whyour/qinglong/tags?page=1&ordering=last_updated
|
||||||
[docker-stars-image]: https://img.shields.io/docker/stars/whyour/qinglong?style=flat
|
[docker-stars-image]: https://img.shields.io/docker/stars/whyour/qinglong?style=flat
|
||||||
[docker-stars-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-stars-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
||||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
|
|
||||||
[Demo](http://demo.dlww.cc:4433/) / [Issues](https://github.com/whyour/qinglong/issues) / [Telegram Channel](https://t.me/jiao_long) / [Buy Me a Coffee](https://www.buymeacoffee.com/qinglong)
|
|
||||||
|
|
||||||
[演示](http://demo.dlww.cc:4433/) / [反馈](https://github.com/whyour/qinglong/issues) / [Telegram 频道](https://t.me/jiao_long) / [打赏开发者](https://user-images.githubusercontent.com/22700758/244744295-29cd0cd1-c8bb-4ea1-adf6-29bd390ad4dd.jpg)
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||

|
[](https://whyour.cn)
|
||||||
|
|
||||||
|
简体中文 | [English](./README-en.md)
|
||||||
|
|
||||||
## 功能
|
## 功能
|
||||||
|
|
||||||
@@ -37,47 +36,98 @@ Timed task management platform supporting Python3, JavaScript, Shell, Typescript
|
|||||||
- 支持暗黑模式
|
- 支持暗黑模式
|
||||||
- 支持手机端操作
|
- 支持手机端操作
|
||||||
|
|
||||||
## 版本
|
## 部署
|
||||||
|
|
||||||
### docker
|
### 本机部署
|
||||||
|
|
||||||
`latest` 镜像是基于 `alpine` 构建,`debian` 镜像是基于 `debian-slim` 构建。如果需要使用 `alpine` 不支持的依赖,建议使用 `debian` 镜像
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker pull whyour/qinglong:latest
|
# 待完善
|
||||||
docker pull whyour/qinglong:debian
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### npm
|
### podman 部署
|
||||||
|
|
||||||
npm 版本支持 `debian/ubuntu/centos/alpine` 系统,需要自行安装 `node/python3`
|
1. podman 安装
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i @whyour/qinglong
|
https://podman.io/getting-started/installation
|
||||||
```
|
```
|
||||||
|
|
||||||
## 内置命令
|
2. 启动容器
|
||||||
|
|
||||||
1. task
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 依次执行,如果设置了随机延迟,将随机延迟一定秒数
|
podman run -dit \
|
||||||
task <file_path>
|
--network bridge \
|
||||||
# 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日,同时记录在日志文件中
|
-v $PWD/ql:/ql/data \
|
||||||
task <file_path> now
|
-p 5700:5700 \
|
||||||
# 并发执行,无论是否设置了随机延迟,均立即运行,前台不产生日,直接记录在日志文件中,且可指定账号执行
|
--name qinglong \
|
||||||
task <file_path> conc <env_name> <account_number>(可选的)
|
--hostname qinglong \
|
||||||
# 指定账号执行,无论是否设置了随机延迟,均立即运行
|
--restart unless-stopped \
|
||||||
task <file_path> desi <env_name> <account_number>
|
docker.io/whyour/qinglong:latest
|
||||||
# 设置任务超时时间
|
|
||||||
task -m <max_time> <file_path>
|
|
||||||
# 实时打印任务日志,创建定时任务时,不用携带此参数
|
|
||||||
task -l <file_path>
|
|
||||||
# 使用 -- 分割,-- 后面的参数会传给脚本,下面的例子,脚本就可接收到参数 -u whyour -p password
|
|
||||||
task <file_path> -- -u whyour -p password
|
|
||||||
```
|
```
|
||||||
|
|
||||||
1. ql
|
### docker 部署
|
||||||
|
|
||||||
|
1. docker 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo curl -sSL get.docker.com | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 配置国内镜像源
|
||||||
|
Configure domestic mirror sources
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p /etc/docker
|
||||||
|
tee /etc/docker/daemon.json <<-'EOF'
|
||||||
|
{
|
||||||
|
"registry-mirrors": [
|
||||||
|
"https://0b27f0a81a00f3560fbdc00ddd2f99e0.mirror.swr.myhuaweicloud.com",
|
||||||
|
"https://ypzju6vq.mirror.aliyuncs.com",
|
||||||
|
"https://registry.docker-cn.com",
|
||||||
|
"http://hub-mirror.c.163.com",
|
||||||
|
"https://docker.mirrors.ustc.edu.cn"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl restart docker
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 启动容器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -dit \
|
||||||
|
-v $PWD/ql:/ql/data \
|
||||||
|
-p 5700:5700 \
|
||||||
|
--name qinglong \
|
||||||
|
--hostname qinglong \
|
||||||
|
--restart unless-stopped \
|
||||||
|
whyour/qinglong:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### docker-compose 部署
|
||||||
|
|
||||||
|
1. docker-compose 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 启动容器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir qinglong
|
||||||
|
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
||||||
|
|
||||||
|
# 启动
|
||||||
|
docker-compose up -d
|
||||||
|
# 停止
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用
|
||||||
|
|
||||||
|
1. 内置命令
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 更新并重启青龙
|
# 更新并重启青龙
|
||||||
@@ -98,87 +148,40 @@ ql check
|
|||||||
ql resetlet
|
ql resetlet
|
||||||
# 禁用两步登录
|
# 禁用两步登录
|
||||||
ql resettfa
|
ql resettfa
|
||||||
|
|
||||||
|
# 依次执行,如果设置了随机延迟,将随机延迟一定秒数
|
||||||
|
task <file_path>
|
||||||
|
# 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日,同时记录在日志文件中
|
||||||
|
task <file_path> now
|
||||||
|
# 并发执行,无论是否设置了随机延迟,均立即运行,前台不产生日,直接记录在日志文件中,且可指定账号执行
|
||||||
|
task <file_path> conc <env_name> <account_number>(可选的)
|
||||||
|
# 指定账号执行,无论是否设置了随机延迟,均立即运行
|
||||||
|
task <file_path> desi <env_name> <account_number>
|
||||||
```
|
```
|
||||||
|
|
||||||
1. 参数说明
|
2. 参数说明
|
||||||
|
|
||||||
- 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: 任务执行时需要并发或者指定时的环境变量名称
|
||||||
- account_number: 任务执行时指定某个环境变量需要执行的账号序号
|
* account_number: 任务执行时指定某个环境变量需要执行的账号序号
|
||||||
- max_time: 超时时间,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
|
||||||
|
|
||||||
## 部署
|
## 链接
|
||||||
|
|
||||||
### docker (推荐)
|
- [nevinee](https://gitee.com/evine)
|
||||||
|
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||||
```bash
|
- [Ant Design](https://ant.design)
|
||||||
# curl -sSL get.docker.com | sh
|
- [Ant Design Pro](https://pro.ant.design/)
|
||||||
docker run -dit \
|
- [Umijs3.0](https://umijs.org)
|
||||||
-v $PWD/ql/data:/ql/data \
|
- [darkreader](https://github.com/darkreader/darkreader)
|
||||||
# 冒号后面的 5700 为默认端口,如果设置了 QlPort, 需要跟 QlPort 保持一致
|
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||||
-p 5700:5700 \
|
|
||||||
# 部署路径非必须,比如 /test
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# 部署端口非必须,当使用 host 模式时,可以设置服务启动后的端口,默认 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
--restart unless-stopped \
|
|
||||||
whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### docker-compose (推荐)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
|
||||||
mkdir qinglong
|
|
||||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
|
||||||
|
|
||||||
# 启动
|
|
||||||
docker-compose up -d
|
|
||||||
# 停止
|
|
||||||
docker-compose down
|
|
||||||
```
|
|
||||||
|
|
||||||
### podman (推荐)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# https://podman.io/getting-started/installation
|
|
||||||
podman run -dit \
|
|
||||||
--network bridge \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
# 冒号后面的 5700 为默认端口,如果设置了 QlPort, 需要跟 QlPort 保持一致
|
|
||||||
-p 5700:5700 \
|
|
||||||
# 部署路径非必须,比如 /test
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# 部署端口非必须,当使用 host 模式时,可以设置服务启动后的端口,默认 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
docker.io/whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本机
|
|
||||||
|
|
||||||
建议使用纯净系统安装,避免系统原有数据丢失,需要自己安装 node/npm/python3/pip3
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install -g @whyour/qinglong
|
|
||||||
qinglong
|
|
||||||
# 根据提示增加环境变量 QL_DIR 和 QL_DATA_DIR
|
|
||||||
export QL_DIR=""
|
|
||||||
export QL_DATA_DIR=""
|
|
||||||
# 再次执行
|
|
||||||
qinglong
|
|
||||||
```
|
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
@@ -187,22 +190,16 @@ $ git clone git@github.com:whyour/qinglong.git
|
|||||||
$ cd qinglong
|
$ cd qinglong
|
||||||
$ cp .env.example .env
|
$ cp .env.example .env
|
||||||
# 推荐使用 pnpm https://pnpm.io/zh/installation
|
# 推荐使用 pnpm https://pnpm.io/zh/installation
|
||||||
$ npm install -g pnpm@8.3.1
|
$ npm install -g pnpm
|
||||||
$ pnpm install
|
$ pnpm install
|
||||||
$ pnpm start
|
$ pnpm start
|
||||||
```
|
```
|
||||||
|
|
||||||
打开你的浏览器,访问 http://127.0.0.1:5700
|
打开你的浏览器,访问 http://127.0.0.1:5700
|
||||||
|
|
||||||
## 链接
|
## 交流
|
||||||
|
|
||||||
- [nevinee](https://gitee.com/evine)
|
[telegram频道](https://t.me/jiao_long)
|
||||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
|
||||||
- [Ant Design](https://ant.design)
|
|
||||||
- [Ant Design Pro](https://pro.ant.design/)
|
|
||||||
- [Umijs](https://umijs.org)
|
|
||||||
- [darkreader](https://github.com/darkreader/darkreader)
|
|
||||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
|
||||||
|
|
||||||
## 名称来源
|
## 名称来源
|
||||||
|
|
||||||
|
|||||||
+3
-4
@@ -5,7 +5,6 @@ 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 { join } from 'path';
|
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
@@ -42,11 +41,11 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
if (req.params.file.includes('sample')) {
|
if (req.params.file.includes('sample')) {
|
||||||
content = getFileContentByName(
|
content = getFileContentByName(
|
||||||
join(config.samplePath, req.params.file),
|
`${config.samplePath}${req.params.file}`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
content = getFileContentByName(
|
content = getFileContentByName(
|
||||||
join(config.configPath, req.params.file),
|
`${config.configPath}${req.params.file}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
@@ -71,7 +70,7 @@ export default (app: Router) => {
|
|||||||
if (config.blackFileList.includes(name)) {
|
if (config.blackFileList.includes(name)) {
|
||||||
res.send({ code: 403, message: '文件无法访问' });
|
res.send({ code: 403, message: '文件无法访问' });
|
||||||
}
|
}
|
||||||
const path = join(config.configPath, name);
|
const path = `${config.configPath}${name}`;
|
||||||
fs.writeFileSync(path, content);
|
fs.writeFileSync(path, content);
|
||||||
res.send({ code: 200, message: '保存成功' });
|
res.send({ code: 200, message: '保存成功' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
+4
-157
@@ -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,141 +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(),
|
|
||||||
filterRelation: Joi.string().optional(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
const data = await cronViewService.create(req.body);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/views',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
name: Joi.string().required(),
|
|
||||||
id: Joi.number().required(),
|
|
||||||
sorts: Joi.array().optional().allow(null),
|
|
||||||
filters: Joi.array().optional(),
|
|
||||||
filterRelation: Joi.string().optional(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
if (req.body.type === 1) {
|
|
||||||
return res.send({ code: 400, message: '参数错误' });
|
|
||||||
} else {
|
|
||||||
const data = await cronViewService.update(req.body);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.delete(
|
|
||||||
'/views',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.array().items(Joi.number().required()),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
const data = await cronViewService.remove(req.body);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/views/move',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
fromIndex: Joi.number().required(),
|
|
||||||
toIndex: Joi.number().required(),
|
|
||||||
id: Joi.number().required(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
const data = await cronViewService.move(req.body);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/views/disable',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.array().items(Joi.number().required()),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
const data = await cronViewService.disabled(req.body);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/views/enable',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.array().items(Joi.number().required()),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const cronViewService = Container.get(CronViewService);
|
|
||||||
const data = await cronViewService.enabled(req.body);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
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);
|
||||||
@@ -152,21 +21,6 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/detail',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const cronService = Container.get(CronService);
|
|
||||||
const data = await cronService.find(req.query as any);
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
logger.error('🔥 error: %o', e);
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
'/',
|
'/',
|
||||||
celebrate({
|
celebrate({
|
||||||
@@ -175,10 +29,6 @@ export default (app: Router) => {
|
|||||||
schedule: Joi.string().required(),
|
schedule: Joi.string().required(),
|
||||||
name: Joi.string().optional(),
|
name: Joi.string().optional(),
|
||||||
labels: Joi.array().optional(),
|
labels: Joi.array().optional(),
|
||||||
sub_id: Joi.number().optional().allow(null),
|
|
||||||
extra_schedules: Joi.array().optional().allow(null),
|
|
||||||
task_before: Joi.string().optional().allow('').allow(null),
|
|
||||||
task_after: Joi.string().optional().allow('').allow(null),
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
@@ -335,10 +185,6 @@ export default (app: Router) => {
|
|||||||
command: Joi.string().required(),
|
command: Joi.string().required(),
|
||||||
schedule: Joi.string().required(),
|
schedule: Joi.string().required(),
|
||||||
name: Joi.string().optional().allow(null),
|
name: Joi.string().optional().allow(null),
|
||||||
sub_id: Joi.number().optional().allow(null),
|
|
||||||
extra_schedules: Joi.array().optional().allow(null),
|
|
||||||
task_before: Joi.string().optional().allow('').allow(null),
|
|
||||||
task_after: Joi.string().optional().allow('').allow(null),
|
|
||||||
id: Joi.number().required(),
|
id: Joi.number().required(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -458,12 +304,13 @@ export default (app: Router) => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.status({
|
const data = await cronService.status({
|
||||||
...req.body,
|
...req.body,
|
||||||
status: req.body.status ? parseInt(req.body.status) : undefined,
|
status: parseInt(req.body.status),
|
||||||
pid: req.body.pid ? parseInt(req.body.pid) : undefined,
|
pid: parseInt(req.body.pid) || '',
|
||||||
});
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
+2
-50
@@ -3,22 +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';
|
|
||||||
import { safeJSONParse } from '../config/util';
|
|
||||||
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);
|
||||||
|
|
||||||
@@ -40,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(''),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -110,6 +94,7 @@ 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);
|
||||||
@@ -192,37 +177,4 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.post(
|
|
||||||
'/upload',
|
|
||||||
upload.single('env'),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const envService = Container.get(EnvService);
|
|
||||||
const fileContent = await fs.promises.readFile(req!.file!.path, 'utf8');
|
|
||||||
const parseContent = safeJSONParse(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);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-31
@@ -3,9 +3,8 @@ 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'];
|
const blacklist = ['.tmp'];
|
||||||
|
|
||||||
@@ -46,33 +45,4 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.delete(
|
|
||||||
'/',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
filename: Joi.string().required(),
|
|
||||||
path: Joi.string().allow(''),
|
|
||||||
type: Joi.string().optional(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
let { filename, path, type } = req.body as {
|
|
||||||
filename: string;
|
|
||||||
path: string;
|
|
||||||
type: string;
|
|
||||||
};
|
|
||||||
const filePath = join(config.logPath, path, filename);
|
|
||||||
if (type === 'directory') {
|
|
||||||
await emptyDir(filePath);
|
|
||||||
} else {
|
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
}
|
|
||||||
res.send({ code: 200 });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
+12
-59
@@ -4,7 +4,6 @@ import {
|
|||||||
readDirs,
|
readDirs,
|
||||||
getLastModifyFilePath,
|
getLastModifyFilePath,
|
||||||
readDir,
|
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';
|
||||||
@@ -34,7 +33,7 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let result = [];
|
let result = [];
|
||||||
const blacklist = ['node_modules', '.git', '.pnpm'];
|
const blacklist = ['node_modules', '.git'];
|
||||||
if (req.query.path) {
|
if (req.query.path) {
|
||||||
const targetPath = path.join(
|
const targetPath = path.join(
|
||||||
config.scriptPath,
|
config.scriptPath,
|
||||||
@@ -78,13 +77,11 @@ 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 {
|
||||||
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) {
|
||||||
@@ -94,7 +91,7 @@ export default (app: Router) => {
|
|||||||
path += '/';
|
path += '/';
|
||||||
}
|
}
|
||||||
if (!path.startsWith('/')) {
|
if (!path.startsWith('/')) {
|
||||||
path = join(config.scriptPath, path);
|
path = `${config.scriptPath}${path}`;
|
||||||
}
|
}
|
||||||
if (config.writePathList.every((x) => !path.startsWith(x))) {
|
if (config.writePathList.every((x) => !path.startsWith(x))) {
|
||||||
return res.send({
|
return res.send({
|
||||||
@@ -108,23 +105,15 @@ export default (app: Router) => {
|
|||||||
return res.send({ code: 200 });
|
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)) {
|
||||||
fs.copyFileSync(
|
fs.copyFileSync(
|
||||||
originFilePath,
|
originFilePath,
|
||||||
join(config.bakPath, originFilename.replace(/\//g, '')),
|
`${config.bakPath}${originFilename.replace(/\//g, '')}`,
|
||||||
);
|
);
|
||||||
if (filename !== originFilename) {
|
if (filename !== originFilename) {
|
||||||
fs.unlinkSync(originFilePath);
|
fs.unlinkSync(originFilePath);
|
||||||
@@ -170,23 +159,17 @@ 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') {
|
|
||||||
await emptyDir(filePath);
|
|
||||||
} else {
|
|
||||||
fs.unlinkSync(filePath);
|
fs.unlinkSync(filePath);
|
||||||
}
|
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -207,7 +190,7 @@ export default (app: Router) => {
|
|||||||
let { filename } = req.body as {
|
let { filename } = req.body as {
|
||||||
filename: string;
|
filename: string;
|
||||||
};
|
};
|
||||||
const filePath = join(config.scriptPath, filename);
|
const filePath = `${config.scriptPath}${filename}`;
|
||||||
// const stats = fs.statSync(filePath);
|
// const stats = fs.statSync(filePath);
|
||||||
// res.set({
|
// res.set({
|
||||||
// 'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
|
// 'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
|
||||||
@@ -255,53 +238,23 @@ 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(''),
|
||||||
pid: Joi.number().optional().allow(''),
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let { filename, path, pid } = req.body;
|
let { filename, content, path } = req.body;
|
||||||
const { name, ext } = parse(filename);
|
const { name, ext } = parse(filename);
|
||||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||||
const logPath = join(config.logPath, path, `${name}.swap`);
|
|
||||||
|
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const result = await scriptService.stopScript(filePath, pid);
|
const result = await scriptService.stopScript(filePath);
|
||||||
setTimeout(() => {
|
|
||||||
emptyDir(logPath);
|
|
||||||
}, 3000);
|
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/rename',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
filename: Joi.string().required(),
|
|
||||||
path: Joi.string().allow(''),
|
|
||||||
newFilename: Joi.string().required(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
let { filename, path, type, newFilename } = req.body as {
|
|
||||||
filename: string;
|
|
||||||
path: string;
|
|
||||||
type: string;
|
|
||||||
newFilename: string;
|
|
||||||
};
|
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
|
||||||
const newPath = join(config.scriptPath, path, newFilename);
|
|
||||||
fs.renameSync(filePath, newPath);
|
|
||||||
res.send({ code: 200 });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -49,9 +49,6 @@ export default (app: Router) => {
|
|||||||
sub_after: Joi.string().optional().allow('').allow(null),
|
sub_after: Joi.string().optional().allow('').allow(null),
|
||||||
schedule_type: Joi.string().required(),
|
schedule_type: Joi.string().required(),
|
||||||
alias: Joi.string().required(),
|
alias: Joi.string().required(),
|
||||||
proxy: Joi.string().optional().allow('').allow(null),
|
|
||||||
autoAddCron: Joi.boolean().optional().allow('').allow(null),
|
|
||||||
autoDelCron: Joi.boolean().optional().allow('').allow(null),
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
@@ -180,9 +177,6 @@ export default (app: Router) => {
|
|||||||
sub_before: Joi.string().optional().allow('').allow(null),
|
sub_before: Joi.string().optional().allow('').allow(null),
|
||||||
sub_after: Joi.string().optional().allow('').allow(null),
|
sub_after: Joi.string().optional().allow('').allow(null),
|
||||||
alias: Joi.string().required(),
|
alias: Joi.string().required(),
|
||||||
proxy: Joi.string().optional().allow('').allow(null),
|
|
||||||
autoAddCron: Joi.boolean().optional().allow('').allow(null),
|
|
||||||
autoDelCron: Joi.boolean().optional().allow('').allow(null),
|
|
||||||
id: Joi.number().required(),
|
id: Joi.number().required(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -210,16 +204,12 @@ export default (app: Router) => {
|
|||||||
'/',
|
'/',
|
||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.array().items(Joi.number().required()),
|
body: Joi.array().items(Joi.number().required()),
|
||||||
query: Joi.object({
|
|
||||||
force: Joi.boolean().optional(),
|
|
||||||
t: Joi.number()
|
|
||||||
})
|
|
||||||
}),
|
}),
|
||||||
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 {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.remove(req.body, req.query);
|
const data = await subscriptionService.remove(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
|
|||||||
+14
-152
@@ -7,25 +7,7 @@ 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 {
|
|
||||||
getUniqPath,
|
|
||||||
handleLogPath,
|
|
||||||
parseVersion,
|
|
||||||
promiseExec,
|
|
||||||
} from '../config/util';
|
|
||||||
import dayjs from 'dayjs';
|
|
||||||
import multer from 'multer';
|
|
||||||
|
|
||||||
const route = Router();
|
const route = Router();
|
||||||
const storage = multer.diskStorage({
|
|
||||||
destination: function (req, file, cb) {
|
|
||||||
cb(null, config.tmpPath);
|
|
||||||
},
|
|
||||||
filename: function (req, file, cb) {
|
|
||||||
cb(null, 'data.tgz');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const upload = multer({ storage: storage });
|
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/system', route);
|
app.use('/system', route);
|
||||||
@@ -35,14 +17,18 @@ export default (app: Router) => {
|
|||||||
try {
|
try {
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
const authInfo = await userService.getUserInfo();
|
const authInfo = await userService.getUserInfo();
|
||||||
const { version, changeLog, changeLogLink, publishTime } =
|
const envCount = await EnvModel.count();
|
||||||
await parseVersion(config.versionFile);
|
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
||||||
|
|
||||||
|
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||||
|
const version = currentVersionFile.match(versionRegx)![1];
|
||||||
|
|
||||||
let isInitialized = true;
|
let isInitialized = true;
|
||||||
if (
|
if (
|
||||||
Object.keys(authInfo).length === 2 &&
|
Object.keys(authInfo).length === 2 &&
|
||||||
authInfo.username === 'admin' &&
|
authInfo.username === 'admin' &&
|
||||||
authInfo.password === 'admin'
|
authInfo.password === 'admin' &&
|
||||||
|
envCount === 0
|
||||||
) {
|
) {
|
||||||
isInitialized = false;
|
isInitialized = false;
|
||||||
}
|
}
|
||||||
@@ -51,10 +37,6 @@ export default (app: Router) => {
|
|||||||
data: {
|
data: {
|
||||||
isInitialized,
|
isInitialized,
|
||||||
version,
|
version,
|
||||||
publishTime: dayjs(publishTime).unix(),
|
|
||||||
branch: process.env.QL_BRANCH || 'master',
|
|
||||||
changeLog,
|
|
||||||
changeLogLink,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -64,12 +46,12 @@ export default (app: Router) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/config',
|
'/log/remove',
|
||||||
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 {
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
const data = await systemService.getSystemConfig();
|
const data = await systemService.getLogRemoveFrequency();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -78,18 +60,19 @@ export default (app: Router) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
route.put(
|
route.put(
|
||||||
'/config',
|
'/log/remove',
|
||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
logRemoveFrequency: Joi.number().optional().allow(null),
|
frequency: Joi.number().required(),
|
||||||
cronConcurrency: Joi.number().optional().allow(null),
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
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 {
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
const result = await systemService.updateSystemConfig(req.body);
|
const result = await systemService.updateLogRemoveFrequency(
|
||||||
|
req.body.frequency,
|
||||||
|
);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -125,25 +108,6 @@ export default (app: Router) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/reload',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
type: Joi.string().required(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const result = await systemService.reloadSystem(req.body.type);
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
route.put(
|
||||||
'/notify',
|
'/notify',
|
||||||
celebrate({
|
celebrate({
|
||||||
@@ -163,106 +127,4 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/command-run',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
command: Joi.string().required(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const command = req.body.command
|
|
||||||
const idStr = `cat ${config.crontabFile} | grep -E "${command}" | perl -pe "s|.*ID=(.*) ${command}.*|\\1|" | head -1 | awk -F " " '{print $1}' | xargs echo -n`;
|
|
||||||
let id = await promiseExec(idStr);
|
|
||||||
const uniqPath = await getUniqPath(command, id);
|
|
||||||
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
|
||||||
const logPath = `${uniqPath}/${logTime}.log`;
|
|
||||||
res.setHeader('Content-type', 'application/octet-stream');
|
|
||||||
await systemService.run(
|
|
||||||
{ ...req.body, logPath },
|
|
||||||
{
|
|
||||||
onStart: async (cp, startTime) => {
|
|
||||||
res.setHeader('QL-Task-Pid', `${cp.pid}`);
|
|
||||||
},
|
|
||||||
onEnd: async (cp, endTime, diff) => {
|
|
||||||
res.end();
|
|
||||||
},
|
|
||||||
onError: async (message: string) => {
|
|
||||||
res.write(`\n${message}`);
|
|
||||||
const absolutePath = await handleLogPath(logPath);
|
|
||||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
|
||||||
},
|
|
||||||
onLog: async (message: string) => {
|
|
||||||
res.write(`\n${message}`);
|
|
||||||
const absolutePath = await handleLogPath(logPath);
|
|
||||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/command-stop',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
command: Joi.string().optional(),
|
|
||||||
pid: Joi.number().optional(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const result = await systemService.stop(req.body);
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/data/export',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
await systemService.exportData(res);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/data/import',
|
|
||||||
upload.single('data'),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const result = await systemService.importData();
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/log',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
await systemService.getSystemLog(res);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { celebrate, Joi } from 'celebrate';
|
|||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { v4 as uuidV4 } from 'uuid';
|
import { v4 as uuidV4 } from 'uuid';
|
||||||
import rateLimit from 'express-rate-limit';
|
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
@@ -27,10 +26,6 @@ export default (app: Router) => {
|
|||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
'/login',
|
'/login',
|
||||||
rateLimit({
|
|
||||||
windowMs: 15 * 60 * 1000,
|
|
||||||
max: 100,
|
|
||||||
}),
|
|
||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
username: Joi.string().required(),
|
username: Joi.string().required(),
|
||||||
|
|||||||
+4
-4
@@ -1,6 +1,9 @@
|
|||||||
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';
|
||||||
|
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
@@ -16,13 +19,10 @@ async function startServer() {
|
|||||||
|
|
||||||
const server = app
|
const server = app
|
||||||
.listen(config.port, () => {
|
.listen(config.port, () => {
|
||||||
Logger.debug(`✌️ 后端服务启动成功!`);
|
Logger.debug(`✌️ Back server launched on port ${config.port}`);
|
||||||
console.debug(`✌️ 后端服务启动成功!`);
|
|
||||||
process.send?.('ready');
|
|
||||||
})
|
})
|
||||||
.on('error', (err) => {
|
.on('error', (err) => {
|
||||||
Logger.error(err);
|
Logger.error(err);
|
||||||
console.error(err);
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
export const LOG_END_SYMBOL = ' ';
|
|
||||||
|
|
||||||
export const TASK_COMMAND = 'task';
|
|
||||||
export const QL_COMMAND = 'ql';
|
|
||||||
|
|
||||||
export const TASK_PREFIX = `${TASK_COMMAND} `;
|
|
||||||
export const QL_PREFIX = `${QL_COMMAND} `;
|
|
||||||
+5
-33
@@ -1,27 +1,14 @@
|
|||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { createRandomString } from './share';
|
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.yaml`;
|
|
||||||
|
|
||||||
const rootPath = process.env.QL_DIR as string;
|
|
||||||
const envFound = dotenv.config({ path: path.join(rootPath, '.env') });
|
|
||||||
|
|
||||||
|
const envFound = dotenv.config();
|
||||||
|
const rootPath = process.cwd();
|
||||||
const dataPath = path.join(rootPath, 'data/');
|
const dataPath = path.join(rootPath, 'data/');
|
||||||
const shellPath = path.join(rootPath, 'shell/');
|
|
||||||
const tmpPath = path.join(rootPath, '.tmp/');
|
|
||||||
const samplePath = path.join(rootPath, 'sample/');
|
const samplePath = path.join(rootPath, 'sample/');
|
||||||
const configPath = path.join(dataPath, 'config/');
|
const configPath = path.join(dataPath, 'config/');
|
||||||
const scriptPath = path.join(dataPath, 'scripts/');
|
const scriptPath = path.join(dataPath, 'scripts/');
|
||||||
@@ -29,8 +16,6 @@ const bakPath = path.join(dataPath, 'bak/');
|
|||||||
const logPath = path.join(dataPath, 'log/');
|
const logPath = path.join(dataPath, 'log/');
|
||||||
const dbPath = path.join(dataPath, 'db/');
|
const dbPath = path.join(dataPath, 'db/');
|
||||||
const uploadPath = path.join(dataPath, 'upload/');
|
const uploadPath = path.join(dataPath, 'upload/');
|
||||||
const sshdPath = path.join(dataPath, 'ssh.d/');
|
|
||||||
const systemLogPath = path.join(dataPath, 'syslog/');
|
|
||||||
|
|
||||||
const envFile = path.join(configPath, 'env.sh');
|
const envFile = path.join(configPath, 'env.sh');
|
||||||
const confFile = path.join(configPath, 'config.sh');
|
const confFile = path.join(configPath, 'config.sh');
|
||||||
@@ -44,9 +29,7 @@ const sqliteFile = path.join(samplePath, 'database.sqlite');
|
|||||||
const authError = '错误的用户名密码,请重试';
|
const authError = '错误的用户名密码,请重试';
|
||||||
const loginFaild = '请先登录!';
|
const loginFaild = '请先登录!';
|
||||||
const configString = 'config sample crontab shareCode diy';
|
const configString = 'config sample crontab shareCode diy';
|
||||||
const versionFile = path.join(rootPath, 'version.yaml');
|
const versionFile = path.join(rootPath, 'src/version.ts');
|
||||||
const dataTgzFile = path.join(tmpPath, 'data.tgz');
|
|
||||||
const shareShellFile = path.join(shellPath, 'share.sh');
|
|
||||||
|
|
||||||
if (envFound.error) {
|
if (envFound.error) {
|
||||||
throw new Error("⚠️ Couldn't find .env file ⚠️");
|
throw new Error("⚠️ Couldn't find .env file ⚠️");
|
||||||
@@ -64,10 +47,6 @@ export default {
|
|||||||
prefix: '/api',
|
prefix: '/api',
|
||||||
},
|
},
|
||||||
rootPath,
|
rootPath,
|
||||||
tmpPath,
|
|
||||||
dataPath,
|
|
||||||
dataTgzFile,
|
|
||||||
shareShellFile,
|
|
||||||
configString,
|
configString,
|
||||||
loginFaild,
|
loginFaild,
|
||||||
authError,
|
authError,
|
||||||
@@ -101,15 +80,8 @@ export default {
|
|||||||
'/api/system',
|
'/api/system',
|
||||||
'/api/user/init',
|
'/api/user/init',
|
||||||
'/api/user/notification/init',
|
'/api/user/notification/init',
|
||||||
'/open/user/login',
|
|
||||||
'/open/user/two-factor/login',
|
|
||||||
'/open/system',
|
|
||||||
'/open/user/init',
|
|
||||||
'/open/user/notification/init',
|
|
||||||
],
|
],
|
||||||
versionFile,
|
versionFile,
|
||||||
lastVersionFile,
|
lastVersionFile,
|
||||||
sqliteFile,
|
sqliteFile,
|
||||||
sshdPath,
|
|
||||||
systemLogPath,
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
import { Request, Response } from 'express';
|
|
||||||
import pick from 'lodash/pick';
|
|
||||||
|
|
||||||
let pickedEnv: Record<string, string>;
|
|
||||||
|
|
||||||
function getPickedEnv() {
|
|
||||||
if (pickedEnv) return pickedEnv;
|
|
||||||
const picked = pick(process.env, ['QlBaseUrl', 'DeployEnv']);
|
|
||||||
if (picked.QlBaseUrl) {
|
|
||||||
if (!picked.QlBaseUrl.startsWith('/')) {
|
|
||||||
picked.QlBaseUrl = `/${picked.QlBaseUrl}`
|
|
||||||
}
|
|
||||||
if (!picked.QlBaseUrl.endsWith('/')) {
|
|
||||||
picked.QlBaseUrl = `${picked.QlBaseUrl}/`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pickedEnv = picked as Record<string, string>;
|
|
||||||
return picked;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function serveEnv(_req: Request, res: Response) {
|
|
||||||
res.type('.js');
|
|
||||||
res.send(
|
|
||||||
Object.entries(getPickedEnv())
|
|
||||||
.map(([k, v]) => `window.__ENV__${k}=${JSON.stringify(v)};`)
|
|
||||||
.join('\n'),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
export function createRandomString(min: number, max: number): string {
|
|
||||||
const num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
|
||||||
const english = [
|
|
||||||
'a',
|
|
||||||
'b',
|
|
||||||
'c',
|
|
||||||
'd',
|
|
||||||
'e',
|
|
||||||
'f',
|
|
||||||
'g',
|
|
||||||
'h',
|
|
||||||
'i',
|
|
||||||
'j',
|
|
||||||
'k',
|
|
||||||
'l',
|
|
||||||
'm',
|
|
||||||
'n',
|
|
||||||
'o',
|
|
||||||
'p',
|
|
||||||
'q',
|
|
||||||
'r',
|
|
||||||
's',
|
|
||||||
't',
|
|
||||||
'u',
|
|
||||||
'v',
|
|
||||||
'w',
|
|
||||||
'x',
|
|
||||||
'y',
|
|
||||||
'z',
|
|
||||||
];
|
|
||||||
const ENGLISH = [
|
|
||||||
'A',
|
|
||||||
'B',
|
|
||||||
'C',
|
|
||||||
'D',
|
|
||||||
'E',
|
|
||||||
'F',
|
|
||||||
'G',
|
|
||||||
'H',
|
|
||||||
'I',
|
|
||||||
'J',
|
|
||||||
'K',
|
|
||||||
'L',
|
|
||||||
'M',
|
|
||||||
'N',
|
|
||||||
'O',
|
|
||||||
'P',
|
|
||||||
'Q',
|
|
||||||
'R',
|
|
||||||
'S',
|
|
||||||
'T',
|
|
||||||
'U',
|
|
||||||
'V',
|
|
||||||
'W',
|
|
||||||
'X',
|
|
||||||
'Y',
|
|
||||||
'Z',
|
|
||||||
];
|
|
||||||
const special = ['-', '_'];
|
|
||||||
const config = num.concat(english).concat(ENGLISH).concat(special);
|
|
||||||
|
|
||||||
const arr = [];
|
|
||||||
arr.push(getOne(num));
|
|
||||||
arr.push(getOne(english));
|
|
||||||
arr.push(getOne(ENGLISH));
|
|
||||||
arr.push(getOne(special));
|
|
||||||
|
|
||||||
const len = min + Math.floor(Math.random() * (max - min + 1));
|
|
||||||
|
|
||||||
for (let i = 4; i < len; i++) {
|
|
||||||
arr.push(config[Math.floor(Math.random() * config.length)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const newArr = [];
|
|
||||||
for (let j = 0; j < len; j++) {
|
|
||||||
newArr.push(arr.splice(Math.random() * arr.length, 1)[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getOne(arr: any[]) {
|
|
||||||
return arr[Math.floor(Math.random() * arr.length)];
|
|
||||||
}
|
|
||||||
|
|
||||||
return newArr.join('');
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import { Subscription } from '../data/subscription';
|
|
||||||
import isNil from 'lodash/isNil';
|
|
||||||
|
|
||||||
export function formatUrl(doc: Subscription) {
|
|
||||||
let url = doc.url;
|
|
||||||
let host = '';
|
|
||||||
if (doc.type === 'private-repo') {
|
|
||||||
if (doc.pull_type === 'ssh-key') {
|
|
||||||
host = doc.url!.replace(/.*\@([^\:]+)\:.*/, '$1');
|
|
||||||
url = doc.url!.replace(host, doc.alias);
|
|
||||||
} else {
|
|
||||||
host = doc.url!.replace(/.*\:\/\/([^\/]+)\/.*/, '$1');
|
|
||||||
const { username, password } = doc.pull_option as any;
|
|
||||||
url = doc.url!.replace(host, `${username}:${password}@${host}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { url, host };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatCommand(doc: Subscription, url?: string) {
|
|
||||||
let command = `SUB_ID=${doc.id} ql `;
|
|
||||||
let _url = url || formatUrl(doc).url;
|
|
||||||
const {
|
|
||||||
type,
|
|
||||||
whitelist,
|
|
||||||
blacklist,
|
|
||||||
dependences,
|
|
||||||
branch,
|
|
||||||
extensions,
|
|
||||||
proxy,
|
|
||||||
autoAddCron,
|
|
||||||
autoDelCron,
|
|
||||||
} = doc;
|
|
||||||
if (type === 'file') {
|
|
||||||
command += `raw "${_url}"`;
|
|
||||||
} else {
|
|
||||||
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${
|
|
||||||
dependences || ''
|
|
||||||
}" "${branch || ''}" "${extensions || ''}" "${proxy || ''}" "${
|
|
||||||
isNil(autoAddCron) ? true : Boolean(autoAddCron)
|
|
||||||
}" "${isNil(autoDelCron) ? true : Boolean(autoDelCron)}"`;
|
|
||||||
}
|
|
||||||
return command;
|
|
||||||
}
|
|
||||||
+103
-250
@@ -3,15 +3,6 @@ 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 { exec } from 'child_process';
|
||||||
import FormData from 'form-data';
|
|
||||||
import psTreeFun from 'pstree.remy';
|
|
||||||
import { promisify } from 'util';
|
|
||||||
import { load } from 'js-yaml';
|
|
||||||
import config from './index';
|
|
||||||
import { TASK_COMMAND } from './const';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
|
|
||||||
export * from './share';
|
|
||||||
|
|
||||||
export function getFileContentByName(fileName: string) {
|
export function getFileContentByName(fileName: string) {
|
||||||
if (fs.existsSync(fileName)) {
|
if (fs.existsSync(fileName)) {
|
||||||
@@ -39,6 +30,91 @@ export function getLastModifyFilePath(dir: string) {
|
|||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function createRandomString(min: number, max: number): string {
|
||||||
|
const num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
||||||
|
const english = [
|
||||||
|
'a',
|
||||||
|
'b',
|
||||||
|
'c',
|
||||||
|
'd',
|
||||||
|
'e',
|
||||||
|
'f',
|
||||||
|
'g',
|
||||||
|
'h',
|
||||||
|
'i',
|
||||||
|
'j',
|
||||||
|
'k',
|
||||||
|
'l',
|
||||||
|
'm',
|
||||||
|
'n',
|
||||||
|
'o',
|
||||||
|
'p',
|
||||||
|
'q',
|
||||||
|
'r',
|
||||||
|
's',
|
||||||
|
't',
|
||||||
|
'u',
|
||||||
|
'v',
|
||||||
|
'w',
|
||||||
|
'x',
|
||||||
|
'y',
|
||||||
|
'z',
|
||||||
|
];
|
||||||
|
const ENGLISH = [
|
||||||
|
'A',
|
||||||
|
'B',
|
||||||
|
'C',
|
||||||
|
'D',
|
||||||
|
'E',
|
||||||
|
'F',
|
||||||
|
'G',
|
||||||
|
'H',
|
||||||
|
'I',
|
||||||
|
'J',
|
||||||
|
'K',
|
||||||
|
'L',
|
||||||
|
'M',
|
||||||
|
'N',
|
||||||
|
'O',
|
||||||
|
'P',
|
||||||
|
'Q',
|
||||||
|
'R',
|
||||||
|
'S',
|
||||||
|
'T',
|
||||||
|
'U',
|
||||||
|
'V',
|
||||||
|
'W',
|
||||||
|
'X',
|
||||||
|
'Y',
|
||||||
|
'Z',
|
||||||
|
];
|
||||||
|
const special = ['-', '_'];
|
||||||
|
const config = num.concat(english).concat(ENGLISH).concat(special);
|
||||||
|
|
||||||
|
const arr = [];
|
||||||
|
arr.push(getOne(num));
|
||||||
|
arr.push(getOne(english));
|
||||||
|
arr.push(getOne(ENGLISH));
|
||||||
|
arr.push(getOne(special));
|
||||||
|
|
||||||
|
const len = min + Math.floor(Math.random() * (max - min + 1));
|
||||||
|
|
||||||
|
for (let i = 4; i < len; i++) {
|
||||||
|
arr.push(config[Math.floor(Math.random() * config.length)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const newArr = [];
|
||||||
|
for (let j = 0; j < len; j++) {
|
||||||
|
newArr.push(arr.splice(Math.random() * arr.length, 1)[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOne(arr: any[]) {
|
||||||
|
return arr[Math.floor(Math.random() * arr.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return newArr.join('');
|
||||||
|
}
|
||||||
|
|
||||||
export function getToken(req: any) {
|
export function getToken(req: any) {
|
||||||
const { authorization = '' } = req.headers;
|
const { authorization = '' } = req.headers;
|
||||||
if (authorization && authorization.split(' ')[0] === 'Bearer') {
|
if (authorization && authorization.split(' ')[0] === 'Bearer') {
|
||||||
@@ -84,11 +160,6 @@ export async function getNetIp(req: any) {
|
|||||||
if (ip.includes('127.0') || ip.includes('192.168') || ip.includes('10.7')) {
|
if (ip.includes('127.0') || ip.includes('192.168') || ip.includes('10.7')) {
|
||||||
ip = '';
|
ip = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ip) {
|
|
||||||
return { address: `获取失败`, ip };
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const baiduApi = got
|
const baiduApi = got
|
||||||
.get(`https://www.cip.cc/${ip}`, { timeout: 10000, retry: 0 })
|
.get(`https://www.cip.cc/${ip}`, { timeout: 10000, retry: 0 })
|
||||||
@@ -170,18 +241,6 @@ export async function createFile(file: string, data: string = '') {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function handleLogPath(
|
|
||||||
logPath: string,
|
|
||||||
data: string = '',
|
|
||||||
): Promise<string> {
|
|
||||||
const absolutePath = path.resolve(config.logPath, logPath);
|
|
||||||
const logFileExist = await fileExist(absolutePath);
|
|
||||||
if (!logFileExist) {
|
|
||||||
await createFile(absolutePath, data);
|
|
||||||
}
|
|
||||||
return absolutePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function concurrentRun(
|
export async function concurrentRun(
|
||||||
fnList: Array<() => Promise<any>> = [],
|
fnList: Array<() => Promise<any>> = [],
|
||||||
max = 5,
|
max = 5,
|
||||||
@@ -224,34 +283,14 @@ enum FileType {
|
|||||||
'file',
|
'file',
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IFile {
|
|
||||||
title: string;
|
|
||||||
key: string;
|
|
||||||
type: 'directory' | 'file';
|
|
||||||
parent: string;
|
|
||||||
mtime: number;
|
|
||||||
size?: number;
|
|
||||||
children?: IFile[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function dirSort(a: IFile, b: IFile): number {
|
|
||||||
if (a.type !== b.type) {
|
|
||||||
return FileType[a.type] < FileType[b.type] ? -1 : 1
|
|
||||||
} else if (a.mtime !== b.mtime) {
|
|
||||||
return a.mtime > b.mtime ? -1 : 1
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readDirs(
|
export function readDirs(
|
||||||
dir: string,
|
dir: string,
|
||||||
baseDir: string = '',
|
baseDir: string = '',
|
||||||
blacklist: string[] = [],
|
blacklist: string[] = [],
|
||||||
): IFile[] {
|
) {
|
||||||
const relativePath = path.relative(baseDir, dir);
|
const relativePath = path.relative(baseDir, dir);
|
||||||
const files = fs.readdirSync(dir);
|
const files = fs.readdirSync(dir);
|
||||||
const result: IFile[] = files
|
const result: any = files
|
||||||
.filter((x) => !blacklist.includes(x))
|
.filter((x) => !blacklist.includes(x))
|
||||||
.map((file: string) => {
|
.map((file: string) => {
|
||||||
const subPath = path.join(dir, file);
|
const subPath = path.join(dir, file);
|
||||||
@@ -262,22 +301,24 @@ export function readDirs(
|
|||||||
title: file,
|
title: file,
|
||||||
key,
|
key,
|
||||||
type: 'directory',
|
type: 'directory',
|
||||||
|
disabled: true,
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
mtime: stats.mtime.getTime(),
|
children: readDirs(subPath, baseDir).sort(
|
||||||
children: readDirs(subPath, baseDir).sort(dirSort),
|
(a: any, b: any) =>
|
||||||
|
(FileType as any)[a.type] - (FileType as any)[b.type],
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
title: file,
|
title: file,
|
||||||
type: 'file',
|
type: 'file',
|
||||||
isLeaf: true,
|
|
||||||
key,
|
key,
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
size: stats.size,
|
|
||||||
mtime: stats.mtime.getTime(),
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
return result.sort(dirSort);
|
return result.sort(
|
||||||
|
(a: any, b: any) => (FileType as any)[a.type] - (FileType as any)[b.type],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readDir(
|
export function readDir(
|
||||||
@@ -303,202 +344,14 @@ export function readDir(
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function emptyDir(path: string) {
|
export function promiseExec(command: string): Promise<string> {
|
||||||
const pathExist = await fileExist(path);
|
|
||||||
if (!pathExist) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const files = fs.readdirSync(path);
|
|
||||||
for (const file of files) {
|
|
||||||
const filePath = `${path}/${file}`;
|
|
||||||
const stats = fs.statSync(filePath);
|
|
||||||
if (stats.isDirectory()) {
|
|
||||||
await emptyDir(filePath);
|
|
||||||
} else {
|
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fs.rmdirSync(path);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function promiseExec(command: string): Promise<string> {
|
|
||||||
try {
|
|
||||||
const { stderr, stdout } = await promisify(exec)(command, { maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' });
|
|
||||||
return stdout || stderr;
|
|
||||||
} catch (error) {
|
|
||||||
return JSON.stringify(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function promiseExecSuccess(command: string): Promise<string> {
|
|
||||||
try {
|
|
||||||
const { stdout } = await promisify(exec)(command, { maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' });
|
|
||||||
return stdout || '';
|
|
||||||
} catch (error) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseHeaders(headers: string) {
|
|
||||||
if (!headers) return {};
|
|
||||||
|
|
||||||
const parsed: any = {};
|
|
||||||
let key;
|
|
||||||
let val;
|
|
||||||
let i;
|
|
||||||
|
|
||||||
headers &&
|
|
||||||
headers.split('\n').forEach(function parser(line) {
|
|
||||||
i = line.indexOf(':');
|
|
||||||
key = line.substring(0, i).trim().toLowerCase();
|
|
||||||
val = line.substring(i + 1).trim();
|
|
||||||
|
|
||||||
if (!key) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
|
|
||||||
});
|
|
||||||
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseBody(
|
|
||||||
body: string,
|
|
||||||
contentType:
|
|
||||||
| 'application/json'
|
|
||||||
| 'multipart/form-data'
|
|
||||||
| 'application/x-www-form-urlencoded',
|
|
||||||
) {
|
|
||||||
if (!body) return '';
|
|
||||||
|
|
||||||
const parsed: any = {};
|
|
||||||
let key;
|
|
||||||
let val;
|
|
||||||
let i;
|
|
||||||
|
|
||||||
body &&
|
|
||||||
body.split('\n').forEach(function parser(line) {
|
|
||||||
i = line.indexOf(':');
|
|
||||||
key = line.substring(0, i).trim().toLowerCase();
|
|
||||||
val = line.substring(i + 1).trim();
|
|
||||||
|
|
||||||
if (!key || parsed[key]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const jsonValue = JSON.parse(val);
|
|
||||||
parsed[key] = jsonValue;
|
|
||||||
} catch (error) {
|
|
||||||
parsed[key] = val;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
switch (contentType) {
|
|
||||||
case 'multipart/form-data':
|
|
||||||
return Object.keys(parsed).reduce((p, c) => {
|
|
||||||
p.append(c, parsed[c]);
|
|
||||||
return p;
|
|
||||||
}, new FormData());
|
|
||||||
case 'application/x-www-form-urlencoded':
|
|
||||||
return Object.keys(parsed).reduce((p, c) => {
|
|
||||||
return p ? `${p}&${c}=${parsed[c]}` : `${c}=${parsed[c]}`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function psTree(pid: number): Promise<number[]> {
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
psTreeFun(pid, (err: any, pids: number[]) => {
|
exec(
|
||||||
if (err) {
|
command,
|
||||||
reject(err);
|
{ maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' },
|
||||||
}
|
(err, stdout, stderr) => {
|
||||||
resolve(pids.filter((x) => !isNaN(x)));
|
resolve(stdout || stderr || JSON.stringify(err));
|
||||||
});
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function killTask(pid: number) {
|
|
||||||
const pids = await psTree(pid);
|
|
||||||
|
|
||||||
if (pids.length) {
|
|
||||||
try {
|
|
||||||
[pid, ...pids].reverse().forEach((x) => {
|
|
||||||
process.kill(x, 15);
|
|
||||||
});
|
|
||||||
} catch (error) { }
|
|
||||||
} else {
|
|
||||||
process.kill(pid, 2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getPid(name: string) {
|
|
||||||
const taskCommand = `ps -eo pid,command | grep "${name}" | grep -v grep | awk '{print $1}' | head -1 | xargs echo -n`;
|
|
||||||
const pid = await promiseExec(taskCommand);
|
|
||||||
return pid ? Number(pid) : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IVersion {
|
|
||||||
version: string;
|
|
||||||
changeLogLink: string;
|
|
||||||
changeLog: string;
|
|
||||||
publishTime: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function parseVersion(path: string): Promise<IVersion> {
|
|
||||||
return load(await promisify(fs.readFile)(path, 'utf8')) as IVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function parseContentVersion(content: string): Promise<IVersion> {
|
|
||||||
return load(content) as IVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getUniqPath(command: string, id: string): Promise<string> {
|
|
||||||
if (/^\d+$/.test(id)) {
|
|
||||||
id = `_${id}`;
|
|
||||||
} else {
|
|
||||||
id = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
const items = command.split(/ +/);
|
|
||||||
let str = items[0];
|
|
||||||
if (items[0] === TASK_COMMAND) {
|
|
||||||
str = items[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
const dotIndex = str.lastIndexOf('.');
|
|
||||||
|
|
||||||
if (dotIndex !== -1) {
|
|
||||||
str = str.slice(0, dotIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
const slashIndex = str.lastIndexOf('/');
|
|
||||||
|
|
||||||
let tempStr = '';
|
|
||||||
if (slashIndex !== -1) {
|
|
||||||
tempStr = str.slice(0, slashIndex);
|
|
||||||
const _slashIndex = tempStr.lastIndexOf('/');
|
|
||||||
if (_slashIndex !== -1) {
|
|
||||||
tempStr = tempStr.slice(_slashIndex + 1);
|
|
||||||
}
|
|
||||||
str = `${tempStr}_${str.slice(slashIndex + 1)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${str}${id}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function safeJSONParse(value?: string) {
|
|
||||||
if (!value) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return JSON.parse(value);
|
|
||||||
} catch (error) {
|
|
||||||
Logger.error('[JSON.parse失败]', error)
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+2
-21
@@ -1,11 +1,10 @@
|
|||||||
import { sequelize } from '.';
|
import { sequelize } from '.';
|
||||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||||
import { NotificationInfo } from './notify';
|
|
||||||
|
|
||||||
export class AuthInfo {
|
export class AuthInfo {
|
||||||
ip?: string;
|
ip?: string;
|
||||||
type: AuthDataType;
|
type: AuthDataType;
|
||||||
info?: AuthModelInfo;
|
info?: any;
|
||||||
id?: number;
|
id?: number;
|
||||||
|
|
||||||
constructor(options: AuthInfo) {
|
constructor(options: AuthInfo) {
|
||||||
@@ -26,27 +25,9 @@ export enum AuthDataType {
|
|||||||
'authToken' = 'authToken',
|
'authToken' = 'authToken',
|
||||||
'notification' = 'notification',
|
'notification' = 'notification',
|
||||||
'removeLogFrequency' = 'removeLogFrequency',
|
'removeLogFrequency' = 'removeLogFrequency',
|
||||||
'systemConfig' = 'systemConfig',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SystemConfigInfo {
|
interface AuthInstance extends Model<AuthInfo, AuthInfo>, AuthInfo {}
|
||||||
logRemoveFrequency?: number;
|
|
||||||
cronConcurrency?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LoginLogInfo {
|
|
||||||
timestamp?: number;
|
|
||||||
address?: string;
|
|
||||||
ip?: string;
|
|
||||||
platform?: string;
|
|
||||||
status?: LoginStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type AuthModelInfo = SystemConfigInfo &
|
|
||||||
Partial<NotificationInfo> &
|
|
||||||
LoginLogInfo;
|
|
||||||
|
|
||||||
export interface AuthInstance extends Model<AuthInfo, AuthInfo>, AuthInfo {}
|
|
||||||
export const AuthModel = sequelize.define<AuthInstance>('Auth', {
|
export const AuthModel = sequelize.define<AuthInstance>('Auth', {
|
||||||
ip: DataTypes.STRING,
|
ip: DataTypes.STRING,
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
|
|||||||
+6
-18
@@ -17,19 +17,15 @@ export class Crontab {
|
|||||||
labels?: string[];
|
labels?: string[];
|
||||||
last_running_time?: number;
|
last_running_time?: number;
|
||||||
last_execution_time?: number;
|
last_execution_time?: number;
|
||||||
sub_id?: number;
|
|
||||||
extra_schedules?: Array<{ schedule: string }>;
|
|
||||||
task_before?: string;
|
|
||||||
task_after?: string;
|
|
||||||
|
|
||||||
constructor(options: Crontab) {
|
constructor(options: Crontab) {
|
||||||
this.name = options.name;
|
this.name = options.name;
|
||||||
this.command = options.command.trim();
|
this.command = options.command;
|
||||||
this.schedule = options.schedule;
|
this.schedule = options.schedule;
|
||||||
this.saved = options.saved;
|
this.saved = options.saved;
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
this.status =
|
this.status =
|
||||||
typeof options.status === 'number' && CrontabStatus[options.status]
|
options.status && CrontabStatus[options.status]
|
||||||
? options.status
|
? options.status
|
||||||
: CrontabStatus.idle;
|
: CrontabStatus.idle;
|
||||||
this.timestamp = new Date().toString();
|
this.timestamp = new Date().toString();
|
||||||
@@ -41,21 +37,17 @@ export class Crontab {
|
|||||||
this.labels = options.labels || [];
|
this.labels = options.labels || [];
|
||||||
this.last_running_time = options.last_running_time || 0;
|
this.last_running_time = options.last_running_time || 0;
|
||||||
this.last_execution_time = options.last_execution_time || 0;
|
this.last_execution_time = options.last_execution_time || 0;
|
||||||
this.sub_id = options.sub_id;
|
|
||||||
this.extra_schedules = options.extra_schedules;
|
|
||||||
this.task_before = options.task_before;
|
|
||||||
this.task_after = options.task_after;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum CrontabStatus {
|
export enum CrontabStatus {
|
||||||
'running' = 0,
|
'running',
|
||||||
'queued' = 0.5,
|
'idle',
|
||||||
'idle' = 1,
|
|
||||||
'disabled',
|
'disabled',
|
||||||
|
'queued',
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CronInstance extends Model<Crontab, Crontab>, Crontab { }
|
interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
|
||||||
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||||
name: {
|
name: {
|
||||||
unique: 'compositeIndex',
|
unique: 'compositeIndex',
|
||||||
@@ -80,8 +72,4 @@ export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
|||||||
labels: DataTypes.JSON,
|
labels: DataTypes.JSON,
|
||||||
last_running_time: DataTypes.NUMBER,
|
last_running_time: DataTypes.NUMBER,
|
||||||
last_execution_time: DataTypes.NUMBER,
|
last_execution_time: DataTypes.NUMBER,
|
||||||
sub_id: { type: DataTypes.NUMBER, allowNull: true },
|
|
||||||
extra_schedules: DataTypes.JSON,
|
|
||||||
task_before: DataTypes.STRING,
|
|
||||||
task_after: DataTypes.STRING,
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
import { sequelize } from '.';
|
|
||||||
import { DataTypes, Model } from 'sequelize';
|
|
||||||
|
|
||||||
export enum CronViewType {
|
|
||||||
'系统' = 1,
|
|
||||||
'个人',
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SortType {
|
|
||||||
type: 'ASC' | 'DESC';
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FilterType {
|
|
||||||
property: string;
|
|
||||||
operation: string;
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CrontabView {
|
|
||||||
name?: string;
|
|
||||||
id?: number;
|
|
||||||
position?: number;
|
|
||||||
isDisabled?: 1 | 0;
|
|
||||||
filters?: FilterType[];
|
|
||||||
sorts?: SortType[];
|
|
||||||
filterRelation?: 'and' | 'or';
|
|
||||||
type?: CronViewType;
|
|
||||||
|
|
||||||
constructor(options: CrontabView) {
|
|
||||||
this.name = options.name;
|
|
||||||
this.id = options.id;
|
|
||||||
this.position = options.position;
|
|
||||||
this.isDisabled = options.isDisabled || 0;
|
|
||||||
this.filters = options.filters;
|
|
||||||
this.sorts = options.sorts;
|
|
||||||
this.filterRelation = options.filterRelation;
|
|
||||||
this.type = options.type || CronViewType.个人;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CronViewInstance
|
|
||||||
extends Model<CrontabView, CrontabView>,
|
|
||||||
CrontabView {}
|
|
||||||
export const CrontabViewModel = sequelize.define<CronViewInstance>(
|
|
||||||
'CrontabView',
|
|
||||||
{
|
|
||||||
name: {
|
|
||||||
unique: 'name',
|
|
||||||
type: DataTypes.STRING,
|
|
||||||
},
|
|
||||||
position: DataTypes.NUMBER,
|
|
||||||
isDisabled: DataTypes.NUMBER,
|
|
||||||
filters: DataTypes.JSON,
|
|
||||||
sorts: DataTypes.JSON,
|
|
||||||
filterRelation: {
|
|
||||||
type: DataTypes.STRING,
|
|
||||||
allowNull: true,
|
|
||||||
},
|
|
||||||
type: DataTypes.NUMBER,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
+9
-25
@@ -4,21 +4,18 @@ import { DataTypes, Model, ModelDefined } from 'sequelize';
|
|||||||
export class Dependence {
|
export class Dependence {
|
||||||
timestamp?: string;
|
timestamp?: string;
|
||||||
id?: number;
|
id?: number;
|
||||||
status: DependenceStatus;
|
status?: DependenceStatus;
|
||||||
type: DependenceTypes;
|
type?: DependenceTypes;
|
||||||
name: string;
|
name?: number;
|
||||||
log?: string[];
|
log?: string[];
|
||||||
remark?: string;
|
remark?: string;
|
||||||
|
|
||||||
constructor(options: Dependence) {
|
constructor(options: Dependence) {
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
this.status =
|
this.status = options.status || DependenceStatus.installing;
|
||||||
typeof options.status === 'number' && DependenceStatus[options.status]
|
|
||||||
? options.status
|
|
||||||
: DependenceStatus.queued;
|
|
||||||
this.type = options.type || DependenceTypes.nodejs;
|
this.type = options.type || DependenceTypes.nodejs;
|
||||||
this.timestamp = new Date().toString();
|
this.timestamp = new Date().toString();
|
||||||
this.name = options.name.trim();
|
this.name = options.name;
|
||||||
this.log = options.log || [];
|
this.log = options.log || [];
|
||||||
this.remark = options.remark || '';
|
this.remark = options.remark || '';
|
||||||
}
|
}
|
||||||
@@ -31,7 +28,6 @@ export enum DependenceStatus {
|
|||||||
'removing',
|
'removing',
|
||||||
'removed',
|
'removed',
|
||||||
'removeFailed',
|
'removeFailed',
|
||||||
'queued',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum DependenceTypes {
|
export enum DependenceTypes {
|
||||||
@@ -42,29 +38,17 @@ export enum DependenceTypes {
|
|||||||
|
|
||||||
export enum InstallDependenceCommandTypes {
|
export enum InstallDependenceCommandTypes {
|
||||||
'pnpm add -g',
|
'pnpm add -g',
|
||||||
'pip3 install --disable-pip-version-check --root-user-action=ignore',
|
'pip3 install',
|
||||||
'apk add --no-check-certificate',
|
'apk add',
|
||||||
}
|
|
||||||
|
|
||||||
export enum GetDependenceCommandTypes {
|
|
||||||
'pnpm ls -g ',
|
|
||||||
'pip3 show --disable-pip-version-check',
|
|
||||||
'apk info -es',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum versionDependenceCommandTypes {
|
|
||||||
'@',
|
|
||||||
'==',
|
|
||||||
'=',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum unInstallDependenceCommandTypes {
|
export enum unInstallDependenceCommandTypes {
|
||||||
'pnpm remove -g',
|
'pnpm remove -g',
|
||||||
'pip3 uninstall --disable-pip-version-check --root-user-action=ignore -y',
|
'pip3 uninstall -y',
|
||||||
'apk del',
|
'apk del',
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DependenceInstance
|
interface DependenceInstance
|
||||||
extends Model<Dependence, Dependence>,
|
extends Model<Dependence, Dependence>,
|
||||||
Dependence {}
|
Dependence {}
|
||||||
export const DependenceModel = sequelize.define<DependenceInstance>(
|
export const DependenceModel = sequelize.define<DependenceInstance>(
|
||||||
|
|||||||
+3
-9
@@ -13,10 +13,7 @@ export class Env {
|
|||||||
constructor(options: Env) {
|
constructor(options: Env) {
|
||||||
this.value = options.value;
|
this.value = options.value;
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
this.status =
|
this.status = options.status || EnvStatus.normal;
|
||||||
typeof options.status === 'number' && EnvStatus[options.status]
|
|
||||||
? options.status
|
|
||||||
: EnvStatus.normal;
|
|
||||||
this.timestamp = new Date().toString();
|
this.timestamp = new Date().toString();
|
||||||
this.position = options.position;
|
this.position = options.position;
|
||||||
this.name = options.name;
|
this.name = options.name;
|
||||||
@@ -29,12 +26,9 @@ export enum EnvStatus {
|
|||||||
'disabled',
|
'disabled',
|
||||||
}
|
}
|
||||||
|
|
||||||
export const maxPosition = 9000000000000000;
|
export const initEnvPosition = 9999999999;
|
||||||
export const initPosition = 4500000000000000;
|
|
||||||
export const stepPosition = 10000000000;
|
|
||||||
export const minPosition = 100;
|
|
||||||
|
|
||||||
export 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', {
|
||||||
value: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
value: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||||
timestamp: DataTypes.STRING,
|
timestamp: DataTypes.STRING,
|
||||||
|
|||||||
+4
-12
@@ -1,23 +1,15 @@
|
|||||||
import { Sequelize, Transaction } from 'sequelize';
|
import { Sequelize } from 'sequelize';
|
||||||
import config from '../config/index';
|
import config from '../config/index';
|
||||||
import { join } from 'path';
|
|
||||||
|
|
||||||
export const sequelize = new Sequelize({
|
export const sequelize = new Sequelize({
|
||||||
dialect: 'sqlite',
|
dialect: 'sqlite',
|
||||||
storage: join(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
-58
@@ -1,24 +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',
|
||||||
'pushMe' = 'pushMe',
|
|
||||||
'feishu' = 'feishu',
|
|
||||||
'webhook' = 'webhook',
|
|
||||||
'chronocat' = 'Chronocat',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class NotificationBaseInfo {
|
abstract class NotificationBaseInfo {
|
||||||
@@ -43,21 +35,13 @@ export class ServerChanNotification extends NotificationBaseInfo {
|
|||||||
|
|
||||||
export class PushDeerNotification extends NotificationBaseInfo {
|
export class PushDeerNotification extends NotificationBaseInfo {
|
||||||
public pushDeerKey = '';
|
public pushDeerKey = '';
|
||||||
public pushDeerUrl = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
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';
|
||||||
public barkLevel = 'active';
|
|
||||||
public barkUrl = '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TelegramBotNotification extends NotificationBaseInfo {
|
export class TelegramBotNotification extends NotificationBaseInfo {
|
||||||
@@ -76,18 +60,10 @@ export class DingtalkBotNotification extends NotificationBaseInfo {
|
|||||||
|
|
||||||
export class WeWorkBotNotification extends NotificationBaseInfo {
|
export class WeWorkBotNotification extends NotificationBaseInfo {
|
||||||
public weWorkBotKey = '';
|
public weWorkBotKey = '';
|
||||||
public weWorkOrigin = '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WeWorkAppNotification extends NotificationBaseInfo {
|
export class WeWorkAppNotification extends NotificationBaseInfo {
|
||||||
public weWorkAppKey = '';
|
public weWorkAppKey = '';
|
||||||
public weWorkOrigin = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
||||||
@@ -105,48 +81,16 @@ export class EmailNotification extends NotificationBaseInfo {
|
|||||||
public emailPass: string = '';
|
public emailPass: string = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class PushMeNotification extends NotificationBaseInfo {
|
|
||||||
public pushMeKey: string = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ChronocatNotification extends NotificationBaseInfo {
|
|
||||||
public chronocatURL: string = '';
|
|
||||||
public chronocatQQ: string = '';
|
|
||||||
public chronocatToekn: 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 {}
|
||||||
PushMeNotification,
|
|
||||||
WebhookNotification,
|
|
||||||
ChronocatNotification,
|
|
||||||
LarkNotification {}
|
|
||||||
|
|
||||||
|
|||||||
+8
-1
@@ -26,7 +26,14 @@ export interface AppToken {
|
|||||||
|
|
||||||
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs';
|
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs';
|
||||||
|
|
||||||
export interface AppInstance extends Model<App, App>, App {}
|
export enum CrontabStatus {
|
||||||
|
'running',
|
||||||
|
'idle',
|
||||||
|
'disabled',
|
||||||
|
'queued',
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AppInstance extends Model<App, App>, App {}
|
||||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||||
name: { type: DataTypes.STRING, unique: 'name' },
|
name: { type: DataTypes.STRING, unique: 'name' },
|
||||||
scopes: DataTypes.JSON,
|
scopes: DataTypes.JSON,
|
||||||
|
|||||||
+1
-2
@@ -16,5 +16,4 @@ export type SockMessageType =
|
|||||||
| 'uninstallDependence'
|
| 'uninstallDependence'
|
||||||
| 'updateSystemVersion'
|
| 'updateSystemVersion'
|
||||||
| 'manuallyRunScript'
|
| 'manuallyRunScript'
|
||||||
| 'runSubscriptionEnd'
|
| 'runSubscriptionEnd';
|
||||||
| 'reloadSystem';
|
|
||||||
|
|||||||
@@ -28,17 +28,14 @@ export class Subscription {
|
|||||||
extensions?: string;
|
extensions?: string;
|
||||||
sub_before?: string;
|
sub_before?: string;
|
||||||
sub_after?: string;
|
sub_after?: string;
|
||||||
proxy?: string;
|
|
||||||
autoAddCron?: 1 | 0;
|
|
||||||
autoDelCron?: 1 | 0;
|
|
||||||
|
|
||||||
constructor(options: Subscription) {
|
constructor(options: Subscription) {
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
this.name = options.name || options.alias;
|
this.name = options.name || options.alias;
|
||||||
this.type = options.type;
|
this.type = options.type;
|
||||||
this.schedule = options.schedule;
|
this.schedule = options.schedule;
|
||||||
this.status = this.status =
|
this.status =
|
||||||
typeof options.status === 'number' && SubscriptionStatus[options.status]
|
options.status && SubscriptionStatus[options.status]
|
||||||
? options.status
|
? options.status
|
||||||
: SubscriptionStatus.idle;
|
: SubscriptionStatus.idle;
|
||||||
this.url = options.url;
|
this.url = options.url;
|
||||||
@@ -57,9 +54,6 @@ export class Subscription {
|
|||||||
this.extensions = options.extensions;
|
this.extensions = options.extensions;
|
||||||
this.sub_before = options.sub_before;
|
this.sub_before = options.sub_before;
|
||||||
this.sub_after = options.sub_after;
|
this.sub_after = options.sub_after;
|
||||||
this.proxy = options.proxy;
|
|
||||||
this.autoAddCron = options.autoAddCron ? 1 : 0;
|
|
||||||
this.autoDelCron = options.autoDelCron ? 1 : 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +64,7 @@ export enum SubscriptionStatus {
|
|||||||
'queued',
|
'queued',
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SubscriptionInstance
|
interface SubscriptionInstance
|
||||||
extends Model<Subscription, Subscription>,
|
extends Model<Subscription, Subscription>,
|
||||||
Subscription {}
|
Subscription {}
|
||||||
export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
||||||
@@ -108,8 +102,5 @@ export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
|||||||
log_path: DataTypes.STRING,
|
log_path: DataTypes.STRING,
|
||||||
schedule_type: DataTypes.STRING,
|
schedule_type: DataTypes.STRING,
|
||||||
alias: { type: DataTypes.STRING, unique: 'alias' },
|
alias: { type: DataTypes.STRING, unique: 'alias' },
|
||||||
proxy: { type: DataTypes.STRING, allowNull: true },
|
|
||||||
autoAddCron: { type: DataTypes.NUMBER, allowNull: true },
|
|
||||||
autoDelCron: { type: DataTypes.NUMBER, allowNull: true },
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
Vendored
-2
@@ -3,5 +3,3 @@ declare namespace Express {
|
|||||||
platform: 'desktop' | 'mobile';
|
platform: 'desktop' | 'mobile';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
declare module 'pstree.remy';
|
|
||||||
|
|||||||
+2
-12
@@ -7,28 +7,18 @@ import linkDeps from './deps';
|
|||||||
import initTask from './initTask';
|
import initTask from './initTask';
|
||||||
|
|
||||||
export default async ({ expressApp }: { expressApp: Application }) => {
|
export default async ({ expressApp }: { expressApp: Application }) => {
|
||||||
try {
|
await depInjectorLoader();
|
||||||
depInjectorLoader();
|
|
||||||
Logger.info('✌️ Dependency Injector loaded');
|
Logger.info('✌️ Dependency Injector loaded');
|
||||||
console.log('✌️ Dependency Injector loaded');
|
|
||||||
|
|
||||||
expressLoader({ app: expressApp });
|
await expressLoader({ app: expressApp });
|
||||||
Logger.info('✌️ Express loaded');
|
Logger.info('✌️ Express loaded');
|
||||||
console.log('✌️ Express loaded');
|
|
||||||
|
|
||||||
await initData();
|
await initData();
|
||||||
Logger.info('✌️ init data loaded');
|
Logger.info('✌️ init data loaded');
|
||||||
console.log('✌️ init data loaded');
|
|
||||||
|
|
||||||
await linkDeps();
|
await linkDeps();
|
||||||
Logger.info('✌️ link deps loaded');
|
Logger.info('✌️ link deps loaded');
|
||||||
console.log('✌️ link deps loaded');
|
|
||||||
|
|
||||||
initTask();
|
initTask();
|
||||||
Logger.info('✌️ init task loaded');
|
Logger.info('✌️ init task loaded');
|
||||||
console.log('✌️ init task loaded');
|
|
||||||
} catch (error) {
|
|
||||||
Logger.error(`✌️ depInjectorLoader expressLoader initData linkDeps failed, ${error}`);
|
|
||||||
console.error(`✌️ depInjectorLoader expressLoader initData linkDeps failed ${error}`);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|||||||
+9
-42
@@ -6,11 +6,10 @@ 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';
|
||||||
import { sequelize } from '../data';
|
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
try {
|
try {
|
||||||
@@ -20,44 +19,13 @@ export default async () => {
|
|||||||
await AuthModel.sync();
|
await AuthModel.sync();
|
||||||
await EnvModel.sync();
|
await EnvModel.sync();
|
||||||
await SubscriptionModel.sync();
|
await SubscriptionModel.sync();
|
||||||
await CrontabViewModel.sync();
|
|
||||||
|
|
||||||
// 初始化新增字段
|
// try {
|
||||||
try {
|
// const queryInterface = sequelize.getQueryInterface();
|
||||||
await sequelize.query(
|
// await queryInterface.addIndex('Crontabs', ['command'], { unique: true });
|
||||||
'alter table CrontabViews add column filterRelation VARCHAR(255)',
|
// await queryInterface.addIndex('Envs', ['name', 'value'], { unique: true });
|
||||||
);
|
// await queryInterface.addIndex('Apps', ['name'], { unique: true });
|
||||||
} catch (error) {}
|
// } catch (error) { }
|
||||||
try {
|
|
||||||
await sequelize.query(
|
|
||||||
'alter table Subscriptions add column proxy VARCHAR(255)',
|
|
||||||
);
|
|
||||||
} catch (error) {}
|
|
||||||
try {
|
|
||||||
await sequelize.query('alter table CrontabViews add column type NUMBER');
|
|
||||||
} catch (error) {}
|
|
||||||
try {
|
|
||||||
await sequelize.query(
|
|
||||||
'alter table Subscriptions add column autoAddCron NUMBER',
|
|
||||||
);
|
|
||||||
} catch (error) {}
|
|
||||||
try {
|
|
||||||
await sequelize.query(
|
|
||||||
'alter table Subscriptions add column autoDelCron NUMBER',
|
|
||||||
);
|
|
||||||
} catch (error) {}
|
|
||||||
try {
|
|
||||||
await sequelize.query('alter table Crontabs add column sub_id NUMBER');
|
|
||||||
} catch (error) { }
|
|
||||||
try {
|
|
||||||
await sequelize.query('alter table Crontabs add column extra_schedules JSON');
|
|
||||||
} catch (error) { }
|
|
||||||
try {
|
|
||||||
await sequelize.query('alter table Crontabs add column task_before TEXT');
|
|
||||||
} catch (error) { }
|
|
||||||
try {
|
|
||||||
await sequelize.query('alter table Crontabs add column task_after TEXT');
|
|
||||||
} catch (error) { }
|
|
||||||
|
|
||||||
// 2.10-2.11 升级
|
// 2.10-2.11 升级
|
||||||
const cronDbFile = path.join(config.rootPath, 'db/crontab.db');
|
const cronDbFile = path.join(config.rootPath, 'db/crontab.db');
|
||||||
@@ -131,10 +99,9 @@ export default async () => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('✌️ DB loaded');
|
|
||||||
Logger.info('✌️ DB loaded');
|
Logger.info('✌️ DB loaded');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('✌️ DB load failed');
|
Logger.info('✌️ DB load failed');
|
||||||
Logger.error(error);
|
Logger.info(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ async function linkCommand() {
|
|||||||
if (fs.existsSync(target)) {
|
if (fs.existsSync(target)) {
|
||||||
fs.unlinkSync(target);
|
fs.unlinkSync(target);
|
||||||
}
|
}
|
||||||
fs.symlink(source, target, (err) => { });
|
fs.symlink(source, target, (err) => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-26
@@ -3,42 +3,39 @@ 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, safeJSONParse } from '../config/util';
|
import { getPlatform, getToken } from '../config/util';
|
||||||
import Container from 'typedi';
|
import Container from 'typedi';
|
||||||
import OpenService from '../services/open';
|
import OpenService from '../services/open';
|
||||||
import rewrite from 'express-urlrewrite';
|
import rewrite from 'express-urlrewrite';
|
||||||
import UserService from '../services/user';
|
import UserService from '../services/user';
|
||||||
|
import handler from 'serve-handler';
|
||||||
import * as Sentry from '@sentry/node';
|
import * as Sentry from '@sentry/node';
|
||||||
import { EnvModel } from '../data/env';
|
import { EnvModel } from '../data/env';
|
||||||
import { errors } from 'celebrate';
|
import { errors } from 'celebrate';
|
||||||
import { createProxyMiddleware } from 'http-proxy-middleware';
|
|
||||||
import { serveEnv } from '../config/serverEnv';
|
|
||||||
import Logger from './logger';
|
|
||||||
|
|
||||||
export default ({ app }: { app: Application }) => {
|
export default ({ app }: { app: Application }) => {
|
||||||
app.enable('trust proxy');
|
app.enable('trust proxy');
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.get(`${config.api.prefix}/env.js`, serveEnv);
|
|
||||||
app.use(`${config.api.prefix}/static`, express.static(config.uploadPath));
|
app.use(`${config.api.prefix}/static`, express.static(config.uploadPath));
|
||||||
|
|
||||||
app.use(
|
app.use((req, res, next) => {
|
||||||
'/api/public',
|
if (req.path.startsWith('/api') || req.path.startsWith('/open')) {
|
||||||
createProxyMiddleware({
|
next();
|
||||||
target: `http://0.0.0.0:${config.publicPort}/api`,
|
} else {
|
||||||
changeOrigin: true,
|
return handler(req, res, {
|
||||||
pathRewrite: { '/api/public': '' },
|
public: 'static/dist',
|
||||||
logProvider: () => Logger
|
rewrites: [{ source: '**', destination: '/index.html' }],
|
||||||
}),
|
});
|
||||||
);
|
}
|
||||||
|
});
|
||||||
app.use(bodyParser.json({ limit: '50mb' }));
|
app.use(bodyParser.json({ limit: '50mb' }));
|
||||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
jwt({
|
jwt({
|
||||||
secret: config.secret,
|
secret: config.secret as string,
|
||||||
algorithms: ['HS384'],
|
algorithms: ['HS384'],
|
||||||
}).unless({
|
}).unless({
|
||||||
path: [...config.apiWhiteList, /^\/open\//],
|
path: [...config.apiWhiteList, /^\/open\//],
|
||||||
@@ -78,24 +75,22 @@ 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();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
||||||
if (data && headerToken) {
|
if (data) {
|
||||||
const { token = '', tokens = {} } = safeJSONParse(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);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -111,7 +106,8 @@ export default ({ app }: { app: Application }) => {
|
|||||||
if (
|
if (
|
||||||
Object.keys(authInfo).length === 2 &&
|
Object.keys(authInfo).length === 2 &&
|
||||||
authInfo.username === 'admin' &&
|
authInfo.username === 'admin' &&
|
||||||
authInfo.password === 'admin'
|
authInfo.password === 'admin' &&
|
||||||
|
envCount === 0
|
||||||
) {
|
) {
|
||||||
isInitialized = false;
|
isInitialized = false;
|
||||||
}
|
}
|
||||||
@@ -172,6 +168,8 @@ export default ({ app }: { app: Application }) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
app.use(Sentry.Handlers.errorHandler());
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
err: Error & { status: number },
|
err: Error & { status: number },
|
||||||
|
|||||||
+15
-28
@@ -4,51 +4,38 @@ 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 { DependenceModel, DependenceStatus } from '../data/dependence';
|
import _ from 'lodash';
|
||||||
|
import { DependenceModel } from '../data/dependence';
|
||||||
import { Op } from 'sequelize';
|
import { Op } from 'sequelize';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { CrontabViewModel, CronViewType } from '../data/cronView';
|
|
||||||
import { initPosition } from '../data/env';
|
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
|
|
||||||
// 初始化新增默认全部任务视图
|
|
||||||
CrontabViewModel.findAll({
|
|
||||||
where: { type: CronViewType.系统, name: '全部任务' },
|
|
||||||
raw: true,
|
|
||||||
}).then((docs) => {
|
|
||||||
if (docs.length === 0) {
|
|
||||||
CrontabViewModel.create({
|
|
||||||
name: '全部任务',
|
|
||||||
type: CronViewType.系统,
|
|
||||||
position: initPosition / 2,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 初始化更新所有任务状态为空闲
|
// 初始化更新所有任务状态为空闲
|
||||||
await CrontabModel.update({ status: CrontabStatus.idle }, { where: {} });
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.idle },
|
||||||
|
{ where: { status: [CrontabStatus.running, CrontabStatus.queued] } },
|
||||||
|
);
|
||||||
|
|
||||||
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
||||||
DependenceModel.findAll({
|
DependenceModel.findAll({
|
||||||
where: {},
|
where: {},
|
||||||
order: [
|
order: [['type', 'DESC']],
|
||||||
['type', 'DESC'],
|
|
||||||
['createdAt', 'DESC'],
|
|
||||||
],
|
|
||||||
raw: true,
|
raw: true,
|
||||||
}).then(async (docs) => {
|
}).then(async (docs) => {
|
||||||
await DependenceModel.update(
|
const groups = _.groupBy(docs, 'type');
|
||||||
{ status: DependenceStatus.queued, log: [] },
|
const keys = Object.keys(groups).sort((a, b) => parseInt(b) - parseInt(a));
|
||||||
{ where: { id: docs.map((x) => x.id!) } },
|
for (const key of keys) {
|
||||||
);
|
const group = groups[key];
|
||||||
dependenceService.installDependenceOneByOne(docs);
|
const depIds = group.map((x) => x.id);
|
||||||
|
await dependenceService.reInstall(depIds as number[]);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 初始化时执行一次所有的 ql repo 任务
|
// 初始化时执行一次所有的ql repo 任务
|
||||||
CrontabModel.findAll({
|
CrontabModel.findAll({
|
||||||
where: {
|
where: {
|
||||||
isDisabled: { [Op.ne]: 1 },
|
isDisabled: { [Op.ne]: 1 },
|
||||||
|
|||||||
+17
-56
@@ -5,7 +5,7 @@ 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/');
|
||||||
@@ -13,22 +13,12 @@ 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 bakPath = path.join(dataPath, 'bak/');
|
||||||
const samplePath = path.join(rootPath, 'sample/');
|
const samplePath = path.join(rootPath, 'sample/');
|
||||||
const tmpPath = path.join(logPath, '.tmp/');
|
|
||||||
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');
|
||||||
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
||||||
const sampleAuthFile = path.join(samplePath, 'auth.sample.json');
|
const sampleAuthFile = path.join(samplePath, 'auth.sample.json');
|
||||||
const sampleTaskShellFile = path.join(samplePath, 'task.sample.sh');
|
|
||||||
const sampleNotifyJsFile = path.join(samplePath, 'notify.js');
|
|
||||||
const sampleNotifyPyFile = path.join(samplePath, 'notify.py');
|
|
||||||
const scriptNotifyJsFile = path.join(scriptPath, 'sendNotify.js');
|
|
||||||
const scriptNotifyPyFile = path.join(scriptPath, 'notify.py');
|
|
||||||
const TaskBeforeFile = path.join(configPath, 'task_before.sh');
|
|
||||||
const TaskAfterFile = path.join(configPath, 'task_after.sh');
|
|
||||||
const homedir = os.homedir();
|
const homedir = os.homedir();
|
||||||
const sshPath = path.resolve(homedir, '.ssh');
|
const sshPath = path.resolve(homedir, '.ssh');
|
||||||
const sshdPath = path.join(dataPath, 'ssh.d');
|
|
||||||
const systemLogPath = path.join(dataPath, 'syslog');
|
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
const authFileExist = await fileExist(authConfigFile);
|
const authFileExist = await fileExist(authConfigFile);
|
||||||
@@ -39,18 +29,19 @@ export default async () => {
|
|||||||
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);
|
const bakDirExist = await fileExist(bakPath);
|
||||||
const sshdDirExist = await fileExist(sshdPath);
|
|
||||||
const systemLogDirExist = await fileExist(systemLogPath);
|
|
||||||
const tmpDirExist = await fileExist(tmpPath);
|
|
||||||
const scriptNotifyJsFileExist = await fileExist(scriptNotifyJsFile);
|
|
||||||
const scriptNotifyPyFileExist = await fileExist(scriptNotifyPyFile);
|
|
||||||
const TaskBeforeFileExist = await fileExist(TaskBeforeFile);
|
|
||||||
const TaskAfterFileExist = await fileExist(TaskAfterFile);
|
|
||||||
|
|
||||||
if (!configDirExist) {
|
if (!configDirExist) {
|
||||||
fs.mkdirSync(configPath);
|
fs.mkdirSync(configPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!authFileExist) {
|
||||||
|
fs.writeFileSync(authConfigFile, fs.readFileSync(sampleAuthFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!confFileExist) {
|
||||||
|
fs.writeFileSync(confFile, fs.readFileSync(sampleConfigFile));
|
||||||
|
}
|
||||||
|
|
||||||
if (!scriptDirExist) {
|
if (!scriptDirExist) {
|
||||||
fs.mkdirSync(scriptPath);
|
fs.mkdirSync(scriptPath);
|
||||||
}
|
}
|
||||||
@@ -59,10 +50,6 @@ export default async () => {
|
|||||||
fs.mkdirSync(logPath);
|
fs.mkdirSync(logPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!tmpDirExist) {
|
|
||||||
fs.mkdirSync(tmpPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!uploadDirExist) {
|
if (!uploadDirExist) {
|
||||||
fs.mkdirSync(uploadPath);
|
fs.mkdirSync(uploadPath);
|
||||||
}
|
}
|
||||||
@@ -75,41 +62,15 @@ export default async () => {
|
|||||||
fs.mkdirSync(bakPath);
|
fs.mkdirSync(bakPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!sshdDirExist) {
|
|
||||||
fs.mkdirSync(sshdPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!systemLogDirExist) {
|
|
||||||
fs.mkdirSync(systemLogPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 初始化文件
|
|
||||||
if (!authFileExist) {
|
|
||||||
fs.writeFileSync(authConfigFile, fs.readFileSync(sampleAuthFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!confFileExist) {
|
|
||||||
fs.writeFileSync(confFile, fs.readFileSync(sampleConfigFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!scriptNotifyJsFileExist) {
|
|
||||||
fs.writeFileSync(scriptNotifyJsFile, fs.readFileSync(sampleNotifyJsFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!scriptNotifyPyFileExist) {
|
|
||||||
fs.writeFileSync(scriptNotifyPyFile, fs.readFileSync(sampleNotifyPyFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!TaskBeforeFileExist) {
|
|
||||||
fs.writeFileSync(TaskBeforeFile, fs.readFileSync(sampleTaskShellFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!TaskAfterFileExist) {
|
|
||||||
fs.writeFileSync(TaskAfterFile, fs.readFileSync(sampleTaskShellFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
dotenv.config({ path: confFile });
|
dotenv.config({ path: confFile });
|
||||||
|
|
||||||
|
// 声明QL_DIR环境变量
|
||||||
|
let qlHomePath = path.join(__dirname, '../../');
|
||||||
|
// 生产环境
|
||||||
|
if (qlHomePath.endsWith('/static/')) {
|
||||||
|
qlHomePath = path.join(qlHomePath, '../');
|
||||||
|
}
|
||||||
|
process.env.QL_DIR = qlHomePath;
|
||||||
|
|
||||||
Logger.info('✌️ Init file down');
|
Logger.info('✌️ Init file down');
|
||||||
console.log('✌️ Init file down');
|
|
||||||
};
|
};
|
||||||
|
|||||||
+16
-31
@@ -1,51 +1,36 @@
|
|||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
|
import _ from 'lodash';
|
||||||
import SystemService from '../services/system';
|
import SystemService from '../services/system';
|
||||||
import ScheduleService, { ScheduleTaskType } 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';
|
|
||||||
import { join } from 'path';
|
|
||||||
|
|
||||||
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 = `tsx ${join(config.rootPath, 'back/token.ts')}`;
|
|
||||||
const tokenFile = join(config.rootPath, 'static/build/token.js');
|
|
||||||
|
|
||||||
if (await fileExist(tokenFile)) {
|
|
||||||
tokenCommand = `node ${tokenFile}`;
|
|
||||||
}
|
|
||||||
const cron = {
|
|
||||||
id: NaN,
|
|
||||||
name: '生成token',
|
|
||||||
command: tokenCommand,
|
|
||||||
} as ScheduleTaskType;
|
|
||||||
await scheduleService.cancelIntervalTask(cron);
|
|
||||||
scheduleService.createIntervalTask(cron, {
|
|
||||||
days: 28,
|
|
||||||
});
|
|
||||||
|
|
||||||
// 运行删除日志任务
|
// 运行删除日志任务
|
||||||
const data = await systemService.getSystemConfig();
|
const data = await systemService.getLogRemoveFrequency();
|
||||||
if (data && data.info && data.info.logRemoveFrequency) {
|
if (data && data.info && data.info.frequency) {
|
||||||
const rmlogCron = {
|
const cron = {
|
||||||
id: data.id as number,
|
id: data.id,
|
||||||
name: '删除日志',
|
name: '删除日志',
|
||||||
command: `ql rmlog ${data.info.logRemoveFrequency}`,
|
command: `ql rmlog ${data.info.frequency}`,
|
||||||
};
|
};
|
||||||
await scheduleService.cancelIntervalTask(rmlogCron);
|
await scheduleService.createIntervalTask(cron, {
|
||||||
scheduleService.createIntervalTask(rmlogCron, {
|
days: data.info.frequency,
|
||||||
days: data.info.logRemoveFrequency,
|
runImmediately: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 运行所有订阅
|
// 运行所有订阅
|
||||||
await subscriptionService.setSshConfig();
|
|
||||||
const subs = await subscriptionService.list();
|
const subs = await subscriptionService.list();
|
||||||
for (const sub of subs) {
|
for (const sub of subs) {
|
||||||
subscriptionService.handleTask(sub, !sub.is_disabled, !sub.is_disabled);
|
await subscriptionService.handleTask(
|
||||||
|
sub,
|
||||||
|
!sub.is_disabled,
|
||||||
|
true,
|
||||||
|
!sub.is_disabled,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
+21
-27
@@ -1,38 +1,32 @@
|
|||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import 'winston-daily-rotate-file';
|
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import path from 'path';
|
|
||||||
|
|
||||||
const levelMap: Record<string, string> = {
|
const transports = [];
|
||||||
info: '🔵',
|
if (process.env.NODE_ENV !== 'development') {
|
||||||
warn: '🟡',
|
transports.push(new winston.transports.Console());
|
||||||
error: '🔴',
|
} else {
|
||||||
debug: '🔶'
|
transports.push(
|
||||||
}
|
new winston.transports.Console({
|
||||||
|
format: winston.format.combine(
|
||||||
const customFormat = winston.format.combine(
|
winston.format.cli(),
|
||||||
winston.format.splat(),
|
winston.format.splat(),
|
||||||
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
|
),
|
||||||
winston.format.align(),
|
}),
|
||||||
winston.format.printf((i) => `[${levelMap[i.level]}${i.level}] [${[i.timestamp]}]: ${i.message}`),
|
);
|
||||||
);
|
}
|
||||||
|
|
||||||
const defaultOptions = {
|
|
||||||
format: customFormat,
|
|
||||||
datePattern: "YYYY-MM-DD",
|
|
||||||
maxSize: "20m",
|
|
||||||
maxFiles: "7d",
|
|
||||||
};
|
|
||||||
|
|
||||||
const LoggerInstance = winston.createLogger({
|
const LoggerInstance = winston.createLogger({
|
||||||
level: config.logs.level,
|
level: config.logs.level,
|
||||||
levels: winston.config.npm.levels,
|
levels: winston.config.npm.levels,
|
||||||
transports: [
|
format: winston.format.combine(
|
||||||
new winston.transports.DailyRotateFile({
|
winston.format.timestamp({
|
||||||
filename: path.join(config.systemLogPath, '%DATE%.log'),
|
format: 'YYYY-MM-DD HH:mm:ss',
|
||||||
...defaultOptions,
|
}),
|
||||||
})
|
winston.format.errors({ stack: true }),
|
||||||
],
|
winston.format.splat(),
|
||||||
|
winston.format.json(),
|
||||||
|
),
|
||||||
|
transports,
|
||||||
});
|
});
|
||||||
|
|
||||||
export default LoggerInstance;
|
export default LoggerInstance;
|
||||||
|
|||||||
+3
-15
@@ -2,32 +2,20 @@ 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';
|
|
||||||
import { parseVersion } from '../config/util';
|
|
||||||
|
|
||||||
export default async ({ expressApp }: { expressApp: Application }) => {
|
|
||||||
const { version } = await parseVersion(config.versionFile);
|
|
||||||
|
|
||||||
|
export default ({ expressApp }: { expressApp: Application }) => {
|
||||||
Sentry.init({
|
Sentry.init({
|
||||||
ignoreErrors: [
|
|
||||||
/SequelizeUniqueConstraintError/i,
|
|
||||||
/Validation error/i,
|
|
||||||
/UnauthorizedError/i,
|
|
||||||
/celebrate request validation failed/i,
|
|
||||||
],
|
|
||||||
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.8,
|
|
||||||
release: version,
|
tracesSampleRate: 1.0,
|
||||||
});
|
});
|
||||||
|
|
||||||
expressApp.use(Sentry.Handlers.requestHandler());
|
expressApp.use(Sentry.Handlers.requestHandler());
|
||||||
expressApp.use(Sentry.Handlers.tracingHandler());
|
expressApp.use(Sentry.Handlers.tracingHandler());
|
||||||
|
|
||||||
Logger.info('✌️ Sentry loaded');
|
Logger.info('✌️ Sentry loaded');
|
||||||
console.log('✌️ Sentry loaded');
|
|
||||||
};
|
};
|
||||||
|
|||||||
+4
-26
@@ -5,34 +5,12 @@ import Sock from './sock';
|
|||||||
export default async ({ server }: { server: Server }) => {
|
export default async ({ server }: { server: Server }) => {
|
||||||
await Sock({ server });
|
await Sock({ server });
|
||||||
Logger.info('✌️ Sock loaded');
|
Logger.info('✌️ Sock loaded');
|
||||||
let exitTime = 0;
|
|
||||||
let timer: NodeJS.Timeout;
|
|
||||||
|
|
||||||
process.on('SIGINT', (singal) => {
|
process.on('SIGINT', () => {
|
||||||
Logger.warn(`Server need close, singal ${singal}`);
|
Logger.info('✌️ Server need close');
|
||||||
console.warn(`Server need close, singal ${singal}`);
|
|
||||||
exitTime++;
|
|
||||||
if (exitTime >= 3) {
|
|
||||||
Logger.warn('Forcing server close');
|
|
||||||
console.warn('Forcing server close');
|
|
||||||
clearTimeout(timer);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
server.close(() => {
|
server.close(() => {
|
||||||
if (timer) {
|
Logger.info('✌️ Server closed');
|
||||||
clearTimeout(timer);
|
process.exit(0);
|
||||||
}
|
|
||||||
timer = setTimeout(() => {
|
|
||||||
process.exit();
|
|
||||||
}, 15000);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('uncaughtException', (error) => {
|
|
||||||
Logger.error('Uncaught exception:', error);
|
|
||||||
});
|
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, promise) => {
|
|
||||||
Logger.error('Unhandled rejection:', reason, promise);
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { Container } from 'typedi';
|
|||||||
import SockService from '../services/sock';
|
import SockService from '../services/sock';
|
||||||
import config from '../config/index';
|
import config from '../config/index';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { getPlatform, safeJSONParse } from '../config/util';
|
import { getPlatform } from '../config/util';
|
||||||
|
|
||||||
export default async ({ server }: { server: Server }) => {
|
export default async ({ server }: { server: Server }) => {
|
||||||
const echo = sockJs.createServer({ prefix: '/api/ws', log: () => {} });
|
const echo = sockJs.createServer({ prefix: '/api/ws', log: () => {} });
|
||||||
@@ -20,7 +20,7 @@ export default async ({ server }: { server: Server }) => {
|
|||||||
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
||||||
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
||||||
if (data) {
|
if (data) {
|
||||||
const { token = '', tokens = {} } = safeJSONParse(data);
|
const { token = '', tokens = {} } = JSON.parse(data);
|
||||||
if (headerToken === token || tokens[platform] === headerToken) {
|
if (headerToken === token || tokens[platform] === headerToken) {
|
||||||
conn.write(JSON.stringify({ type: 'ping', message: 'hanhh' }));
|
conn.write(JSON.stringify({ type: 'ping', message: 'hanhh' }));
|
||||||
sockService.addClient(conn);
|
sockService.addClient(conn);
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package com.ql.cron;
|
|
||||||
|
|
||||||
service Cron {
|
|
||||||
rpc addCron(AddCronRequest) returns (AddCronResponse);
|
|
||||||
rpc delCron(DeleteCronRequest) returns (DeleteCronResponse);
|
|
||||||
}
|
|
||||||
|
|
||||||
message ISchedule { string schedule = 1; }
|
|
||||||
|
|
||||||
message ICron {
|
|
||||||
string id = 1;
|
|
||||||
string schedule = 2;
|
|
||||||
string command = 3;
|
|
||||||
repeated ISchedule extra_schedules = 4;
|
|
||||||
string name = 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AddCronRequest { repeated ICron crons = 1; }
|
|
||||||
|
|
||||||
message AddCronResponse {}
|
|
||||||
|
|
||||||
message DeleteCronRequest { repeated string ids = 1; }
|
|
||||||
|
|
||||||
message DeleteCronResponse {}
|
|
||||||
@@ -1,502 +0,0 @@
|
|||||||
/* eslint-disable */
|
|
||||||
import {
|
|
||||||
CallOptions,
|
|
||||||
ChannelCredentials,
|
|
||||||
Client,
|
|
||||||
ClientOptions,
|
|
||||||
ClientUnaryCall,
|
|
||||||
handleUnaryCall,
|
|
||||||
makeGenericClientConstructor,
|
|
||||||
Metadata,
|
|
||||||
ServiceError,
|
|
||||||
UntypedServiceImplementation,
|
|
||||||
} from "@grpc/grpc-js";
|
|
||||||
import _m0 from "protobufjs/minimal";
|
|
||||||
|
|
||||||
export const protobufPackage = "com.ql.cron";
|
|
||||||
|
|
||||||
export interface ISchedule {
|
|
||||||
schedule: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ICron {
|
|
||||||
id: string;
|
|
||||||
schedule: string;
|
|
||||||
command: string;
|
|
||||||
extraSchedules: ISchedule[];
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AddCronRequest {
|
|
||||||
crons: ICron[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AddCronResponse {
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DeleteCronRequest {
|
|
||||||
ids: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DeleteCronResponse {
|
|
||||||
}
|
|
||||||
|
|
||||||
function createBaseISchedule(): ISchedule {
|
|
||||||
return { schedule: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ISchedule = {
|
|
||||||
encode(message: ISchedule, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
if (message.schedule !== "") {
|
|
||||||
writer.uint32(10).string(message.schedule);
|
|
||||||
}
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): ISchedule {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseISchedule();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
case 1:
|
|
||||||
if (tag !== 10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.schedule = reader.string();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(object: any): ISchedule {
|
|
||||||
return { schedule: isSet(object.schedule) ? String(object.schedule) : "" };
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(message: ISchedule): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
message.schedule !== undefined && (obj.schedule = message.schedule);
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<ISchedule>, I>>(base?: I): ISchedule {
|
|
||||||
return ISchedule.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<ISchedule>, I>>(object: I): ISchedule {
|
|
||||||
const message = createBaseISchedule();
|
|
||||||
message.schedule = object.schedule ?? "";
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function createBaseICron(): ICron {
|
|
||||||
return { id: "", schedule: "", command: "", extraSchedules: [], name: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ICron = {
|
|
||||||
encode(message: ICron, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
if (message.id !== "") {
|
|
||||||
writer.uint32(10).string(message.id);
|
|
||||||
}
|
|
||||||
if (message.schedule !== "") {
|
|
||||||
writer.uint32(18).string(message.schedule);
|
|
||||||
}
|
|
||||||
if (message.command !== "") {
|
|
||||||
writer.uint32(26).string(message.command);
|
|
||||||
}
|
|
||||||
for (const v of message.extraSchedules) {
|
|
||||||
ISchedule.encode(v!, writer.uint32(34).fork()).ldelim();
|
|
||||||
}
|
|
||||||
if (message.name !== "") {
|
|
||||||
writer.uint32(42).string(message.name);
|
|
||||||
}
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): ICron {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseICron();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
case 1:
|
|
||||||
if (tag !== 10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.id = reader.string();
|
|
||||||
continue;
|
|
||||||
case 2:
|
|
||||||
if (tag !== 18) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.schedule = reader.string();
|
|
||||||
continue;
|
|
||||||
case 3:
|
|
||||||
if (tag !== 26) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.command = reader.string();
|
|
||||||
continue;
|
|
||||||
case 4:
|
|
||||||
if (tag !== 34) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.extraSchedules.push(ISchedule.decode(reader, reader.uint32()));
|
|
||||||
continue;
|
|
||||||
case 5:
|
|
||||||
if (tag !== 42) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.name = reader.string();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(object: any): ICron {
|
|
||||||
return {
|
|
||||||
id: isSet(object.id) ? String(object.id) : "",
|
|
||||||
schedule: isSet(object.schedule) ? String(object.schedule) : "",
|
|
||||||
command: isSet(object.command) ? String(object.command) : "",
|
|
||||||
extraSchedules: Array.isArray(object?.extraSchedules)
|
|
||||||
? object.extraSchedules.map((e: any) => ISchedule.fromJSON(e))
|
|
||||||
: [],
|
|
||||||
name: isSet(object.name) ? String(object.name) : "",
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(message: ICron): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
message.id !== undefined && (obj.id = message.id);
|
|
||||||
message.schedule !== undefined && (obj.schedule = message.schedule);
|
|
||||||
message.command !== undefined && (obj.command = message.command);
|
|
||||||
if (message.extraSchedules) {
|
|
||||||
obj.extraSchedules = message.extraSchedules.map((e) => e ? ISchedule.toJSON(e) : undefined);
|
|
||||||
} else {
|
|
||||||
obj.extraSchedules = [];
|
|
||||||
}
|
|
||||||
message.name !== undefined && (obj.name = message.name);
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<ICron>, I>>(base?: I): ICron {
|
|
||||||
return ICron.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<ICron>, I>>(object: I): ICron {
|
|
||||||
const message = createBaseICron();
|
|
||||||
message.id = object.id ?? "";
|
|
||||||
message.schedule = object.schedule ?? "";
|
|
||||||
message.command = object.command ?? "";
|
|
||||||
message.extraSchedules = object.extraSchedules?.map((e) => ISchedule.fromPartial(e)) || [];
|
|
||||||
message.name = object.name ?? "";
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function createBaseAddCronRequest(): AddCronRequest {
|
|
||||||
return { crons: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const AddCronRequest = {
|
|
||||||
encode(message: AddCronRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
for (const v of message.crons) {
|
|
||||||
ICron.encode(v!, writer.uint32(10).fork()).ldelim();
|
|
||||||
}
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): AddCronRequest {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseAddCronRequest();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
case 1:
|
|
||||||
if (tag !== 10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.crons.push(ICron.decode(reader, reader.uint32()));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(object: any): AddCronRequest {
|
|
||||||
return { crons: Array.isArray(object?.crons) ? object.crons.map((e: any) => ICron.fromJSON(e)) : [] };
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(message: AddCronRequest): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
if (message.crons) {
|
|
||||||
obj.crons = message.crons.map((e) => e ? ICron.toJSON(e) : undefined);
|
|
||||||
} else {
|
|
||||||
obj.crons = [];
|
|
||||||
}
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<AddCronRequest>, I>>(base?: I): AddCronRequest {
|
|
||||||
return AddCronRequest.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(object: I): AddCronRequest {
|
|
||||||
const message = createBaseAddCronRequest();
|
|
||||||
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function createBaseAddCronResponse(): AddCronResponse {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const AddCronResponse = {
|
|
||||||
encode(_: AddCronResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): AddCronResponse {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseAddCronResponse();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(_: any): AddCronResponse {
|
|
||||||
return {};
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(_: AddCronResponse): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<AddCronResponse>, I>>(base?: I): AddCronResponse {
|
|
||||||
return AddCronResponse.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(_: I): AddCronResponse {
|
|
||||||
const message = createBaseAddCronResponse();
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function createBaseDeleteCronRequest(): DeleteCronRequest {
|
|
||||||
return { ids: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DeleteCronRequest = {
|
|
||||||
encode(message: DeleteCronRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
for (const v of message.ids) {
|
|
||||||
writer.uint32(10).string(v!);
|
|
||||||
}
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): DeleteCronRequest {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseDeleteCronRequest();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
case 1:
|
|
||||||
if (tag !== 10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.ids.push(reader.string());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(object: any): DeleteCronRequest {
|
|
||||||
return { ids: Array.isArray(object?.ids) ? object.ids.map((e: any) => String(e)) : [] };
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(message: DeleteCronRequest): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
if (message.ids) {
|
|
||||||
obj.ids = message.ids.map((e) => e);
|
|
||||||
} else {
|
|
||||||
obj.ids = [];
|
|
||||||
}
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(base?: I): DeleteCronRequest {
|
|
||||||
return DeleteCronRequest.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(object: I): DeleteCronRequest {
|
|
||||||
const message = createBaseDeleteCronRequest();
|
|
||||||
message.ids = object.ids?.map((e) => e) || [];
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function createBaseDeleteCronResponse(): DeleteCronResponse {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DeleteCronResponse = {
|
|
||||||
encode(_: DeleteCronResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): DeleteCronResponse {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseDeleteCronResponse();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(_: any): DeleteCronResponse {
|
|
||||||
return {};
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(_: DeleteCronResponse): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(base?: I): DeleteCronResponse {
|
|
||||||
return DeleteCronResponse.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(_: I): DeleteCronResponse {
|
|
||||||
const message = createBaseDeleteCronResponse();
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export type CronService = typeof CronService;
|
|
||||||
export const CronService = {
|
|
||||||
addCron: {
|
|
||||||
path: "/com.ql.cron.Cron/addCron",
|
|
||||||
requestStream: false,
|
|
||||||
responseStream: false,
|
|
||||||
requestSerialize: (value: AddCronRequest) => Buffer.from(AddCronRequest.encode(value).finish()),
|
|
||||||
requestDeserialize: (value: Buffer) => AddCronRequest.decode(value),
|
|
||||||
responseSerialize: (value: AddCronResponse) => Buffer.from(AddCronResponse.encode(value).finish()),
|
|
||||||
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
|
|
||||||
},
|
|
||||||
delCron: {
|
|
||||||
path: "/com.ql.cron.Cron/delCron",
|
|
||||||
requestStream: false,
|
|
||||||
responseStream: false,
|
|
||||||
requestSerialize: (value: DeleteCronRequest) => Buffer.from(DeleteCronRequest.encode(value).finish()),
|
|
||||||
requestDeserialize: (value: Buffer) => DeleteCronRequest.decode(value),
|
|
||||||
responseSerialize: (value: DeleteCronResponse) => Buffer.from(DeleteCronResponse.encode(value).finish()),
|
|
||||||
responseDeserialize: (value: Buffer) => DeleteCronResponse.decode(value),
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export interface CronServer extends UntypedServiceImplementation {
|
|
||||||
addCron: handleUnaryCall<AddCronRequest, AddCronResponse>;
|
|
||||||
delCron: handleUnaryCall<DeleteCronRequest, DeleteCronResponse>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CronClient extends Client {
|
|
||||||
addCron(
|
|
||||||
request: AddCronRequest,
|
|
||||||
callback: (error: ServiceError | null, response: AddCronResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
addCron(
|
|
||||||
request: AddCronRequest,
|
|
||||||
metadata: Metadata,
|
|
||||||
callback: (error: ServiceError | null, response: AddCronResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
addCron(
|
|
||||||
request: AddCronRequest,
|
|
||||||
metadata: Metadata,
|
|
||||||
options: Partial<CallOptions>,
|
|
||||||
callback: (error: ServiceError | null, response: AddCronResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
delCron(
|
|
||||||
request: DeleteCronRequest,
|
|
||||||
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
delCron(
|
|
||||||
request: DeleteCronRequest,
|
|
||||||
metadata: Metadata,
|
|
||||||
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
delCron(
|
|
||||||
request: DeleteCronRequest,
|
|
||||||
metadata: Metadata,
|
|
||||||
options: Partial<CallOptions>,
|
|
||||||
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const CronClient = makeGenericClientConstructor(CronService, "com.ql.cron.Cron") as unknown as {
|
|
||||||
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): CronClient;
|
|
||||||
service: typeof CronService;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
|
||||||
|
|
||||||
export type DeepPartial<T> = T extends Builtin ? T
|
|
||||||
: T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
|
|
||||||
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
|
||||||
: Partial<T>;
|
|
||||||
|
|
||||||
type KeysOfUnion<T> = T extends T ? keyof T : never;
|
|
||||||
export type Exact<P, I extends P> = P extends Builtin ? P
|
|
||||||
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
|
|
||||||
|
|
||||||
function isSet(value: any): boolean {
|
|
||||||
return value !== null && value !== undefined;
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package com.ql.health;
|
|
||||||
|
|
||||||
message HealthCheckRequest {
|
|
||||||
string service = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message HealthCheckResponse {
|
|
||||||
enum ServingStatus {
|
|
||||||
UNKNOWN = 0;
|
|
||||||
SERVING = 1;
|
|
||||||
NOT_SERVING = 2;
|
|
||||||
SERVICE_UNKNOWN = 3;
|
|
||||||
}
|
|
||||||
ServingStatus status = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
service Health {
|
|
||||||
rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
|
|
||||||
rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
|
|
||||||
}
|
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
/* eslint-disable */
|
|
||||||
import {
|
|
||||||
CallOptions,
|
|
||||||
ChannelCredentials,
|
|
||||||
Client,
|
|
||||||
ClientOptions,
|
|
||||||
ClientReadableStream,
|
|
||||||
ClientUnaryCall,
|
|
||||||
handleServerStreamingCall,
|
|
||||||
handleUnaryCall,
|
|
||||||
makeGenericClientConstructor,
|
|
||||||
Metadata,
|
|
||||||
ServiceError,
|
|
||||||
UntypedServiceImplementation,
|
|
||||||
} from "@grpc/grpc-js";
|
|
||||||
import _m0 from "protobufjs/minimal";
|
|
||||||
|
|
||||||
export const protobufPackage = "com.ql.health";
|
|
||||||
|
|
||||||
export interface HealthCheckRequest {
|
|
||||||
service: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HealthCheckResponse {
|
|
||||||
status: HealthCheckResponse_ServingStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum HealthCheckResponse_ServingStatus {
|
|
||||||
UNKNOWN = 0,
|
|
||||||
SERVING = 1,
|
|
||||||
NOT_SERVING = 2,
|
|
||||||
SERVICE_UNKNOWN = 3,
|
|
||||||
UNRECOGNIZED = -1,
|
|
||||||
}
|
|
||||||
|
|
||||||
export function healthCheckResponse_ServingStatusFromJSON(object: any): HealthCheckResponse_ServingStatus {
|
|
||||||
switch (object) {
|
|
||||||
case 0:
|
|
||||||
case "UNKNOWN":
|
|
||||||
return HealthCheckResponse_ServingStatus.UNKNOWN;
|
|
||||||
case 1:
|
|
||||||
case "SERVING":
|
|
||||||
return HealthCheckResponse_ServingStatus.SERVING;
|
|
||||||
case 2:
|
|
||||||
case "NOT_SERVING":
|
|
||||||
return HealthCheckResponse_ServingStatus.NOT_SERVING;
|
|
||||||
case 3:
|
|
||||||
case "SERVICE_UNKNOWN":
|
|
||||||
return HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN;
|
|
||||||
case -1:
|
|
||||||
case "UNRECOGNIZED":
|
|
||||||
default:
|
|
||||||
return HealthCheckResponse_ServingStatus.UNRECOGNIZED;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function healthCheckResponse_ServingStatusToJSON(object: HealthCheckResponse_ServingStatus): string {
|
|
||||||
switch (object) {
|
|
||||||
case HealthCheckResponse_ServingStatus.UNKNOWN:
|
|
||||||
return "UNKNOWN";
|
|
||||||
case HealthCheckResponse_ServingStatus.SERVING:
|
|
||||||
return "SERVING";
|
|
||||||
case HealthCheckResponse_ServingStatus.NOT_SERVING:
|
|
||||||
return "NOT_SERVING";
|
|
||||||
case HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN:
|
|
||||||
return "SERVICE_UNKNOWN";
|
|
||||||
case HealthCheckResponse_ServingStatus.UNRECOGNIZED:
|
|
||||||
default:
|
|
||||||
return "UNRECOGNIZED";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function createBaseHealthCheckRequest(): HealthCheckRequest {
|
|
||||||
return { service: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const HealthCheckRequest = {
|
|
||||||
encode(message: HealthCheckRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
if (message.service !== "") {
|
|
||||||
writer.uint32(10).string(message.service);
|
|
||||||
}
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): HealthCheckRequest {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseHealthCheckRequest();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
case 1:
|
|
||||||
if (tag !== 10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.service = reader.string();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(object: any): HealthCheckRequest {
|
|
||||||
return { service: isSet(object.service) ? String(object.service) : "" };
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(message: HealthCheckRequest): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
message.service !== undefined && (obj.service = message.service);
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(base?: I): HealthCheckRequest {
|
|
||||||
return HealthCheckRequest.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(object: I): HealthCheckRequest {
|
|
||||||
const message = createBaseHealthCheckRequest();
|
|
||||||
message.service = object.service ?? "";
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function createBaseHealthCheckResponse(): HealthCheckResponse {
|
|
||||||
return { status: 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const HealthCheckResponse = {
|
|
||||||
encode(message: HealthCheckResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
|
|
||||||
if (message.status !== 0) {
|
|
||||||
writer.uint32(8).int32(message.status);
|
|
||||||
}
|
|
||||||
return writer;
|
|
||||||
},
|
|
||||||
|
|
||||||
decode(input: _m0.Reader | Uint8Array, length?: number): HealthCheckResponse {
|
|
||||||
const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);
|
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
|
||||||
const message = createBaseHealthCheckResponse();
|
|
||||||
while (reader.pos < end) {
|
|
||||||
const tag = reader.uint32();
|
|
||||||
switch (tag >>> 3) {
|
|
||||||
case 1:
|
|
||||||
if (tag !== 8) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.status = reader.int32() as any;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ((tag & 7) === 4 || tag === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
reader.skipType(tag & 7);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
|
|
||||||
fromJSON(object: any): HealthCheckResponse {
|
|
||||||
return { status: isSet(object.status) ? healthCheckResponse_ServingStatusFromJSON(object.status) : 0 };
|
|
||||||
},
|
|
||||||
|
|
||||||
toJSON(message: HealthCheckResponse): unknown {
|
|
||||||
const obj: any = {};
|
|
||||||
message.status !== undefined && (obj.status = healthCheckResponse_ServingStatusToJSON(message.status));
|
|
||||||
return obj;
|
|
||||||
},
|
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(base?: I): HealthCheckResponse {
|
|
||||||
return HealthCheckResponse.fromPartial(base ?? {});
|
|
||||||
},
|
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(object: I): HealthCheckResponse {
|
|
||||||
const message = createBaseHealthCheckResponse();
|
|
||||||
message.status = object.status ?? 0;
|
|
||||||
return message;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export type HealthService = typeof HealthService;
|
|
||||||
export const HealthService = {
|
|
||||||
check: {
|
|
||||||
path: "/com.ql.health.Health/Check",
|
|
||||||
requestStream: false,
|
|
||||||
responseStream: false,
|
|
||||||
requestSerialize: (value: HealthCheckRequest) => Buffer.from(HealthCheckRequest.encode(value).finish()),
|
|
||||||
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
|
|
||||||
responseSerialize: (value: HealthCheckResponse) => Buffer.from(HealthCheckResponse.encode(value).finish()),
|
|
||||||
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
path: "/com.ql.health.Health/Watch",
|
|
||||||
requestStream: false,
|
|
||||||
responseStream: true,
|
|
||||||
requestSerialize: (value: HealthCheckRequest) => Buffer.from(HealthCheckRequest.encode(value).finish()),
|
|
||||||
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
|
|
||||||
responseSerialize: (value: HealthCheckResponse) => Buffer.from(HealthCheckResponse.encode(value).finish()),
|
|
||||||
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export interface HealthServer extends UntypedServiceImplementation {
|
|
||||||
check: handleUnaryCall<HealthCheckRequest, HealthCheckResponse>;
|
|
||||||
watch: handleServerStreamingCall<HealthCheckRequest, HealthCheckResponse>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HealthClient extends Client {
|
|
||||||
check(
|
|
||||||
request: HealthCheckRequest,
|
|
||||||
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
check(
|
|
||||||
request: HealthCheckRequest,
|
|
||||||
metadata: Metadata,
|
|
||||||
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
check(
|
|
||||||
request: HealthCheckRequest,
|
|
||||||
metadata: Metadata,
|
|
||||||
options: Partial<CallOptions>,
|
|
||||||
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
|
|
||||||
): ClientUnaryCall;
|
|
||||||
watch(request: HealthCheckRequest, options?: Partial<CallOptions>): ClientReadableStream<HealthCheckResponse>;
|
|
||||||
watch(
|
|
||||||
request: HealthCheckRequest,
|
|
||||||
metadata?: Metadata,
|
|
||||||
options?: Partial<CallOptions>,
|
|
||||||
): ClientReadableStream<HealthCheckResponse>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const HealthClient = makeGenericClientConstructor(HealthService, "com.ql.health.Health") as unknown as {
|
|
||||||
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): HealthClient;
|
|
||||||
service: typeof HealthService;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
|
||||||
|
|
||||||
export type DeepPartial<T> = T extends Builtin ? T
|
|
||||||
: T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
|
|
||||||
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
|
||||||
: Partial<T>;
|
|
||||||
|
|
||||||
type KeysOfUnion<T> = T extends T ? keyof T : never;
|
|
||||||
export type Exact<P, I extends P> = P extends Builtin ? P
|
|
||||||
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
|
|
||||||
|
|
||||||
function isSet(value: any): boolean {
|
|
||||||
return value !== null && value !== undefined;
|
|
||||||
}
|
|
||||||
+11
-16
@@ -1,22 +1,20 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
|
import { exec } from 'child_process';
|
||||||
import Logger from './loaders/logger';
|
import Logger from './loaders/logger';
|
||||||
import config from './config';
|
import config from './config';
|
||||||
import { HealthClient } from './protos/health';
|
|
||||||
import { credentials } from '@grpc/grpc-js';
|
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const client = new HealthClient(
|
|
||||||
`0.0.0.0:${config.cronPort}`,
|
|
||||||
credentials.createInsecure(),
|
|
||||||
);
|
|
||||||
|
|
||||||
app.get('/api/health', (req, res) => {
|
app.get('/api/public/panel/log', (req, res) => {
|
||||||
client.check({ service: 'cron' }, (err, response) => {
|
exec(
|
||||||
if (err) {
|
'pm2 logs panel --lines 500 --nostream --timestamp',
|
||||||
return res.status(200).send({ code: 500, error: err });
|
(err, stdout, stderr) => {
|
||||||
|
if (err || stderr) {
|
||||||
|
return res.send({ code: 400, message: (err && err.message) || stderr });
|
||||||
}
|
}
|
||||||
return res.status(200).send({ code: 200, data: response });
|
return res.send({ code: 200, data: stdout });
|
||||||
});
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
app
|
app
|
||||||
@@ -24,12 +22,9 @@ 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}`);
|
||||||
console.debug(`✌️ 公共服务启动成功!`);
|
|
||||||
process.send?.('ready');
|
|
||||||
})
|
})
|
||||||
.on('error', (err) => {
|
.on('error', (err) => {
|
||||||
Logger.error(err);
|
Logger.error(err);
|
||||||
console.error(err);
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import schedule from 'node-schedule';
|
||||||
|
import express from 'express';
|
||||||
|
import { exec } from 'child_process';
|
||||||
|
import Logger from './loaders/logger';
|
||||||
|
import { CrontabModel, CrontabStatus } from './data/cron';
|
||||||
|
import config from './config';
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
CrontabModel.findAll({ where: {} })
|
||||||
|
.then((docs) => {
|
||||||
|
if (docs && docs.length > 0) {
|
||||||
|
for (let i = 0; i < docs.length; i++) {
|
||||||
|
const task = docs[i];
|
||||||
|
const _schedule = task.schedule && task.schedule.split(/ +/);
|
||||||
|
if (
|
||||||
|
_schedule &&
|
||||||
|
_schedule.length > 5 &&
|
||||||
|
task.status !== CrontabStatus.disabled &&
|
||||||
|
!task.isDisabled
|
||||||
|
) {
|
||||||
|
schedule.scheduleJob(task.schedule, function () {
|
||||||
|
let command = task.command as string;
|
||||||
|
if (!command.includes('task ') && !command.includes('ql ')) {
|
||||||
|
command = `task ${command}`;
|
||||||
|
}
|
||||||
|
exec(command);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
Logger.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
app
|
||||||
|
.listen(config.cronPort, async () => {
|
||||||
|
await require('./loaders/sentry').default({ expressApp: app });
|
||||||
|
await require('./loaders/db').default();
|
||||||
|
|
||||||
|
await run();
|
||||||
|
Logger.info(`
|
||||||
|
################################################
|
||||||
|
🛡️ Schedule listening on port: ${config.cronPort} 🛡️
|
||||||
|
################################################
|
||||||
|
`);
|
||||||
|
})
|
||||||
|
.on('error', (err) => {
|
||||||
|
Logger.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
|
|
||||||
import { AddCronRequest, AddCronResponse } from '../protos/cron';
|
|
||||||
import nodeSchedule from 'node-schedule';
|
|
||||||
import { scheduleStacks } from './data';
|
|
||||||
import { runCron } from '../shared/runCron';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
|
|
||||||
const addCron = (
|
|
||||||
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
|
|
||||||
callback: sendUnaryData<AddCronResponse>,
|
|
||||||
) => {
|
|
||||||
for (const item of call.request.crons) {
|
|
||||||
const { id, schedule, command, extraSchedules, name } = item;
|
|
||||||
if (scheduleStacks.has(id)) {
|
|
||||||
scheduleStacks.get(id)?.forEach((x) => x.cancel());
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger.info(
|
|
||||||
'[schedule][创建定时任务], 任务ID: %s, 名称: %s, cron: %s, 执行命令: %s',
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
schedule,
|
|
||||||
command,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (extraSchedules?.length) {
|
|
||||||
extraSchedules.forEach(x => {
|
|
||||||
Logger.info(
|
|
||||||
'[schedule][创建定时任务], 任务ID: %s, 名称: %s, cron: %s, 执行命令: %s',
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
x.schedule,
|
|
||||||
command,
|
|
||||||
);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
scheduleStacks.set(id, [
|
|
||||||
nodeSchedule.scheduleJob(id, schedule, async () => {
|
|
||||||
Logger.info(`[schedule][准备运行任务] 命令: ${command}`);
|
|
||||||
runCron(command, { name, schedule, extraSchedules });
|
|
||||||
}),
|
|
||||||
...(extraSchedules?.length
|
|
||||||
? extraSchedules.map((x) =>
|
|
||||||
nodeSchedule.scheduleJob(id, x.schedule, async () => {
|
|
||||||
Logger.info(`[schedule][准备运行任务] 命令: ${command}`);
|
|
||||||
runCron(command, { name, schedule, extraSchedules });
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: []),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
callback(null, null);
|
|
||||||
};
|
|
||||||
|
|
||||||
export { addCron };
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import { credentials } from '@grpc/grpc-js';
|
|
||||||
import {
|
|
||||||
AddCronRequest,
|
|
||||||
AddCronResponse,
|
|
||||||
CronClient,
|
|
||||||
DeleteCronRequest,
|
|
||||||
DeleteCronResponse,
|
|
||||||
} from '../protos/cron';
|
|
||||||
import config from '../config';
|
|
||||||
|
|
||||||
class Client {
|
|
||||||
private client = new CronClient(
|
|
||||||
`0.0.0.0:${config.cronPort}`,
|
|
||||||
credentials.createInsecure(),
|
|
||||||
);
|
|
||||||
|
|
||||||
addCron(request: AddCronRequest['crons']): Promise<AddCronResponse> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
this.client.addCron({ crons: request }, (err, res) => {
|
|
||||||
if (err) {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
resolve(res);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
delCron(request: DeleteCronRequest['ids']): Promise<DeleteCronResponse> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
this.client.delCron({ ids: request }, (err, res) => {
|
|
||||||
if (err) {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
resolve(res);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new Client();
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import nodeSchedule from 'node-schedule';
|
|
||||||
import { ToadScheduler } from 'toad-scheduler';
|
|
||||||
|
|
||||||
export const scheduleStacks = new Map<string, nodeSchedule.Job[]>();
|
|
||||||
|
|
||||||
export const intervalSchedule = new ToadScheduler();
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
|
|
||||||
import { DeleteCronRequest, DeleteCronResponse } from '../protos/cron';
|
|
||||||
import { scheduleStacks } from './data';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
|
|
||||||
const delCron = (
|
|
||||||
call: ServerUnaryCall<DeleteCronRequest, DeleteCronResponse>,
|
|
||||||
callback: sendUnaryData<DeleteCronResponse>,
|
|
||||||
) => {
|
|
||||||
for (const id of call.request.ids) {
|
|
||||||
if (scheduleStacks.has(id)) {
|
|
||||||
Logger.info(
|
|
||||||
'[schedule][取消定时任务], 任务ID: %s',
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
scheduleStacks.get(id)?.forEach(x => x.cancel());
|
|
||||||
scheduleStacks.delete(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
callback(null, null);
|
|
||||||
};
|
|
||||||
|
|
||||||
export { delCron };
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
|
|
||||||
import { HealthCheckRequest, HealthCheckResponse } from '../protos/health';
|
|
||||||
import config from '../config';
|
|
||||||
import { promiseExec } from '../config/util';
|
|
||||||
|
|
||||||
const check = async (
|
|
||||||
call: ServerUnaryCall<HealthCheckRequest, HealthCheckResponse>,
|
|
||||||
callback: sendUnaryData<HealthCheckResponse>,
|
|
||||||
) => {
|
|
||||||
switch (call.request.service) {
|
|
||||||
case 'cron':
|
|
||||||
const res = await promiseExec(
|
|
||||||
`curl -s http://0.0.0.0:${config.port}/api/system`,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (res.includes('200')) {
|
|
||||||
return callback(null, { status: 1 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const panelErrLog = await promiseExec(
|
|
||||||
`tail -n 300 ~/.pm2/logs/panel-error.log`,
|
|
||||||
);
|
|
||||||
const scheduleErrLog = await promiseExec(
|
|
||||||
`tail -n 300 ~/.pm2/logs/schedule-error.log`,
|
|
||||||
);
|
|
||||||
return callback(
|
|
||||||
new Error(`${scheduleErrLog || ''}\n${panelErrLog || ''}\n${res}`.trim()),
|
|
||||||
);
|
|
||||||
|
|
||||||
default:
|
|
||||||
return callback(null, { status: 1 });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export { check };
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import { Server, ServerCredentials } from '@grpc/grpc-js';
|
|
||||||
import { CronService } from '../protos/cron';
|
|
||||||
import { addCron } from './addCron';
|
|
||||||
import { delCron } from './delCron';
|
|
||||||
import { HealthService } from '../protos/health';
|
|
||||||
import { check } from './health';
|
|
||||||
import config from '../config';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
|
|
||||||
const server = new Server();
|
|
||||||
server.addService(HealthService, { check });
|
|
||||||
server.addService(CronService, { addCron, delCron });
|
|
||||||
server.bindAsync(
|
|
||||||
`0.0.0.0:${config.cronPort}`,
|
|
||||||
ServerCredentials.createInsecure(),
|
|
||||||
(err, port) => {
|
|
||||||
if (err) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
server.start();
|
|
||||||
Logger.debug(`✌️ 定时服务启动成功!`);
|
|
||||||
console.debug(`✌️ 定时服务启动成功!`);
|
|
||||||
process.send?.('ready');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
+205
-291
@@ -2,28 +2,23 @@ import { Service, Inject } from 'typedi';
|
|||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||||
import { exec, execSync } from 'child_process';
|
import { exec, execSync, spawn } from 'child_process';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import cron_parser from 'cron-parser';
|
import cron_parser from 'cron-parser';
|
||||||
import { getFileContentByName, fileExist, killTask, getUniqPath, safeJSONParse } from '../config/util';
|
import { getFileContentByName, concurrentRun, fileExist } from '../config/util';
|
||||||
import { promises, existsSync } from 'fs';
|
import { promises, existsSync } from 'fs';
|
||||||
import { Op, where, col as colFn, FindOptions, fn } from 'sequelize';
|
import { promisify } from 'util';
|
||||||
|
import { Op } from 'sequelize';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { TASK_PREFIX, QL_PREFIX } from '../config/const';
|
|
||||||
import cronClient from '../schedule/client';
|
|
||||||
import taskLimit from '../shared/pLimit';
|
|
||||||
import { spawn } from 'cross-spawn';
|
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import pickBy from 'lodash/pickBy';
|
|
||||||
import omit from 'lodash/omit';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class CronService {
|
export default class CronService {
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
private isSixCron(cron: Crontab) {
|
private isSixCron(cron: Crontab) {
|
||||||
const { schedule } = cron;
|
const { schedule } = cron;
|
||||||
if (Number(schedule?.split(/ +/).length) > 5) {
|
if (schedule?.split(/ +/).length === 6) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -33,12 +28,7 @@ export default class CronService {
|
|||||||
const tab = new Crontab(payload);
|
const tab = new Crontab(payload);
|
||||||
tab.saved = false;
|
tab.saved = false;
|
||||||
const doc = await this.insert(tab);
|
const doc = await this.insert(tab);
|
||||||
if (this.isSixCron(doc) || doc.extra_schedules?.length) {
|
await this.set_crontab(this.isSixCron(doc));
|
||||||
await cronClient.addCron([
|
|
||||||
{ name: doc.name || '', id: String(doc.id), schedule: doc.schedule!, command: this.makeCommand(doc), extraSchedules: doc.extra_schedules || [] },
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
await this.set_crontab();
|
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,28 +37,9 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: Crontab): Promise<Crontab> {
|
public async update(payload: Crontab): Promise<Crontab> {
|
||||||
const doc = await this.getDb({ id: payload.id });
|
payload.saved = false;
|
||||||
const tab = new Crontab({ ...doc, ...payload });
|
const newDoc = await this.updateDb(payload);
|
||||||
tab.saved = false;
|
await this.set_crontab(this.isSixCron(newDoc));
|
||||||
const newDoc = await this.updateDb(tab);
|
|
||||||
if (doc.isDisabled === 1) {
|
|
||||||
return newDoc;
|
|
||||||
}
|
|
||||||
if (this.isSixCron(doc) || doc.extra_schedules?.length) {
|
|
||||||
await cronClient.delCron([String(doc.id)]);
|
|
||||||
}
|
|
||||||
if (this.isSixCron(newDoc) || newDoc.extra_schedules?.length) {
|
|
||||||
await cronClient.addCron([
|
|
||||||
{
|
|
||||||
name: doc.name || '',
|
|
||||||
id: String(newDoc.id),
|
|
||||||
schedule: newDoc.schedule!,
|
|
||||||
command: this.makeCommand(newDoc),
|
|
||||||
extraSchedules: newDoc.extra_schedules || []
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
await this.set_crontab();
|
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +63,7 @@ export default class CronService {
|
|||||||
last_running_time: number;
|
last_running_time: number;
|
||||||
last_execution_time: number;
|
last_execution_time: number;
|
||||||
}) {
|
}) {
|
||||||
let options: any = {
|
const options: any = {
|
||||||
status,
|
status,
|
||||||
pid,
|
pid,
|
||||||
log_path,
|
log_path,
|
||||||
@@ -102,19 +73,12 @@ export default class CronService {
|
|||||||
options.last_running_time = last_running_time;
|
options.last_running_time = last_running_time;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const id of ids) {
|
return await CrontabModel.update({ ...options }, { where: { id: ids } });
|
||||||
const cron = await this.getDb({ id });
|
|
||||||
if (status === CrontabStatus.idle && log_path !== cron.log_path) {
|
|
||||||
options = omit(options, ['status', 'log_path', 'pid']);
|
|
||||||
}
|
|
||||||
await CrontabModel.update({ ...pickBy(options, (v) => v === 0 || !!v) }, { where: { id } });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[]) {
|
public async remove(ids: number[]) {
|
||||||
await CrontabModel.destroy({ where: { id: ids } });
|
await CrontabModel.destroy({ where: { id: ids } });
|
||||||
await cronClient.delCron(ids.map(String));
|
await this.set_crontab(true);
|
||||||
await this.set_crontab();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async pin(ids: number[]) {
|
public async pin(ids: number[]) {
|
||||||
@@ -149,80 +113,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 = {};
|
||||||
const primaryOperate = viewQuery.filterRelation === 'or' ? Op.or : Op.and;
|
|
||||||
if (!query[primaryOperate]) {
|
|
||||||
query[primaryOperate] = [];
|
|
||||||
}
|
|
||||||
for (const col of viewQuery.filters) {
|
|
||||||
const { property, value, operation } = col;
|
|
||||||
let q: any = {};
|
|
||||||
let operate2 = null;
|
|
||||||
let operate = null;
|
|
||||||
switch (operation) {
|
|
||||||
case 'Reg':
|
|
||||||
operate = Op.like;
|
|
||||||
operate2 = Op.or;
|
|
||||||
break;
|
|
||||||
case 'NotReg':
|
|
||||||
operate = Op.notLike;
|
|
||||||
operate2 = Op.and;
|
|
||||||
break;
|
|
||||||
case 'In':
|
|
||||||
q[Op.or] = [
|
|
||||||
{
|
|
||||||
[property]: Array.isArray(value) ? value : [value],
|
|
||||||
},
|
|
||||||
property === 'status' && value.includes(2)
|
|
||||||
? { isDisabled: 1 }
|
|
||||||
: {},
|
|
||||||
];
|
|
||||||
break;
|
|
||||||
case 'Nin':
|
|
||||||
q[Op.and] = [
|
|
||||||
{
|
|
||||||
[property]: {
|
|
||||||
[Op.notIn]: Array.isArray(value) ? value : [value],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
property === 'status' && value.includes(2)
|
|
||||||
? { isDisabled: { [Op.ne]: 1 } }
|
|
||||||
: {},
|
|
||||||
];
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (operate && operate2) {
|
|
||||||
q[property] = {
|
|
||||||
[Op.or]: [
|
|
||||||
{
|
|
||||||
[operate2]: [
|
|
||||||
{ [operate]: `%${value}%` },
|
|
||||||
{ [operate]: `%${encodeURI(value)}%` },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
[operate2]: [
|
|
||||||
where(colFn(property), operate, `%${value}%`),
|
|
||||||
where(colFn(property), operate, `%${encodeURI(value)}%`),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
query[primaryOperate].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':
|
||||||
@@ -230,21 +123,24 @@ 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]: `%${encodeURI(textArray[1])}%` },
|
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
||||||
],
|
],
|
||||||
|
},
|
||||||
};
|
};
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
{ [Op.like]: `%${encodeURI(searchText)}%` },
|
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
q[Op.or] = [
|
query = {
|
||||||
|
[Op.or]: [
|
||||||
{
|
{
|
||||||
name: reg,
|
name: reg,
|
||||||
},
|
},
|
||||||
@@ -257,109 +153,23 @@ 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 (!filterQuery[key]) continue;
|
|
||||||
if (key === 'status') {
|
|
||||||
if (filterQuery[key].includes(CrontabStatus.disabled)) {
|
|
||||||
q = { [Op.or]: [{ [key]: filterQuery[key] }, { isDisabled: 1 }] };
|
|
||||||
} else {
|
|
||||||
q = { [Op.and]: [{ [key]: filterQuery[key] }, { isDisabled: 0 }] };
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
q[key] = filterQuery[key];
|
|
||||||
}
|
|
||||||
query[Op.and].push(q);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private formatViewSort(order: string[][], viewQuery: any) {
|
|
||||||
if (viewQuery.sorts && viewQuery.sorts.length > 0) {
|
|
||||||
for (const { property, type } of viewQuery.sorts) {
|
|
||||||
order.unshift([property, type]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async find({
|
|
||||||
log_path,
|
|
||||||
}: {
|
|
||||||
log_path: string;
|
|
||||||
}): Promise<Crontab | null> {
|
|
||||||
try {
|
try {
|
||||||
const result = await CrontabModel.findOne({ where: { log_path } });
|
const result = await CrontabModel.findAll({
|
||||||
return result;
|
|
||||||
} catch (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async crontabs(params?: {
|
|
||||||
searchValue: string;
|
|
||||||
page: string;
|
|
||||||
size: string;
|
|
||||||
sorter: string;
|
|
||||||
filters: string;
|
|
||||||
queryString: string;
|
|
||||||
}): Promise<{ data: Crontab[]; total: number }> {
|
|
||||||
const searchText = params?.searchValue;
|
|
||||||
const page = Number(params?.page || '0');
|
|
||||||
const size = Number(params?.size || '0');
|
|
||||||
const viewQuery = safeJSONParse(params?.queryString);
|
|
||||||
const filterQuery = safeJSONParse(params?.filters);
|
|
||||||
const sorterQuery = safeJSONParse(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,
|
where: query,
|
||||||
order: order,
|
order: [['createdAt', 'DESC']],
|
||||||
};
|
});
|
||||||
if (page && size) {
|
return result as any;
|
||||||
condition.offset = (page - 1) * size;
|
|
||||||
condition.limit = size;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const result = await CrontabModel.findAll(condition);
|
|
||||||
const count = await CrontabModel.count({ where: query });
|
|
||||||
return { data: result, total: count };
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: FindOptions<Crontab>['where']): Promise<Crontab> {
|
public async getDb(query: any): Promise<Crontab> {
|
||||||
const doc: any = await CrontabModel.findOne({ where: { ...query } });
|
const doc: any = await CrontabModel.findOne({ where: { ...query } });
|
||||||
return doc && (doc.get({ plain: true }) as Crontab);
|
return doc && (doc.get({ plain: true }) as Crontab);
|
||||||
}
|
}
|
||||||
@@ -369,9 +179,10 @@ export default class CronService {
|
|||||||
{ status: CrontabStatus.queued },
|
{ status: CrontabStatus.queued },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
);
|
);
|
||||||
ids.forEach((id) => {
|
concurrentRun(
|
||||||
this.runSingle(id);
|
ids.map((id) => async () => await this.runSingle(id)),
|
||||||
});
|
10,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop(ids: number[]) {
|
public async stop(ids: number[]) {
|
||||||
@@ -379,11 +190,31 @@ export default class CronService {
|
|||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
if (doc.pid) {
|
if (doc.pid) {
|
||||||
try {
|
try {
|
||||||
await killTask(doc.pid);
|
process.kill(-doc.pid);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(error);
|
this.logger.silly(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const err = await this.killTask(doc.command);
|
||||||
|
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||||
|
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||||
|
|
||||||
|
const endTime = dayjs();
|
||||||
|
const diffTimeStr = doc.last_execution_time
|
||||||
|
? `,耗时 ${endTime.diff(
|
||||||
|
dayjs(doc.last_execution_time * 1000),
|
||||||
|
'second',
|
||||||
|
)}`
|
||||||
|
: '';
|
||||||
|
if (logFileExist) {
|
||||||
|
const str = err ? `\n${err}` : '';
|
||||||
|
fs.appendFileSync(
|
||||||
|
`${absolutePath}`,
|
||||||
|
`${str}\n## 执行结束... ${endTime.format(
|
||||||
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
|
)}${diffTimeStr}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
@@ -392,72 +223,112 @@ export default class CronService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runSingle(cronId: number): Promise<number | void> {
|
public async killTask(name: string) {
|
||||||
return taskLimit.runWithCronLimit(() => {
|
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
||||||
|
const execAsync = promisify(exec);
|
||||||
|
try {
|
||||||
|
let pid = (await execAsync(taskCommand)).stdout;
|
||||||
|
if (pid) {
|
||||||
|
pid = (await execAsync(`pstree -p ${pid}`)).stdout;
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let pids = pid.match(/\(\d+/g);
|
||||||
|
const killLogs = [];
|
||||||
|
if (pids && pids.length > 0) {
|
||||||
|
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
||||||
|
pids = pids.slice(0, 3);
|
||||||
|
for (const id of pids) {
|
||||||
|
const c = `kill -9 ${id.slice(1)}`;
|
||||||
|
try {
|
||||||
|
const { stdout, stderr } = await execAsync(c);
|
||||||
|
if (stderr) {
|
||||||
|
killLogs.push(stderr);
|
||||||
|
}
|
||||||
|
if (stdout) {
|
||||||
|
killLogs.push(stdout);
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
killLogs.push(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return killLogs.length > 0 ? JSON.stringify(killLogs) : '';
|
||||||
|
} catch (e) {
|
||||||
|
return JSON.stringify(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runSingle(cronId: number): Promise<number> {
|
||||||
return new Promise(async (resolve: any) => {
|
return new Promise(async (resolve: any) => {
|
||||||
const cron = await this.getDb({ id: cronId });
|
const cron = await this.getDb({ id: cronId });
|
||||||
const params = { name: cron.name, command: cron.command, schedule: cron.schedule, extraSchedules: cron.extra_schedules };
|
|
||||||
if (cron.status !== CrontabStatus.queued) {
|
if (cron.status !== CrontabStatus.queued) {
|
||||||
resolve(params);
|
resolve();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logger.info(`[panel][开始执行任务] 参数 ${JSON.stringify(params)}`);
|
|
||||||
|
|
||||||
let { id, command, log_path } = cron;
|
let { id, command, log_path } = cron;
|
||||||
const uniqPath = await getUniqPath(command, `${id}`);
|
const absolutePath = path.resolve(config.logPath, `${log_path}`);
|
||||||
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
const logFileExist = log_path && (await fileExist(absolutePath));
|
||||||
const logDirPath = path.resolve(config.logPath, `${uniqPath}`);
|
|
||||||
if (log_path?.split('/')?.every(x => x !== uniqPath)) {
|
|
||||||
fs.mkdirSync(logDirPath, { recursive: true });
|
|
||||||
}
|
|
||||||
const logPath = `${uniqPath}/${logTime}.log`;
|
|
||||||
const absolutePath = path.resolve(config.logPath, `${logPath}`);
|
|
||||||
|
|
||||||
const cp = spawn(`real_log_path=${logPath} no_delay=true ${this.makeCommand(cron)}`, { shell: '/bin/bash' });
|
this.logger.silly('Running job');
|
||||||
|
this.logger.silly('ID: ' + id);
|
||||||
|
this.logger.silly('Original command: ' + command);
|
||||||
|
|
||||||
|
let cmdStr = command;
|
||||||
|
if (!cmdStr.includes('task ') && !cmdStr.includes('ql ')) {
|
||||||
|
cmdStr = `task ${cmdStr}`;
|
||||||
|
}
|
||||||
|
if (cmdStr.endsWith('.js')) {
|
||||||
|
cmdStr = `${cmdStr} now`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cp = spawn(cmdStr, { shell: '/bin/bash' });
|
||||||
|
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{ status: CrontabStatus.running, pid: cp.pid, log_path: logPath },
|
{ status: CrontabStatus.running, pid: cp.pid },
|
||||||
{ where: { id } },
|
{ where: { id } },
|
||||||
);
|
);
|
||||||
cp.stderr.on('data', (data) => {
|
cp.stderr.on('data', (data) => {
|
||||||
fs.appendFileSync(`${absolutePath}`, `${data.toString()}`);
|
if (logFileExist) {
|
||||||
|
fs.appendFileSync(`${absolutePath}`, `${data}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
cp.on('error', (err) => {
|
cp.on('error', (err) => {
|
||||||
|
if (logFileExist) {
|
||||||
fs.appendFileSync(`${absolutePath}`, `${JSON.stringify(err)}`);
|
fs.appendFileSync(`${absolutePath}`, `${JSON.stringify(err)}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.on('exit', async (code) => {
|
cp.on('exit', async (code, signal) => {
|
||||||
|
this.logger.info(
|
||||||
|
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||||
|
);
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{ status: CrontabStatus.idle, pid: undefined },
|
{ status: CrontabStatus.idle, pid: undefined },
|
||||||
{ where: { id } },
|
{ where: { id } },
|
||||||
);
|
);
|
||||||
resolve({ ...params, pid: cp.pid, code });
|
resolve();
|
||||||
});
|
});
|
||||||
|
cp.on('close', async (code) => {
|
||||||
|
this.logger.info(`${command} pid: ${cp.pid} closed ${code}`);
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.idle, pid: undefined },
|
||||||
|
{ where: { id } },
|
||||||
|
);
|
||||||
|
resolve();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
public async disabled(ids: number[]) {
|
||||||
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||||
await cronClient.delCron(ids.map(String));
|
await this.set_crontab(true);
|
||||||
await this.set_crontab();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async enabled(ids: number[]) {
|
public async enabled(ids: number[]) {
|
||||||
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||||
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
await this.set_crontab(true);
|
||||||
const sixCron = docs
|
|
||||||
.filter((x) => this.isSixCron(x))
|
|
||||||
.map((doc) => ({
|
|
||||||
name: doc.name || '',
|
|
||||||
id: String(doc.id),
|
|
||||||
schedule: doc.schedule!,
|
|
||||||
command: this.makeCommand(doc),
|
|
||||||
extraSchedules: doc.extra_schedules || []
|
|
||||||
}));
|
|
||||||
await cronClient.addCron(sixCron);
|
|
||||||
await this.set_crontab();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async log(id: number) {
|
public async log(id: number) {
|
||||||
@@ -470,17 +341,35 @@ export default class CronService {
|
|||||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||||
if (logFileExist) {
|
if (logFileExist) {
|
||||||
return getFileContentByName(`${absolutePath}`);
|
return getFileContentByName(`${absolutePath}`);
|
||||||
|
}
|
||||||
|
const [, commandStr, url] = doc.command.split(/ +/);
|
||||||
|
let logPath = this.getKey(commandStr);
|
||||||
|
const isQlCommand = doc.command.startsWith('ql ');
|
||||||
|
const key =
|
||||||
|
(url && ['repo', 'raw'].includes(commandStr) && this.getKey(url)) ||
|
||||||
|
logPath;
|
||||||
|
if (isQlCommand) {
|
||||||
|
logPath = 'update';
|
||||||
|
}
|
||||||
|
let logDir = `${config.logPath}${logPath}`;
|
||||||
|
if (existsSync(logDir)) {
|
||||||
|
let files = await promises.readdir(logDir);
|
||||||
|
if (isQlCommand) {
|
||||||
|
files = files.filter((x) => x.includes(key));
|
||||||
|
}
|
||||||
|
return getFileContentByName(`${logDir}/${files[files.length - 1]}`);
|
||||||
} else {
|
} else {
|
||||||
return '任务未运行';
|
return '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async logs(id: number) {
|
public async logs(id: number) {
|
||||||
const doc = await this.getDb({ id });
|
const doc = await this.getDb({ id });
|
||||||
if (!doc || !doc.log_path) {
|
if (!doc) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (doc.log_path) {
|
||||||
const relativeDir = path.dirname(`${doc.log_path}`);
|
const relativeDir = path.dirname(`${doc.log_path}`);
|
||||||
const dir = path.resolve(config.logPath, relativeDir);
|
const dir = path.resolve(config.logPath, relativeDir);
|
||||||
if (existsSync(dir)) {
|
if (existsSync(dir)) {
|
||||||
@@ -492,52 +381,89 @@ export default class CronService {
|
|||||||
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => b.time - a.time);
|
.sort((a, b) => b.time - a.time);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const [, commandStr, url] = doc.command.split(/ +/);
|
||||||
|
let logPath = this.getKey(commandStr);
|
||||||
|
const isQlCommand = doc.command.startsWith('ql ');
|
||||||
|
const key =
|
||||||
|
(url && ['repo', 'raw'].includes(commandStr) && this.getKey(url)) ||
|
||||||
|
logPath;
|
||||||
|
if (isQlCommand) {
|
||||||
|
logPath = 'update';
|
||||||
|
}
|
||||||
|
let logDir = `${config.logPath}${logPath}`;
|
||||||
|
if (existsSync(logDir)) {
|
||||||
|
let files = await promises.readdir(logDir);
|
||||||
|
if (isQlCommand) {
|
||||||
|
files = files.filter((x) => x.includes(key));
|
||||||
|
}
|
||||||
|
return files
|
||||||
|
.map((x) => ({
|
||||||
|
filename: x,
|
||||||
|
directory: logPath,
|
||||||
|
time: fs.statSync(`${logDir}/${x}`).mtime.getTime(),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => b.time - a.time);
|
||||||
} else {
|
} else {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private makeCommand(tab: Crontab) {
|
private getKey(command: string): string {
|
||||||
let command = tab.command.trim();
|
const start =
|
||||||
if (!command.startsWith(TASK_PREFIX) && !command.startsWith(QL_PREFIX)) {
|
command.lastIndexOf('/') !== -1 ? command.lastIndexOf('/') + 1 : 0;
|
||||||
command = `${TASK_PREFIX}${tab.command}`;
|
const end =
|
||||||
|
command.lastIndexOf('.') !== -1
|
||||||
|
? command.lastIndexOf('.')
|
||||||
|
: command.length;
|
||||||
|
|
||||||
|
const tmpStr = command.substring(0, start - 1);
|
||||||
|
let index = 0;
|
||||||
|
if (tmpStr.lastIndexOf('/') !== -1 && tmpStr.startsWith('http')) {
|
||||||
|
index = tmpStr.lastIndexOf('/');
|
||||||
|
} else if (tmpStr.lastIndexOf(':') !== -1 && tmpStr.startsWith('git@')) {
|
||||||
|
index = tmpStr.lastIndexOf(':');
|
||||||
}
|
}
|
||||||
let commandVariable = `no_tee=true ID=${tab.id} `
|
if (index) {
|
||||||
if (tab.task_before) {
|
return `${tmpStr.substring(index + 1)}_${command.substring(start, end)}`;
|
||||||
commandVariable += `task_before='${tab.task_before.replace(/'/g, "'\\''")
|
} else {
|
||||||
.trim()}' `;
|
return command.substring(start, end);
|
||||||
}
|
}
|
||||||
if (tab.task_after) {
|
|
||||||
commandVariable += `task_after='${tab.task_after.replace(/'/g, "'\\''")
|
|
||||||
.trim()}' `;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const crontab_job_string = `${commandVariable}${command}`;
|
private make_command(tab: Crontab) {
|
||||||
|
const crontab_job_string = `ID=${tab.id} ${tab.command}`;
|
||||||
return crontab_job_string;
|
return crontab_job_string;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async set_crontab(data?: { data: Crontab[]; total: number }) {
|
private async set_crontab(needReloadSchedule: boolean = false) {
|
||||||
const tabs = data ?? (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 || tab.extra_schedules?.length) {
|
if (tab.isDisabled === 1 || _schedule!.length !== 5) {
|
||||||
crontab_string += '# ';
|
crontab_string += '# ';
|
||||||
crontab_string += tab.schedule;
|
crontab_string += tab.schedule;
|
||||||
crontab_string += ' ';
|
crontab_string += ' ';
|
||||||
crontab_string += this.makeCommand(tab);
|
crontab_string += this.make_command(tab);
|
||||||
crontab_string += '\n';
|
crontab_string += '\n';
|
||||||
} else {
|
} else {
|
||||||
crontab_string += tab.schedule;
|
crontab_string += tab.schedule;
|
||||||
crontab_string += ' ';
|
crontab_string += ' ';
|
||||||
crontab_string += this.makeCommand(tab);
|
crontab_string += this.make_command(tab);
|
||||||
crontab_string += '\n';
|
crontab_string += '\n';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.logger.silly(crontab_string);
|
||||||
fs.writeFileSync(config.crontabFile, crontab_string);
|
fs.writeFileSync(config.crontabFile, crontab_string);
|
||||||
|
|
||||||
execSync(`crontab ${config.crontabFile}`);
|
execSync(`crontab ${config.crontabFile}`);
|
||||||
|
if (needReloadSchedule) {
|
||||||
|
exec(`pm2 reload schedule`);
|
||||||
|
}
|
||||||
await CrontabModel.update({ saved: true }, { where: {} });
|
await CrontabModel.update({ saved: true }, { where: {} });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -575,19 +501,7 @@ export default class CronService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async autosave_crontab() {
|
public autosave_crontab() {
|
||||||
const tabs = await this.crontabs();
|
return this.set_crontab();
|
||||||
this.set_crontab(tabs);
|
|
||||||
|
|
||||||
const sixCron = tabs.data
|
|
||||||
.filter((x) => this.isSixCron(x) && x.isDisabled !== 1)
|
|
||||||
.map((doc) => ({
|
|
||||||
name: doc.name || '',
|
|
||||||
id: String(doc.id),
|
|
||||||
schedule: doc.schedule!,
|
|
||||||
command: this.makeCommand(doc),
|
|
||||||
extraSchedules: doc.extra_schedules || []
|
|
||||||
}));
|
|
||||||
await cronClient.addCron(sixCron);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
|
||||||
import winston from 'winston';
|
|
||||||
import { CrontabView, CrontabViewModel } from '../data/cronView';
|
|
||||||
import {
|
|
||||||
initPosition,
|
|
||||||
maxPosition,
|
|
||||||
minPosition,
|
|
||||||
stepPosition,
|
|
||||||
} from '../data/env';
|
|
||||||
import { FindOptions } from 'sequelize';
|
|
||||||
|
|
||||||
@Service()
|
|
||||||
export default class CronViewService {
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
|
||||||
|
|
||||||
public async create(payload: CrontabView): Promise<CrontabView> {
|
|
||||||
let position = initPosition;
|
|
||||||
const views = await this.list();
|
|
||||||
if (views && views.length > 0 && views[views.length - 1].position) {
|
|
||||||
position = views[views.length - 1].position as number;
|
|
||||||
}
|
|
||||||
position = position / 2;
|
|
||||||
const tab = new CrontabView({ ...payload, position });
|
|
||||||
const doc = await this.insert(tab);
|
|
||||||
|
|
||||||
await this.checkPosition(tab.position!);
|
|
||||||
return doc;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async insert(payload: CrontabView): Promise<CrontabView> {
|
|
||||||
return await CrontabViewModel.create(payload, { returning: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
public async update(payload: CrontabView): Promise<CrontabView> {
|
|
||||||
const doc = await this.getDb({ id: payload.id });
|
|
||||||
const tab = new CrontabView({ ...doc, ...payload });
|
|
||||||
const newDoc = await this.updateDb(tab);
|
|
||||||
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: FindOptions<CrontabView>['where'],
|
|
||||||
): Promise<CrontabView> {
|
|
||||||
const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
|
|
||||||
return doc && (doc.get({ plain: true }) as CrontabView);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
|
||||||
await CrontabViewModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
|
||||||
}
|
|
||||||
|
|
||||||
public async enabled(ids: number[]) {
|
|
||||||
await CrontabViewModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
|
||||||
}
|
|
||||||
|
|
||||||
private async checkPosition(position: number) {
|
|
||||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
|
||||||
if (precisionPosition < minPosition || precisionPosition > maxPosition) {
|
|
||||||
const envs = await this.list();
|
|
||||||
let position = initPosition;
|
|
||||||
for (const env of envs) {
|
|
||||||
position = position - stepPosition;
|
|
||||||
await this.updateDb({ id: env.id, position });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getPrecisionPosition(position: number): number {
|
|
||||||
return parseFloat(position.toPrecision(16));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async move({
|
|
||||||
id,
|
|
||||||
fromIndex,
|
|
||||||
toIndex,
|
|
||||||
}: {
|
|
||||||
fromIndex: number;
|
|
||||||
toIndex: number;
|
|
||||||
id: number;
|
|
||||||
}): Promise<CrontabView> {
|
|
||||||
let targetPosition: number;
|
|
||||||
const isUpward = fromIndex > toIndex;
|
|
||||||
const views = await this.list();
|
|
||||||
if (toIndex === 0 || toIndex === views.length - 1) {
|
|
||||||
targetPosition = isUpward
|
|
||||||
? views[0].position! * 2
|
|
||||||
: views[toIndex].position! / 2;
|
|
||||||
} else {
|
|
||||||
targetPosition = isUpward
|
|
||||||
? (views[toIndex].position! + views[toIndex - 1].position!) / 2
|
|
||||||
: (views[toIndex].position! + views[toIndex + 1].position!) / 2;
|
|
||||||
}
|
|
||||||
const newDoc = await this.update({
|
|
||||||
id,
|
|
||||||
position: this.getPrecisionPosition(targetPosition),
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.checkPosition(targetPosition);
|
|
||||||
return newDoc;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+41
-111
@@ -8,15 +8,13 @@ import {
|
|||||||
DependenceTypes,
|
DependenceTypes,
|
||||||
unInstallDependenceCommandTypes,
|
unInstallDependenceCommandTypes,
|
||||||
DependenceModel,
|
DependenceModel,
|
||||||
GetDependenceCommandTypes,
|
|
||||||
versionDependenceCommandTypes,
|
|
||||||
} from '../data/dependence';
|
} from '../data/dependence';
|
||||||
import { spawn } from 'cross-spawn';
|
import _ from 'lodash';
|
||||||
|
import { spawn } from 'child_process';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import { FindOptions, Op } from 'sequelize';
|
import { Op } from 'sequelize';
|
||||||
import { promiseExecSuccess } from '../config/util';
|
import { concurrentRun } from '../config/util';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import taskLimit from '../shared/pLimit';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class DependenceService {
|
export default class DependenceService {
|
||||||
@@ -27,7 +25,7 @@ export default class DependenceService {
|
|||||||
|
|
||||||
public async create(payloads: Dependence[]): Promise<Dependence[]> {
|
public async create(payloads: Dependence[]): Promise<Dependence[]> {
|
||||||
const tabs = payloads.map((x) => {
|
const tabs = payloads.map((x) => {
|
||||||
const tab = new Dependence({ ...x, status: DependenceStatus.queued });
|
const tab = new Dependence({ ...x, status: DependenceStatus.installing });
|
||||||
return tab;
|
return tab;
|
||||||
});
|
});
|
||||||
const docs = await this.insert(tabs);
|
const docs = await this.insert(tabs);
|
||||||
@@ -48,7 +46,7 @@ export default class DependenceService {
|
|||||||
const tab = new Dependence({
|
const tab = new Dependence({
|
||||||
...doc,
|
...doc,
|
||||||
...other,
|
...other,
|
||||||
status: DependenceStatus.queued,
|
status: DependenceStatus.installing,
|
||||||
});
|
});
|
||||||
const newDoc = await this.updateDb(tab);
|
const newDoc = await this.updateDb(tab);
|
||||||
this.installDependenceOneByOne([newDoc]);
|
this.installDependenceOneByOne([newDoc]);
|
||||||
@@ -62,7 +60,7 @@ export default class DependenceService {
|
|||||||
|
|
||||||
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
||||||
await DependenceModel.update(
|
await DependenceModel.update(
|
||||||
{ status: DependenceStatus.queued, log: [] },
|
{ status: DependenceStatus.removing, log: [] },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
);
|
);
|
||||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
@@ -81,7 +79,7 @@ export default class DependenceService {
|
|||||||
): Promise<Dependence[]> {
|
): Promise<Dependence[]> {
|
||||||
let condition = { ...query, type: DependenceTypes[type as any] };
|
let condition = { ...query, type: DependenceTypes[type as any] };
|
||||||
if (searchValue) {
|
if (searchValue) {
|
||||||
const encodeText = encodeURI(searchValue);
|
const encodeText = encodeURIComponent(searchValue);
|
||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchValue}%` },
|
{ [Op.like]: `%${searchValue}%` },
|
||||||
@@ -102,19 +100,23 @@ export default class DependenceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public installDependenceOneByOne(
|
private installDependenceOneByOne(
|
||||||
docs: Dependence[],
|
docs: Dependence[],
|
||||||
isInstall: boolean = true,
|
isInstall: boolean = true,
|
||||||
force: boolean = false,
|
force: boolean = false,
|
||||||
) {
|
) {
|
||||||
docs.forEach((dep) => {
|
concurrentRun(
|
||||||
this.installOrUninstallDependency(dep, isInstall, force);
|
docs.map(
|
||||||
});
|
(dep) => async () =>
|
||||||
|
await this.installOrUninstallDependencies([dep], isInstall, force),
|
||||||
|
),
|
||||||
|
1,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async reInstall(ids: number[]): Promise<Dependence[]> {
|
public async reInstall(ids: number[]): Promise<Dependence[]> {
|
||||||
await DependenceModel.update(
|
await DependenceModel.update(
|
||||||
{ status: DependenceStatus.queued, log: [] },
|
{ status: DependenceStatus.installing, log: [] },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -123,61 +125,46 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(
|
public async getDb(query: any): Promise<Dependence> {
|
||||||
query: FindOptions<Dependence>['where'],
|
|
||||||
): Promise<Dependence> {
|
|
||||||
const doc: any = await DependenceModel.findOne({ where: { ...query } });
|
const doc: any = await DependenceModel.findOne({ where: { ...query } });
|
||||||
return doc && (doc.get({ plain: true }) as Dependence);
|
return doc && (doc.get({ plain: true }) as Dependence);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateLog(ids: number[], log: string): Promise<void> {
|
private async updateLog(ids: number[], log: string): Promise<void> {
|
||||||
taskLimit.updateDepLog(async () => {
|
const doc = await DependenceModel.findOne({ where: { id: ids } });
|
||||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
|
||||||
for (const doc of docs) {
|
|
||||||
const newLog = doc?.log ? [...doc.log, log] : [log];
|
const newLog = doc?.log ? [...doc.log, log] : [log];
|
||||||
await DependenceModel.update(
|
await DependenceModel.update({ log: newLog }, { where: { id: ids } });
|
||||||
{ log: newLog },
|
|
||||||
{ where: { id: doc.id } },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public installOrUninstallDependency(
|
public installOrUninstallDependencies(
|
||||||
dependency: Dependence,
|
dependencies: Dependence[],
|
||||||
isInstall: boolean = true,
|
isInstall: boolean = true,
|
||||||
force: boolean = false,
|
force: boolean = false,
|
||||||
) {
|
) {
|
||||||
return taskLimit.runOneByOne(() => {
|
|
||||||
return new Promise(async (resolve) => {
|
return new Promise(async (resolve) => {
|
||||||
const depIds = [dependency.id!];
|
if (dependencies.length === 0) {
|
||||||
const status = isInstall
|
resolve(null);
|
||||||
? DependenceStatus.installing
|
return;
|
||||||
: DependenceStatus.removing;
|
}
|
||||||
await DependenceModel.update({ status }, { where: { id: depIds } });
|
const socketMessageType = !force
|
||||||
|
|
||||||
const socketMessageType = isInstall
|
|
||||||
? 'installDependence'
|
? 'installDependence'
|
||||||
: 'uninstallDependence';
|
: 'uninstallDependence';
|
||||||
let depName = dependency.name.trim();
|
const depNames = dependencies.map((x) => x.name).join(' ');
|
||||||
const depRunCommand = (
|
const depRunCommand = (
|
||||||
isInstall
|
isInstall
|
||||||
? InstallDependenceCommandTypes
|
? InstallDependenceCommandTypes
|
||||||
: unInstallDependenceCommandTypes
|
: unInstallDependenceCommandTypes
|
||||||
)[dependency.type];
|
)[dependencies[0].type as any];
|
||||||
const actionText = isInstall ? '安装' : '删除';
|
const actionText = isInstall ? '安装' : '删除';
|
||||||
|
const depIds = dependencies.map((x) => x.id) as number[];
|
||||||
const startTime = dayjs();
|
const startTime = dayjs();
|
||||||
|
|
||||||
const message = `开始${actionText}依赖 ${depName},开始时间 ${startTime.format(
|
const message = `开始${actionText}依赖 ${depNames},开始时间 ${startTime.format(
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
)}\n\n`;
|
)}\n\n`;
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
@@ -185,66 +172,9 @@ export default class DependenceService {
|
|||||||
message,
|
message,
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
this.updateLog(depIds, message);
|
await this.updateLog(depIds, message);
|
||||||
|
|
||||||
// 判断是否已经安装过依赖
|
const cp = spawn(`${depRunCommand} ${depNames}`, { shell: '/bin/bash' });
|
||||||
if (isInstall) {
|
|
||||||
const getCommandPrefix = GetDependenceCommandTypes[dependency.type];
|
|
||||||
const depVersionStr = versionDependenceCommandTypes[dependency.type];
|
|
||||||
let depVersion = '';
|
|
||||||
if (depName.includes(depVersionStr)) {
|
|
||||||
const symbolRegx = new RegExp(
|
|
||||||
`(.*)${depVersionStr}([0-9\\.\\-\\+a-zA-Z]*)`,
|
|
||||||
);
|
|
||||||
const [, _depName, _depVersion] = depName.match(symbolRegx) || [];
|
|
||||||
if (_depVersion && _depName) {
|
|
||||||
depName = _depName;
|
|
||||||
depVersion = _depVersion;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const isNodeDependence = dependency.type === DependenceTypes.nodejs;
|
|
||||||
const isLinuxDependence = dependency.type === DependenceTypes.linux;
|
|
||||||
const isPythonDependence =
|
|
||||||
dependency.type === DependenceTypes.python3;
|
|
||||||
const depInfo = (
|
|
||||||
await promiseExecSuccess(
|
|
||||||
isNodeDependence
|
|
||||||
? `${getCommandPrefix} | grep "${depName}" | head -1`
|
|
||||||
: `${getCommandPrefix} ${depName}`,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.replace(/\s{2,}/, ' ')
|
|
||||||
.replace(/\s+$/, '');
|
|
||||||
|
|
||||||
if (
|
|
||||||
depInfo &&
|
|
||||||
((isNodeDependence && depInfo.split(' ')?.[0] === depName) ||
|
|
||||||
(isLinuxDependence &&
|
|
||||||
depInfo.toLocaleLowerCase().includes('installed')) ||
|
|
||||||
isPythonDependence) &&
|
|
||||||
(!depVersion || depInfo.includes(depVersion))
|
|
||||||
) {
|
|
||||||
const endTime = dayjs();
|
|
||||||
const _message = `检测到已经安装 ${depName}\n\n${depInfo}\n\n跳过安装\n\n依赖${actionText}成功,结束时间 ${endTime.format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
)},耗时 ${endTime.diff(startTime, 'second')} 秒`;
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: socketMessageType,
|
|
||||||
message: _message,
|
|
||||||
references: depIds,
|
|
||||||
});
|
|
||||||
this.updateLog(depIds, _message);
|
|
||||||
await DependenceModel.update(
|
|
||||||
{ status: DependenceStatus.installed },
|
|
||||||
{ where: { id: depIds } },
|
|
||||||
);
|
|
||||||
return resolve(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const cp = spawn(`${depRunCommand} ${dependency.name.trim()}`, {
|
|
||||||
shell: '/bin/bash',
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.stdout.on('data', async (data) => {
|
cp.stdout.on('data', async (data) => {
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
@@ -252,7 +182,7 @@ export default class DependenceService {
|
|||||||
message: data.toString(),
|
message: data.toString(),
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
this.updateLog(depIds, data.toString());
|
await this.updateLog(depIds, data.toString());
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.stderr.on('data', async (data) => {
|
cp.stderr.on('data', async (data) => {
|
||||||
@@ -261,7 +191,7 @@ export default class DependenceService {
|
|||||||
message: data.toString(),
|
message: data.toString(),
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
this.updateLog(depIds, data.toString());
|
await this.updateLog(depIds, data.toString());
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.on('error', async (err) => {
|
cp.on('error', async (err) => {
|
||||||
@@ -270,10 +200,11 @@ export default class DependenceService {
|
|||||||
message: JSON.stringify(err),
|
message: JSON.stringify(err),
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
this.updateLog(depIds, JSON.stringify(err));
|
await this.updateLog(depIds, JSON.stringify(err));
|
||||||
|
resolve(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.on('exit', async (code) => {
|
cp.on('close', async (code) => {
|
||||||
const endTime = dayjs();
|
const endTime = dayjs();
|
||||||
const isSucceed = code === 0;
|
const isSucceed = code === 0;
|
||||||
const resultText = isSucceed ? '成功' : '失败';
|
const resultText = isSucceed ? '成功' : '失败';
|
||||||
@@ -286,7 +217,7 @@ export default class DependenceService {
|
|||||||
message,
|
message,
|
||||||
references: depIds,
|
references: depIds,
|
||||||
});
|
});
|
||||||
this.updateLog(depIds, message);
|
await this.updateLog(depIds, message);
|
||||||
|
|
||||||
let status = null;
|
let status = null;
|
||||||
if (isSucceed) {
|
if (isSucceed) {
|
||||||
@@ -308,6 +239,5 @@ export default class DependenceService {
|
|||||||
resolve(null);
|
resolve(null);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+36
-68
@@ -1,18 +1,11 @@
|
|||||||
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,
|
import { Op } from 'sequelize';
|
||||||
EnvStatus,
|
|
||||||
initPosition,
|
|
||||||
maxPosition,
|
|
||||||
minPosition,
|
|
||||||
stepPosition,
|
|
||||||
} from '../data/env';
|
|
||||||
import groupBy from 'lodash/groupBy';
|
|
||||||
import { FindOptions, Op } from 'sequelize';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class EnvService {
|
export default class EnvService {
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,9 +37,7 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: Env): Promise<Env> {
|
public async update(payload: Env): Promise<Env> {
|
||||||
const doc = await this.getDb({ id: payload.id });
|
const newDoc = await this.updateDb(payload);
|
||||||
const tab = new Env({ ...doc, ...payload });
|
|
||||||
const newDoc = await this.updateDb(tab);
|
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
@@ -81,47 +67,28 @@ 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, envs[toIndex].position!);
|
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async checkPosition(position: number, edge: number = 0) {
|
public async envs(
|
||||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
searchText: string = '',
|
||||||
if (
|
sort: any = { position: -1 },
|
||||||
precisionPosition < minPosition ||
|
query: any = {},
|
||||||
precisionPosition > maxPosition ||
|
): Promise<Env[]> {
|
||||||
Math.abs(precisionPosition - edge) < minPosition
|
|
||||||
) {
|
|
||||||
const envs = await this.envs();
|
|
||||||
let position = initPosition;
|
|
||||||
for (const env of envs) {
|
|
||||||
position = position - stepPosition;
|
|
||||||
await this.updateDb({ id: env.id, position });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getPrecisionPosition(position: number): number {
|
|
||||||
return parseFloat(position.toPrecision(16));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const encodeText = encodeURI(searchText);
|
const encodeText = encodeURIComponent(searchText);
|
||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
@@ -145,10 +112,7 @@ export default class EnvService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.find(condition, [
|
const result = await this.find(condition, [['position', 'DESC']]);
|
||||||
['position', 'DESC'],
|
|
||||||
['createdAt', 'ASC'],
|
|
||||||
]);
|
|
||||||
return result as any;
|
return result as any;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
@@ -163,7 +127,7 @@ export default class EnvService {
|
|||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: FindOptions<Env>['where']): Promise<Env> {
|
public async getDb(query: any): Promise<Env> {
|
||||||
const doc: any = await EnvModel.findOne({ where: { ...query } });
|
const doc: any = await EnvModel.findOne({ where: { ...query } });
|
||||||
return doc && (doc.get({ plain: true }) as Env);
|
return doc && (doc.get({ plain: true }) as Env);
|
||||||
}
|
}
|
||||||
@@ -187,24 +151,28 @@ 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(/'/g, "'\\''")
|
.replace(/(\\)[^\n]/g, '\\\\')
|
||||||
|
.replace(/(\\$)/, '\\\\')
|
||||||
|
.replace(/"/g, '\\"')
|
||||||
.trim();
|
.trim();
|
||||||
env_string += `export ${key}='${value}'\n`;
|
env_string += `export ${key}="${value}"\n`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+57
-401
@@ -1,12 +1,11 @@
|
|||||||
import crypto from 'crypto';
|
|
||||||
import got from 'got';
|
|
||||||
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
|
||||||
import nodemailer from 'nodemailer';
|
|
||||||
import { Inject, Service } from 'typedi';
|
|
||||||
import winston from 'winston';
|
|
||||||
import { parseBody, parseHeaders } from '../config/util';
|
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import winston from 'winston';
|
||||||
import UserService from './user';
|
import UserService from './user';
|
||||||
|
import got from 'got';
|
||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class NotificationService {
|
export default class NotificationService {
|
||||||
@@ -18,29 +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],
|
||||||
['pushMe', this.pushMe],
|
|
||||||
['webhook', this.webhook],
|
|
||||||
['lark', this.lark],
|
|
||||||
['chronocat', this.chronocat],
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
private timeout = 10000;
|
||||||
private title = '';
|
private title = '';
|
||||||
private content = '';
|
private content = '';
|
||||||
private params!: Omit<NotificationInfo, 'type'>;
|
private params!: Omit<NotificationInfo, 'type'>;
|
||||||
private gotOption = {
|
|
||||||
timeout: 10000,
|
|
||||||
retry: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
@@ -80,11 +70,11 @@ export default class NotificationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async gotify() {
|
private async gotify() {
|
||||||
const { gotifyUrl, gotifyToken, gotifyPriority = 1 } = this.params;
|
const { gotifyUrl, gotifyToken, gotifyPriority } = this.params;
|
||||||
try {
|
|
||||||
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(
|
||||||
@@ -95,34 +85,20 @@ export default class NotificationService {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (typeof res.id === 'number') {
|
return typeof res.id === 'number';
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async goCqHttpBot() {
|
private async goCqHttpBot() {
|
||||||
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
||||||
try {
|
|
||||||
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 },
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (res.retcode === 0) {
|
return res.retcode === 0;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async serverChan() {
|
private async serverChan() {
|
||||||
@@ -130,98 +106,53 @@ export default class NotificationService {
|
|||||||
const url = serverChanKey.startsWith('SCT')
|
const url = serverChanKey.startsWith('SCT')
|
||||||
? `https://sctapi.ftqq.com/${serverChanKey}.send`
|
? `https://sctapi.ftqq.com/${serverChanKey}.send`
|
||||||
: `https://sc.ftqq.com/${serverChanKey}.send`;
|
: `https://sc.ftqq.com/${serverChanKey}.send`;
|
||||||
try {
|
|
||||||
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' },
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (res.errno === 0 || res.data.errno === 0) {
|
return res.errno === 0 || res.data.errno === 0;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async pushDeer() {
|
private async pushDeer() {
|
||||||
const { pushDeerKey, pushDeerUrl } = this.params;
|
const { pushDeerKey } = this.params;
|
||||||
const url = pushDeerUrl || `https://api2.pushdeer.com/message/push`;
|
const url = `https://api2.pushdeer.com/message/push`;
|
||||||
try {
|
|
||||||
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`,
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (
|
return (
|
||||||
res.content.result.length !== undefined &&
|
res.content.result.length !== undefined && res.content.result.length > 0
|
||||||
res.content.result.length > 0
|
);
|
||||||
) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async chat() {
|
|
||||||
const { chatUrl, chatToken } = this.params;
|
|
||||||
const url = `${chatUrl}${chatToken}`;
|
|
||||||
try {
|
|
||||||
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();
|
|
||||||
if (res.success) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async bark() {
|
private async bark() {
|
||||||
let { barkPush, barkIcon, barkSound, barkGroup, barkLevel, barkUrl } =
|
let { barkPush, barkIcon, barkSound, barkGroup } = this.params;
|
||||||
this.params;
|
if (!barkPush.startsWith('http') && !barkPush.startsWith('https')) {
|
||||||
if (!barkPush.startsWith('http')) {
|
|
||||||
barkPush = `https://api.day.app/${barkPush}`;
|
barkPush = `https://api.day.app/${barkPush}`;
|
||||||
}
|
}
|
||||||
const url = `${barkPush}/${encodeURIComponent(
|
const url = `${barkPush}/${encodeURIComponent(
|
||||||
this.title,
|
this.title,
|
||||||
)}/${encodeURIComponent(
|
)}/${encodeURIComponent(
|
||||||
this.content,
|
this.content,
|
||||||
)}?icon=${barkIcon}&sound=${barkSound}&group=${barkGroup}&level=${barkLevel}&url=${barkUrl}`;
|
)}?icon=${barkIcon}?sound=${barkSound}&group=${barkGroup}`;
|
||||||
|
|
||||||
try {
|
|
||||||
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();
|
||||||
if (res.code === 200) {
|
return res.code === 200;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async telegramBot() {
|
private async telegramBot() {
|
||||||
@@ -253,23 +184,16 @@ export default class NotificationService {
|
|||||||
https: httpsAgent,
|
https: httpsAgent,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
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,
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (res.ok) {
|
return !!res.ok;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async dingtalkBot() {
|
private async dingtalkBot() {
|
||||||
@@ -283,10 +207,10 @@ export default class NotificationService {
|
|||||||
secretParam = `×tamp=${dateNow}&sign=${result}`;
|
secretParam = `×tamp=${dateNow}&sign=${result}`;
|
||||||
}
|
}
|
||||||
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
|
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
|
||||||
try {
|
|
||||||
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: {
|
||||||
@@ -295,24 +219,16 @@ export default class NotificationService {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (res.errcode === 0) {
|
return res.errcode === 0;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async weWorkBot() {
|
private async weWorkBot() {
|
||||||
const { weWorkBotKey, weWorkOrigin = 'https://qyapi.weixin.qq.com' } =
|
const { weWorkBotKey } = this.params;
|
||||||
this.params;
|
const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${weWorkBotKey}`;
|
||||||
const url = `${weWorkOrigin}/cgi-bin/webhook/send?key=${weWorkBotKey}`;
|
|
||||||
try {
|
|
||||||
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: {
|
||||||
@@ -321,25 +237,18 @@ export default class NotificationService {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
if (res.errcode === 0) {
|
return res.errcode === 0;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async weWorkApp() {
|
private async weWorkApp() {
|
||||||
const { weWorkAppKey, weWorkOrigin = 'https://qyapi.weixin.qq.com' } =
|
const { weWorkAppKey } = this.params;
|
||||||
this.params;
|
|
||||||
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
||||||
weWorkAppKey.split(',');
|
weWorkAppKey.split(',');
|
||||||
const url = `${weWorkOrigin}/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,
|
||||||
@@ -385,12 +294,12 @@ export default class NotificationService {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(
|
.post(
|
||||||
`${weWorkOrigin}/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,
|
||||||
@@ -401,93 +310,31 @@ export default class NotificationService {
|
|||||||
)
|
)
|
||||||
.json();
|
.json();
|
||||||
|
|
||||||
if (res.errcode === 0) {
|
return res.errcode === 0;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res: any = await got
|
|
||||||
.post(url, {
|
|
||||||
...this.gotOption,
|
|
||||||
json: {
|
|
||||||
...json,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.json();
|
|
||||||
if (res.code === 0) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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()}`;
|
||||||
try {
|
|
||||||
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' },
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
|
|
||||||
if (res.ret === 0) {
|
return res.ret === 0;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async pushPlus() {
|
private async pushPlus() {
|
||||||
const { pushPlusToken, pushPlusUser } = this.params;
|
const { pushPlusToken, pushPlusUser } = this.params;
|
||||||
const url = `https://www.pushplus.plus/send`;
|
const url = `https://www.pushplus.plus/send`;
|
||||||
try {
|
|
||||||
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}`,
|
||||||
@@ -497,48 +344,11 @@ export default class NotificationService {
|
|||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
|
|
||||||
if (res.code === 200) {
|
return res.code === 200;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async lark() {
|
|
||||||
let { larkKey } = this.params;
|
|
||||||
|
|
||||||
if (!larkKey.startsWith('http')) {
|
|
||||||
larkKey = `https://open.feishu.cn/open-apis/bot/v2/hook/${larkKey}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res: any = await got
|
|
||||||
.post(larkKey, {
|
|
||||||
...this.gotOption,
|
|
||||||
json: {
|
|
||||||
msg_type: 'text',
|
|
||||||
content: { text: `${this.title}\n\n${this.content}` },
|
|
||||||
},
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
})
|
|
||||||
.json();
|
|
||||||
if (res.StatusCode === 0) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async email() {
|
private async email() {
|
||||||
const { emailPass, emailService, emailUser } = this.params;
|
const { emailPass, emailService, emailUser } = this.params;
|
||||||
|
|
||||||
try {
|
|
||||||
const transporter = nodemailer.createTransport({
|
const transporter = nodemailer.createTransport({
|
||||||
service: emailService,
|
service: emailService,
|
||||||
auth: {
|
auth: {
|
||||||
@@ -556,160 +366,6 @@ export default class NotificationService {
|
|||||||
|
|
||||||
transporter.close();
|
transporter.close();
|
||||||
|
|
||||||
if (info.messageId) {
|
return !!info.messageId;
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(info));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async pushMe() {
|
|
||||||
const { pushMeKey } = this.params;
|
|
||||||
try {
|
|
||||||
const res: any = await got.post(
|
|
||||||
`https://push.i-i.me/?push_key=${pushMeKey}`,
|
|
||||||
{
|
|
||||||
...this.gotOption,
|
|
||||||
json: {
|
|
||||||
title: this.title,
|
|
||||||
content: this.content,
|
|
||||||
},
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (res.body === 'success') {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(res.body);
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async chronocat() {
|
|
||||||
const { chronocatURL, chronocatQQ, chronocatToekn } = this.params;
|
|
||||||
try {
|
|
||||||
const user_ids = chronocatQQ
|
|
||||||
.match(/user_id=(\d+)/g)
|
|
||||||
?.map((match: any) => match.split('=')[1]);
|
|
||||||
const group_ids = chronocatQQ
|
|
||||||
.match(/group_id=(\d+)/g)
|
|
||||||
?.map((match: any) => match.split('=')[1]);
|
|
||||||
|
|
||||||
const url = `${chronocatURL}/api/message/send`;
|
|
||||||
const headers = {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${chronocatToekn}`,
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const [chat_type, ids] of [
|
|
||||||
[1, user_ids],
|
|
||||||
[2, group_ids],
|
|
||||||
]) {
|
|
||||||
if (!ids) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let _ids: any = ids;
|
|
||||||
for (const chat_id of _ids) {
|
|
||||||
const data = {
|
|
||||||
peer: {
|
|
||||||
chatType: chat_type,
|
|
||||||
peerUin: chat_id,
|
|
||||||
},
|
|
||||||
elements: [
|
|
||||||
{
|
|
||||||
elementType: 1,
|
|
||||||
textElement: {
|
|
||||||
content: `${this.title}\n\n${this.content}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
const res: any = await got.post(url, {
|
|
||||||
...this.gotOption,
|
|
||||||
json: data,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
if (res.body === 'success') {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(res.body);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
const res = await got(formatUrl, options);
|
|
||||||
if (String(res.statusCode).startsWith('20')) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(JSON.stringify(res));
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
throw new Error(error.response ? error.response.body : error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-8
@@ -75,7 +75,7 @@ export default class OpenService {
|
|||||||
): Promise<App[]> {
|
): Promise<App[]> {
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const encodeText = encodeURI(searchText);
|
const encodeText = encodeURIComponent(searchText);
|
||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
@@ -119,7 +119,7 @@ export default class OpenService {
|
|||||||
(x) => x.expiration >= timestamp,
|
(x) => x.expiration >= timestamp,
|
||||||
);
|
);
|
||||||
let tokens = invalidTokens;
|
let tokens = invalidTokens;
|
||||||
if (invalidTokens.length >= 5) {
|
if (invalidTokens.length > 5) {
|
||||||
tokens = [
|
tokens = [
|
||||||
...invalidTokens.slice(0, 4),
|
...invalidTokens.slice(0, 4),
|
||||||
{ ...invalidTokens[4], expiration },
|
{ ...invalidTokens[4], expiration },
|
||||||
@@ -145,7 +145,7 @@ export default class OpenService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async generateSystemToken(): Promise<{
|
public async findSystemToken(): Promise<{
|
||||||
value: string;
|
value: string;
|
||||||
expiration: number;
|
expiration: number;
|
||||||
}> {
|
}> {
|
||||||
@@ -158,13 +158,21 @@ export default class OpenService {
|
|||||||
scopes: ['crons', 'system'],
|
scopes: ['crons', 'system'],
|
||||||
} as App);
|
} as App);
|
||||||
}
|
}
|
||||||
const { data } = await this.authToken({
|
const nowTime = Math.round(Date.now() / 1000);
|
||||||
|
let token;
|
||||||
|
if (
|
||||||
|
!systemApp.tokens ||
|
||||||
|
!systemApp.tokens.length ||
|
||||||
|
nowTime > [...systemApp.tokens].pop()!.expiration
|
||||||
|
) {
|
||||||
|
const authToken = await this.authToken({
|
||||||
client_id: systemApp.client_id,
|
client_id: systemApp.client_id,
|
||||||
client_secret: systemApp.client_secret,
|
client_secret: systemApp.client_secret,
|
||||||
});
|
});
|
||||||
return {
|
token = authToken.data;
|
||||||
...data,
|
} else {
|
||||||
value: data.token,
|
token = [...systemApp.tokens].pop();
|
||||||
};
|
}
|
||||||
|
return token;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-57
@@ -1,18 +1,16 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import nodeSchedule from 'node-schedule';
|
import nodeSchedule from 'node-schedule';
|
||||||
import { ChildProcessWithoutNullStreams } from 'child_process';
|
import { ChildProcessWithoutNullStreams, exec, spawn } from 'child_process';
|
||||||
import {
|
import {
|
||||||
ToadScheduler,
|
ToadScheduler,
|
||||||
LongIntervalJob,
|
LongIntervalJob,
|
||||||
|
AsyncTask,
|
||||||
SimpleIntervalSchedule,
|
SimpleIntervalSchedule,
|
||||||
Task,
|
|
||||||
} from 'toad-scheduler';
|
} from 'toad-scheduler';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import taskLimit from '../shared/pLimit';
|
|
||||||
import { spawn } from 'cross-spawn';
|
|
||||||
|
|
||||||
export interface ScheduleTaskType {
|
interface ScheduleTaskType {
|
||||||
id: number;
|
id: number;
|
||||||
command: string;
|
command: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -42,39 +40,28 @@ export default class ScheduleService {
|
|||||||
|
|
||||||
private maxBuffer = 200 * 1024 * 1024;
|
private maxBuffer = 200 * 1024 * 1024;
|
||||||
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
async runTask(
|
async runTask(command: string, callbacks: TaskCallbacks = {}) {
|
||||||
command: string,
|
|
||||||
callbacks: TaskCallbacks = {},
|
|
||||||
params: {
|
|
||||||
schedule?: string;
|
|
||||||
name?: string;
|
|
||||||
command?: string;
|
|
||||||
},
|
|
||||||
completionTime: 'start' | 'end' = 'end',
|
|
||||||
) {
|
|
||||||
return taskLimit.runWithCronLimit(() => {
|
|
||||||
return new Promise(async (resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
this.logger.info(`[panel][开始执行任务] 参数 ${JSON.stringify({ ...params, command })}`);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const startTime = dayjs();
|
const startTime = dayjs();
|
||||||
await callbacks.onBefore?.(startTime);
|
await callbacks.onBefore?.(startTime);
|
||||||
|
|
||||||
const cp = spawn(command, { shell: '/bin/bash' });
|
const cp = spawn(command, { shell: '/bin/bash' });
|
||||||
|
|
||||||
|
// TODO:
|
||||||
callbacks.onStart?.(cp, startTime);
|
callbacks.onStart?.(cp, startTime);
|
||||||
completionTime === 'start' && resolve(cp.pid);
|
|
||||||
|
|
||||||
cp.stdout.on('data', async (data) => {
|
cp.stdout.on('data', async (data) => {
|
||||||
await callbacks.onLog?.(data.toString());
|
await callbacks.onLog?.(data.toString());
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.stderr.on('data', async (data) => {
|
cp.stderr.on('data', async (data) => {
|
||||||
this.logger.info(
|
this.logger.error(
|
||||||
'[panel][执行任务失败] 命令: %s, 错误信息: %j',
|
'执行任务 %s 失败,时间:%s, 错误信息:%j',
|
||||||
command,
|
command,
|
||||||
|
new Date().toLocaleString(),
|
||||||
data.toString(),
|
data.toString(),
|
||||||
);
|
);
|
||||||
await callbacks.onError?.(data.toString());
|
await callbacks.onError?.(data.toString());
|
||||||
@@ -82,32 +69,41 @@ export default class ScheduleService {
|
|||||||
|
|
||||||
cp.on('error', async (err) => {
|
cp.on('error', async (err) => {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
'[panel][创建任务失败] 命令: %s, 错误信息: %j',
|
'创建任务 %s 失败,时间:%s, 错误信息:%j',
|
||||||
command,
|
command,
|
||||||
|
new Date().toLocaleString(),
|
||||||
err,
|
err,
|
||||||
);
|
);
|
||||||
await callbacks.onError?.(JSON.stringify(err));
|
await callbacks.onError?.(JSON.stringify(err));
|
||||||
});
|
});
|
||||||
|
|
||||||
cp.on('exit', async (code) => {
|
cp.on('exit', async (code, signal) => {
|
||||||
|
this.logger.info(
|
||||||
|
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
||||||
endTime.diff(startTime, 'seconds'),
|
endTime.diff(startTime, 'seconds'),
|
||||||
);
|
);
|
||||||
resolve({ ...params, pid: cp.pid, code });
|
resolve(null);
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(
|
await this.logger.error(
|
||||||
'[panel][执行任务失败] 命令: %s, 错误信息: %j',
|
'执行任务%s失败,时间:%s, 错误信息:%j',
|
||||||
command,
|
command,
|
||||||
|
new Date().toLocaleString(),
|
||||||
error,
|
error,
|
||||||
);
|
);
|
||||||
await callbacks.onError?.(JSON.stringify(error));
|
await callbacks.onError?.(JSON.stringify(error));
|
||||||
|
resolve(null);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async createCronTask(
|
async createCronTask(
|
||||||
@@ -117,7 +113,7 @@ export default class ScheduleService {
|
|||||||
) {
|
) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'[panel][创建cron任务], 任务ID: %s, cron: %s, 任务名: %s, 执行命令: %s',
|
'[创建cron任务],任务ID: %s,cron: %s,任务名: %s,执行命令: %s',
|
||||||
_id,
|
_id,
|
||||||
schedule,
|
schedule,
|
||||||
name,
|
name,
|
||||||
@@ -127,30 +123,19 @@ export default class ScheduleService {
|
|||||||
this.scheduleStacks.set(
|
this.scheduleStacks.set(
|
||||||
_id,
|
_id,
|
||||||
nodeSchedule.scheduleJob(_id, schedule, async () => {
|
nodeSchedule.scheduleJob(_id, schedule, async () => {
|
||||||
this.runTask(command, callbacks, {
|
await this.runTask(command, callbacks);
|
||||||
name,
|
|
||||||
schedule,
|
|
||||||
command,
|
|
||||||
});
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (runImmediately) {
|
if (runImmediately) {
|
||||||
this.runTask(command, callbacks, {
|
await this.runTask(command, callbacks);
|
||||||
name,
|
|
||||||
schedule,
|
|
||||||
command,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
|
async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info('[panel][取消定时任务], 任务名: %s', name);
|
this.logger.info('[取消定时任务],任务名:%s', name);
|
||||||
if (this.scheduleStacks.has(_id)) {
|
this.scheduleStacks.has(_id) && this.scheduleStacks.get(_id)?.cancel();
|
||||||
this.scheduleStacks.get(_id)?.cancel();
|
|
||||||
this.scheduleStacks.delete(_id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async createIntervalTask(
|
async createIntervalTask(
|
||||||
@@ -161,30 +146,30 @@ export default class ScheduleService {
|
|||||||
) {
|
) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'[panel][创建interval任务], 任务ID: %s, 任务名: %s, 执行命令: %s',
|
'[创建interval任务],任务ID: %s,任务名: %s,执行命令: %s',
|
||||||
_id,
|
_id,
|
||||||
name,
|
name,
|
||||||
command,
|
command,
|
||||||
);
|
);
|
||||||
const task = new Task(
|
const task = new AsyncTask(
|
||||||
name,
|
name,
|
||||||
() => {
|
async () => {
|
||||||
this.runTask(command, callbacks, {
|
return new Promise(async (resolve, reject) => {
|
||||||
name,
|
await this.runTask(command, callbacks);
|
||||||
command,
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
(err) => {
|
(err) => {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
'[执行任务失败] 命令: %s, 错误信息: %j',
|
'执行任务%s失败,时间:%s, 错误信息:%j',
|
||||||
command,
|
command,
|
||||||
|
new Date().toLocaleString(),
|
||||||
err,
|
err,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const job = new LongIntervalJob(
|
const job = new LongIntervalJob(
|
||||||
{ runImmediately: false, ...schedule },
|
{ ...schedule, runImmediately: false },
|
||||||
task,
|
task,
|
||||||
_id,
|
_id,
|
||||||
);
|
);
|
||||||
@@ -192,16 +177,13 @@ export default class ScheduleService {
|
|||||||
this.intervalSchedule.addIntervalJob(job);
|
this.intervalSchedule.addIntervalJob(job);
|
||||||
|
|
||||||
if (runImmediately) {
|
if (runImmediately) {
|
||||||
this.runTask(command, callbacks, {
|
await this.runTask(command, callbacks);
|
||||||
name,
|
|
||||||
command,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancelIntervalTask({ id = 0, name }: ScheduleTaskType) {
|
async cancelIntervalTask({ id = 0, name }: ScheduleTaskType) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info('[取消interval任务], 任务ID: %s, 任务名: %s', _id, name);
|
this.logger.info('[取消interval任务],任务ID: %s,任务名:%s', _id, name);
|
||||||
this.intervalSchedule.removeById(_id);
|
this.intervalSchedule.removeById(_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+15
-19
@@ -6,8 +6,6 @@ import SockService from './sock';
|
|||||||
import CronService from './cron';
|
import CronService from './cron';
|
||||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { TASK_COMMAND } from '../config/const';
|
|
||||||
import { getPid, killTask } from '../config/util';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class ScriptService {
|
export default class ScriptService {
|
||||||
@@ -16,14 +14,14 @@ export default class ScriptService {
|
|||||||
private sockService: SockService,
|
private sockService: SockService,
|
||||||
private cronService: CronService,
|
private cronService: CronService,
|
||||||
private scheduleService: ScheduleService,
|
private scheduleService: ScheduleService,
|
||||||
) { }
|
) {}
|
||||||
|
|
||||||
private taskCallbacks(filePath: string): TaskCallbacks {
|
private taskCallbacks(filePath: string): TaskCallbacks {
|
||||||
return {
|
return {
|
||||||
onEnd: async (cp, endTime, diff) => {
|
onEnd: async (cp, endTime, diff) => {
|
||||||
try {
|
try {
|
||||||
fs.unlinkSync(filePath);
|
fs.unlinkSync(filePath);
|
||||||
} catch (error) { }
|
} catch (error) {}
|
||||||
},
|
},
|
||||||
onError: async (message: string) => {
|
onError: async (message: string) => {
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
@@ -42,25 +40,23 @@ export default class ScriptService {
|
|||||||
|
|
||||||
public async runScript(filePath: string) {
|
public async runScript(filePath: string) {
|
||||||
const relativePath = path.relative(config.scriptPath, filePath);
|
const relativePath = path.relative(config.scriptPath, filePath);
|
||||||
const command = `${TASK_COMMAND} -l ${relativePath} now`;
|
const command = `task -l ${relativePath} now`;
|
||||||
const pid = await this.scheduleService.runTask(
|
this.scheduleService.runTask(command, this.taskCallbacks(filePath));
|
||||||
command,
|
|
||||||
this.taskCallbacks(filePath),
|
|
||||||
{ command },
|
|
||||||
'start',
|
|
||||||
);
|
|
||||||
|
|
||||||
return { code: 200, data: pid };
|
return { code: 200 };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stopScript(filePath: string, pid: number) {
|
public async stopScript(filePath: string) {
|
||||||
if (!pid) {
|
|
||||||
const relativePath = path.relative(config.scriptPath, filePath);
|
const relativePath = path.relative(config.scriptPath, filePath);
|
||||||
pid = await getPid(`${TASK_COMMAND} -l ${relativePath} now`) as number;
|
const err = await this.cronService.killTask(`task -l ${relativePath} now`);
|
||||||
}
|
|
||||||
try {
|
const str = err ? `\n${err}` : '';
|
||||||
await killTask(pid);
|
this.sockService.sendMessage({
|
||||||
} catch (error) { }
|
type: 'manuallyRunScript',
|
||||||
|
message: `${str}\n## 执行结束... ${new Date()
|
||||||
|
.toLocaleString('zh', { hour12: false })
|
||||||
|
.replace(' 24:', ' 00:')} `,
|
||||||
|
});
|
||||||
|
|
||||||
return { code: 200 };
|
return { code: 200 };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { SockMessage } from '../data/sock';
|
|||||||
export default class SockService {
|
export default class SockService {
|
||||||
private clients: Connection[] = [];
|
private clients: Connection[] = [];
|
||||||
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
public getClients() {
|
public getClients() {
|
||||||
return this.clients;
|
return this.clients;
|
||||||
|
|||||||
+39
-71
@@ -1,42 +1,20 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import fs, { existsSync } from 'fs';
|
import fs from 'fs';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { Subscription } from '../data/subscription';
|
|
||||||
import { formatUrl } from '../config/subscription';
|
|
||||||
import config from '../config';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class SshKeyService {
|
export default class SshKeyService {
|
||||||
private homedir = os.homedir();
|
private homedir = os.homedir();
|
||||||
private sshPath = config.sshdPath;
|
private sshPath = path.resolve(this.homedir, '.ssh');
|
||||||
private sshConfigFilePath = path.resolve(this.homedir, '.ssh', 'config');
|
private sshConfigFilePath = path.resolve(this.sshPath, 'config');
|
||||||
private sshConfigHeader = `Include ${path.join(this.sshPath, '*.config')}`;
|
|
||||||
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
this.initSshConfigFile();
|
|
||||||
}
|
|
||||||
|
|
||||||
private initSshConfigFile() {
|
|
||||||
let config = '';
|
|
||||||
if (existsSync(this.sshConfigFilePath)) {
|
|
||||||
config = fs.readFileSync(this.sshConfigFilePath, { encoding: 'utf-8' });
|
|
||||||
} else {
|
|
||||||
fs.writeFileSync(this.sshConfigFilePath, '');
|
|
||||||
}
|
|
||||||
if (!config.includes(this.sshConfigHeader)) {
|
|
||||||
fs.writeFileSync(
|
|
||||||
this.sshConfigFilePath,
|
|
||||||
`${this.sshConfigHeader}\n\n${config}`,
|
|
||||||
{ encoding: 'utf-8' },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private generatePrivateKeyFile(alias: string, key: string): void {
|
private generatePrivateKeyFile(alias: string, key: string): void {
|
||||||
try {
|
try {
|
||||||
fs.writeFileSync(path.join(this.sshPath, alias), `${key}${os.EOL}`, {
|
fs.writeFileSync(`${this.sshPath}/${alias}`, key, {
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
mode: '400',
|
mode: '400',
|
||||||
});
|
});
|
||||||
@@ -45,72 +23,62 @@ 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 {
|
||||||
const filePath = path.join(this.sshPath, alias);
|
fs.unlinkSync(`${this.sshPath}/${alias}`);
|
||||||
if (existsSync(filePath)) {
|
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('删除私钥文件失败', error);
|
this.logger.error('删除私钥文件失败', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateSingleSshConfig(alias: string, host: string, proxy?: string) {
|
private generateSingleSshConfig(alias: string, host: string): string {
|
||||||
if (host === 'github.com') {
|
return `\nHost ${alias}\n Hostname ${host}\n IdentityFile ${this.sshPath}/${alias}\n StrictHostKeyChecking no`;
|
||||||
host = `ssh.github.com\n Port 443\n HostkeyAlgorithms +ssh-rsa`;
|
|
||||||
}
|
}
|
||||||
const proxyStr = proxy
|
|
||||||
? ` ProxyCommand nc -v -x ${proxy} %h %p 2>/dev/null\n`
|
private generateSshConfig(configs: string[]) {
|
||||||
: '';
|
try {
|
||||||
const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${path.join(
|
for (const config of configs) {
|
||||||
this.sshPath,
|
fs.appendFileSync(this.sshConfigFilePath, config, {
|
||||||
alias,
|
|
||||||
)}\n StrictHostKeyChecking no\n${proxyStr}`;
|
|
||||||
fs.writeFileSync(`${path.join(this.sshPath, `${alias}.config`)}`, config, {
|
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('写入ssh配置文件失败', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private removeSshConfig(alias: string) {
|
private removeSshConfig(alias: string) {
|
||||||
try {
|
try {
|
||||||
const filePath = path.join(this.sshPath, `${alias}.config`);
|
const configRegx = this.getConfigRegx(alias);
|
||||||
if (existsSync(filePath)) {
|
const data = fs
|
||||||
fs.unlinkSync(filePath);
|
.readFileSync(this.sshConfigFilePath, { encoding: 'utf8' })
|
||||||
}
|
.replace(configRegx, '')
|
||||||
|
.replace(/\n[\n]+/g, '\n');
|
||||||
|
fs.writeFileSync(this.sshConfigFilePath, data, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`删除ssh配置文件${alias}失败`, error);
|
this.logger.error(`删除ssh配置文件${alias}失败`, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public addSSHKey(
|
public addSSHKey(key: string, alias: string, host: string): void {
|
||||||
key: string,
|
|
||||||
alias: string,
|
|
||||||
host: string,
|
|
||||||
proxy?: string,
|
|
||||||
): void {
|
|
||||||
this.generatePrivateKeyFile(alias, key);
|
this.generatePrivateKeyFile(alias, key);
|
||||||
this.generateSingleSshConfig(alias, host, proxy);
|
const config = this.generateSingleSshConfig(alias, host);
|
||||||
|
this.removeSshConfig(alias);
|
||||||
|
this.generateSshConfig([config]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public removeSSHKey(alias: string, host: string, proxy?: string): void {
|
public removeSSHKey(alias: string, host: string): void {
|
||||||
this.removePrivateKeyFile(alias);
|
this.removePrivateKeyFile(alias);
|
||||||
this.removeSshConfig(alias);
|
const config = this.generateSingleSshConfig(alias, host);
|
||||||
}
|
this.removeSshConfig(config);
|
||||||
|
|
||||||
public setSshConfig(docs: Subscription[]) {
|
|
||||||
for (const doc of docs) {
|
|
||||||
if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
|
|
||||||
const { alias, proxy } = doc;
|
|
||||||
const { host } = formatUrl(doc);
|
|
||||||
this.removePrivateKeyFile(alias);
|
|
||||||
this.removeSshConfig(alias);
|
|
||||||
this.generatePrivateKeyFile(
|
|
||||||
alias,
|
|
||||||
(doc.pull_option as any).private_key,
|
|
||||||
);
|
|
||||||
this.generateSingleSshConfig(alias, host, proxy);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+175
-70
@@ -6,30 +6,29 @@ import {
|
|||||||
SubscriptionModel,
|
SubscriptionModel,
|
||||||
SubscriptionStatus,
|
SubscriptionStatus,
|
||||||
} from '../data/subscription';
|
} from '../data/subscription';
|
||||||
import { ChildProcessWithoutNullStreams } from 'child_process';
|
import {
|
||||||
|
ChildProcessWithoutNullStreams,
|
||||||
|
exec,
|
||||||
|
execSync,
|
||||||
|
spawn,
|
||||||
|
} from 'child_process';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
import cron_parser from 'cron-parser';
|
||||||
import {
|
import {
|
||||||
getFileContentByName,
|
getFileContentByName,
|
||||||
concurrentRun,
|
concurrentRun,
|
||||||
fileExist,
|
fileExist,
|
||||||
createFile,
|
createFile,
|
||||||
killTask,
|
|
||||||
handleLogPath,
|
|
||||||
promiseExec,
|
|
||||||
emptyDir,
|
|
||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import { promises, existsSync } from 'fs';
|
import { promises, existsSync } from 'fs';
|
||||||
import { FindOptions, Op } from 'sequelize';
|
import { promisify } from 'util';
|
||||||
import path, { join } from 'path';
|
import { Op } from 'sequelize';
|
||||||
|
import path from 'path';
|
||||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
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 dayjs from 'dayjs';
|
||||||
import { LOG_END_SYMBOL } from '../config/const';
|
|
||||||
import { formatCommand, formatUrl } from '../config/subscription';
|
|
||||||
import { CrontabModel } from '../data/cron';
|
|
||||||
import CrontabService from './cron';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class SubscriptionService {
|
export default class SubscriptionService {
|
||||||
@@ -38,16 +37,32 @@ export default class SubscriptionService {
|
|||||||
private scheduleService: ScheduleService,
|
private scheduleService: ScheduleService,
|
||||||
private sockService: SockService,
|
private sockService: SockService,
|
||||||
private sshKeyService: SshKeyService,
|
private sshKeyService: SshKeyService,
|
||||||
private crontabService: CrontabService,
|
) {}
|
||||||
) { }
|
|
||||||
|
|
||||||
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}%` },
|
||||||
{ [Op.like]: `%${encodeURI(searchText)}%` },
|
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
query = {
|
query = {
|
||||||
@@ -56,33 +71,80 @@ 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;
|
return result as any;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private formatCommand(doc: Subscription, url?: string) {
|
||||||
|
let command = 'ql ';
|
||||||
|
let _url = url || this.formatUrl(doc).url;
|
||||||
|
const { type, whitelist, blacklist, dependences, branch, extensions } = doc;
|
||||||
|
if (type === 'file') {
|
||||||
|
command += `raw "${_url}"`;
|
||||||
|
} else {
|
||||||
|
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${
|
||||||
|
dependences || ''
|
||||||
|
}" "${branch || ''}" "${extensions || ''}"`;
|
||||||
|
}
|
||||||
|
return command;
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatUrl(doc: Subscription) {
|
||||||
|
let url = doc.url;
|
||||||
|
let host = '';
|
||||||
|
if (doc.type === 'private-repo') {
|
||||||
|
if (doc.pull_type === 'ssh-key') {
|
||||||
|
host = doc.url!.replace(/.*\@([^\:]+)\:.*/, '$1');
|
||||||
|
url = doc.url!.replace(host, doc.alias);
|
||||||
|
} else {
|
||||||
|
host = doc.url!.replace(/.*\:\/\/([^\/]+)\/.*/, '$1');
|
||||||
|
const { username, password } = doc.pull_option as any;
|
||||||
|
url = doc.url!.replace(host, `${username}:${password}@${host}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { url, host };
|
||||||
|
}
|
||||||
|
|
||||||
public async handleTask(
|
public async handleTask(
|
||||||
doc: Subscription,
|
doc: Subscription,
|
||||||
needCreate = true,
|
needCreate = true,
|
||||||
|
needAddKey = true,
|
||||||
runImmediately = false,
|
runImmediately = false,
|
||||||
) {
|
) {
|
||||||
const { url } = formatUrl(doc);
|
const { url, host } = this.formatUrl(doc);
|
||||||
|
if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
|
||||||
|
if (needAddKey) {
|
||||||
|
this.sshKeyService.addSSHKey(
|
||||||
|
(doc.pull_option as any).private_key,
|
||||||
|
doc.alias,
|
||||||
|
host,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.sshKeyService.removeSSHKey(doc.alias, host);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
doc.command = formatCommand(doc, url as string);
|
doc.command = this.formatCommand(doc, url as string);
|
||||||
|
|
||||||
if (doc.schedule_type === 'crontab') {
|
if (doc.schedule_type === 'crontab') {
|
||||||
this.scheduleService.cancelCronTask(doc as any);
|
this.scheduleService.cancelCronTask(doc as any);
|
||||||
@@ -105,9 +167,28 @@ export default class SubscriptionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async setSshConfig() {
|
private async promiseExec(command: string): Promise<string> {
|
||||||
const docs = await SubscriptionModel.findAll();
|
return new Promise((resolve, reject) => {
|
||||||
this.sshKeyService.setSshConfig(docs);
|
exec(
|
||||||
|
command,
|
||||||
|
{ maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' },
|
||||||
|
(err, stdout, stderr) => {
|
||||||
|
resolve(stdout || stderr || JSON.stringify(err));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleLogPath(
|
||||||
|
logPath: string,
|
||||||
|
data: string = '',
|
||||||
|
): Promise<string> {
|
||||||
|
const absolutePath = path.resolve(config.logPath, logPath);
|
||||||
|
const logFileExist = await fileExist(absolutePath);
|
||||||
|
if (!logFileExist) {
|
||||||
|
await createFile(absolutePath, data);
|
||||||
|
}
|
||||||
|
return absolutePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
private taskCallbacks(doc: Subscription): TaskCallbacks {
|
private taskCallbacks(doc: Subscription): TaskCallbacks {
|
||||||
@@ -122,7 +203,7 @@ export default class SubscriptionService {
|
|||||||
},
|
},
|
||||||
{ where: { id: doc.id } },
|
{ where: { id: doc.id } },
|
||||||
);
|
);
|
||||||
const absolutePath = await handleLogPath(
|
const absolutePath = await this.handleLogPath(
|
||||||
logPath as string,
|
logPath as string,
|
||||||
`## 开始执行... ${startTime.format('YYYY-MM-DD HH:mm:ss')}\n`,
|
`## 开始执行... ${startTime.format('YYYY-MM-DD HH:mm:ss')}\n`,
|
||||||
);
|
);
|
||||||
@@ -132,7 +213,7 @@ export default class SubscriptionService {
|
|||||||
try {
|
try {
|
||||||
if (doc.sub_before) {
|
if (doc.sub_before) {
|
||||||
fs.appendFileSync(absolutePath, `\n## 执行before命令...\n\n`);
|
fs.appendFileSync(absolutePath, `\n## 执行before命令...\n\n`);
|
||||||
beforeStr = await promiseExec(doc.sub_before);
|
beforeStr = await this.promiseExec(doc.sub_before);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
beforeStr =
|
beforeStr =
|
||||||
@@ -152,14 +233,14 @@ export default class SubscriptionService {
|
|||||||
},
|
},
|
||||||
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 handleLogPath(sub.log_path as string);
|
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||||
|
|
||||||
// 执行 sub_after
|
// 执行 sub_after
|
||||||
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\n`);
|
||||||
afterStr = await promiseExec(sub.sub_after);
|
afterStr = await this.promiseExec(sub.sub_after);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
afterStr =
|
afterStr =
|
||||||
@@ -173,7 +254,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(
|
||||||
@@ -189,12 +270,12 @@ export default class SubscriptionService {
|
|||||||
},
|
},
|
||||||
onError: async (message: string) => {
|
onError: async (message: string) => {
|
||||||
const sub = await this.getDb({ id: doc.id });
|
const sub = await this.getDb({ id: doc.id });
|
||||||
const absolutePath = await handleLogPath(sub.log_path as string);
|
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
fs.appendFileSync(absolutePath, `\n${message}`);
|
||||||
},
|
},
|
||||||
onLog: async (message: string) => {
|
onLog: async (message: string) => {
|
||||||
const sub = await this.getDb({ id: doc.id });
|
const sub = await this.getDb({ id: doc.id });
|
||||||
const absolutePath = await handleLogPath(sub.log_path as string);
|
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
fs.appendFileSync(absolutePath, `\n${message}`);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -204,7 +285,6 @@ export default class SubscriptionService {
|
|||||||
const tab = new Subscription(payload);
|
const tab = new Subscription(payload);
|
||||||
const doc = await this.insert(tab);
|
const doc = await this.insert(tab);
|
||||||
await this.handleTask(doc);
|
await this.handleTask(doc);
|
||||||
await this.setSshConfig();
|
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,11 +293,8 @@ export default class SubscriptionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: Subscription): Promise<Subscription> {
|
public async update(payload: Subscription): Promise<Subscription> {
|
||||||
const doc = await this.getDb({ id: payload.id });
|
const newDoc = await this.updateDb(payload);
|
||||||
const tab = new Subscription({ ...doc, ...payload });
|
|
||||||
const newDoc = await this.updateDb(tab);
|
|
||||||
await this.handleTask(newDoc, !newDoc.is_disabled);
|
await this.handleTask(newDoc, !newDoc.is_disabled);
|
||||||
await this.setSshConfig();
|
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,29 +334,15 @@ export default class SubscriptionService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[], query: any) {
|
public async remove(ids: number[]) {
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
await this.handleTask(doc, false);
|
await this.handleTask(doc, false, false);
|
||||||
}
|
}
|
||||||
await SubscriptionModel.destroy({ where: { id: ids } });
|
await SubscriptionModel.destroy({ where: { id: ids } });
|
||||||
await this.setSshConfig();
|
|
||||||
|
|
||||||
if (query?.force === true) {
|
|
||||||
const crons = await CrontabModel.findAll({ where: { sub_id: ids } });
|
|
||||||
if (crons?.length) {
|
|
||||||
await this.crontabService.remove(crons.map(x => x.id!))
|
|
||||||
}
|
|
||||||
for (const doc of docs) {
|
|
||||||
const filePath = join(config.scriptPath, doc.alias);
|
|
||||||
emptyDir(filePath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(
|
public async getDb(query: any): Promise<Subscription> {
|
||||||
query: FindOptions<Subscription>['where'],
|
|
||||||
): Promise<Subscription> {
|
|
||||||
const doc: any = await SubscriptionModel.findOne({ where: { ...query } });
|
const doc: any = await SubscriptionModel.findOne({ where: { ...query } });
|
||||||
return doc && (doc.get({ plain: true }) as Subscription);
|
return doc && (doc.get({ plain: true }) as Subscription);
|
||||||
}
|
}
|
||||||
@@ -289,9 +352,10 @@ export default class SubscriptionService {
|
|||||||
{ status: SubscriptionStatus.queued },
|
{ status: SubscriptionStatus.queued },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
);
|
);
|
||||||
ids.forEach((id) => {
|
concurrentRun(
|
||||||
this.runSingle(id);
|
ids.map((id) => async () => await this.runSingle(id)),
|
||||||
});
|
10,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop(ids: number[]) {
|
public async stop(ids: number[]) {
|
||||||
@@ -299,11 +363,20 @@ export default class SubscriptionService {
|
|||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
if (doc.pid) {
|
if (doc.pid) {
|
||||||
try {
|
try {
|
||||||
await killTask(doc.pid);
|
process.kill(-doc.pid);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(error);
|
this.logger.silly(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const command = this.formatCommand(doc);
|
||||||
|
const err = await this.killTask(command);
|
||||||
|
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
||||||
|
const str = err ? `\n${err}` : '';
|
||||||
|
|
||||||
|
fs.appendFileSync(
|
||||||
|
`${absolutePath}`,
|
||||||
|
`${str}\n## 执行结束... ${dayjs().format('YYYY-MM-DD HH:mm:ss')} `,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await SubscriptionModel.update(
|
await SubscriptionModel.update(
|
||||||
@@ -312,37 +385,69 @@ export default class SubscriptionService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async killTask(name: string) {
|
||||||
|
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
||||||
|
const execAsync = promisify(exec);
|
||||||
|
try {
|
||||||
|
let pid = (await execAsync(taskCommand)).stdout;
|
||||||
|
if (pid) {
|
||||||
|
pid = (await execAsync(`pstree -p ${pid}`)).stdout;
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let pids = pid.match(/\(\d+/g);
|
||||||
|
const killLogs = [];
|
||||||
|
if (pids && pids.length > 0) {
|
||||||
|
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
||||||
|
for (const id of pids) {
|
||||||
|
const c = `kill -9 ${id.slice(1)}`;
|
||||||
|
try {
|
||||||
|
const { stdout, stderr } = await execAsync(c);
|
||||||
|
if (stderr) {
|
||||||
|
killLogs.push(stderr);
|
||||||
|
}
|
||||||
|
if (stdout) {
|
||||||
|
killLogs.push(stdout);
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
killLogs.push(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return killLogs.length > 0 ? JSON.stringify(killLogs) : '';
|
||||||
|
} catch (e) {
|
||||||
|
return JSON.stringify(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async runSingle(subscriptionId: number) {
|
private async runSingle(subscriptionId: number) {
|
||||||
const subscription = await this.getDb({ id: subscriptionId });
|
const subscription = await this.getDb({ id: subscriptionId });
|
||||||
if (subscription.status !== SubscriptionStatus.queued) {
|
if (subscription.status !== SubscriptionStatus.queued) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const command = formatCommand(subscription);
|
const command = this.formatCommand(subscription);
|
||||||
|
|
||||||
this.scheduleService.runTask(command, this.taskCallbacks(subscription), {
|
await this.scheduleService.runTask(
|
||||||
name: subscription.name,
|
command,
|
||||||
schedule: subscription.schedule,
|
this.taskCallbacks(subscription),
|
||||||
command
|
);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
public async disabled(ids: number[]) {
|
||||||
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
await this.setSshConfig();
|
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
await this.handleTask(doc, false);
|
await this.handleTask(doc, false);
|
||||||
}
|
}
|
||||||
|
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async enabled(ids: number[]) {
|
public async enabled(ids: number[]) {
|
||||||
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
await this.setSshConfig();
|
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
await this.handleTask(doc);
|
await this.handleTask(doc);
|
||||||
}
|
}
|
||||||
|
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async log(id: number) {
|
public async log(id: number) {
|
||||||
@@ -351,7 +456,7 @@ export default class SubscriptionService {
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
const absolutePath = await handleLogPath(doc.log_path as string);
|
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
||||||
return getFileContentByName(absolutePath);
|
return getFileContentByName(absolutePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+48
-180
@@ -1,34 +1,15 @@
|
|||||||
import { Response } from 'express';
|
|
||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import {
|
import * as fs from 'fs';
|
||||||
AuthDataType,
|
import _ from 'lodash';
|
||||||
AuthInfo,
|
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
||||||
AuthInstance,
|
|
||||||
AuthModel,
|
|
||||||
AuthModelInfo,
|
|
||||||
} from '../data/auth';
|
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
import NotificationService from './notify';
|
import NotificationService from './notify';
|
||||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
import ScheduleService from './schedule';
|
||||||
import { spawn } from 'cross-spawn';
|
import { spawn } from 'child_process';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import got from 'got';
|
import got from 'got';
|
||||||
import {
|
|
||||||
getPid,
|
|
||||||
killTask,
|
|
||||||
parseContentVersion,
|
|
||||||
parseVersion,
|
|
||||||
promiseExec,
|
|
||||||
readDirs,
|
|
||||||
} from '../config/util';
|
|
||||||
import { TASK_COMMAND } from '../config/const';
|
|
||||||
import taskLimit from '../shared/pLimit';
|
|
||||||
import tar from 'tar';
|
|
||||||
import path from 'path';
|
|
||||||
import fs from 'fs';
|
|
||||||
import sum from 'lodash/sum';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class SystemService {
|
export default class SystemService {
|
||||||
@@ -39,22 +20,22 @@ export default class SystemService {
|
|||||||
@Inject('logger') private logger: winston.Logger,
|
@Inject('logger') private logger: winston.Logger,
|
||||||
private scheduleService: ScheduleService,
|
private scheduleService: ScheduleService,
|
||||||
private sockService: SockService,
|
private sockService: SockService,
|
||||||
) { }
|
) {}
|
||||||
|
|
||||||
public async getSystemConfig() {
|
public async getLogRemoveFrequency() {
|
||||||
const doc = await this.getDb({ type: AuthDataType.systemConfig });
|
const doc = await this.getDb({ type: AuthDataType.removeLogFrequency });
|
||||||
return doc || ({} as AuthInstance);
|
return doc || {};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateAuthDb(payload: AuthInfo): Promise<AuthInstance> {
|
private async updateAuthDb(payload: AuthInfo): Promise<any> {
|
||||||
await AuthModel.upsert({ ...payload });
|
await AuthModel.upsert({ ...payload });
|
||||||
const doc = await this.getDb({ type: payload.type });
|
const doc = await this.getDb({ type: payload.type });
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<AuthInstance> {
|
public async getDb(query: any): Promise<any> {
|
||||||
const doc: any = await AuthModel.findOne({ where: { ...query } });
|
const doc: any = await AuthModel.findOne({ where: { ...query } });
|
||||||
return doc && doc.get({ plain: true });
|
return doc && (doc.get({ plain: true }) as any);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
||||||
@@ -75,61 +56,56 @@ export default class SystemService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateSystemConfig(info: AuthModelInfo) {
|
public async updateLogRemoveFrequency(frequency: number) {
|
||||||
const oDoc = await this.getSystemConfig();
|
const oDoc = await this.getLogRemoveFrequency();
|
||||||
const result = await this.updateAuthDb({
|
const result = await this.updateAuthDb({
|
||||||
...oDoc,
|
...oDoc,
|
||||||
type: AuthDataType.systemConfig,
|
type: AuthDataType.removeLogFrequency,
|
||||||
info,
|
info: { frequency },
|
||||||
});
|
});
|
||||||
if (info.logRemoveFrequency) {
|
|
||||||
const cron = {
|
const cron = {
|
||||||
id: result.id || NaN,
|
id: result.id,
|
||||||
name: '删除日志',
|
name: '删除日志',
|
||||||
command: `ql rmlog ${info.logRemoveFrequency}`,
|
command: `ql rmlog ${frequency}`,
|
||||||
};
|
};
|
||||||
await this.scheduleService.cancelIntervalTask(cron);
|
await this.scheduleService.cancelIntervalTask(cron);
|
||||||
if (info.logRemoveFrequency > 0) {
|
if (frequency > 0) {
|
||||||
this.scheduleService.createIntervalTask(cron, {
|
await this.scheduleService.createIntervalTask(cron, {
|
||||||
days: info.logRemoveFrequency,
|
days: frequency,
|
||||||
|
runImmediately: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
return { code: 200, data: { ...cron } };
|
||||||
if (info.cronConcurrency) {
|
|
||||||
await taskLimit.setCustomLimit(info.cronConcurrency);
|
|
||||||
}
|
|
||||||
return { code: 200, data: info };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async checkUpdate() {
|
public async checkUpdate() {
|
||||||
try {
|
try {
|
||||||
const currentVersionContent = await parseVersion(config.versionFile);
|
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
||||||
|
const logRegx = /.*export const changeLog = \`((.*\n.*)+)\`;/;
|
||||||
|
|
||||||
let lastVersionContent;
|
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||||
|
const currentVersion = currentVersionFile.match(versionRegx)![1];
|
||||||
|
|
||||||
|
let lastVersion = '';
|
||||||
|
let lastLog = '';
|
||||||
try {
|
try {
|
||||||
const result = await got.get(
|
const result = await got.get(config.lastVersionFile, {
|
||||||
`${config.lastVersionFile}?t=${Date.now()}`,
|
timeout: 6000,
|
||||||
{
|
retry: 0,
|
||||||
timeout: 30000,
|
});
|
||||||
},
|
const lastVersionFileContent = result.body;
|
||||||
);
|
lastVersion = lastVersionFileContent.match(versionRegx)![1];
|
||||||
lastVersionContent = await parseContentVersion(result.body);
|
lastLog = lastVersionFileContent.match(logRegx)
|
||||||
} catch (error) { }
|
? lastVersionFileContent.match(logRegx)![1]
|
||||||
|
: '';
|
||||||
if (!lastVersionContent) {
|
} catch (error) {}
|
||||||
lastVersionContent = currentVersionContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: {
|
||||||
hasNewVersion: this.checkHasNewVersion(
|
hasNewVersion: this.checkHasNewVersion(currentVersion, lastVersion),
|
||||||
currentVersionContent.version,
|
lastVersion,
|
||||||
lastVersionContent.version,
|
lastLog,
|
||||||
),
|
|
||||||
lastVersion: lastVersionContent.version,
|
|
||||||
lastLog: lastVersionContent.changeLog,
|
|
||||||
lastLogLink: lastVersionContent.changeLogLink,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -160,8 +136,12 @@ export default class SystemService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async updateSystem() {
|
public async updateSystem() {
|
||||||
const cp = spawn('ql -l update false', { 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',
|
||||||
@@ -186,33 +166,6 @@ export default class SystemService {
|
|||||||
return { code: 200 };
|
return { code: 200 };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async reloadSystem(target: 'system' | 'data') {
|
|
||||||
const cp = spawn(`ql -l reload ${target || ''}`, { shell: '/bin/bash' });
|
|
||||||
|
|
||||||
cp.stdout.on('data', (data) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: 'reloadSystem',
|
|
||||||
message: data.toString(),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.stderr.on('data', (data) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: 'reloadSystem',
|
|
||||||
message: data.toString(),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.on('error', (err) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: 'reloadSystem',
|
|
||||||
message: JSON.stringify(err),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
return { code: 200 };
|
|
||||||
}
|
|
||||||
|
|
||||||
public async notify({ title, content }: { title: string; content: string }) {
|
public async notify({ title, content }: { title: string; content: string }) {
|
||||||
const isSuccess = await this.notificationService.notify(title, content);
|
const isSuccess = await this.notificationService.notify(title, content);
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
@@ -221,89 +174,4 @@ export default class SystemService {
|
|||||||
return { code: 400, message: '通知发送失败,请检查系统设置/通知配置' };
|
return { code: 400, message: '通知发送失败,请检查系统设置/通知配置' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async run(
|
|
||||||
{ command, logPath }: { command: string; logPath: string },
|
|
||||||
callback: TaskCallbacks,
|
|
||||||
) {
|
|
||||||
if (!command.startsWith(TASK_COMMAND)) {
|
|
||||||
command = `${TASK_COMMAND} ${command}`;
|
|
||||||
}
|
|
||||||
this.scheduleService.runTask(
|
|
||||||
`real_log_path=${logPath} real_time=true ${command}`,
|
|
||||||
callback,
|
|
||||||
{
|
|
||||||
command,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async stop({ command, pid }: { command: string; pid: number }) {
|
|
||||||
if (!pid && !command) {
|
|
||||||
return { code: 400, message: '参数错误' };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pid) {
|
|
||||||
await killTask(pid);
|
|
||||||
return { code: 200 };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!command.startsWith(TASK_COMMAND)) {
|
|
||||||
command = `${TASK_COMMAND} ${command}`;
|
|
||||||
}
|
|
||||||
const _pid = await getPid(command);
|
|
||||||
if (_pid) {
|
|
||||||
await killTask(_pid);
|
|
||||||
return { code: 200 };
|
|
||||||
} else {
|
|
||||||
return { code: 400, message: '任务未找到' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async exportData(res: Response) {
|
|
||||||
try {
|
|
||||||
await tar.create(
|
|
||||||
{ gzip: true, file: config.dataTgzFile, cwd: config.rootPath },
|
|
||||||
['data'],
|
|
||||||
);
|
|
||||||
res.download(config.dataTgzFile);
|
|
||||||
} catch (error: any) {
|
|
||||||
return res.send({ code: 400, message: error.message });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async importData() {
|
|
||||||
try {
|
|
||||||
await promiseExec(`rm -rf ${path.join(config.tmpPath, 'data')}`);
|
|
||||||
await tar.x({ file: config.dataTgzFile, cwd: config.tmpPath });
|
|
||||||
return { code: 200 };
|
|
||||||
} catch (error: any) {
|
|
||||||
return { code: 400, message: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getSystemLog(res: Response) {
|
|
||||||
const result = readDirs(config.systemLogPath, config.systemLogPath);
|
|
||||||
const logs = result.reverse().filter((x) => x.title.endsWith('.log'));
|
|
||||||
res.set({
|
|
||||||
'Content-Length': sum(logs.map((x) => x.size)),
|
|
||||||
});
|
|
||||||
(function sendFiles(res, fileNames) {
|
|
||||||
if (fileNames.length === 0) {
|
|
||||||
res.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentLog = fileNames.shift();
|
|
||||||
if (currentLog) {
|
|
||||||
const currentFileStream = fs.createReadStream(
|
|
||||||
path.join(config.systemLogPath, currentLog.title),
|
|
||||||
);
|
|
||||||
currentFileStream.on('end', () => {
|
|
||||||
sendFiles(res, fileNames);
|
|
||||||
});
|
|
||||||
currentFileStream.pipe(res, { end: false });
|
|
||||||
}
|
|
||||||
})(res, logs);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-65
@@ -1,27 +1,17 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import {
|
import { createRandomString, getNetIp, getPlatform } from '../config/util';
|
||||||
createRandomString,
|
|
||||||
fileExist,
|
|
||||||
getNetIp,
|
|
||||||
getPlatform,
|
|
||||||
safeJSONParse,
|
|
||||||
} 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 {
|
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
||||||
AuthDataType,
|
|
||||||
AuthInfo,
|
|
||||||
AuthModel,
|
|
||||||
AuthModelInfo,
|
|
||||||
LoginStatus,
|
|
||||||
} from '../data/auth';
|
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
import NotificationService from './notify';
|
import NotificationService from './notify';
|
||||||
import { Request } from 'express';
|
import { Request } from 'express';
|
||||||
import ScheduleService from './schedule';
|
import ScheduleService from './schedule';
|
||||||
|
import { spawn } from 'child_process';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
|
|
||||||
@@ -75,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',
|
||||||
@@ -170,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();
|
||||||
}
|
}
|
||||||
@@ -194,14 +170,12 @@ export default class UserService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getLoginLog(): Promise<Array<AuthModelInfo | undefined>> {
|
public async getLoginLog(): Promise<AuthInfo[]> {
|
||||||
const docs = await AuthModel.findAll({
|
const docs = await AuthModel.findAll({
|
||||||
where: { type: AuthDataType.loginLog },
|
where: { type: AuthDataType.loginLog },
|
||||||
});
|
});
|
||||||
if (docs && docs.length > 0) {
|
if (docs && docs.length > 0) {
|
||||||
const result = docs.sort(
|
const result = docs.sort((a, b) => b.info.timestamp - a.info.timestamp);
|
||||||
(a, b) => b.info!.timestamp! - a.info!.timestamp!,
|
|
||||||
);
|
|
||||||
if (result.length > 100) {
|
if (result.length > 100) {
|
||||||
await AuthModel.destroy({
|
await AuthModel.destroy({
|
||||||
where: { id: result[result.length - 1].id },
|
where: { id: result[result.length - 1].id },
|
||||||
@@ -218,16 +192,17 @@ export default class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private initAuthInfo() {
|
private initAuthInfo() {
|
||||||
|
const newPassword = createRandomString(16, 22);
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
config.authConfigFile,
|
config.authConfigFile,
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
username: 'admin',
|
username: 'admin',
|
||||||
password: 'admin',
|
password: newPassword,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
code: 100,
|
code: 100,
|
||||||
message: '未找到认证文件,重新初始化',
|
message: '已初始化密码,请前往auth.json查看并重新登录',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,18 +227,13 @@ export default class UserService {
|
|||||||
return { code: 200, data: avatar, message: '更新成功' };
|
return { code: 200, data: avatar, message: '更新成功' };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getUserInfo(): Promise<any> {
|
public getUserInfo(): Promise<any> {
|
||||||
const authFileExist = await fileExist(config.authConfigFile);
|
return new Promise((resolve) => {
|
||||||
if (!authFileExist) {
|
fs.readFile(config.authConfigFile, 'utf8', (err, data) => {
|
||||||
fs.writeFileSync(
|
if (err) console.log(err);
|
||||||
config.authConfigFile,
|
resolve(JSON.parse(data));
|
||||||
JSON.stringify({
|
});
|
||||||
username: 'admin',
|
});
|
||||||
password: 'admin',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return this.getAuthInfo();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public initTwoFactor() {
|
public initTwoFactor() {
|
||||||
@@ -328,7 +298,7 @@ export default class UserService {
|
|||||||
|
|
||||||
private getAuthInfo() {
|
private getAuthInfo() {
|
||||||
const content = fs.readFileSync(config.authConfigFile, 'utf8');
|
const content = fs.readFileSync(config.authConfigFile, 'utf8');
|
||||||
return safeJSONParse(content);
|
return JSON.parse(content || '{}');
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateAuthInfo(authInfo: any, info: any) {
|
private updateAuthInfo(authInfo: any, info: any) {
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
|
||||||
import os from 'os';
|
|
||||||
import { AuthDataType, AuthModel } from '../data/auth';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
|
|
||||||
class TaskLimit {
|
|
||||||
private oneLimit = new PQueue({ concurrency: 1 });
|
|
||||||
private updateLogLimit = new PQueue({ concurrency: 1 });
|
|
||||||
private cronLimit = new PQueue({ concurrency: Math.max(os.cpus().length, 4) });
|
|
||||||
|
|
||||||
get cronLimitActiveCount() {
|
|
||||||
return this.cronLimit.pending;
|
|
||||||
}
|
|
||||||
|
|
||||||
get cronLimitPendingCount() {
|
|
||||||
return this.cronLimit.size;
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.setCustomLimit();
|
|
||||||
this.handleEvents();
|
|
||||||
}
|
|
||||||
|
|
||||||
private handleEvents() {
|
|
||||||
this.cronLimit.on('add', () => {
|
|
||||||
Logger.info(
|
|
||||||
`[schedule][任务加入队列] 运行中任务数: ${this.cronLimitActiveCount}, 等待中任务数: ${this.cronLimitPendingCount}`,
|
|
||||||
);
|
|
||||||
})
|
|
||||||
this.cronLimit.on('active', () => {
|
|
||||||
Logger.info(
|
|
||||||
`[schedule][开始处理任务] 运行中任务数: ${this.cronLimitActiveCount + 1}, 等待中任务数: ${this.cronLimitPendingCount}`,
|
|
||||||
);
|
|
||||||
})
|
|
||||||
this.cronLimit.on('completed', (param) => {
|
|
||||||
Logger.info(
|
|
||||||
`[schedule][任务处理成功] 参数 ${JSON.stringify(param)}`,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('error', error => {
|
|
||||||
Logger.error(
|
|
||||||
`[schedule][任务处理错误] 参数 ${JSON.stringify(error)}`,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('next', () => {
|
|
||||||
Logger.info(
|
|
||||||
`[schedule][任务处理结束] 运行中任务数: ${this.cronLimitActiveCount}, 等待中任务数: ${this.cronLimitPendingCount}`,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('idle', () => {
|
|
||||||
Logger.info(
|
|
||||||
`[schedule][任务队列] 空闲中...`,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public async setCustomLimit(limit?: number) {
|
|
||||||
if (limit) {
|
|
||||||
this.cronLimit.concurrency = limit;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await AuthModel.sync();
|
|
||||||
const doc = await AuthModel.findOne({
|
|
||||||
where: { type: AuthDataType.systemConfig },
|
|
||||||
});
|
|
||||||
if (doc?.info?.cronConcurrency) {
|
|
||||||
this.cronLimit.concurrency = doc.info.cronConcurrency;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async runWithCronLimit<T>(fn: () => Promise<T>, options?: Partial<QueueAddOptions>): Promise<T | void> {
|
|
||||||
return this.cronLimit.add(fn, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
public runOneByOne<T>(fn: () => Promise<T>, options?: Partial<QueueAddOptions>): Promise<T | void> {
|
|
||||||
return this.oneLimit.add(fn, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
public updateDepLog<T>(fn: () => Promise<T>, options?: Partial<QueueAddOptions>): Promise<T | void> {
|
|
||||||
return this.updateLogLimit.add(fn, options);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new TaskLimit();
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { spawn } from 'cross-spawn';
|
|
||||||
import taskLimit from './pLimit';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
|
|
||||||
export function runCron(cmd: string, options?: { schedule: string; extraSchedules: Array<{ schedule: string }>; name: string }): Promise<number | void> {
|
|
||||||
return taskLimit.runWithCronLimit(() => {
|
|
||||||
return new Promise(async (resolve: any) => {
|
|
||||||
Logger.info(`[schedule][开始执行任务] 参数 ${JSON.stringify({ ...options, command: cmd })}`);
|
|
||||||
const cp = spawn(cmd, { shell: '/bin/bash' });
|
|
||||||
|
|
||||||
cp.stderr.on('data', (data) => {
|
|
||||||
Logger.info(
|
|
||||||
'[schedule][执行任务失败] 命令: %s, 错误信息: %j',
|
|
||||||
cmd,
|
|
||||||
data.toString(),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
cp.on('error', (err) => {
|
|
||||||
Logger.error(
|
|
||||||
'[schedule][创建任务失败] 命令: %s, 错误信息: %j',
|
|
||||||
cmd,
|
|
||||||
err,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.on('exit', async (code) => {
|
|
||||||
resolve({ ...options, command: cmd, pid: cp.pid, code });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,40 +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';
|
|
||||||
import os from 'os';
|
|
||||||
|
|
||||||
const tokenFile = path.join(config.configPath, 'token.json');
|
|
||||||
|
|
||||||
async function getToken() {
|
|
||||||
try {
|
|
||||||
Container.set('logger', LoggerInstance);
|
|
||||||
const openService = Container.get(OpenService);
|
|
||||||
const appToken = await openService.generateSystemToken();
|
|
||||||
console.log(appToken.value);
|
|
||||||
await writeFile({
|
|
||||||
value: appToken.value,
|
|
||||||
expiration: appToken.expiration,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.log(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function writeFile(data: any) {
|
|
||||||
return new Promise<void>((resolve, reject) => {
|
|
||||||
fs.writeFile(
|
|
||||||
tokenFile,
|
|
||||||
`${JSON.stringify(data)}${os.EOL}`,
|
|
||||||
{ encoding: 'utf8' },
|
|
||||||
() => {
|
|
||||||
resolve();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
getToken();
|
|
||||||
+17
-37
@@ -1,34 +1,27 @@
|
|||||||
FROM python:3.10-alpine as builder
|
FROM node:alpine
|
||||||
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
|
||||||
RUN set -x \
|
|
||||||
&& apk update \
|
|
||||||
&& apk add nodejs npm git \
|
|
||||||
&& npm i -g pnpm@8.3.1 \
|
|
||||||
&& cd /tmp/build \
|
|
||||||
&& pnpm --registry https://registry.npmmirror.com install --prod
|
|
||||||
|
|
||||||
FROM python:3.10-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 PNPM_HOME=/root/.local/share/pnpm \
|
||||||
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/share/pnpm:/root/.local/share/pnpm/global/5/node_modules:$PNPM_HOME \
|
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/share/pnpm:/root/.local/share/pnpm/global/5/node_modules:$PNPM_HOME \
|
||||||
NODE_PATH=/usr/local/bin:/usr/local/pnpm-global/5/node_modules:/usr/local/lib/node_modules:/root/.local/share/pnpm/global/5/node_modules \
|
LANG=zh_CN.UTF-8 \
|
||||||
LANG=C.UTF-8 \
|
|
||||||
SHELL=/bin/bash \
|
SHELL=/bin/bash \
|
||||||
PS1="\u@\h:\w \$ " \
|
PS1="\u@\h:\w \$ " \
|
||||||
QL_DIR=/ql \
|
QL_DIR=/ql \
|
||||||
QL_BRANCH=${QL_BRANCH}
|
QL_BRANCH=${QL_BRANCH}
|
||||||
|
|
||||||
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
RUN set -x \
|
RUN set -x \
|
||||||
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
||||||
&& apk update -f \
|
&& apk update -f \
|
||||||
&& apk upgrade \
|
&& apk upgrade \
|
||||||
&& apk --no-cache add -f bash \
|
&& apk --no-cache add -f bash \
|
||||||
coreutils \
|
coreutils \
|
||||||
|
moreutils \
|
||||||
git \
|
git \
|
||||||
curl \
|
curl \
|
||||||
wget \
|
wget \
|
||||||
@@ -36,43 +29,30 @@ RUN set -x \
|
|||||||
perl \
|
perl \
|
||||||
openssl \
|
openssl \
|
||||||
nginx \
|
nginx \
|
||||||
nodejs \
|
python3 \
|
||||||
jq \
|
jq \
|
||||||
openssh \
|
openssh \
|
||||||
procps \
|
py3-pip \
|
||||||
netcat-openbsd \
|
|
||||||
npm \
|
|
||||||
&& 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@8.3.1 \
|
&& pnpm add -g pm2 ts-node typescript tslib \
|
||||||
&& cd && pnpm config set registry https://registry.npmmirror.com \
|
&& git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||||
&& pnpm add -g pm2 tsx \
|
|
||||||
&& rm -rf /root/.pnpm-store \
|
|
||||||
&& rm -rf /root/.local/share/pnpm/store \
|
|
||||||
&& rm -rf /root/.cache \
|
|
||||||
&& rm -rf /root/.npm
|
|
||||||
|
|
||||||
ARG SOURCE_COMMIT
|
|
||||||
RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
|
||||||
&& cd ${QL_DIR} \
|
&& cd ${QL_DIR} \
|
||||||
&& cp -f .env.example .env \
|
&& cp -f .env.example .env \
|
||||||
&& chmod 777 ${QL_DIR}/shell/*.sh \
|
&& chmod 777 ${QL_DIR}/shell/*.sh \
|
||||||
&& chmod 777 ${QL_DIR}/docker/*.sh \
|
&& chmod 777 ${QL_DIR}/docker/*.sh \
|
||||||
&& git clone --depth=1 -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
|
&& pnpm install --prod \
|
||||||
|
&& rm -rf /root/.pnpm-store \
|
||||||
|
&& rm -rf /root/.local/share/pnpm/store \
|
||||||
|
&& rm -rf /root/.cache \
|
||||||
|
&& rm -rf /root/.npm \
|
||||||
|
&& git clone -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
|
||||||
&& mkdir -p ${QL_DIR}/static \
|
&& mkdir -p ${QL_DIR}/static \
|
||||||
&& cp -rf /static/* ${QL_DIR}/static \
|
&& cp -rf /static/* ${QL_DIR}/static \
|
||||||
&& rm -rf /static
|
&& rm -rf /static
|
||||||
|
|
||||||
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
|
||||||
|
|
||||||
WORKDIR ${QL_DIR}
|
|
||||||
|
|
||||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
|
||||||
CMD curl -sf http://127.0.0.1:5400/api/health || exit 1
|
|
||||||
|
|
||||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
|
|||||||
@@ -1,15 +1,9 @@
|
|||||||
version: '2'
|
version: '2'
|
||||||
services:
|
services:
|
||||||
web:
|
web:
|
||||||
# alpine 基础镜像版本
|
|
||||||
image: whyour/qinglong:latest
|
image: whyour/qinglong:latest
|
||||||
# debian-slim 基础镜像版本
|
|
||||||
# image: whyour/qinglong:debian
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/ql/data
|
- ./data:/ql/data
|
||||||
ports:
|
ports:
|
||||||
- "0.0.0.0:5700:5700"
|
- "0.0.0.0:5700:5700"
|
||||||
environment:
|
|
||||||
# 部署路径非必须,以斜杠开头和结尾,比如 /test/
|
|
||||||
QlBaseUrl: '/'
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+23
-23
@@ -7,49 +7,49 @@ link_shell
|
|||||||
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
|
||||||
init_nginx
|
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||||
fix_config
|
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
||||||
|
|
||||||
pm2 l &>/dev/null
|
pm2 l &>/dev/null
|
||||||
|
echo
|
||||||
|
|
||||||
echo -e "======================2. 安装依赖========================\n"
|
echo -e "======================2. 安装依赖========================\n"
|
||||||
patch_version
|
update_depend
|
||||||
if [[ $PipMirror ]]; then
|
|
||||||
pip3 config set global.index-url $PipMirror
|
|
||||||
fi
|
|
||||||
current_npm_registry=$(cd && pnpm config get registry)
|
|
||||||
is_equal_registry=$(echo $current_npm_registry | grep "${NpmMirror}")
|
|
||||||
if [[ "$is_equal_registry" == "" ]]; then
|
|
||||||
cd && pnpm config set registry $NpmMirror
|
|
||||||
pnpm install -g
|
|
||||||
fi
|
|
||||||
if [[ ! -s $dir_scripts/package.json ]] || [[ $(diff $dir_sample/package.json $dir_scripts/package.json) ]]; then
|
|
||||||
cp -f $dir_sample/package.json $dir_scripts/package.json
|
|
||||||
npm_install_2 $dir_scripts
|
|
||||||
fi
|
|
||||||
echo
|
echo
|
||||||
|
|
||||||
echo -e "======================3. 启动nginx========================\n"
|
echo -e "======================3. 启动nginx========================\n"
|
||||||
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
|
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
|
||||||
echo -e "nginx启动成功...\n"
|
echo -e "nginx启动成功...\n"
|
||||||
|
|
||||||
echo -e "======================4. 启动pm2服务========================\n"
|
echo -e "======================4. 启动面板监控========================\n"
|
||||||
reload_pm2
|
pm2 delete public &>/dev/null
|
||||||
|
pm2 start $dir_static/build/public.js -n public --source-map-support --time
|
||||||
|
echo -e "监控服务启动成功...\n"
|
||||||
|
|
||||||
|
echo -e "======================5. 启动控制面板========================\n"
|
||||||
|
pm2 delete panel &>/dev/null
|
||||||
|
pm2 start $dir_static/build/app.js -n panel --source-map-support --time
|
||||||
|
echo -e "控制面板启动成功...\n"
|
||||||
|
|
||||||
|
echo -e "======================6. 启动定时任务========================\n"
|
||||||
|
pm2 delete schedule &>/dev/null
|
||||||
|
pm2 start $dir_static/build/schedule.js -n schedule --source-map-support --time
|
||||||
|
echo -e "定时任务启动成功...\n"
|
||||||
|
|
||||||
if [[ $AutoStartBot == true ]]; then
|
if [[ $AutoStartBot == true ]]; then
|
||||||
echo -e "======================5. 启动bot========================\n"
|
echo -e "======================7. 启动bot========================\n"
|
||||||
nohup ql -l 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 "====================6. 执行自定义脚本========================\n"
|
echo -e "======================8. 执行自定义脚本========================\n"
|
||||||
nohup ql -l extra >$dir_log/extra.log 2>&1 &
|
nohup ql extra >>$dir_log/start.log 2>&1 &
|
||||||
echo -e "自定义脚本后台执行中...\n"
|
echo -e "自定义脚本后台执行中...\n"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo -e "############################################################\n"
|
echo -e "############################################################\n"
|
||||||
echo -e "容器启动成功..."
|
echo -e "容器启动成功..."
|
||||||
|
echo -e "\n请先访问5700端口,登录成功面板之后再执行添加定时任务..."
|
||||||
echo -e "############################################################\n"
|
echo -e "############################################################\n"
|
||||||
|
|
||||||
crond -f >/dev/null
|
crond -f >/dev/null
|
||||||
|
|||||||
+12
-17
@@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -12,35 +12,32 @@ map $http_upgrade $connection_upgrade {
|
|||||||
}
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
IPV4_CONFIG
|
listen 5700;
|
||||||
IPV6_CONFIG
|
root /ql/static/dist;
|
||||||
ssl_session_timeout 5m;
|
ssl_session_timeout 5m;
|
||||||
|
|
||||||
location QL_BASE_URLapi/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/;
|
proxy_pass http://public;
|
||||||
proxy_buffering off;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
location QL_BASE_URLapi/ {
|
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_buffering off;
|
|
||||||
|
|
||||||
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_URLopen/ {
|
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;
|
||||||
proxy_buffering off;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gzip on;
|
gzip on;
|
||||||
@@ -51,12 +48,10 @@ server {
|
|||||||
gzip_comp_level 6;
|
gzip_comp_level 6;
|
||||||
gzip_buffers 16 8k;
|
gzip_buffers 16 8k;
|
||||||
gzip_http_version 1.0;
|
gzip_http_version 1.0;
|
||||||
QL_ROOT_CONFIG
|
|
||||||
|
|
||||||
location QL_BASE_URL_LOCATION {
|
location / {
|
||||||
QL_ALIAS_CONFIG
|
|
||||||
index index.html index.htm;
|
index index.html index.htm;
|
||||||
try_files $uri QL_BASE_URLindex.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ~ .*\.(html)$ {
|
location ~ .*\.(html)$ {
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ http {
|
|||||||
|
|
||||||
server_tokens off;
|
server_tokens off;
|
||||||
|
|
||||||
client_max_body_size 4096m;
|
client_max_body_size 20m;
|
||||||
client_body_buffer_size 20m;
|
client_body_buffer_size 20m;
|
||||||
|
|
||||||
keepalive_timeout 65;
|
keepalive_timeout 65;
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
apps: [
|
|
||||||
{
|
|
||||||
name: 'schedule',
|
|
||||||
max_restarts: 10,
|
|
||||||
kill_timeout: 15000,
|
|
||||||
wait_ready: true,
|
|
||||||
listen_timeout: 10000,
|
|
||||||
source_map_support: true,
|
|
||||||
time: true,
|
|
||||||
script: 'static/build/schedule/index.js',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'public',
|
|
||||||
max_restarts: 10,
|
|
||||||
kill_timeout: 15000,
|
|
||||||
wait_ready: true,
|
|
||||||
listen_timeout: 10000,
|
|
||||||
source_map_support: true,
|
|
||||||
time: true,
|
|
||||||
script: 'static/build/public.js',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'panel',
|
|
||||||
max_restarts: 10,
|
|
||||||
kill_timeout: 15000,
|
|
||||||
wait_ready: true,
|
|
||||||
listen_timeout: 10000,
|
|
||||||
source_map_support: true,
|
|
||||||
time: true,
|
|
||||||
script: 'static/build/app.js',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"watch": ["back", ".env"],
|
"watch": ["back", ".env"],
|
||||||
"ext": "js,ts,json",
|
"ext": "js,ts,json",
|
||||||
"exec": "ts-node -P tsconfig.back.json ./back/app.ts"
|
"ignore": ["src/**/*.spec.ts"],
|
||||||
|
"exec": "ts-node --transpile-only ./back/app.ts"
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-75
@@ -2,18 +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 -P tsconfig.back.json ./back/public.ts",
|
"start:public": "ts-node back/public.ts",
|
||||||
"start:rpc": "ts-node -P tsconfig.back.json ./back/schedule/index.ts",
|
"build:front": "umi build",
|
||||||
"build:front": "max 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/index.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",
|
||||||
"gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true",
|
|
||||||
"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"
|
||||||
},
|
},
|
||||||
@@ -30,141 +28,99 @@
|
|||||||
},
|
},
|
||||||
"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",
|
|
||||||
"styled-components"
|
|
||||||
],
|
|
||||||
"allowedVersions": {
|
"allowedVersions": {
|
||||||
"react": "18",
|
"react": "17",
|
||||||
"react-dom": "18",
|
"react-dom": "17"
|
||||||
"dva-core": "2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@grpc/grpc-js": "^1.8.13",
|
|
||||||
"@otplib/preset-default": "^12.0.1",
|
"@otplib/preset-default": "^12.0.1",
|
||||||
"@sentry/node": "^7.12.1",
|
"@sentry/node": "^7.0.0",
|
||||||
"@sentry/tracing": "^7.12.1",
|
"@sentry/tracing": "^7.0.0",
|
||||||
"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",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"cron-parser": "^4.2.1",
|
"cron-parser": "^4.2.1",
|
||||||
"cross-spawn": "^7.0.3",
|
|
||||||
"dayjs": "^1.11.2",
|
"dayjs": "^1.11.2",
|
||||||
"dotenv": "^16.0.0",
|
"dotenv": "^16.0.0",
|
||||||
"express": "^4.17.3",
|
"express": "^4.17.3",
|
||||||
"express-jwt": "^6.1.1",
|
"express-jwt": "^6.1.1",
|
||||||
"express-rate-limit": "^7.0.0",
|
|
||||||
"express-urlrewrite": "^1.4.0",
|
"express-urlrewrite": "^1.4.0",
|
||||||
"form-data": "^4.0.0",
|
|
||||||
"got": "^11.8.2",
|
"got": "^11.8.2",
|
||||||
"hpagent": "^1.2.0",
|
"hpagent": "^0.1.2",
|
||||||
"http-proxy-middleware": "^2.0.6",
|
|
||||||
"iconv-lite": "^0.6.3",
|
"iconv-lite": "^0.6.3",
|
||||||
"js-yaml": "^4.1.0",
|
|
||||||
"jsonwebtoken": "^8.5.1",
|
"jsonwebtoken": "^8.5.1",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"multer": "^1.4.4",
|
"multer": "^1.4.4",
|
||||||
"nedb": "^1.8.0",
|
"nedb": "^1.8.0",
|
||||||
"node-schedule": "^2.1.0",
|
"node-schedule": "^2.1.0",
|
||||||
"nodemailer": "^6.7.2",
|
"nodemailer": "^6.7.2",
|
||||||
"p-queue-cjs": "7.3.4",
|
"p-queue": "7.2.0",
|
||||||
"protobufjs": "^7.2.3",
|
|
||||||
"pstree.remy": "^1.1.8",
|
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"sequelize": "^6.25.5",
|
"sequelize": "^6.20.1",
|
||||||
"serve-handler": "^6.1.3",
|
"serve-handler": "^6.1.3",
|
||||||
"sockjs": "^0.3.24",
|
"sockjs": "^0.3.24",
|
||||||
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
"sqlite3": "npm:@louislam/sqlite3@^15.0.6",
|
||||||
"tar": "^6.1.15",
|
|
||||||
"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",
|
||||||
"winston": "^3.6.0",
|
"winston": "^3.6.0",
|
||||||
"winston-daily-rotate-file": "^4.7.1",
|
|
||||||
"yargs": "^17.3.1"
|
"yargs": "^17.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ant-design/icons": "^4.7.0",
|
"@ant-design/icons": "^4.7.0",
|
||||||
"@ant-design/pro-layout": "6.38.22",
|
"@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": "^7.0.0",
|
||||||
"@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/cross-spawn": "^6.0.2",
|
|
||||||
"@types/express": "^4.17.13",
|
"@types/express": "^4.17.13",
|
||||||
"@types/express-jwt": "^6.0.4",
|
"@types/express-jwt": "^6.0.4",
|
||||||
"@types/file-saver": "^2.0.5",
|
|
||||||
"@types/js-yaml": "^4.0.5",
|
|
||||||
"@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-copy-to-clipboard": "^5.0.4",
|
"@types/react-dom": "^17.0.13",
|
||||||
"@types/react-dom": "^18.0.6",
|
|
||||||
"@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/tar": "^6.1.5",
|
|
||||||
"@types/uuid": "^8.3.4",
|
"@types/uuid": "^8.3.4",
|
||||||
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
"@umijs/plugin-antd": "^0.15.0",
|
||||||
"@uiw/react-codemirror": "^4.21.9",
|
"@umijs/plugin-esbuild": "^1.4.1",
|
||||||
"@umijs/max": "^4.0.72",
|
|
||||||
"@umijs/ssr-darkreader": "^4.9.45",
|
"@umijs/ssr-darkreader": "^4.9.45",
|
||||||
"ahooks": "^3.7.8",
|
"@umijs/test": "^3.5.21",
|
||||||
"ansi-to-react": "^6.1.6",
|
"ansi-to-react": "^6.1.6",
|
||||||
"antd": "^4.24.8",
|
"antd": "^4.20.5",
|
||||||
"antd-img-crop": "^4.2.3",
|
"antd-img-crop": "^4.2.3",
|
||||||
"axios": "^1.4.0",
|
"codemirror": "^5.65.2",
|
||||||
"compression-webpack-plugin": "9.2.0",
|
"compression-webpack-plugin": "9.2.0",
|
||||||
"concurrently": "^7.0.0",
|
"concurrently": "^7.0.0",
|
||||||
"file-saver": "^2.0.5",
|
"lint-staged": "^12.3.4",
|
||||||
"lint-staged": "^13.0.3",
|
|
||||||
"monaco-editor": "0.33.0",
|
|
||||||
"nodemon": "^2.0.15",
|
"nodemon": "^2.0.15",
|
||||||
"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",
|
||||||
"rc-virtual-list": "3.5.3",
|
"react": "17.x",
|
||||||
"react": "18.2.0",
|
"react-codemirror2": "^7.2.1",
|
||||||
"react-copy-to-clipboard": "^5.1.0",
|
|
||||||
"react-diff-viewer": "^3.1.1",
|
"react-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-intl-universal": "^2.6.21",
|
|
||||||
"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",
|
||||||
"ts-proto": "^1.146.0",
|
"typescript": "^4.6.2",
|
||||||
"tslib": "^2.4.0",
|
"umi": "^3.5.21",
|
||||||
"tsx": "^3.12.3",
|
"umi-request": "^1.4.0",
|
||||||
"typescript": "5.2.2",
|
|
||||||
"vh-check": "^2.0.5",
|
"vh-check": "^2.0.5",
|
||||||
"virtualizedtableforantd4": "1.3.0",
|
|
||||||
"webpack": "^5.70.0",
|
"webpack": "^5.70.0",
|
||||||
"yorkie": "^2.0.0"
|
"yorkie": "^2.0.0"
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
-16347
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
+13
-66
@@ -1,3 +1,9 @@
|
|||||||
|
## Version: v2.8.0
|
||||||
|
## Date: 2021-06-20
|
||||||
|
## Update Content: 可持续发展纲要\n1. session管理破坏性修改\n2. 配置管理可编辑config下文件\n3. 自定义脚本改为查看脚本\n4. 移除互助相关
|
||||||
|
|
||||||
|
## 上面版本号中,如果第2位数字有变化,那么代表增加了新的参数,如果只有第3位数字有变化,仅代表更新了注释,没有增加新的参数,可更新可不更新
|
||||||
|
|
||||||
## 在运行 ql repo 命令时,是否自动删除失效的脚本与定时任务
|
## 在运行 ql repo 命令时,是否自动删除失效的脚本与定时任务
|
||||||
AutoDelCron="true"
|
AutoDelCron="true"
|
||||||
|
|
||||||
@@ -10,29 +16,19 @@ DefaultCronRule=""
|
|||||||
## ql repo命令拉取脚本时需要拉取的文件后缀,直接写文件后缀名即可
|
## ql repo命令拉取脚本时需要拉取的文件后缀,直接写文件后缀名即可
|
||||||
RepoFileExtensions="js py"
|
RepoFileExtensions="js py"
|
||||||
|
|
||||||
## 代理地址,支持HTTP/SOCK5,例如 http://127.0.0.1:7890
|
## 代理地址,支持http/https/socks,例如 http://127.0.0.1:7890
|
||||||
ProxyUrl=""
|
ProxyUrl=""
|
||||||
|
|
||||||
## 资源告警阙值,默认CPU 80%、内存80%、磁盘90%
|
## 设置定时任务执行的超时时间,默认1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
||||||
CpuWarn=80
|
CommandTimeoutTime="1h"
|
||||||
MemoryWarn=80
|
|
||||||
DiskWarn=90
|
|
||||||
|
|
||||||
## 设置定时任务执行的超时时间,例如1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
## 设置批量执行任务时的并发数,默认同时执行5个任务
|
||||||
CommandTimeoutTime=""
|
MaxConcurrentNum="5"
|
||||||
|
|
||||||
## 在运行 task 命令时,随机延迟启动任务的最大延迟时间
|
## 在运行 task 命令时,随机延迟启动任务的最大延迟时间
|
||||||
## 默认给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"
|
||||||
|
|
||||||
@@ -42,12 +38,9 @@ AutoStartBot=""
|
|||||||
## 是否使用第三方bot,默认不使用,使用时填入仓库地址,存到ql/repo目录下,文件夹命名为diybot
|
## 是否使用第三方bot,默认不使用,使用时填入仓库地址,存到ql/repo目录下,文件夹命名为diybot
|
||||||
BotRepoUrl=""
|
BotRepoUrl=""
|
||||||
|
|
||||||
## 安装python依赖时指定pip源
|
## 安装bot依赖时指定pip源,默认使用清华源,如不需要源,设置此参数为空
|
||||||
PipMirror="https://pypi.doubanio.com/simple/"
|
PipMirror="https://pypi.doubanio.com/simple/"
|
||||||
|
|
||||||
## 安装node依赖时指定npm源
|
|
||||||
NpmMirror="https://registry.npmmirror.com"
|
|
||||||
|
|
||||||
## 通知环境变量
|
## 通知环境变量
|
||||||
## 1. Server酱
|
## 1. Server酱
|
||||||
## https://sct.ftqq.com
|
## https://sct.ftqq.com
|
||||||
@@ -58,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"
|
||||||
@@ -91,10 +84,6 @@ export TG_API_HOST=""
|
|||||||
export DD_BOT_TOKEN=""
|
export DD_BOT_TOKEN=""
|
||||||
export DD_BOT_SECRET=""
|
export DD_BOT_SECRET=""
|
||||||
|
|
||||||
## 企业微信反向代理地址
|
|
||||||
## (环境变量名 QYWX_ORIGIN)
|
|
||||||
export QYWX_ORIGIN=""
|
|
||||||
|
|
||||||
## 5. 企业微信机器人
|
## 5. 企业微信机器人
|
||||||
## 官方说明文档:https://work.weixin.qq.com/api/doc/90000/90136/91770
|
## 官方说明文档:https://work.weixin.qq.com/api/doc/90000/90136/91770
|
||||||
## 下方填写密钥,企业微信推送 webhook 后面的 key
|
## 下方填写密钥,企业微信推送 webhook 后面的 key
|
||||||
@@ -140,46 +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=""
|
|
||||||
|
|
||||||
## 14. SMTP
|
|
||||||
## 暂时只支持在 Python 中调用 notify.py 以发送 SMTP 邮件通知
|
|
||||||
## smtp_server 填写 SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
|
|
||||||
export SMTP_SERVER=""
|
|
||||||
## smtp_ssl 填写 SMTP 发送邮件服务器是否使用 SSL,内容应为 true 或 false
|
|
||||||
export SMTP_SSL="false"
|
|
||||||
## smtp_email 填写 SMTP 收发件邮箱,通知将会由自己发给自己
|
|
||||||
export SMTP_EMAIL=""
|
|
||||||
## smtp_password 填写 SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
|
||||||
export SMTP_PASSWORD=""
|
|
||||||
## smtp_name 填写 SMTP 收发件人姓名,可随意填写
|
|
||||||
export SMTP_NAME=""
|
|
||||||
|
|
||||||
## 15. PushMe
|
|
||||||
## 官方说明文档:https://push.i-i.me/
|
|
||||||
## PUSHME_KEY (必填)填写PushMe APP上获取的push_key
|
|
||||||
export PUSHME_KEY=""
|
|
||||||
|
|
||||||
## 13. CHRONOCAT
|
|
||||||
## CHRONOCAT_URL 推送 http://127.0.0.1:16530
|
|
||||||
## CHRONOCAT_TOKEN 填写在CHRONOCAT文件生成的访问密钥
|
|
||||||
## CHRONOCAT_QQ 个人:user_id=个人QQ 群则填入group_id=QQ群 多个用英文;隔开同时支持个人和群 如:user_id=xxx;group_id=xxxx;group_id=xxxxx
|
|
||||||
## CHRONOCAT相关API https://chronocat.vercel.app/install/docker/official/
|
|
||||||
export CHRONOCAT_URL=""
|
|
||||||
export CHRONOCAT_QQ="" #
|
|
||||||
export CHRONOCAT_TOKEN=""
|
|
||||||
|
|
||||||
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
||||||
|
|||||||
+83
-593
File diff suppressed because one or more lines are too long
+14
-379
@@ -9,10 +9,6 @@ import re
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import smtplib
|
|
||||||
from email.mime.text import MIMEText
|
|
||||||
from email.header import Header
|
|
||||||
from email.utils import formataddr
|
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
@@ -40,8 +36,6 @@ push_config = {
|
|||||||
'BARK_GROUP': '', # bark 推送分组
|
'BARK_GROUP': '', # bark 推送分组
|
||||||
'BARK_SOUND': '', # bark 推送声音
|
'BARK_SOUND': '', # bark 推送声音
|
||||||
'BARK_ICON': '', # bark 推送图标
|
'BARK_ICON': '', # bark 推送图标
|
||||||
'BARK_LEVEL': '', # bark 推送时效性
|
|
||||||
'BARK_URL': '', # bark 推送跳转URL
|
|
||||||
|
|
||||||
'CONSOLE': True, # 控制台输出
|
'CONSOLE': True, # 控制台输出
|
||||||
|
|
||||||
@@ -67,10 +61,6 @@ push_config = {
|
|||||||
'PUSH_KEY': '', # server 酱的 PUSH_KEY,兼容旧版与 Turbo 版
|
'PUSH_KEY': '', # server 酱的 PUSH_KEY,兼容旧版与 Turbo 版
|
||||||
|
|
||||||
'DEER_KEY': '', # PushDeer 的 PUSHDEER_KEY
|
'DEER_KEY': '', # PushDeer 的 PUSHDEER_KEY
|
||||||
'DEER_URL': '', # PushDeer 的 PUSHDEER_URL
|
|
||||||
|
|
||||||
'CHAT_URL': '', # synology chat url
|
|
||||||
'CHAT_TOKEN': '', # synology chat token
|
|
||||||
|
|
||||||
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
||||||
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
||||||
@@ -78,8 +68,6 @@ push_config = {
|
|||||||
'QMSG_KEY': '', # qmsg 酱的 QMSG_KEY
|
'QMSG_KEY': '', # qmsg 酱的 QMSG_KEY
|
||||||
'QMSG_TYPE': '', # qmsg 酱的 QMSG_TYPE
|
'QMSG_TYPE': '', # qmsg 酱的 QMSG_TYPE
|
||||||
|
|
||||||
'QYWX_ORIGIN': '', # 企业微信代理地址
|
|
||||||
|
|
||||||
'QYWX_AM': '', # 企业微信应用
|
'QYWX_AM': '', # 企业微信应用
|
||||||
|
|
||||||
'QYWX_KEY': '', # 企业微信机器人
|
'QYWX_KEY': '', # 企业微信机器人
|
||||||
@@ -90,28 +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要对应好
|
|
||||||
|
|
||||||
'SMTP_SERVER': '', # SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
|
|
||||||
'SMTP_SSL': 'false', # SMTP 发送邮件服务器是否使用 SSL,填写 true 或 false
|
|
||||||
'SMTP_EMAIL': '', # SMTP 收发件邮箱,通知将会由自己发给自己
|
|
||||||
'SMTP_PASSWORD': '', # SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
|
||||||
'SMTP_NAME': '', # SMTP 收发件人姓名,可随意填写
|
|
||||||
|
|
||||||
'PUSHME_KEY': '', # PushMe 酱的 PUSHME_KEY
|
|
||||||
|
|
||||||
'CHRONOCAT_QQ': '', # qq号
|
|
||||||
'CHRONOCAT_TOKEN': '', # CHRONOCAT 的token
|
|
||||||
'CHRONOCAT_URL': '', # CHRONOCAT的url地址
|
|
||||||
|
|
||||||
'WEBHOOK_URL': '', # 自定义通知 请求地址
|
|
||||||
'WEBHOOK_BODY': '', # 自定义通知 请求体
|
|
||||||
'WEBHOOK_HEADERS': '', # 自定义通知 请求头
|
|
||||||
'WEBHOOK_METHOD': '', # 自定义通知 请求方法
|
|
||||||
'WEBHOOK_CONTENT_TYPE': '' # 自定义通知 content-type
|
|
||||||
}
|
}
|
||||||
notify_function = []
|
notify_function = []
|
||||||
# fmt: on
|
# fmt: on
|
||||||
@@ -142,8 +108,6 @@ def bark(title: str, content: str) -> None:
|
|||||||
"BARK_GROUP": "group",
|
"BARK_GROUP": "group",
|
||||||
"BARK_SOUND": "sound",
|
"BARK_SOUND": "sound",
|
||||||
"BARK_ICON": "icon",
|
"BARK_ICON": "icon",
|
||||||
"BARK_LEVEL": "level",
|
|
||||||
"BARK_URL": "url",
|
|
||||||
}
|
}
|
||||||
params = ""
|
params = ""
|
||||||
for pair in filter(
|
for pair in filter(
|
||||||
@@ -238,7 +202,7 @@ def go_cqhttp(title: str, content: str) -> None:
|
|||||||
print("go-cqhttp 推送失败!")
|
print("go-cqhttp 推送失败!")
|
||||||
|
|
||||||
|
|
||||||
def gotify(title: str, content: str) -> None:
|
def gotify(title:str,content:str) -> None:
|
||||||
"""
|
"""
|
||||||
使用 gotify 推送消息。
|
使用 gotify 推送消息。
|
||||||
"""
|
"""
|
||||||
@@ -248,12 +212,8 @@ def gotify(title: str, content: str) -> None:
|
|||||||
print("gotify 服务启动")
|
print("gotify 服务启动")
|
||||||
|
|
||||||
url = f'{push_config.get("GOTIFY_URL")}/message?token={push_config.get("GOTIFY_TOKEN")}'
|
url = f'{push_config.get("GOTIFY_URL")}/message?token={push_config.get("GOTIFY_TOKEN")}'
|
||||||
data = {
|
data = {"title": title,"message": content,"priority": push_config.get("GOTIFY_PRIORITY")}
|
||||||
"title": title,
|
response = requests.post(url,data=data).json()
|
||||||
"message": content,
|
|
||||||
"priority": push_config.get("GOTIFY_PRIORITY"),
|
|
||||||
}
|
|
||||||
response = requests.post(url, data=data).json()
|
|
||||||
|
|
||||||
if response.get("id"):
|
if response.get("id"):
|
||||||
print("gotify 推送成功!")
|
print("gotify 推送成功!")
|
||||||
@@ -291,10 +251,10 @@ def serverJ(title: str, content: str) -> None:
|
|||||||
print("serverJ 服务启动")
|
print("serverJ 服务启动")
|
||||||
|
|
||||||
data = {"text": title, "desp": content.replace("\n", "\n\n")}
|
data = {"text": title, "desp": content.replace("\n", "\n\n")}
|
||||||
if push_config.get("PUSH_KEY").find("SCT") != -1:
|
if push_config.get("PUSH_KEY").index("SCT") != -1:
|
||||||
url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send'
|
url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send'
|
||||||
else:
|
else:
|
||||||
url = f'https://sc.ftqq.com/{push_config.get("PUSH_KEY")}.send'
|
url = f'https://sc.ftqq.com/${push_config.get("PUSH_KEY")}.send'
|
||||||
response = requests.post(url, data=data).json()
|
response = requests.post(url, data=data).json()
|
||||||
|
|
||||||
if response.get("errno") == 0 or response.get("code") == 0:
|
if response.get("errno") == 0 or response.get("code") == 0:
|
||||||
@@ -311,16 +271,8 @@ def pushdeer(title: str, content: str) -> None:
|
|||||||
print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送")
|
print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送")
|
||||||
return
|
return
|
||||||
print("PushDeer 服务启动")
|
print("PushDeer 服务启动")
|
||||||
data = {
|
data = {"text": title, "desp": content, "type": "markdown", "pushkey": push_config.get("DEER_KEY")}
|
||||||
"text": title,
|
url = 'https://api2.pushdeer.com/message/push'
|
||||||
"desp": content,
|
|
||||||
"type": "markdown",
|
|
||||||
"pushkey": push_config.get("DEER_KEY"),
|
|
||||||
}
|
|
||||||
url = "https://api2.pushdeer.com/message/push"
|
|
||||||
if push_config.get("DEER_URL"):
|
|
||||||
url = push_config.get("DEER_URL")
|
|
||||||
|
|
||||||
response = requests.post(url, data=data).json()
|
response = requests.post(url, data=data).json()
|
||||||
|
|
||||||
if len(response.get("content").get("result")) > 0:
|
if len(response.get("content").get("result")) > 0:
|
||||||
@@ -329,24 +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+ 推送消息。
|
||||||
@@ -371,6 +305,7 @@ def pushplus_bot(title: str, content: str) -> None:
|
|||||||
print("PUSHPLUS 推送成功!")
|
print("PUSHPLUS 推送成功!")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
url_old = "http://pushplus.hxtrip.com/send"
|
url_old = "http://pushplus.hxtrip.com/send"
|
||||||
headers["Accept"] = "application/json"
|
headers["Accept"] = "application/json"
|
||||||
response = requests.post(url=url_old, data=body, headers=headers).json()
|
response = requests.post(url=url_old, data=body, headers=headers).json()
|
||||||
@@ -441,12 +376,9 @@ class WeCom:
|
|||||||
self.CORPID = corpid
|
self.CORPID = corpid
|
||||||
self.CORPSECRET = corpsecret
|
self.CORPSECRET = corpsecret
|
||||||
self.AGENTID = agentid
|
self.AGENTID = agentid
|
||||||
self.ORIGIN = "https://qyapi.weixin.qq.com"
|
|
||||||
if push_config.get("QYWX_ORIGIN"):
|
|
||||||
self.ORIGIN = push_config.get("QYWX_ORIGIN")
|
|
||||||
|
|
||||||
def get_access_token(self):
|
def get_access_token(self):
|
||||||
url = f"{self.ORIGIN}/cgi-bin/gettoken"
|
url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
|
||||||
values = {
|
values = {
|
||||||
"corpid": self.CORPID,
|
"corpid": self.CORPID,
|
||||||
"corpsecret": self.CORPSECRET,
|
"corpsecret": self.CORPSECRET,
|
||||||
@@ -457,7 +389,8 @@ class WeCom:
|
|||||||
|
|
||||||
def send_text(self, message, touser="@all"):
|
def send_text(self, message, touser="@all"):
|
||||||
send_url = (
|
send_url = (
|
||||||
f"{self.ORIGIN}/cgi-bin/message/send?access_token={self.get_access_token()}"
|
"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
|
||||||
|
+ self.get_access_token()
|
||||||
)
|
)
|
||||||
send_values = {
|
send_values = {
|
||||||
"touser": touser,
|
"touser": touser,
|
||||||
@@ -473,7 +406,8 @@ class WeCom:
|
|||||||
|
|
||||||
def send_mpnews(self, title, message, media_id, touser="@all"):
|
def send_mpnews(self, title, message, media_id, touser="@all"):
|
||||||
send_url = (
|
send_url = (
|
||||||
f"{self.ORIGIN}/cgi-bin/message/send?access_token={self.get_access_token()}"
|
"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
|
||||||
|
+ self.get_access_token()
|
||||||
)
|
)
|
||||||
send_values = {
|
send_values = {
|
||||||
"touser": touser,
|
"touser": touser,
|
||||||
@@ -507,11 +441,7 @@ def wecom_bot(title: str, content: str) -> None:
|
|||||||
return
|
return
|
||||||
print("企业微信机器人服务启动")
|
print("企业微信机器人服务启动")
|
||||||
|
|
||||||
origin = "https://qyapi.weixin.qq.com"
|
url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={push_config.get('QYWX_KEY')}"
|
||||||
if push_config.get("QYWX_ORIGIN"):
|
|
||||||
origin = push_config.get("QYWX_ORIGIN")
|
|
||||||
|
|
||||||
url = f"{origin}/cgi-bin/webhook/send?key={push_config.get('QYWX_KEY')}"
|
|
||||||
headers = {"Content-Type": "application/json;charset=utf-8"}
|
headers = {"Content-Type": "application/json;charset=utf-8"}
|
||||||
data = {"msgtype": "text", "text": {"content": f"{title}\n\n{content}"}}
|
data = {"msgtype": "text", "text": {"content": f"{title}\n\n{content}"}}
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
@@ -569,268 +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 smtp(title: str, content: str) -> None:
|
|
||||||
"""
|
|
||||||
使用 SMTP 邮件 推送消息。
|
|
||||||
"""
|
|
||||||
if (
|
|
||||||
not push_config.get("SMTP_SERVER")
|
|
||||||
or not push_config.get("SMTP_SSL")
|
|
||||||
or not push_config.get("SMTP_EMAIL")
|
|
||||||
or not push_config.get("SMTP_PASSWORD")
|
|
||||||
or not push_config.get("SMTP_NAME")
|
|
||||||
):
|
|
||||||
print(
|
|
||||||
"SMTP 邮件 的 SMTP_SERVER 或者 SMTP_SSL 或者 SMTP_EMAIL 或者 SMTP_PASSWORD 或者 SMTP_NAME 未设置!!\n取消推送"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
print("SMTP 邮件 服务启动")
|
|
||||||
|
|
||||||
message = MIMEText(content, "plain", "utf-8")
|
|
||||||
message["From"] = formataddr(
|
|
||||||
(
|
|
||||||
Header(push_config.get("SMTP_NAME"), "utf-8").encode(),
|
|
||||||
push_config.get("SMTP_EMAIL"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
message["To"] = formataddr(
|
|
||||||
(
|
|
||||||
Header(push_config.get("SMTP_NAME"), "utf-8").encode(),
|
|
||||||
push_config.get("SMTP_EMAIL"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
message["Subject"] = Header(title, "utf-8")
|
|
||||||
|
|
||||||
try:
|
|
||||||
smtp_server = (
|
|
||||||
smtplib.SMTP_SSL(push_config.get("SMTP_SERVER"))
|
|
||||||
if push_config.get("SMTP_SSL") == "true"
|
|
||||||
else smtplib.SMTP(push_config.get("SMTP_SERVER"))
|
|
||||||
)
|
|
||||||
smtp_server.login(
|
|
||||||
push_config.get("SMTP_EMAIL"), push_config.get("SMTP_PASSWORD")
|
|
||||||
)
|
|
||||||
smtp_server.sendmail(
|
|
||||||
push_config.get("SMTP_EMAIL"),
|
|
||||||
push_config.get("SMTP_EMAIL"),
|
|
||||||
message.as_bytes(),
|
|
||||||
)
|
|
||||||
smtp_server.close()
|
|
||||||
print("SMTP 邮件 推送成功!")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"SMTP 邮件 推送失败!{e}")
|
|
||||||
|
|
||||||
|
|
||||||
def pushme(title: str, content: str) -> None:
|
|
||||||
"""
|
|
||||||
使用 PushMe 推送消息。
|
|
||||||
"""
|
|
||||||
if not push_config.get("PUSHME_KEY"):
|
|
||||||
print("PushMe 服务的 PUSHME_KEY 未设置!!\n取消推送")
|
|
||||||
return
|
|
||||||
print("PushMe 服务启动")
|
|
||||||
|
|
||||||
url = f'https://push.i-i.me/?push_key={push_config.get("PUSHME_KEY")}'
|
|
||||||
data = {
|
|
||||||
"title": title,
|
|
||||||
"content": content,
|
|
||||||
}
|
|
||||||
response = requests.post(url, data=data)
|
|
||||||
|
|
||||||
if response.status_code == 200 and response.text == "success":
|
|
||||||
print("PushMe 推送成功!")
|
|
||||||
else:
|
|
||||||
print(f"PushMe 推送失败!{response.status_code} {response.text}")
|
|
||||||
|
|
||||||
|
|
||||||
def chronocat(title: str, content: str) -> None:
|
|
||||||
"""
|
|
||||||
使用 CHRONOCAT 推送消息。
|
|
||||||
"""
|
|
||||||
if (
|
|
||||||
not push_config.get("CHRONOCAT_URL")
|
|
||||||
or not push_config.get("CHRONOCAT_QQ")
|
|
||||||
or not push_config.get("CHRONOCAT_TOKEN")
|
|
||||||
):
|
|
||||||
print("CHRONOCAT 服务的 CHRONOCAT_URL 或 CHRONOCAT_QQ 未设置!!\n取消推送")
|
|
||||||
return
|
|
||||||
|
|
||||||
print("CHRONOCAT 服务启动")
|
|
||||||
|
|
||||||
user_ids = re.findall(r"user_id=(\d+)", push_config.get("CHRONOCAT_QQ"))
|
|
||||||
group_ids = re.findall(r"group_id=(\d+)", push_config.get("CHRONOCAT_QQ"))
|
|
||||||
|
|
||||||
url = f'{push_config.get("CHRONOCAT_URL")}/api/message/send'
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Authorization": f'Bearer {push_config.get("CHRONOCAT_TOKEN")}',
|
|
||||||
}
|
|
||||||
|
|
||||||
for chat_type, ids in [(1, user_ids), (2, group_ids)]:
|
|
||||||
if not ids:
|
|
||||||
continue
|
|
||||||
for chat_id in ids:
|
|
||||||
data = {
|
|
||||||
"peer": {"chatType": chat_type, "peerUin": chat_id},
|
|
||||||
"elements": [
|
|
||||||
{
|
|
||||||
"elementType": 1,
|
|
||||||
"textElement": {"content": f"{title}\n\n{content}"},
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}
|
|
||||||
response = requests.post(url, headers=headers, data=json.dumps(data))
|
|
||||||
if response.status_code == 200:
|
|
||||||
if chat_type == 1:
|
|
||||||
print(f"QQ个人消息:{ids}推送成功!")
|
|
||||||
else:
|
|
||||||
print(f"QQ群消息:{ids}推送成功!")
|
|
||||||
else:
|
|
||||||
if chat_type == 1:
|
|
||||||
print(f"QQ个人消息:{ids}推送失败!")
|
|
||||||
else:
|
|
||||||
print(f"QQ群消息:{ids}推送失败!")
|
|
||||||
|
|
||||||
|
|
||||||
def parse_headers(headers):
|
|
||||||
if not headers:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
parsed = {}
|
|
||||||
lines = headers.split("\n")
|
|
||||||
|
|
||||||
for line in lines:
|
|
||||||
i = line.find(":")
|
|
||||||
if i == -1:
|
|
||||||
continue
|
|
||||||
|
|
||||||
key = line[:i].strip().lower()
|
|
||||||
val = line[i + 1 :].strip()
|
|
||||||
parsed[key] = parsed.get(key, "") + ", " + val if key in parsed else val
|
|
||||||
|
|
||||||
return parsed
|
|
||||||
|
|
||||||
|
|
||||||
def parse_body(body, content_type):
|
|
||||||
if not body:
|
|
||||||
return ""
|
|
||||||
|
|
||||||
parsed = {}
|
|
||||||
lines = body.split("\n")
|
|
||||||
|
|
||||||
for line in lines:
|
|
||||||
i = line.find(":")
|
|
||||||
if i == -1:
|
|
||||||
continue
|
|
||||||
|
|
||||||
key = line[:i].strip().lower()
|
|
||||||
val = line[i + 1 :].strip()
|
|
||||||
|
|
||||||
if not key or key in parsed:
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_value = json.loads(val)
|
|
||||||
parsed[key] = json_value
|
|
||||||
except:
|
|
||||||
parsed[key] = val
|
|
||||||
|
|
||||||
if content_type == "application/x-www-form-urlencoded":
|
|
||||||
data = urlencode(parsed, doseq=True)
|
|
||||||
return data
|
|
||||||
|
|
||||||
if content_type == "application/json":
|
|
||||||
data = json.dumps(parsed)
|
|
||||||
return data
|
|
||||||
|
|
||||||
return parsed
|
|
||||||
|
|
||||||
|
|
||||||
def format_notify_content(url, body, title, content):
|
|
||||||
if "$title" not in url and "$title" not in body:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
formatted_url = url.replace("$title", urllib.parse.quote_plus(title)).replace(
|
|
||||||
"$content", urllib.parse.quote_plus(content)
|
|
||||||
)
|
|
||||||
formatted_body = body.replace("$title", title).replace("$content", content)
|
|
||||||
|
|
||||||
return formatted_url, formatted_body
|
|
||||||
|
|
||||||
|
|
||||||
def custom_notify(title: str, content: str) -> None:
|
|
||||||
"""
|
|
||||||
通过 自定义通知 推送消息。
|
|
||||||
"""
|
|
||||||
if not push_config.get("WEBHOOK_URL") or not push_config.get("WEBHOOK_METHOD"):
|
|
||||||
print("自定义通知的 WEBHOOK_URL 或 WEBHOOK_METHOD 未设置!!\n取消推送")
|
|
||||||
return
|
|
||||||
|
|
||||||
print("自定义通知服务启动")
|
|
||||||
|
|
||||||
WEBHOOK_URL = push_config.get("WEBHOOK_URL")
|
|
||||||
WEBHOOK_METHOD = push_config.get("WEBHOOK_METHOD")
|
|
||||||
WEBHOOK_CONTENT_TYPE = push_config.get("WEBHOOK_CONTENT_TYPE")
|
|
||||||
WEBHOOK_BODY = push_config.get("WEBHOOK_BODY")
|
|
||||||
WEBHOOK_HEADERS = push_config.get("WEBHOOK_HEADERS")
|
|
||||||
|
|
||||||
formatUrl, formatBody = format_notify_content(
|
|
||||||
WEBHOOK_URL, WEBHOOK_BODY, title, content
|
|
||||||
)
|
|
||||||
|
|
||||||
if not formatUrl and not formatBody:
|
|
||||||
print("请求头或者请求体中必须包含 $title 和 $content")
|
|
||||||
return
|
|
||||||
|
|
||||||
headers = parse_headers(WEBHOOK_HEADERS)
|
|
||||||
body = parse_body(formatBody, WEBHOOK_CONTENT_TYPE)
|
|
||||||
response = requests.request(
|
|
||||||
method=WEBHOOK_METHOD, url=formatUrl, headers=headers, timeout=15, data=body
|
|
||||||
)
|
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
print("自定义通知推送成功!")
|
|
||||||
else:
|
|
||||||
print(f"自定义通知推送失败!{response.status_code} {response.text}")
|
|
||||||
|
|
||||||
|
|
||||||
def one() -> str:
|
def one() -> str:
|
||||||
"""
|
"""
|
||||||
获取一条一言。
|
获取一条一言。
|
||||||
@@ -859,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"):
|
||||||
@@ -871,30 +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)
|
|
||||||
if (
|
|
||||||
push_config.get("SMTP_SERVER")
|
|
||||||
and push_config.get("SMTP_SSL")
|
|
||||||
and push_config.get("SMTP_EMAIL")
|
|
||||||
and push_config.get("SMTP_PASSWORD")
|
|
||||||
and push_config.get("SMTP_NAME")
|
|
||||||
):
|
|
||||||
notify_function.append(smtp)
|
|
||||||
if push_config.get("PUSHME_KEY"):
|
|
||||||
notify_function.append(pushme)
|
|
||||||
if (
|
|
||||||
push_config.get("CHRONOCAT_URL")
|
|
||||||
and push_config.get("CHRONOCAT_QQ")
|
|
||||||
and push_config.get("CHRONOCAT_TOKEN")
|
|
||||||
):
|
|
||||||
notify_function.append(chronocat)
|
|
||||||
if push_config.get("WEBHOOK_URL") and push_config.get("WEBHOOK_METHOD"):
|
|
||||||
notify_function.append(custom_notify)
|
|
||||||
|
|
||||||
|
|
||||||
def send(title: str, content: str) -> None:
|
def send(title: str, content: str) -> None:
|
||||||
@@ -902,13 +544,6 @@ def send(title: str, content: str) -> None:
|
|||||||
print(f"{title} 推送内容为空!")
|
print(f"{title} 推送内容为空!")
|
||||||
return
|
return
|
||||||
|
|
||||||
# 根据标题跳过一些消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔
|
|
||||||
skipTitle = os.getenv("SKIP_PUSH_TITLE")
|
|
||||||
if skipTitle:
|
|
||||||
if title in re.split("\n", skipTitle):
|
|
||||||
print(f"{title} 在SKIP_PUSH_TITLE环境变量内,跳过推送!")
|
|
||||||
return
|
|
||||||
|
|
||||||
hitokoto = push_config.get("HITOKOTO")
|
hitokoto = push_config.get("HITOKOTO")
|
||||||
|
|
||||||
text = one() if hitokoto else ""
|
text = one() if hitokoto else ""
|
||||||
|
|||||||
+5
-1
@@ -3,8 +3,12 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"crypto-js": "^4.0.0",
|
||||||
|
"download": "^8.0.0",
|
||||||
|
"http-server": "^0.12.3",
|
||||||
"got": "^11.5.1",
|
"got": "^11.5.1",
|
||||||
"nodemailer": "^6.8.0",
|
"qrcode-terminal": "^0.12.0",
|
||||||
|
"request": "^2.88.2",
|
||||||
"tough-cookie": "^4.0.0",
|
"tough-cookie": "^4.0.0",
|
||||||
"tunnel": "0.0.6",
|
"tunnel": "0.0.6",
|
||||||
"ws": "^7.4.3"
|
"ws": "^7.4.3"
|
||||||
|
|||||||
+2
-2
@@ -5,14 +5,14 @@ const envFound = dotenv.config();
|
|||||||
const accessKey = process.env.QINIU_AK;
|
const accessKey = process.env.QINIU_AK;
|
||||||
const secretKey = process.env.QINIU_SK;
|
const secretKey = process.env.QINIU_SK;
|
||||||
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
|
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
|
||||||
const key = 'version.yaml';
|
const key = 'version.ts';
|
||||||
const options = {
|
const options = {
|
||||||
scope: `${process.env.QINIU_SCOPE}:${key}`,
|
scope: `${process.env.QINIU_SCOPE}:${key}`,
|
||||||
};
|
};
|
||||||
const putPolicy = new qiniu.rs.PutPolicy(options);
|
const putPolicy = new qiniu.rs.PutPolicy(options);
|
||||||
const uploadToken = putPolicy.uploadToken(mac);
|
const uploadToken = putPolicy.uploadToken(mac);
|
||||||
|
|
||||||
const localFile = 'version.yaml';
|
const localFile = 'src/version.ts';
|
||||||
const config = new qiniu.conf.Config({ zone: qiniu.zone.Zone_z1 });
|
const config = new qiniu.conf.Config({ zone: qiniu.zone.Zone_z1 });
|
||||||
const formUploader = new qiniu.form_up.FormUploader(config);
|
const formUploader = new qiniu.form_up.FormUploader(config);
|
||||||
const putExtra = new qiniu.form_up.PutExtra(
|
const putExtra = new qiniu.form_up.PutExtra(
|
||||||
|
|||||||
+28
-75
@@ -1,25 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
create_token() {
|
|
||||||
local token_command="tsx ${dir_root}/back/token.ts"
|
|
||||||
local token_file="${dir_root}/static/build/token.js"
|
|
||||||
if [[ -f $token_file ]]; then
|
|
||||||
token_command="node ${token_file}"
|
|
||||||
fi
|
|
||||||
token=$(eval "$token_command")
|
|
||||||
}
|
|
||||||
|
|
||||||
get_token() {
|
get_token() {
|
||||||
if [[ -f $file_auth_token ]]; then
|
token=$(ts-node-transpile-only "$dir_shell/token.ts")
|
||||||
token=$(cat $file_auth_token | jq -r .value)
|
|
||||||
local expiration=$(cat $file_auth_token | jq -r .expiration)
|
|
||||||
local currentTimeStamp=$(date +%s)
|
|
||||||
if [[ $currentTimeStamp -ge $expiration ]]; then
|
|
||||||
create_token
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
create_token
|
|
||||||
fi
|
|
||||||
}
|
}
|
||||||
|
|
||||||
add_cron_api() {
|
add_cron_api() {
|
||||||
@@ -28,16 +10,10 @@ add_cron_api() {
|
|||||||
local schedule=$(echo "$1" | awk -F ":" '{print $1}')
|
local schedule=$(echo "$1" | awk -F ":" '{print $1}')
|
||||||
local command=$(echo "$1" | awk -F ":" '{print $2}')
|
local command=$(echo "$1" | awk -F ":" '{print $2}')
|
||||||
local name=$(echo "$1" | awk -F ":" '{print $3}')
|
local name=$(echo "$1" | awk -F ":" '{print $3}')
|
||||||
local sub_id=$(echo "$1" | awk -F ":" '{print $4}')
|
|
||||||
else
|
else
|
||||||
local schedule="$1"
|
local schedule=$1
|
||||||
local command="$2"
|
local command=$2
|
||||||
local name="$3"
|
local name=$3
|
||||||
local sub_id="$4"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! $sub_id ]]; then
|
|
||||||
sub_id="null"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
@@ -49,11 +25,11 @@ add_cron_api() {
|
|||||||
-H "Origin: http://0.0.0.0:5700" \
|
-H "Origin: http://0.0.0.0:5700" \
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
-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" \
|
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
||||||
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \
|
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
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 "$name -> 添加成功"
|
echo -e "$name -> 添加成功"
|
||||||
else
|
else
|
||||||
@@ -69,10 +45,10 @@ update_cron_api() {
|
|||||||
local name=$(echo "$1" | awk -F ":" '{print $3}')
|
local name=$(echo "$1" | awk -F ":" '{print $3}')
|
||||||
local id=$(echo "$1" | awk -F ":" '{print $4}')
|
local id=$(echo "$1" | awk -F ":" '{print $4}')
|
||||||
else
|
else
|
||||||
local schedule="$1"
|
local schedule=$1
|
||||||
local command="$2"
|
local command=$2
|
||||||
local name="$3"
|
local name=$3
|
||||||
local id="$4"
|
local id=$4
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
@@ -88,8 +64,8 @@ update_cron_api() {
|
|||||||
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\",\"id\":\"$id\"}" \
|
--data-raw "{\"name\":\"$name\",\"command\":\"$command\",\"schedule\":\"$schedule\",\"id\":\"$id\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
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 "$name -> 更新成功"
|
echo -e "$name -> 更新成功"
|
||||||
else
|
else
|
||||||
@@ -103,8 +79,8 @@ update_cron_command_api() {
|
|||||||
local command=$(echo "$1" | awk -F ":" '{print $1}')
|
local command=$(echo "$1" | awk -F ":" '{print $1}')
|
||||||
local id=$(echo "$1" | awk -F ":" '{print $2}')
|
local id=$(echo "$1" | awk -F ":" '{print $2}')
|
||||||
else
|
else
|
||||||
local command="$1"
|
local command=$1
|
||||||
local id="$2"
|
local id=$2
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
@@ -120,8 +96,8 @@ update_cron_command_api() {
|
|||||||
--data-raw "{\"command\":\"$command\",\"id\":\"$id\"}" \
|
--data-raw "{\"command\":\"$command\",\"id\":\"$id\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
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 "$command -> 更新成功"
|
echo -e "$command -> 更新成功"
|
||||||
else
|
else
|
||||||
@@ -130,7 +106,7 @@ update_cron_command_api() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
del_cron_api() {
|
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/open/crons?t=$currentTimeStamp" \
|
||||||
@@ -145,8 +121,8 @@ del_cron_api() {
|
|||||||
--data-raw "[$ids]" \
|
--data-raw "[$ids]" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
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 "成功"
|
echo -e "成功"
|
||||||
else
|
else
|
||||||
@@ -175,16 +151,16 @@ update_cron() {
|
|||||||
--data-raw "{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime}" \
|
--data-raw "{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
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"
|
echo -e "\n## 更新任务状态失败(${message})\n" >> $dir_log/$log_path
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
notify_api() {
|
notify_api() {
|
||||||
local title="$1"
|
local title=$1
|
||||||
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/open/system/notify?t=$currentTimeStamp" \
|
||||||
@@ -199,36 +175,13 @@ notify_api() {
|
|||||||
--data-raw "{\"title\":\"$title\",\"content\":\"$content\"}" \
|
--data-raw "{\"title\":\"$title\",\"content\":\"$content\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
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 "通知发送成功🎉"
|
echo -e "通知发送成功"
|
||||||
else
|
else
|
||||||
echo -e "通知失败(${message})"
|
echo -e "通知失败(${message})"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
find_cron_api() {
|
|
||||||
local params="$1"
|
|
||||||
local currentTimeStamp=$(date +%s)
|
|
||||||
local api=$(
|
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/detail?$params&t=$currentTimeStamp" \
|
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer $token" \
|
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--compressed
|
|
||||||
)
|
|
||||||
data=$(echo "$api" | jq -r .data)
|
|
||||||
if [[ $data == 'null' ]]; then
|
|
||||||
echo -e ""
|
|
||||||
else
|
|
||||||
name=$(echo "$api" | jq -r .data.name)
|
|
||||||
echo -e "$name"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
get_token
|
get_token
|
||||||
|
|||||||
Executable → Regular
+9
-4
@@ -1,5 +1,9 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
## 导入通用变量与函数
|
||||||
|
dir_shell=$QL_DIR/shell
|
||||||
|
. $dir_shell/share.sh
|
||||||
|
|
||||||
if [[ -z ${BotRepoUrl} ]]; then
|
if [[ -z ${BotRepoUrl} ]]; then
|
||||||
url="https://github.com/SuMaiKaDe/bot.git"
|
url="https://github.com/SuMaiKaDe/bot.git"
|
||||||
repo_path="${dir_repo}/dockerbot"
|
repo_path="${dir_repo}/dockerbot"
|
||||||
@@ -31,10 +35,11 @@ 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
|
||||||
if [[ ! $(pip3 show "${LREAD%%=*}" 2>/dev/null) ]]; then
|
do
|
||||||
|
if [[ ! $(pip3 show "${LREAD%%=*}" 2>/dev/null) ]]; then
|
||||||
pip3 --default-timeout=100 install ${LREAD}
|
pip3 --default-timeout=100 install ${LREAD}
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
echo -e "\npython3依赖安装成功...\n"
|
echo -e "\npython3依赖安装成功...\n"
|
||||||
@@ -42,6 +47,6 @@ echo -e "\npython3依赖安装成功...\n"
|
|||||||
echo -e "4、启动bot程序...\n"
|
echo -e "4、启动bot程序...\n"
|
||||||
make_dir $dir_log/bot
|
make_dir $dir_log/bot
|
||||||
cd $dir_data
|
cd $dir_data
|
||||||
ps -eo pid,command | grep "python3 -m jbot" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
|
ps -ef | grep "python3 -m jbot" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
|
||||||
nohup python3 -m jbot >$dir_log/bot/nohup.log 2>&1 &
|
nohup python3 -m jbot >$dir_log/bot/nohup.log 2>&1 &
|
||||||
echo -e "bot启动成功...\n"
|
echo -e "bot启动成功...\n"
|
||||||
|
|||||||
Executable → Regular
+19
-18
@@ -1,5 +1,9 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
dir_shell=$QL_DIR/shell
|
||||||
|
. $dir_shell/share.sh
|
||||||
|
. $dir_shell/api.sh
|
||||||
|
|
||||||
reset_env() {
|
reset_env() {
|
||||||
echo -e "---> 1. 开始检测配置文件\n"
|
echo -e "---> 1. 开始检测配置文件\n"
|
||||||
fix_config
|
fix_config
|
||||||
@@ -25,7 +29,8 @@ copy_dep() {
|
|||||||
echo -e "---> 通知文件复制完成\n"
|
echo -e "---> 通知文件复制完成\n"
|
||||||
|
|
||||||
echo -e "---> 2. 复制nginx配置文件\n"
|
echo -e "---> 2. 复制nginx配置文件\n"
|
||||||
init_nginx
|
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||||
|
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
||||||
echo -e "---> 配置文件复制完成\n"
|
echo -e "---> 配置文件复制完成\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,12 +38,12 @@ pm2_log() {
|
|||||||
echo -e "---> pm2日志"
|
echo -e "---> pm2日志"
|
||||||
local panelOut="/root/.pm2/logs/panel-out.log"
|
local panelOut="/root/.pm2/logs/panel-out.log"
|
||||||
local panelError="/root/.pm2/logs/panel-error.log"
|
local panelError="/root/.pm2/logs/panel-error.log"
|
||||||
tail -n 300 "$panelOut"
|
tail -n 100 "$panelOut"
|
||||||
tail -n 300 "$panelError"
|
tail -n 100 "$panelError"
|
||||||
}
|
}
|
||||||
|
|
||||||
check_nginx() {
|
check_nginx() {
|
||||||
local nginxPid=$(ps -eo pid,command | grep nginx | grep -v grep)
|
local nginxPid=$(ps -ef | grep nginx | grep -v grep)
|
||||||
echo -e "=====> 检测nginx服务\n$nginxPid"
|
echo -e "=====> 检测nginx服务\n$nginxPid"
|
||||||
if [[ $nginxPid ]]; then
|
if [[ $nginxPid ]]; then
|
||||||
echo -e "\n=====> nginx服务正常\n"
|
echo -e "\n=====> nginx服务正常\n"
|
||||||
@@ -54,6 +59,9 @@ check_ql() {
|
|||||||
echo -e "\n=====> 检测面板\n\n$api\n"
|
echo -e "\n=====> 检测面板\n\n$api\n"
|
||||||
if [[ $api =~ "<div id=\"root\"></div>" ]]; then
|
if [[ $api =~ "<div id=\"root\"></div>" ]]; then
|
||||||
echo -e "=====> 面板服务启动正常\n"
|
echo -e "=====> 面板服务启动正常\n"
|
||||||
|
else
|
||||||
|
echo -e "=====> 面板服务异常,重置基础环境\n"
|
||||||
|
reset_env
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,8 +69,9 @@ check_pm2() {
|
|||||||
pm2_log
|
pm2_log
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/system?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5600/api/user?t=$currentTimeStamp" \
|
||||||
-H 'Accept: */*' \
|
-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 '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 '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' \
|
-H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \
|
||||||
@@ -71,24 +80,16 @@ check_pm2() {
|
|||||||
echo -e "\n=====> 检测后台\n\n$api\n"
|
echo -e "\n=====> 检测后台\n\n$api\n"
|
||||||
if [[ $api =~ "{\"code\"" ]]; then
|
if [[ $api =~ "{\"code\"" ]]; then
|
||||||
echo -e "=====> 后台服务启动正常\n"
|
echo -e "=====> 后台服务启动正常\n"
|
||||||
|
else
|
||||||
|
echo -e "=====> 后台服务异常,重置基础环境并重启后台\n"
|
||||||
|
reset_env
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
echo -e "=====> 开始检测"
|
echo -e "=====> 开始检测"
|
||||||
npm i -g pnpm@8.3.1
|
npm i -g pnpm
|
||||||
patch_version
|
pnpm add -g pm2
|
||||||
|
|
||||||
if [[ $PipMirror ]]; then
|
|
||||||
pip3 config set global.index-url $PipMirror
|
|
||||||
fi
|
|
||||||
if [[ $NpmMirror ]]; then
|
|
||||||
cd && pnpm config set registry $NpmMirror
|
|
||||||
pnpm install -g
|
|
||||||
fi
|
|
||||||
|
|
||||||
pnpm add -g pm2 tsx
|
|
||||||
reset_env
|
|
||||||
copy_dep
|
copy_dep
|
||||||
check_ql
|
check_ql
|
||||||
check_nginx
|
check_nginx
|
||||||
|
|||||||
-248
@@ -1,248 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
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 "任务随机延迟 $delay_second 秒,配置文件参数 RandomDelay 置空可取消延迟 \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}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
|
|
||||||
[[ -z ${array_scripts_name[i]} ]] && array_scripts_name[i]="<未识别出活动名称>"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
cd $dir_current
|
|
||||||
}
|
|
||||||
|
|
||||||
## 使用说明
|
|
||||||
usage() {
|
|
||||||
gen_array_scripts
|
|
||||||
echo -e "task命令运行本程序自动添加进crontab的脚本,需要输入脚本的绝对路径或去掉 “$dir_scripts/” 目录后的相对路径(定时任务中请写作相对路径),用法为:"
|
|
||||||
echo -e "1.$cmd_task <file_name> # 依次执行,如果设置了随机延迟,将随机延迟一定秒数"
|
|
||||||
echo -e "2.$cmd_task <file_name> now # 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日志,同时记录在日志文件中"
|
|
||||||
echo -e "3.$cmd_task <file_name> conc <环境变量名称> <账号编号,空格分隔>(可选的) # 并发执行,无论是否设置了随机延迟,均立即运行,前台不产生日志,直接记录在日志文件中,且可指定账号执行"
|
|
||||||
echo -e "4.$cmd_task <file_name> desi <环境变量名称> <账号编号,空格分隔> # 指定账号执行,无论是否设置了随机延迟,均立即运行"
|
|
||||||
if [[ ${#array_scripts[*]} -gt 0 ]]; then
|
|
||||||
echo -e "\n当前有以下脚本可以运行:"
|
|
||||||
for ((i = 0; i < ${#array_scripts[*]}; i++)); do
|
|
||||||
echo -e "$(($i + 1)). ${array_scripts_name[i]}:${array_scripts[i]}"
|
|
||||||
done
|
|
||||||
else
|
|
||||||
echo -e "\n暂无脚本可以执行"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
## run nohup,$1:文件名,不含路径,带后缀
|
|
||||||
run_nohup() {
|
|
||||||
local file_name=$1
|
|
||||||
nohup node $file_name &>$log_path &
|
|
||||||
}
|
|
||||||
|
|
||||||
check_server() {
|
|
||||||
if [[ $cpu_warn ]] && [[ $mem_warn ]] && [[ $disk_warn ]]; then
|
|
||||||
local top_result=$(top -b -n 1)
|
|
||||||
cpu_use=$(echo "$top_result" | grep CPU | grep -v -E 'grep|PID' | awk '{print $2}' | cut -f 1 -d "%" | head -n 1)
|
|
||||||
|
|
||||||
mem_free=$(free -m | grep "Mem" | awk '{print $3}' | head -n 1)
|
|
||||||
mem_total=$(free -m | grep "Mem" | awk '{print $2}' | head -n 1)
|
|
||||||
mem_use=$(printf "%d%%" $((mem_free * 100 / mem_total)) | cut -f 1 -d "%" | head -n 1)
|
|
||||||
|
|
||||||
disk_use=$(df -P | grep /dev | grep -v -E '(tmp|boot|shm)' | awk '{print $5}' | cut -f 1 -d "%" | head -n 1)
|
|
||||||
if [[ $cpu_use -gt $cpu_warn ]] && [[ $cpu_warn ]] || [[ $mem_free -lt $mem_warn ]] || [[ $disk_use -gt $disk_warn ]]; then
|
|
||||||
local resource=$(echo "$top_result" | grep -v -E 'grep|Mem|idle|Load|tr' | awk '{$2="";$3="";$4="";$5="";$7="";print $0}' | head -n 10 | tr '\n' '|' | sed s/\|/\\\\n/g)
|
|
||||||
notify_api "服务器资源异常警告" "当前CPU占用 $cpu_use% 内存占用 $mem_use% 磁盘占用 $disk_use% \n资源占用详情 \n\n $resource"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
env_str_to_array() {
|
|
||||||
local IFS="&"
|
|
||||||
read -ra array <<<"${!env_param}"
|
|
||||||
}
|
|
||||||
|
|
||||||
## 正常运行单个脚本,$1:传入参数
|
|
||||||
run_normal() {
|
|
||||||
local file_param=$1
|
|
||||||
if [[ $# -eq 1 ]] && [[ "$real_time" != "true" ]] && [[ "$no_delay" != "true" ]]; 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 "${script_params[@]}"
|
|
||||||
}
|
|
||||||
|
|
||||||
## 并发执行时,设定的 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
|
|
||||||
|
|
||||||
env_str_to_array
|
|
||||||
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=$(
|
|
||||||
IFS="&"
|
|
||||||
echo "${array_run[*]}"
|
|
||||||
)
|
|
||||||
[[ ! -z $cookieStr ]] && export "${env_param}=${cookieStr}"
|
|
||||||
|
|
||||||
env_str_to_array
|
|
||||||
single_log_time=$(date "+%Y-%m-%d-%H-%M-%S.%3N")
|
|
||||||
|
|
||||||
cd $dir_scripts
|
|
||||||
local relative_path="${file_param%/*}"
|
|
||||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
|
||||||
cd ${relative_path}
|
|
||||||
file_param=${file_param/$relative_path\//}
|
|
||||||
fi
|
|
||||||
for i in "${!array[@]}"; do
|
|
||||||
export "${env_param}=${array[i]}"
|
|
||||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
|
||||||
eval $timeoutCmd $which_program $file_param "${script_params[@]}" &>$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
|
|
||||||
|
|
||||||
env_str_to_array
|
|
||||||
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=$(
|
|
||||||
IFS="&"
|
|
||||||
echo "${array_run[*]}"
|
|
||||||
)
|
|
||||||
[[ ! -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 "${script_params[@]}"
|
|
||||||
}
|
|
||||||
|
|
||||||
## 运行其他命令
|
|
||||||
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_start "${task_shell_params[@]}"
|
|
||||||
run_task_before "${task_shell_params[@]}"
|
|
||||||
main "${task_shell_params[@]}"
|
|
||||||
run_task_after "${task_shell_params[@]}"
|
|
||||||
handle_task_end "${task_shell_params[@]}"
|
|
||||||
Executable → Regular
+2
-2
@@ -11,9 +11,9 @@ echo -e "提交master代码"
|
|||||||
git push
|
git push
|
||||||
|
|
||||||
echo -e "更新cdn文件"
|
echo -e "更新cdn文件"
|
||||||
tsx sample/tool.ts
|
ts-node sample/tool.ts
|
||||||
|
|
||||||
string=$(cat version.yaml | grep "version" | egrep "[^ ]*" -o | egrep "\d\.*")
|
string=$(cat src/version.ts | grep "version" | egrep "[^\']*" -o | egrep "\d\.*")
|
||||||
version="v$string"
|
version="v$string"
|
||||||
echo -e "当前版本$version"
|
echo -e "当前版本$version"
|
||||||
|
|
||||||
|
|||||||
+6
-12
@@ -1,8 +1,12 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
## 导入通用变量与函数
|
||||||
|
dir_shell=$QL_DIR/shell
|
||||||
|
. $dir_shell/share.sh
|
||||||
|
|
||||||
days=$1
|
days=$1
|
||||||
|
|
||||||
## 删除运行脚本的旧日志
|
## 删除运行js脚本的旧日志
|
||||||
remove_js_log() {
|
remove_js_log() {
|
||||||
local log_full_path_list=$(find $dir_log/ -name "*.log")
|
local log_full_path_list=$(find $dir_log/ -name "*.log")
|
||||||
local diff_time
|
local diff_time
|
||||||
@@ -14,17 +18,7 @@ remove_js_log() {
|
|||||||
else
|
else
|
||||||
diff_time=$(($(date +%s) - $(date +%s -d "$log_date")))
|
diff_time=$(($(date +%s) - $(date +%s -d "$log_date")))
|
||||||
fi
|
fi
|
||||||
if [[ $diff_time -gt $((${days} * 86400)) ]]; then
|
[[ $diff_time -gt $((${days} * 86400)) ]] && rm -vf $log
|
||||||
local log_path=$(echo "$log" | sed "s,${dir_log}/,,g")
|
|
||||||
local result=$(find_cron_api "log_path=$log_path")
|
|
||||||
echo -e "查询文件 $log_path"
|
|
||||||
if [[ -z $result ]]; then
|
|
||||||
echo -e "删除中~"
|
|
||||||
rm -vf $log
|
|
||||||
else
|
|
||||||
echo -e "正在被 $result 使用,跳过~"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
}
|
}
|
||||||
|
|||||||
+101
-149
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
## 目录
|
## 目录
|
||||||
dir_root=$QL_DIR
|
dir_root=$QL_DIR
|
||||||
dir_tmp=$dir_root/.tmp
|
|
||||||
dir_data=$dir_root/data
|
dir_data=$dir_root/data
|
||||||
dir_shell=$dir_root/shell
|
dir_shell=$dir_root/shell
|
||||||
dir_sample=$dir_root/sample
|
dir_sample=$dir_root/sample
|
||||||
@@ -19,14 +18,12 @@ dir_update_log=$dir_log/update
|
|||||||
ql_static_repo=$dir_repo/static
|
ql_static_repo=$dir_repo/static
|
||||||
|
|
||||||
## 文件
|
## 文件
|
||||||
file_ecosystem_js=$dir_root/ecosystem.config.js
|
|
||||||
file_config_sample=$dir_sample/config.sample.sh
|
file_config_sample=$dir_sample/config.sample.sh
|
||||||
file_env=$dir_config/env.sh
|
file_env=$dir_config/env.sh
|
||||||
file_sharecode=$dir_config/sharecode.sh
|
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
|
||||||
@@ -36,6 +33,7 @@ file_notify_js_sample=$dir_sample/notify.js
|
|||||||
file_notify_py_sample=$dir_sample/notify.py
|
file_notify_py_sample=$dir_sample/notify.py
|
||||||
file_notify_py=$dir_scripts/notify.py
|
file_notify_py=$dir_scripts/notify.py
|
||||||
file_notify_js=$dir_scripts/sendNotify.js
|
file_notify_js=$dir_scripts/sendNotify.js
|
||||||
|
task_error_log_path=$dir_log/task_error.log
|
||||||
nginx_app_conf=$dir_root/docker/front.conf
|
nginx_app_conf=$dir_root/docker/front.conf
|
||||||
nginx_conf=$dir_root/docker/nginx.conf
|
nginx_conf=$dir_root/docker/nginx.conf
|
||||||
dep_notify_py=$dir_dep/notify.py
|
dep_notify_py=$dir_dep/notify.py
|
||||||
@@ -68,9 +66,7 @@ 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"}
|
||||||
ql_port=${QlPort:-"5700"}
|
|
||||||
command_timeout_time=${CommandTimeoutTime:-""}
|
|
||||||
proxy_url=${ProxyUrl:-""}
|
proxy_url=${ProxyUrl:-""}
|
||||||
file_extensions=${RepoFileExtensions:-"js py"}
|
file_extensions=${RepoFileExtensions:-"js py"}
|
||||||
current_branch=${QL_BRANCH}
|
current_branch=${QL_BRANCH}
|
||||||
@@ -80,17 +76,9 @@ 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}
|
|
||||||
mem_warn=${MemoryWarn}
|
|
||||||
disk_warn=${DiskWarn}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
set_proxy() {
|
set_proxy() {
|
||||||
local proxy="$1"
|
|
||||||
if [[ $proxy ]]; then
|
|
||||||
proxy_url="$proxy"
|
|
||||||
fi
|
|
||||||
if [[ $proxy_url ]]; then
|
if [[ $proxy_url ]]; then
|
||||||
export http_proxy="${proxy_url}"
|
export http_proxy="${proxy_url}"
|
||||||
export https_proxy="${proxy_url}"
|
export https_proxy="${proxy_url}"
|
||||||
@@ -174,7 +162,6 @@ define_cmd() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fix_config() {
|
fix_config() {
|
||||||
make_dir $dir_tmp
|
|
||||||
make_dir $dir_static
|
make_dir $dir_static
|
||||||
make_dir $dir_data
|
make_dir $dir_data
|
||||||
make_dir $dir_config
|
make_dir $dir_config
|
||||||
@@ -256,14 +243,26 @@ 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.npmmirror.com || 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.npmmirror.com || npm install --production
|
||||||
else
|
else
|
||||||
pnpm install --loglevel error --production
|
pnpm install --loglevel error --production --registry=https://registry.npmmirror.com || pnpm install --production --loglevel error
|
||||||
fi
|
fi
|
||||||
exit_status=$?
|
unset_proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
npm_install_1() {
|
||||||
|
local dir_current=$(pwd)
|
||||||
|
local dir_work=$1
|
||||||
|
|
||||||
|
cd $dir_work
|
||||||
|
echo -e "运行 npm install...\n"
|
||||||
|
npm_install_sub
|
||||||
|
[[ $? -ne 0 ]] && echo -e "\nnpm install 运行不成功,请进入 $dir_work 目录后手动运行 npm install...\n"
|
||||||
|
cd $dir_current
|
||||||
}
|
}
|
||||||
|
|
||||||
npm_install_2() {
|
npm_install_2() {
|
||||||
@@ -271,8 +270,12 @@ npm_install_2() {
|
|||||||
local dir_work=$1
|
local dir_work=$1
|
||||||
|
|
||||||
cd $dir_work
|
cd $dir_work
|
||||||
echo -e "安装 $dir_work 依赖包...\n"
|
echo -e "检测到 $dir_work 的依赖包有变化,运行 npm install...\n"
|
||||||
npm_install_sub
|
npm_install_sub
|
||||||
|
if [[ $? -ne 0 ]]; then
|
||||||
|
echo -e "\n安装 $dir_work 的依赖包运行不成功,再次尝试一遍...\n"
|
||||||
|
npm_install_1 $dir_work
|
||||||
|
fi
|
||||||
cd $dir_current
|
cd $dir_current
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,22 +287,74 @@ diff_and_copy() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
update_depend() {
|
||||||
|
local dir_current=$(pwd)
|
||||||
|
|
||||||
|
if [[ ! -s $dir_scripts/package.json ]] || [[ $(diff $dir_sample/package.json $dir_scripts/package.json) ]]; then
|
||||||
|
cp -f $dir_sample/package.json $dir_scripts/package.json
|
||||||
|
npm_install_2 $dir_scripts
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd $dir_current
|
||||||
|
}
|
||||||
|
|
||||||
git_clone_scripts() {
|
git_clone_scripts() {
|
||||||
local url="$1"
|
local url=$1
|
||||||
local dir="$2"
|
local dir=$2
|
||||||
local branch="$3"
|
local branch=$3
|
||||||
local proxy="$4"
|
|
||||||
[[ $branch ]] && local part_cmd="-b $branch "
|
[[ $branch ]] && local part_cmd="-b $branch "
|
||||||
echo -e "开始拉取仓库 ${uniq_path} 到 $dir\n"
|
echo -e "开始克隆仓库 $url 到 $dir\n"
|
||||||
|
|
||||||
set_proxy "$proxy"
|
set_proxy
|
||||||
|
git clone $part_cmd $url $dir
|
||||||
git clone --depth=1 $part_cmd $url $dir 2>&1
|
|
||||||
exit_status=$?
|
exit_status=$?
|
||||||
|
|
||||||
unset_proxy
|
unset_proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
git_pull_scripts() {
|
||||||
|
local dir_current=$(pwd)
|
||||||
|
local dir_work="$1"
|
||||||
|
local branch="$2"
|
||||||
|
cd $dir_work
|
||||||
|
echo -e "开始更新仓库:$dir_work\n"
|
||||||
|
|
||||||
|
set_proxy
|
||||||
|
git fetch --all
|
||||||
|
exit_status=$?
|
||||||
|
git pull &>/dev/null
|
||||||
|
unset_proxy
|
||||||
|
reset_branch "$branch"
|
||||||
|
|
||||||
|
cd $dir_current
|
||||||
|
}
|
||||||
|
|
||||||
|
reset_romote_url() {
|
||||||
|
local dir_current=$(pwd)
|
||||||
|
local dir_work=$1
|
||||||
|
local url=$2
|
||||||
|
local branch="$3"
|
||||||
|
|
||||||
|
if [[ -d "$dir_work/.git" ]]; then
|
||||||
|
cd $dir_work
|
||||||
|
[[ -f ".git/index.lock" ]] && rm -f .git/index.lock >/dev/null
|
||||||
|
git remote set-url origin $url &>/dev/null
|
||||||
|
|
||||||
|
local part_cmd=""
|
||||||
|
reset_branch "$branch"
|
||||||
|
cd $dir_current
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
reset_branch() {
|
||||||
|
local branch="$1"
|
||||||
|
if [[ $branch ]]; then
|
||||||
|
part_cmd="origin/${branch}"
|
||||||
|
git checkout -B "$branch"
|
||||||
|
git branch --set-upstream-to=$part_cmd $branch
|
||||||
|
fi
|
||||||
|
git reset --hard $part_cmd &>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
random_range() {
|
random_range() {
|
||||||
local beg=$1
|
local beg=$1
|
||||||
local end=$2
|
local end=$2
|
||||||
@@ -307,9 +362,19 @@ random_range() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
reload_pm2() {
|
reload_pm2() {
|
||||||
cd $dir_root
|
pm2 l &>/dev/null
|
||||||
pm2 flush &>/dev/null
|
|
||||||
env ALL_PROXY= HTTP_PROXY= HTTPS_PROXY= all_proxy= http_proxy= https_proxy= pm2 startOrGracefulReload $file_ecosystem_js --update-env
|
echo -e "启动面板服务\n"
|
||||||
|
pm2 delete panel --source-map-support --time &>/dev/null
|
||||||
|
pm2 start $dir_static/build/app.js -n panel --source-map-support --time &>/dev/null
|
||||||
|
|
||||||
|
echo -e "启动定时任务服务\n"
|
||||||
|
pm2 delete schedule --source-map-support --time &>/dev/null
|
||||||
|
pm2 start $dir_static/build/schedule.js -n schedule --source-map-support --time &>/dev/null
|
||||||
|
|
||||||
|
echo -e "启动公开服务\n"
|
||||||
|
pm2 delete public --source-map-support --time &>/dev/null
|
||||||
|
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
|
||||||
}
|
}
|
||||||
|
|
||||||
diff_time() {
|
diff_time() {
|
||||||
@@ -341,9 +406,9 @@ format_log_time() {
|
|||||||
local time="$2"
|
local time="$2"
|
||||||
|
|
||||||
if [[ $is_macos -eq 1 ]]; then
|
if [[ $is_macos -eq 1 ]]; then
|
||||||
echo $(date -j -f "$format" "$time" "+%Y-%m-%d-%H-%M-%S-%3N")
|
echo $(date -j -f "$format" "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||||
else
|
else
|
||||||
echo $(date -d "$time" "+%Y-%m-%d-%H-%M-%S-%3N")
|
echo $(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,123 +423,10 @@ format_timestamp() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
patch_version() {
|
|
||||||
git config --global pull.rebase false
|
|
||||||
|
|
||||||
cp -f $dir_root/.env.example $dir_root/.env
|
|
||||||
|
|
||||||
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 [[ -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_nginx() {
|
|
||||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
|
||||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
|
||||||
local location_url="/"
|
|
||||||
local aliasStr=""
|
|
||||||
local rootStr=""
|
|
||||||
if [[ $ql_base_url != "/" ]]; then
|
|
||||||
if [[ $ql_base_url != /* ]]; then
|
|
||||||
ql_base_url="/$ql_base_url"
|
|
||||||
fi
|
|
||||||
if [[ $ql_base_url != */ ]]; then
|
|
||||||
ql_base_url="$ql_base_url/"
|
|
||||||
fi
|
|
||||||
location_url="^~${ql_base_url%*/}"
|
|
||||||
aliasStr="alias ${dir_static}/dist;"
|
|
||||||
if ! grep -q "<base href=\"$ql_base_url\">" "${dir_static}/dist/index.html"; then
|
|
||||||
awk -v text="<base href=\"$ql_base_url\">" '/<link/ && !inserted {print text; inserted=1} 1' "${dir_static}/dist/index.html" >temp.html
|
|
||||||
mv temp.html "${dir_static}/dist/index.html"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
rootStr="root ${dir_static}/dist;"
|
|
||||||
fi
|
|
||||||
sed -i "s,QL_ALIAS_CONFIG,${aliasStr},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,QL_ROOT_CONFIG,${rootStr},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,QL_BASE_URL_LOCATION,${location_url},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,QL_BASE_URL,${ql_base_url},g" /etc/nginx/conf.d/front.conf
|
|
||||||
|
|
||||||
local ipv6=$(ip a | grep inet6)
|
|
||||||
local ipv6Str=""
|
|
||||||
if [[ $ipv6 ]]; then
|
|
||||||
ipv6Str="listen [::]:${ql_port} ipv6only=on;"
|
|
||||||
fi
|
|
||||||
|
|
||||||
local ipv4Str="listen ${ql_port};"
|
|
||||||
sed -i "s,IPV6_CONFIG,${ipv6Str},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,IPV4_CONFIG,${ipv4Str},g" /etc/nginx/conf.d/front.conf
|
|
||||||
}
|
|
||||||
|
|
||||||
handle_task_start() {
|
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
|
||||||
echo -e "## 开始执行... $begin_time\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
run_task_before() {
|
|
||||||
[[ $is_macos -eq 0 ]] && check_server
|
|
||||||
|
|
||||||
. $file_task_before "$@"
|
|
||||||
|
|
||||||
if [[ $task_before ]]; then
|
|
||||||
echo -e "执行前置命令\n"
|
|
||||||
eval "$task_before"
|
|
||||||
echo -e "\n执行前置命令结束\n"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
run_task_after() {
|
|
||||||
. $file_task_after "$@"
|
|
||||||
|
|
||||||
if [[ $task_after ]]; then
|
|
||||||
echo -e "\n执行后置命令\n"
|
|
||||||
eval "$task_after"
|
|
||||||
echo -e "\n执行后置命令结束"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
handle_task_end() {
|
|
||||||
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))
|
|
||||||
|
|
||||||
[[ "$diff_time" == 0 ]] && diff_time=1
|
|
||||||
|
|
||||||
echo -e "\n## 执行结束... $end_time 耗时 $diff_time 秒 "
|
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
|
||||||
}
|
|
||||||
|
|
||||||
init_env
|
init_env
|
||||||
detect_termux
|
detect_termux
|
||||||
detect_macos
|
detect_macos
|
||||||
define_cmd
|
define_cmd
|
||||||
|
fix_config
|
||||||
|
|
||||||
import_config $1
|
import_config $1 >$task_error_log_path 2>&1
|
||||||
|
|||||||
+330
-80
@@ -5,53 +5,87 @@ dir_shell=$QL_DIR/shell
|
|||||||
. $dir_shell/share.sh
|
. $dir_shell/share.sh
|
||||||
. $dir_shell/api.sh
|
. $dir_shell/api.sh
|
||||||
|
|
||||||
trap "single_hanle" 2 3 20 15 14 19 1
|
|
||||||
single_hanle() {
|
|
||||||
eval handle_task_end "$@" "$cmd"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
## 选择python3还是node
|
## 选择python3还是node
|
||||||
define_program() {
|
define_program() {
|
||||||
local file_param=$1
|
local file_param=$1
|
||||||
if [[ $file_param == *.js ]] || [[ $file_param == *.mjs ]]; then
|
if [[ $file_param == *.js ]]; then
|
||||||
which_program="node"
|
which_program="node"
|
||||||
elif [[ $file_param == *.py ]] || [[ $file_param == *.pyc ]]; then
|
elif [[ $file_param == *.py ]] || [[ $file_param == *.pyc ]]; then
|
||||||
which_program="python3"
|
which_program="python3"
|
||||||
elif [[ $file_param == *.sh ]]; then
|
elif [[ $file_param == *.sh ]]; then
|
||||||
which_program="bash"
|
which_program="bash"
|
||||||
elif [[ $file_param == *.ts ]]; then
|
elif [[ $file_param == *.ts ]]; then
|
||||||
if ! type tsx &>/dev/null; then
|
|
||||||
which_program="ts-node-transpile-only"
|
which_program="ts-node-transpile-only"
|
||||||
else
|
|
||||||
which_program="tsx"
|
|
||||||
fi
|
|
||||||
else
|
else
|
||||||
which_program=""
|
which_program=""
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
handle_log_path() {
|
random_delay() {
|
||||||
local file_param=$1
|
local random_delay_max=$RandomDelay
|
||||||
|
if [[ $random_delay_max ]] && [[ $random_delay_max -gt 0 ]]; then
|
||||||
if [[ -z $file_param ]]; then
|
local current_min=$(date "+%-M")
|
||||||
file_param="task"
|
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
|
||||||
|
|
||||||
if [[ -z $ID ]]; then
|
|
||||||
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}')
|
|
||||||
fi
|
fi
|
||||||
local suffix=""
|
}
|
||||||
if [[ ! -z $ID ]]; then
|
|
||||||
if [[ "$ID" -gt 0 ]] 2>/dev/null; then
|
## scripts目录下所有可运行脚本数组
|
||||||
suffix="_${ID}"
|
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
|
else
|
||||||
ID=""
|
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
|
||||||
|
define_program "$file_param"
|
||||||
|
if [[ $file_param == *.js ]]; then
|
||||||
|
if [[ $# -eq 1 ]]; then
|
||||||
|
random_delay
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
time=$(date "+$mtime_format")
|
local time=$(date "+$time_format")
|
||||||
log_time=$(format_log_time "$mtime_format" "$time")
|
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
|
||||||
@@ -63,80 +97,296 @@ 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"
|
||||||
|
|
||||||
if [[ $real_log_path ]]; then
|
|
||||||
log_path="$real_log_path"
|
|
||||||
fi
|
|
||||||
|
|
||||||
cmd="2>&1 | tee -a $dir_log/$log_path"
|
|
||||||
make_dir "$dir_log/$log_dir"
|
|
||||||
if [[ "$no_tee" == "true" ]]; then
|
|
||||||
cmd=">> $dir_log/$log_path 2>&1"
|
cmd=">> $dir_log/$log_path 2>&1"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(format_time "$time_format" "$time")
|
||||||
|
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||||
|
|
||||||
|
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||||
|
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||||
|
|
||||||
|
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||||
|
eval . $file_task_before "$@" $cmd
|
||||||
|
|
||||||
|
cd $dir_scripts
|
||||||
|
local relative_path="${file_param%/*}"
|
||||||
|
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||||
|
cd ${relative_path}
|
||||||
|
file_param=${file_param/$relative_path\//}
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$real_time" == "true" ]]; then
|
eval $timeoutCmd $which_program $file_param $cmd
|
||||||
cmd=""
|
|
||||||
fi
|
eval . $file_task_after "$@" $cmd
|
||||||
|
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||||
|
local end_timestamp=$(date "+%s")
|
||||||
|
local diff_time=$(expr $end_timestamp - $begin_timestamp)
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||||
|
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
format_params() {
|
## 并发执行时,设定的 RandomDelay 不会生效,即所有任务立即执行
|
||||||
time_format="%Y-%m-%d %H:%M:%S"
|
run_concurrent() {
|
||||||
if [[ $is_macos -eq 1 ]]; then
|
local file_param="$1"
|
||||||
mtime_format=$time_format
|
local env_param="$2"
|
||||||
else
|
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|")
|
||||||
mtime_format="%Y-%m-%d %H:%M:%S.%3N"
|
if [[ ! $env_param ]]; then
|
||||||
|
echo -e "\n 缺少并发运行的环境变量参数"
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
timeoutCmd=""
|
|
||||||
if [[ $command_timeout_time ]]; then
|
|
||||||
if type timeout &>/dev/null; then
|
|
||||||
timeoutCmd="timeout --foreground -s 2 -k 10s $command_timeout_time "
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
# params=$(echo "$@" | sed -E 's/([^ ])&([^ ])/\1\\\&\2/g')
|
|
||||||
|
|
||||||
# 分割 task 内置参数和脚本参数
|
local envs=$(eval echo "\$${env_param}")
|
||||||
task_shell_params=()
|
local array=($(echo $envs | sed 's/&/ /g'))
|
||||||
script_params=()
|
local tempArr=$(echo $num_param | perl -pe "s|(\d+)(-\|~\|_)(\d+)|{\1..\3}|g")
|
||||||
found_double_dash=false
|
local runArr=($(eval echo $tempArr))
|
||||||
|
runArr=($(awk -v RS=' ' '!a[$1]++' <<< ${runArr[@]}))
|
||||||
|
|
||||||
for arg in "$@"; do
|
local n=0
|
||||||
if $found_double_dash; then
|
for i in ${runArr[@]}; do
|
||||||
script_params+=("$arg")
|
array_run[n]=${array[$i - 1]}
|
||||||
elif [ "$arg" == "--" ]; then
|
let n++
|
||||||
found_double_dash=true
|
|
||||||
else
|
|
||||||
task_shell_params+=("$arg")
|
|
||||||
fi
|
|
||||||
done
|
done
|
||||||
|
|
||||||
|
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||||
|
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||||
|
|
||||||
|
define_program "$file_param"
|
||||||
|
local time=$(date "+$time_format")
|
||||||
|
log_time=$(format_log_time "$time_format" "$time")
|
||||||
|
log_dir_tmp="${file_param##*/}"
|
||||||
|
if [[ $file_param =~ "/" ]]; then
|
||||||
|
if [[ $file_param == /* ]]; then
|
||||||
|
log_dir_tmp_path="${file_param:1}"
|
||||||
|
else
|
||||||
|
log_dir_tmp_path="${file_param}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||||
|
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||||
|
log_dir="${log_dir_tmp%.*}"
|
||||||
|
log_path="$log_dir/$log_time.log"
|
||||||
|
cmd=">> $dir_log/$log_path 2>&1"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(format_time "$time_format" "$time")
|
||||||
|
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||||
|
|
||||||
|
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||||
|
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||||
|
|
||||||
|
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||||
|
eval . $file_task_before "$@" $cmd
|
||||||
|
|
||||||
|
local envs=$(eval echo "\$${env_param}")
|
||||||
|
local array=($(echo $envs | sed 's/&/ /g'))
|
||||||
|
single_log_time=$(date "+%Y-%m-%d-%H-%M-%S.%N")
|
||||||
|
|
||||||
|
cd $dir_scripts
|
||||||
|
local relative_path="${file_param%/*}"
|
||||||
|
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||||
|
cd ${relative_path}
|
||||||
|
file_param=${file_param/$relative_path\//}
|
||||||
|
fi
|
||||||
|
for i in "${!array[@]}"; do
|
||||||
|
export ${env_param}=${array[i]}
|
||||||
|
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||||
|
eval $timeoutCmd $which_program $file_param &>$single_log_path &
|
||||||
|
done
|
||||||
|
|
||||||
|
wait
|
||||||
|
for i in "${!array[@]}"; do
|
||||||
|
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||||
|
eval cat $single_log_path $cmd
|
||||||
|
[[ -f $single_log_path ]] && rm -f $single_log_path
|
||||||
|
done
|
||||||
|
|
||||||
|
eval . $file_task_after "$@" $cmd
|
||||||
|
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||||
|
local end_timestamp=$(date "+%s")
|
||||||
|
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||||
|
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
init_begin_time() {
|
run_designated() {
|
||||||
begin_time=$(format_time "$time_format" "$time")
|
local file_param="$1"
|
||||||
begin_timestamp=$(format_timestamp "$time_format" "$time")
|
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 "+$time_format")
|
||||||
|
log_time=$(format_log_time "$time_format" "$time")
|
||||||
|
log_dir_tmp="${file_param##*/}"
|
||||||
|
if [[ $file_param =~ "/" ]]; then
|
||||||
|
if [[ $file_param == /* ]]; then
|
||||||
|
log_dir_tmp_path="${file_param:1}"
|
||||||
|
else
|
||||||
|
log_dir_tmp_path="${file_param}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||||
|
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||||
|
log_dir="${log_dir_tmp%.*}"
|
||||||
|
log_path="$log_dir/$log_time.log"
|
||||||
|
cmd=">> $dir_log/$log_path 2>&1"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(format_time "$time_format" "$time")
|
||||||
|
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||||
|
|
||||||
|
local envs=$(eval echo "\$${env_param}")
|
||||||
|
local array=($(echo $envs | sed 's/&/ /g'))
|
||||||
|
local tempArr=$(echo $num_param | perl -pe "s|(\d+)(-\|~\|_)(\d+)|{\1..\3}|g")
|
||||||
|
local runArr=($(eval echo $tempArr))
|
||||||
|
runArr=($(awk -v RS=' ' '!a[$1]++' <<< ${runArr[@]}))
|
||||||
|
|
||||||
|
local n=0
|
||||||
|
for i in ${runArr[@]}; do
|
||||||
|
array_run[n]=${array[$i - 1]}
|
||||||
|
let n++
|
||||||
|
done
|
||||||
|
|
||||||
|
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||||
|
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||||
|
|
||||||
|
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||||
|
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||||
|
|
||||||
|
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||||
|
eval . $file_task_before "$@" $cmd
|
||||||
|
|
||||||
|
cd $dir_scripts
|
||||||
|
local relative_path="${file_param%/*}"
|
||||||
|
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||||
|
cd ${relative_path}
|
||||||
|
file_param=${file_param/$relative_path\//}
|
||||||
|
fi
|
||||||
|
eval $timeoutCmd $which_program $file_param $cmd
|
||||||
|
|
||||||
|
eval . $file_task_after "$@" $cmd
|
||||||
|
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||||
|
local end_timestamp=$(date "+%s")
|
||||||
|
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||||
|
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
while getopts ":lm:" opt; do
|
## 运行其他命令
|
||||||
|
run_else() {
|
||||||
|
local file_param="$1"
|
||||||
|
define_program "$file_param"
|
||||||
|
local time=$(date "+$time_format")
|
||||||
|
log_time=$(format_log_time "$time_format" "$time")
|
||||||
|
log_dir_tmp="${file_param##*/}"
|
||||||
|
if [[ $file_param =~ "/" ]]; then
|
||||||
|
if [[ $file_param == /* ]]; then
|
||||||
|
log_dir_tmp_path="${file_param:1}"
|
||||||
|
else
|
||||||
|
log_dir_tmp_path="${file_param}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||||
|
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||||
|
log_dir="${log_dir_tmp%.*}"
|
||||||
|
log_path="$log_dir/$log_time.log"
|
||||||
|
cmd=">> $dir_log/$log_path 2>&1"
|
||||||
|
[[ "$show_log" == "true" ]] && cmd=""
|
||||||
|
make_dir "$dir_log/$log_dir"
|
||||||
|
|
||||||
|
local begin_time=$(format_time "$time_format" "$time")
|
||||||
|
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||||
|
|
||||||
|
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||||
|
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||||
|
|
||||||
|
local id=$(cat $list_crontab_user | grep -E "$cmd_task $@" | perl -pe "s|.*ID=(.*) $cmd_task $@\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||||
|
eval . $file_task_before "$@" $cmd
|
||||||
|
|
||||||
|
cd $dir_scripts
|
||||||
|
local relative_path="${file_param%/*}"
|
||||||
|
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||||
|
cd ${relative_path}
|
||||||
|
file_param=${file_param/$relative_path\//}
|
||||||
|
fi
|
||||||
|
|
||||||
|
shift
|
||||||
|
eval $timeoutCmd $which_program "$file_param" "$@" $cmd
|
||||||
|
|
||||||
|
eval . $file_task_after "$file_param" "$@" $cmd
|
||||||
|
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||||
|
local end_timestamp=$(date "+%s")
|
||||||
|
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||||
|
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||||
|
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
## 命令检测
|
||||||
|
main() {
|
||||||
|
show_log="false"
|
||||||
|
while getopts ":l" opt
|
||||||
|
do
|
||||||
case $opt in
|
case $opt in
|
||||||
l)
|
l)
|
||||||
show_log="true"
|
show_log="true"
|
||||||
;;
|
;;
|
||||||
m)
|
esac
|
||||||
max_time="$OPTARG"
|
done
|
||||||
|
[[ "$show_log" == "true" ]] && shift $(($OPTIND - 1))
|
||||||
|
|
||||||
|
timeoutCmd=""
|
||||||
|
if type timeout &>/dev/null; then
|
||||||
|
timeoutCmd="timeout -k 10s $command_timeout_time "
|
||||||
|
fi
|
||||||
|
|
||||||
|
time_format="%Y-%m-%d %H:%M:%S"
|
||||||
|
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||||
|
case $# in
|
||||||
|
1)
|
||||||
|
run_normal "$1"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
case $2 in
|
||||||
|
now)
|
||||||
|
run_normal "$1" "$2"
|
||||||
|
;;
|
||||||
|
conc)
|
||||||
|
run_concurrent "$1" "$3" "$*"
|
||||||
|
;;
|
||||||
|
desi)
|
||||||
|
run_designated "$1" "$3" "$*"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
run_else "$@"
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
done
|
;;
|
||||||
[[ $show_log ]] && shift $(($OPTIND - 1))
|
esac
|
||||||
if [[ $max_time ]]; then
|
[[ -f "$dir_log/$log_path" ]] && cat "$dir_log/$log_path"
|
||||||
shift $(($OPTIND - 1))
|
elif [[ $# -eq 0 ]]; then
|
||||||
command_timeout_time="$max_time"
|
echo
|
||||||
fi
|
usage
|
||||||
|
else
|
||||||
|
run_else "$@"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
format_params "$@"
|
main "$@"
|
||||||
define_program "${task_shell_params[@]}"
|
|
||||||
handle_log_path "${task_shell_params[@]}"
|
|
||||||
init_begin_time
|
|
||||||
|
|
||||||
eval . $dir_shell/otask.sh "$cmd"
|
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user