mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5afac3a3ac | ||
|
|
71ba1534f2 | ||
|
|
791cf657b5 | ||
|
|
c1ef021009 | ||
|
|
90fe63211d | ||
|
|
b60cda66bb | ||
|
|
7efe81df9e | ||
|
|
0d492e94f4 | ||
|
|
a45efbd69b | ||
|
|
035f0eb9e3 | ||
|
|
7d0cae7839 | ||
|
|
46e71d8213 | ||
|
|
372afb92c6 | ||
|
|
69d9307be9 | ||
|
|
c3908e956f | ||
|
|
1e749f3731 | ||
|
|
a68f4b0cde | ||
|
|
07541569c5 | ||
|
|
70f2bef5d2 | ||
|
|
805a716033 | ||
|
|
e77d4c4337 | ||
|
|
b309ac7613 | ||
|
|
8dd379b6b9 | ||
|
|
0b52e05af8 | ||
|
|
e9852a0002 | ||
|
|
20be84b352 | ||
|
|
4ab24ea1b9 | ||
|
|
417f91207f | ||
|
|
f723631647 | ||
|
|
6657ff0560 | ||
|
|
0593dae41d | ||
|
|
445dee00f7 | ||
|
|
6ca28190b0 | ||
|
|
510534ee0c | ||
|
|
2e7f3a1578 | ||
|
|
591a17e7ee | ||
|
|
bd7c361300 | ||
|
|
409b3281cc | ||
|
|
ac6de4911a | ||
|
|
1628e05ece | ||
|
|
7b7e03b503 | ||
|
|
8d14c9dae1 | ||
|
|
4d6d0a55e7 | ||
|
|
8ab2dc3280 | ||
|
|
3f54048127 | ||
|
|
47c2c61f33 | ||
|
|
47d2fc24bc | ||
|
|
7a8a8ab9b3 | ||
|
|
2ac4581d54 | ||
|
|
68ad01e0e8 | ||
|
|
cdeca4b808 | ||
|
|
55945e4cd1 | ||
|
|
b39036f8f8 | ||
|
|
f07093d29f | ||
|
|
11c789c71c | ||
|
|
81898f9dd7 | ||
|
|
6dba8ae72d | ||
|
|
c47896e787 | ||
|
|
14cb1f7788 | ||
|
|
892d91edc4 | ||
|
|
74916670eb | ||
|
|
b31eab02d7 | ||
|
|
9c258ab113 | ||
|
|
3bcba11b33 | ||
|
|
15140fd87d | ||
|
|
e83058c3bc | ||
|
|
29f0c2c9ac | ||
|
|
f25fe27473 | ||
|
|
0ae1f284ec | ||
|
|
49c441117a | ||
|
|
7bc5ff01a6 | ||
|
|
8128fb8a9f | ||
|
|
315ae49360 | ||
|
|
35c6475534 | ||
|
|
7f3e60423b | ||
|
|
0a723318a1 | ||
|
|
2c1e7535b8 | ||
|
|
48d1fba699 | ||
|
|
06f861baaf | ||
|
|
bbbd353567 | ||
|
|
8283f62db2 | ||
|
|
1a94a660a5 | ||
|
|
5c393fef36 | ||
|
|
53346a3962 | ||
|
|
4e66a3aff5 | ||
|
|
b79d10b452 | ||
|
|
3dc3ece993 | ||
|
|
792cf9ad20 | ||
|
|
201f41e15b | ||
|
|
71e7ba9cb6 | ||
|
|
a7562259d1 | ||
|
|
18671264bf | ||
|
|
37bcb77be0 | ||
|
|
563457cf1b | ||
|
|
d2cf482d11 | ||
|
|
2713942a68 | ||
|
|
62168979e3 | ||
|
|
f8aba4b1fb | ||
|
|
52a89a21f6 | ||
|
|
ca8790bbec | ||
|
|
be1d68c0d1 | ||
|
|
95afcbc9dd | ||
|
|
20249119a0 | ||
|
|
6e0ee6f627 | ||
|
|
13e7dac333 | ||
|
|
b89dc6dfc6 | ||
|
|
897b710527 | ||
|
|
5afec03548 | ||
|
|
c6a25e5359 | ||
|
|
3777a4e7b4 | ||
|
|
9b7d4cb8fe | ||
|
|
59f7b72bb1 | ||
|
|
4d97f0f44d | ||
|
|
de9e9ce627 | ||
|
|
f056b611a4 | ||
|
|
659484511f | ||
|
|
9ed107980c | ||
|
|
4a3ac7dc4b | ||
|
|
c3a0f58003 | ||
|
|
23781d8b34 | ||
|
|
c1d6a0a40b | ||
|
|
82c9978514 | ||
|
|
9f6d4943ea | ||
|
|
c4a44a48c5 | ||
|
|
d2fef75e01 | ||
|
|
085cb789b5 | ||
|
|
20f615eadf | ||
|
|
66a2769e7c | ||
|
|
899a30eacd | ||
|
|
8760ac2964 | ||
|
|
62a29867a3 | ||
|
|
4938635ef4 | ||
|
|
046239404f | ||
|
|
b90243f55c | ||
|
|
43c0cd8132 | ||
|
|
533e12a796 | ||
|
|
bd004a0489 | ||
|
|
41befcc0a8 | ||
|
|
9fb9b3d121 | ||
|
|
5055045d22 | ||
|
|
9f7beb934d | ||
|
|
26b06c17c5 | ||
|
|
b8a9b26ca3 | ||
|
|
b6376ed2e8 | ||
|
|
99f6073c8e | ||
|
|
5e73f0390f | ||
|
|
c35cfba8b0 | ||
|
|
aac109621a | ||
|
|
a340964c82 | ||
|
|
00818b694a | ||
|
|
ec5b885476 | ||
|
|
9d55cb108c | ||
|
|
4c19054b30 | ||
|
|
2a41f64d1b | ||
|
|
d3023d31e3 | ||
|
|
eddc03e295 | ||
|
|
77a8e00b17 | ||
|
|
99281a061e | ||
|
|
22eedebf14 | ||
|
|
d7e0531935 | ||
|
|
16734326cf | ||
|
|
956cfe18be | ||
|
|
a864a56917 | ||
|
|
ab3fc9b5f1 | ||
|
|
8d899f1a53 | ||
|
|
a1eef2c644 | ||
|
|
aab096843c | ||
|
|
acc7443004 | ||
|
|
042d7d3b8e | ||
|
|
0511a4af0d | ||
|
|
748a099087 | ||
|
|
742d0b2135 | ||
|
|
2081364325 | ||
|
|
39dc31916e | ||
|
|
5395cebdb4 | ||
|
|
fe934fa4af | ||
|
|
461fa8e131 | ||
|
|
4618a19c04 | ||
|
|
e2bd15683e | ||
|
|
648b9c4520 | ||
|
|
b4e4e84bbd | ||
|
|
aa5d6f3cb6 | ||
|
|
e9416c23df | ||
|
|
ef4999be55 | ||
|
|
e7be4999b0 | ||
|
|
5907553670 | ||
|
|
0b9066525a | ||
|
|
ac904cae61 | ||
|
|
4d5fa320ea | ||
|
|
003defedcf | ||
|
|
40e8041401 | ||
|
|
a8174e89be | ||
|
|
cce83f7a4c | ||
|
|
4f7649f157 | ||
|
|
b002cbef3a | ||
|
|
1d93fe0de0 | ||
|
|
2d936f1341 | ||
|
|
b40673e9ac | ||
|
|
637874e426 | ||
|
|
de71d1a258 | ||
|
|
e174e190ee | ||
|
|
89164a3bd2 | ||
|
|
a9b9c4d7ad | ||
|
|
f947866c32 | ||
|
|
a2e33d1ed4 | ||
|
|
b1a242c8ee | ||
|
|
0bf28e9ab3 | ||
|
|
624c9374e5 | ||
|
|
a9da8fffc1 | ||
|
|
b4e5db9da9 | ||
|
|
2e27d4057e | ||
|
|
e7d023a7e0 | ||
|
|
39bfd39559 | ||
|
|
6832cb4e22 | ||
|
|
590dbba19b | ||
|
|
3987ef8d97 | ||
|
|
8b0dedaf8c | ||
|
|
04edd97967 | ||
|
|
6131fe0110 | ||
|
|
665c344ae4 | ||
|
|
373b8c97d7 | ||
|
|
56eb0c5408 | ||
|
|
fe55929959 | ||
|
|
01e2bd007d | ||
|
|
4e091b0c3e | ||
|
|
db94cd3799 | ||
|
|
a15192b9b2 | ||
|
|
efd4f1d5ab | ||
|
|
bd166ee794 | ||
|
|
93e94ea94c | ||
|
|
88b87de391 | ||
|
|
8affff96f3 | ||
|
|
936b565fb1 | ||
|
|
b69ff2895e | ||
|
|
f3791cbb62 | ||
|
|
b0f3b51736 | ||
|
|
3aa112e373 | ||
|
|
683482e067 | ||
|
|
5a2caeb66b | ||
|
|
ee6e5bd8b4 | ||
|
|
f970322f0a | ||
|
|
1718120623 | ||
|
|
702c3160ec | ||
|
|
db227e56bf | ||
|
|
84828865f7 | ||
|
|
87455cebc0 | ||
|
|
9f4435b237 | ||
|
|
e5bc4b3b04 | ||
|
|
11e1b50000 | ||
|
|
bec226ae13 | ||
|
|
c9ecdc6c97 | ||
|
|
4cf64e7af0 | ||
|
|
4ce01c5f0e | ||
|
|
2eff99abe1 | ||
|
|
5bf57185d9 | ||
|
|
c59dac19ae | ||
|
|
f1ef8e72ae | ||
|
|
5b1accffb7 | ||
|
|
f64ff83414 | ||
|
|
26c914d1db | ||
|
|
8f75a54110 | ||
|
|
874b6e3a56 | ||
|
|
f305d45225 | ||
|
|
a7f97bd729 | ||
|
|
0bbb7c7b89 | ||
|
|
f7465759c7 | ||
|
|
998e82d323 | ||
|
|
f8dfee8945 | ||
|
|
86e3d8736b | ||
|
|
85d32d00e1 | ||
|
|
6a52e2f804 | ||
|
|
b4cb72c5d0 | ||
|
|
79fd4ec58f | ||
|
|
49ed5c6632 | ||
|
|
ffba7ee4a1 | ||
|
|
91d080472f | ||
|
|
826f214f0f | ||
|
|
ca150dc6a6 | ||
|
|
ae5db60211 | ||
|
|
490bdc15f6 | ||
|
|
1377fe31aa | ||
|
|
3d1cf6bf2e | ||
|
|
6ac755b478 | ||
|
|
e70fa83074 | ||
|
|
41521f1d08 | ||
|
|
8b7bef097c | ||
|
|
618756d4a9 | ||
|
|
70d0c71414 | ||
|
|
65eb9c806d | ||
|
|
50718ba714 | ||
|
|
7c3bb90d12 | ||
|
|
f66390eabd | ||
|
|
481646501c | ||
|
|
5baa8e4391 | ||
|
|
3d11210aeb | ||
|
|
e1863407f2 | ||
|
|
0c28b63ab7 | ||
|
|
8b8bd279c6 | ||
|
|
01b404765e | ||
|
|
c231a871d7 | ||
|
|
598c6b4e57 | ||
|
|
2295fabcc5 | ||
|
|
be94d796ac | ||
|
|
c84908d7fa | ||
|
|
d8ae039b92 | ||
|
|
bce1431d03 | ||
|
|
9db0095e29 | ||
|
|
77dc7817fb | ||
|
|
d0dd97631e | ||
|
|
d11d6d0c18 | ||
|
|
0af687f781 | ||
|
|
8db997abe8 | ||
|
|
aab6bbeb15 | ||
|
|
df1addc1ff | ||
|
|
1f8f35476a | ||
|
|
5354fc76db | ||
|
|
b29a9e012c | ||
|
|
6e5d89c197 | ||
|
|
d6cfb18f06 | ||
|
|
9a3e38051d | ||
|
|
b705ad6ee8 | ||
|
|
db564d1add | ||
|
|
4f422c0658 | ||
|
|
f267720af4 | ||
|
|
4a0c66bcc0 | ||
|
|
ef7283a9fd | ||
|
|
4498449eea | ||
|
|
ebb9676a51 | ||
|
|
6fb39ce835 | ||
|
|
59c26d90d3 | ||
|
|
1d2df860e8 | ||
|
|
ce22cad5b2 | ||
|
|
dc44ce6b1a | ||
|
|
b27ee23cc3 | ||
|
|
083c8869aa | ||
|
|
6a971a0d6e | ||
|
|
a25bfb6912 | ||
|
|
f19dd21155 | ||
|
|
79b342d1d2 | ||
|
|
20b0d75b0d | ||
|
|
c89724906e | ||
|
|
c3a548ece3 | ||
|
|
b431e39f8f | ||
|
|
710746809b | ||
|
|
8a225e9beb | ||
|
|
a5ecb204b2 | ||
|
|
f1f009da3b | ||
|
|
7291098f98 | ||
|
|
666545ff03 | ||
|
|
81e2bbb14c | ||
|
|
970dff144c | ||
|
|
819b15b15e | ||
|
|
3fa57c69ac | ||
|
|
18689c8119 | ||
|
|
61e7049baa | ||
|
|
39c40a328d | ||
|
|
955d815d14 | ||
|
|
3a3b945de8 | ||
|
|
73c53dbc8d | ||
|
|
f76828d4ec | ||
|
|
7b2956eb0a | ||
|
|
b2167ae5e4 | ||
|
|
98dfa4c425 | ||
|
|
5bf08b76de | ||
|
|
5c5b4f804e | ||
|
|
6455245d11 | ||
|
|
2ff3d9c601 | ||
|
|
d342fbf29f | ||
|
|
f865018cd6 | ||
|
|
3b9a4f0834 | ||
|
|
67bc305950 | ||
|
|
97f128d59f | ||
|
|
e25885c4d9 | ||
|
|
c285026339 | ||
|
|
6c34045a48 | ||
|
|
e1e6261b4f | ||
|
|
697bcb5922 | ||
|
|
e05b0a2491 | ||
|
|
e1655455d8 | ||
|
|
9921dab064 | ||
|
|
403ab7f0f0 | ||
|
|
9bc7ca4094 | ||
|
|
e924aa76b0 | ||
|
|
0c46606e14 | ||
|
|
dbfa4049f5 | ||
|
|
622fe2a8f8 | ||
|
|
7bce5c4f6a | ||
|
|
1f7f2c8971 | ||
|
|
437a849c2a | ||
|
|
8f7261dd50 | ||
|
|
76fa82c3a7 | ||
|
|
46c9774efa | ||
|
|
1bc64a23e3 | ||
|
|
cc9a17afa3 | ||
|
|
fcbcfc3a03 | ||
|
|
0144f3b131 | ||
|
|
518436d5ca | ||
|
|
1961a6b913 | ||
|
|
5edebdd5f3 | ||
|
|
48edf2c212 | ||
|
|
9b16dca9da | ||
|
|
9479c2498c | ||
|
|
4a18bcabe2 | ||
|
|
34f690c53d | ||
|
|
e70cd6579f | ||
|
|
99c047e9c7 | ||
|
|
978ae326f8 | ||
|
|
b01f27f2d3 | ||
|
|
4d34e0dd96 | ||
|
|
9b0065e533 | ||
|
|
34a51feee9 | ||
|
|
679091de59 | ||
|
|
c6220cb920 | ||
|
|
633b30269c | ||
|
|
8ad26267d8 | ||
|
|
7cfb125682 | ||
|
|
a2dc5de5ce | ||
|
|
4f41ff29ec | ||
|
|
13d95b8c19 | ||
|
|
335c13ab44 | ||
|
|
015cdc10a7 | ||
|
|
a5075ab28f | ||
|
|
2e3c3274c7 | ||
|
|
443c581955 | ||
|
|
5e41faf590 | ||
|
|
0579fb83d3 | ||
|
|
2864845d5b | ||
|
|
659dddace7 | ||
|
|
b096f30558 | ||
|
|
dcfb72143a | ||
|
|
c63bcd7706 | ||
|
|
bac306f9b3 | ||
|
|
a6fd96e97b | ||
|
|
7edd91f923 | ||
|
|
66df445bd5 | ||
|
|
5c03034bb4 |
+3
-1
@@ -1,3 +1,4 @@
|
|||||||
|
UPDATE_PORT=5300
|
||||||
PUBLIC_PORT=5400
|
PUBLIC_PORT=5400
|
||||||
CRON_PORT=5500
|
CRON_PORT=5500
|
||||||
BACK_PORT=5600
|
BACK_PORT=5600
|
||||||
@@ -9,4 +10,5 @@ SECRET='whyour'
|
|||||||
|
|
||||||
QINIU_AK=''
|
QINIU_AK=''
|
||||||
QINIU_SK=''
|
QINIU_SK=''
|
||||||
QINIU_SCOPE=''
|
QINIU_SCOPE=''
|
||||||
|
TEMP=''
|
||||||
|
|||||||
@@ -2,58 +2,51 @@ name: Build And Push Docker Image
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "*.md"
|
||||||
branches:
|
branches:
|
||||||
- 'master'
|
- "master"
|
||||||
- 'develop'
|
- "develop"
|
||||||
# Sequence of patterns matched against refs/tags
|
|
||||||
tags:
|
tags:
|
||||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
- "v*"
|
||||||
schedule:
|
schedule:
|
||||||
# 参考 https://jasonet.co/posts/scheduled-actions/
|
- cron: "00 20 * * *"
|
||||||
# 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:
|
to_gitlab:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: pixta-dev/repository-mirroring-action@v1
|
- uses: pixta-dev/repository-mirroring-action@v1
|
||||||
with:
|
with:
|
||||||
target_repo_url:
|
target_repo_url: git@gitlab.com:whyour/qinglong.git
|
||||||
git@gitlab.com:whyour/qinglong.git
|
ssh_private_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||||
ssh_private_key:
|
|
||||||
${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
|
|
||||||
to_gitee:
|
to_gitee:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: pixta-dev/repository-mirroring-action@v1
|
- uses: pixta-dev/repository-mirroring-action@v1
|
||||||
with:
|
with:
|
||||||
target_repo_url:
|
target_repo_url: git@gitee.com:whyour/qinglong.git
|
||||||
git@gitee.com:whyour/qinglong.git
|
ssh_private_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||||
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@v4
|
||||||
- uses: pnpm/action-setup@v2
|
- uses: pnpm/action-setup@v3
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: "8.3.1"
|
||||||
|
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
cache: 'pnpm'
|
cache: "pnpm"
|
||||||
|
|
||||||
- name: build front and back
|
- name: build front and back
|
||||||
run: |
|
run: |
|
||||||
@@ -85,40 +78,43 @@ jobs:
|
|||||||
export GIT_SSH_COMMAND="ssh -v -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no -l git"
|
export GIT_SSH_COMMAND="ssh -v -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no -l git"
|
||||||
git remote add gitee "${REPO_GITEE}"
|
git remote add gitee "${REPO_GITEE}"
|
||||||
git remote add gitlab "${REPO_GITLAB}"
|
git remote add gitlab "${REPO_GITLAB}"
|
||||||
|
git gc
|
||||||
git push --force --quiet gitee ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
git push --force --quiet gitee ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
||||||
git push --force --quiet gitlab ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
git push --force --quiet gitlab ${GITHUB_BRANCH}:${GITHUB_BRANCH}
|
||||||
|
|
||||||
build:
|
build:
|
||||||
needs: build-static
|
needs: build-static
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
# 由于 ubuntu-latest 中使用 linux6.x 内核 linux/s390x npm 无法使用
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
# runs-on: self-hosted
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
packages: write
|
packages: write
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
- uses: pnpm/action-setup@v2
|
- uses: pnpm/action-setup@v3
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: "8.3.1"
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
cache: 'pnpm'
|
cache: "pnpm"
|
||||||
|
|
||||||
- name: Setup timezone
|
- name: Setup timezone
|
||||||
uses: zcong1993/setup-timezone@master
|
uses: szenius/set-timezone@v1.2
|
||||||
with:
|
with:
|
||||||
timezone: Asia/Shanghai
|
timezoneLinux: Asia/Shanghai
|
||||||
|
|
||||||
- name: Login to DockerHub
|
- name: Login to DockerHub
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v3
|
||||||
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@v2
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
@@ -126,41 +122,114 @@ jobs:
|
|||||||
|
|
||||||
- name: Extract metadata (tags, labels) for Docker
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v4
|
uses: docker/metadata-action@v5
|
||||||
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@v2
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
id: docker_build
|
id: docker_build
|
||||||
uses: docker/build-push-action@v3
|
uses: docker/build-push-action@v5
|
||||||
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
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||||
context: docker/
|
# platforms: linux/amd64,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||||
|
context: .
|
||||||
|
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
|
- name: Image digest
|
||||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
run: |
|
||||||
|
echo ${{ steps.docker_build.outputs.digest }}
|
||||||
|
|
||||||
|
build310:
|
||||||
|
if: ${{ github.ref_name == 'master' }}
|
||||||
|
needs: build-static
|
||||||
|
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
packages: write
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: pnpm/action-setup@v3
|
||||||
|
with:
|
||||||
|
version: "8.3.1"
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
cache: "pnpm"
|
||||||
|
|
||||||
|
- name: Setup timezone
|
||||||
|
uses: szenius/set-timezone@v1.2
|
||||||
|
with:
|
||||||
|
timezoneLinux: Asia/Shanghai
|
||||||
|
|
||||||
|
- name: Login to DockerHub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
|
- name: Login to GHCR
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Build and push python3.10
|
||||||
|
id: docker_build_310
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
build-args: |
|
||||||
|
MAINTAINER=${{ github.repository_owner }}
|
||||||
|
QL_BRANCH=${{ github.ref_name }}
|
||||||
|
SOURCE_COMMIT=${{ github.sha }}
|
||||||
|
network: host
|
||||||
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||||
|
context: .
|
||||||
|
file: ./docker/310.Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: whyour/qinglong:python3.10
|
||||||
|
cache-from: type=registry,ref=whyour/qinglong:cache-python3.10
|
||||||
|
cache-to: type=registry,ref=whyour/qinglong:cache-python3.10,mode=max
|
||||||
|
|
||||||
|
- name: Image digest
|
||||||
|
run: |
|
||||||
|
echo ${{ steps.docker_build_310.outputs.digest }}
|
||||||
|
|||||||
+1
-8
@@ -22,11 +22,4 @@
|
|||||||
.env
|
.env
|
||||||
.history
|
.history
|
||||||
.version.ts
|
.version.ts
|
||||||
|
/.tmp
|
||||||
/config
|
|
||||||
/log
|
|
||||||
/db
|
|
||||||
/manual_log
|
|
||||||
/scripts
|
|
||||||
/bak
|
|
||||||
node_modules
|
|
||||||
@@ -1,2 +1 @@
|
|||||||
sentrycli_cdnurl=https://npmmirror.com/mirrors/sentry-cli/
|
|
||||||
strict-peer-dependencies=false
|
strict-peer-dependencies=false
|
||||||
@@ -6,3 +6,20 @@ 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
|
||||||
|
version.ts
|
||||||
|
/.tmp
|
||||||
@@ -1,24 +1,36 @@
|
|||||||
import { defineConfig } from '@umijs/max';
|
import { defineConfig } from '@umijs/max';
|
||||||
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',
|
||||||
antd: {},
|
antd: {},
|
||||||
|
locale: {
|
||||||
|
antd: true,
|
||||||
|
title: true,
|
||||||
|
baseNavigator: true,
|
||||||
|
},
|
||||||
outputPath: 'static/dist',
|
outputPath: 'static/dist',
|
||||||
fastRefresh: true,
|
fastRefresh: true,
|
||||||
favicons: ['/images/favicon.svg'],
|
favicons: [`https://qn.whyour.cn/favicon.svg`],
|
||||||
mfsu: {
|
publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
|
||||||
strategy: 'eager',
|
|
||||||
},
|
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api/public': {
|
[`${baseUrl}api/update`]: {
|
||||||
|
target: 'http://127.0.0.1:5300/',
|
||||||
|
changeOrigin: true,
|
||||||
|
pathRewrite: { [`^${baseUrl}api/update`]: '/api' },
|
||||||
|
},
|
||||||
|
[`${baseUrl}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' },
|
||||||
},
|
},
|
||||||
'/api': {
|
[`${baseUrl}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: any) => {
|
||||||
@@ -36,7 +48,14 @@ export default defineConfig({
|
|||||||
'react-dom': 'window.ReactDOM',
|
'react-dom': 'window.ReactDOM',
|
||||||
},
|
},
|
||||||
headScripts: [
|
headScripts: [
|
||||||
|
`./api/env.js`,
|
||||||
'https://gw.alipayobjects.com/os/lib/react/18.2.0/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/18.2.0/umd/react-dom.production.min.js',
|
'https://gw.alipayobjects.com/os/lib/react-dom/18.2.0/umd/react-dom.production.min.js',
|
||||||
],
|
],
|
||||||
|
copy: [
|
||||||
|
{
|
||||||
|
from: 'node_modules/monaco-editor/min/vs',
|
||||||
|
to: 'static/dist/monaco-editor/min/vs',
|
||||||
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
+124
-128
@@ -1,30 +1,29 @@
|
|||||||
<p align="center">
|
|
||||||
<a href="https://github.com/whyour/qinglong">
|
|
||||||
<img width="150" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.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">
|
||||||
|
|
||||||
Timed task management panel with python3, javaScript, shell, typescript support
|
<h1 align="center">Qinglong</h1>
|
||||||
|
|
||||||
[![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]
|
[简体中文](./README.md) | English
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
@@ -36,84 +35,49 @@ Timed task management panel with python3, javaScript, shell, typescript support
|
|||||||
- Support dark mode
|
- Support dark mode
|
||||||
- Support cell phone operation
|
- Support cell phone operation
|
||||||
|
|
||||||
|
## Version
|
||||||
|
|
||||||
|
### docker
|
||||||
|
|
||||||
|
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
|
||||||
|
docker pull whyour/qinglong:latest
|
||||||
|
docker pull whyour/qinglong:debian
|
||||||
|
```
|
||||||
|
|
||||||
|
### npm
|
||||||
|
|
||||||
|
The npm version supports `debian/ubuntu/alpine` systems and requires `node/npm/python3/pip3/pnpm` to be installed.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i @whyour/qinglong
|
||||||
|
```
|
||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
|
|
||||||
### Local Deployment
|
### Docker (Recommended)
|
||||||
|
|
||||||
```bash
|
|
||||||
# To be refined, see the development steps first (not supported on windows yet)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Podman Deployment
|
|
||||||
|
|
||||||
1. podman installation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
https://podman.io/getting-started/installation
|
|
||||||
```
|
|
||||||
|
|
||||||
2. start the container
|
|
||||||
|
|
||||||
```bash
|
|
||||||
podman run -dit \
|
|
||||||
--network bridge \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
-p 5700:5700 \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
docker.io/whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 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
|
```bash
|
||||||
|
# curl -sSL get.docker.com | sh
|
||||||
docker run -dit \
|
docker run -dit \
|
||||||
-v $PWD/ql/data:/ql/data \
|
-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 \
|
-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 \
|
--name qinglong \
|
||||||
--hostname qinglong \
|
--hostname qinglong \
|
||||||
--restart unless-stopped \
|
--restart unless-stopped \
|
||||||
whyour/qinglong:latest
|
whyour/qinglong:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker-compose Deployment
|
### Docker-compose (Recommended)
|
||||||
|
|
||||||
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
|
```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
|
mkdir qinglong
|
||||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
||||||
|
|
||||||
@@ -123,13 +87,66 @@ docker-compose up -d
|
|||||||
docker-compose down
|
docker-compose down
|
||||||
```
|
```
|
||||||
|
|
||||||
3. access
|
### Podman (Recommended)
|
||||||
|
|
||||||
Open your browser and visit http://{ip}:5700
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
## Use
|
### Npm
|
||||||
|
|
||||||
1. built-in commands
|
It is recommended to use a pure system installation to avoid losing the original system data, you need to install node/npm/python3/pip3/pnpm yourself
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Debian/Ubuntu
|
||||||
|
curl -sL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install -g node-pre-gyp pnpm@8.3.1
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
## Built-in commands
|
||||||
|
|
||||||
|
- task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 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>
|
||||||
|
# Set task timeout
|
||||||
|
task -m <max_time> <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
|
||||||
|
```
|
||||||
|
|
||||||
|
- ql
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Update and restart Green Dragon
|
# Update and restart Green Dragon
|
||||||
@@ -150,36 +167,33 @@ 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>
|
|
||||||
# Set task timeout
|
|
||||||
task -m <max_time> <file_path>
|
|
||||||
# Print task log in real time, no need to carry this parameter when creating timed tasks
|
|
||||||
task -l <file_path>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
2. parameter description
|
| **Parameter** | **Description** |
|
||||||
|
|---|---|
|
||||||
|
| file_url | Script 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 |
|
||||||
|
| 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 |
|
||||||
|
| extensions | Pull the branch of the repository |
|
||||||
|
| branch | Number of days of logs to be kept |
|
||||||
|
| days | File path for task execution |
|
||||||
|
| file_path | The name of the environment variable that needs to be concurrent or specified at the time of task execution |
|
||||||
|
|
||||||
* file_url: Script address
|
## Development
|
||||||
* 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
|
```bash
|
||||||
* blacklist: Blacklisting when pulling repositories, i.e. strings that are not included in the path of the script to be pulled
|
git clone https://github.com/whyour/qinglong.git
|
||||||
* 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
|
cd qinglong
|
||||||
* branch: Pull the branch of the repository
|
cp .env.example .env
|
||||||
* days: Number of days of logs to be kept
|
# Recommended use pnpm https://pnpm.io/zh/installation
|
||||||
* file_path: File path for task execution
|
npm install -g pnpm@8.3.1
|
||||||
* env_name: The name of the environment variable that needs to be concurrent or specified at the time of task execution
|
pnpm install
|
||||||
* account_number: Specify the account number of an environment variable to be executed when the task is executed
|
pnpm start
|
||||||
* max_time: Timeout, suffix "s" for seconds (default), "m" for minutes, "h" for hours, "d" for days
|
```
|
||||||
|
|
||||||
|
Open your browser and visit <http://127.0.0.1:5700>
|
||||||
|
|
||||||
## Links
|
## Links
|
||||||
|
|
||||||
@@ -191,28 +205,10 @@ task -l <file_path>
|
|||||||
- [darkreader](https://github.com/darkreader/darkreader)
|
- [darkreader](https://github.com/darkreader/darkreader)
|
||||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ git clone git@github.com:whyour/qinglong.git
|
|
||||||
$ cd qinglong
|
|
||||||
$ cp .env.example .env
|
|
||||||
# Recommended use pnpm https://pnpm.io/zh/installation
|
|
||||||
$ npm install -g pnpm
|
|
||||||
$ pnpm install
|
|
||||||
$ pnpm start
|
|
||||||
```
|
|
||||||
|
|
||||||
Open your browser and visit http://127.0.0.1:5700
|
|
||||||
|
|
||||||
## Communication
|
|
||||||
|
|
||||||
[telegram channel](https://t.me/jiao_long)
|
|
||||||
|
|
||||||
## Name Origin
|
## Name Origin
|
||||||
|
|
||||||
The Green Dragon, also known as the Canglong, is one of the four elephants and one of the [four spirits of the heavens](https://zh.wikipedia.org/wiki/%E5%A4%A9%E4%B9%8B%E5%9B%9B%E7%81%B5) in traditional Chinese culture. According to the Five Elements, it is a spirit animal representing the East as a green dragon, the five elements are wood, and the season represented is spring, with the eight trigrams dominating vibration. Like the Ying Long, the Cang Long has feathered wings. According to the Zhang Guo Xing Zong (Zhang Guo Xing Zong), "a true dragon is one that has complementary wings".
|
The Green Dragon, also known as the Canglong, is one of the four elephants and one of the [four spirits of the heavens](https://zh.wikipedia.org/wiki/%E5%A4%A9%E4%B9%8B%E5%9B%9B%E7%81%B5) in traditional Chinese culture. According to the Five Elements, it is a spirit animal representing the East as a green dragon, the five elements are wood, and the season represented is spring, with the eight trigrams dominating vibration. Like the Ying Long, the Cang Long has feathered wings. According to the Zhang Guo Xing Zong (Zhang Guo Xing Zong), "a true dragon is one that has complementary wings".
|
||||||
|
|
||||||
In the Book of the Later Han Dynasty (後漢書-律曆志下), it is written: "The sun is in the sky, a cold and a summer, the four seasons are ready, all things are changed, the regency moves, and the green dragon moves to the star, which is called the year. (The Year of the Star)
|
In the Book of the Later Han Dynasty (後漢書-律曆志下), it is written: "The sun is in the sky, a cold and a summer, the four seasons are ready, all things are changed, the regency moves, and the green dragon moves to the star, which is called the year. (The Year of the Star)
|
||||||
|
|
||||||
Among the [twenty-eight Chinese constellations](https://zh.wikipedia.org/wiki/%E4%BA%8C%E5%8D%81%E5%85%AB%E5%AE%BF), the Green Dragon is the generic name for the seven eastern constellations (Horn, Hyper, Diao, Fang, Heart, Tail and Minchi). It is known in Taoism as "Mengzhang" and in different Taoist scriptures as "Dijun", "Shengjian", "Shenjian" and He is also known in different Daoist scriptures as "Dijun", "Shengjun", "Shenjun" and "Ghost Catcher"[1], and is the guardian deity of Daoism, together with the White Tiger Supervisor of Soldiers.
|
Among the [twenty-eight Chinese constellations](https://zh.wikipedia.org/wiki/%E4%BA%8C%E5%8D%81%E5%85%AB%E5%AE%BF), the Green Dragon is the generic name for the seven eastern constellations (Horn, Hyper, Diao, Fang, Heart, Tail and Minchi). It is known in Taoism as "Mengzhang" and in different Taoist scriptures as "Dijun", "Shengjian", "Shenjian" and He is also known in different Daoist scriptures as "Dijun", "Shengjun", "Shenjun" and "Ghost Catcher"[1], and is the guardian deity of Daoism, together with the White Tiger Supervisor of Soldiers.
|
||||||
|
|||||||
@@ -1,30 +1,31 @@
|
|||||||
<p align="center">
|
<div align="center">
|
||||||
<a href="https://github.com/whyour/qinglong">
|
<img width="100" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
||||||
<img width="150" src="https://user-images.githubusercontent.com/22700758/191449379-f9f56204-0e31-4a16-be5a-331f52696a73.png">
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h1 align="center">青龙</h1>
|
<h1 align="center">青龙</h1>
|
||||||
|
|
||||||
<div align="center">
|
简体中文 | [English](./README-en.md)
|
||||||
|
|
||||||
支持python3、javaScript、shell、typescript 的定时任务管理面板
|
支持 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]
|
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)
|

|
||||||
|
|
||||||
简体中文 | [English](./README-en.md)
|
|
||||||
|
|
||||||
## 功能
|
## 功能
|
||||||
|
|
||||||
@@ -36,85 +37,49 @@
|
|||||||
- 支持暗黑模式
|
- 支持暗黑模式
|
||||||
- 支持手机端操作
|
- 支持手机端操作
|
||||||
|
|
||||||
|
## 版本
|
||||||
|
|
||||||
|
### docker
|
||||||
|
|
||||||
|
`latest` 镜像是基于 `alpine` 构建,`debian` 镜像是基于 `debian-slim` 构建。如果需要使用 `alpine` 不支持的依赖,建议使用 `debian` 镜像
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker pull whyour/qinglong:latest
|
||||||
|
docker pull whyour/qinglong:debian
|
||||||
|
```
|
||||||
|
|
||||||
|
### npm
|
||||||
|
|
||||||
|
npm 版本支持 `debian/ubuntu/alpine` 系统,需要自行安装 `node/npm/python3/pip3/pnpm`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i @whyour/qinglong
|
||||||
|
```
|
||||||
|
|
||||||
## 部署
|
## 部署
|
||||||
|
|
||||||
### 本机部署
|
### docker (推荐)
|
||||||
|
|
||||||
```bash
|
|
||||||
# 待完善,可先参考开发步骤 (windows暂时不支持)
|
|
||||||
```
|
|
||||||
|
|
||||||
### podman 部署
|
|
||||||
|
|
||||||
1. podman 安装
|
|
||||||
|
|
||||||
```bash
|
|
||||||
https://podman.io/getting-started/installation
|
|
||||||
```
|
|
||||||
|
|
||||||
2. 启动容器
|
|
||||||
|
|
||||||
```bash
|
|
||||||
podman run -dit \
|
|
||||||
--network bridge \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
-p 5700:5700 \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
docker.io/whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 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
|
```bash
|
||||||
|
# curl -sSL get.docker.com | sh
|
||||||
docker run -dit \
|
docker run -dit \
|
||||||
-v $PWD/ql/data:/ql/data \
|
-v $PWD/ql/data:/ql/data \
|
||||||
|
# 冒号后面的 5700 为默认端口,如果设置了 QlPort, 需要跟 QlPort 保持一致
|
||||||
-p 5700:5700 \
|
-p 5700:5700 \
|
||||||
|
# 部署路径非必须,比如 /test
|
||||||
|
-e QlBaseUrl="/" \
|
||||||
|
# 部署端口非必须,当使用 host 模式时,可以设置服务启动后的端口,默认 5700
|
||||||
|
-e QlPort="5700" \
|
||||||
--name qinglong \
|
--name qinglong \
|
||||||
--hostname qinglong \
|
--hostname qinglong \
|
||||||
--restart unless-stopped \
|
--restart unless-stopped \
|
||||||
whyour/qinglong:latest
|
whyour/qinglong:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
### docker-compose 部署
|
### 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
|
```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
|
mkdir qinglong
|
||||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
||||||
|
|
||||||
@@ -124,34 +89,49 @@ docker-compose up -d
|
|||||||
docker-compose down
|
docker-compose down
|
||||||
```
|
```
|
||||||
|
|
||||||
3. 访问
|
### podman (推荐)
|
||||||
|
|
||||||
打开你的浏览器,访问 http://{ip}:5700
|
|
||||||
|
|
||||||
## 使用
|
|
||||||
|
|
||||||
1. 内置命令
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 更新并重启青龙
|
# https://podman.io/getting-started/installation
|
||||||
ql update
|
podman run -dit \
|
||||||
# 运行自定义脚本extra.sh
|
--network bridge \
|
||||||
ql extra
|
-v $PWD/ql/data:/ql/data \
|
||||||
# 添加单个脚本文件
|
# 冒号后面的 5700 为默认端口,如果设置了 QlPort, 需要跟 QlPort 保持一致
|
||||||
ql raw <file_url>
|
-p 5700:5700 \
|
||||||
# 添加单个仓库的指定脚本
|
# 部署路径非必须,比如 /test
|
||||||
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch> <extensions>
|
-e QlBaseUrl="/" \
|
||||||
# 删除旧日志
|
# 部署端口非必须,当使用 host 模式时,可以设置服务启动后的端口,默认 5700
|
||||||
ql rmlog <days>
|
-e QlPort="5700" \
|
||||||
# 启动tg-bot
|
--name qinglong \
|
||||||
ql bot
|
--hostname qinglong \
|
||||||
# 检测青龙环境并修复
|
docker.io/whyour/qinglong:latest
|
||||||
ql check
|
```
|
||||||
# 重置登录错误次数
|
|
||||||
ql resetlet
|
|
||||||
# 禁用两步登录
|
|
||||||
ql resettfa
|
|
||||||
|
|
||||||
|
### npm
|
||||||
|
|
||||||
|
建议使用纯净系统安装,避免系统原有数据丢失,需要自己安装 node/npm/python3/pip3/pnpm
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Debian/Ubuntu
|
||||||
|
curl -sL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install -g node-pre-gyp pnpm@8.3.1
|
||||||
|
npm install -g @whyour/qinglong
|
||||||
|
qinglong
|
||||||
|
# 根据提示增加环境变量 QL_DIR 和 QL_DATA_DIR
|
||||||
|
export QL_DIR=""
|
||||||
|
export QL_DATA_DIR=""
|
||||||
|
# 再次执行
|
||||||
|
qinglong
|
||||||
|
```
|
||||||
|
|
||||||
|
## 内置命令
|
||||||
|
|
||||||
|
- task
|
||||||
|
|
||||||
|
```bash
|
||||||
# 依次执行,如果设置了随机延迟,将随机延迟一定秒数
|
# 依次执行,如果设置了随机延迟,将随机延迟一定秒数
|
||||||
task <file_path>
|
task <file_path>
|
||||||
# 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日,同时记录在日志文件中
|
# 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日,同时记录在日志文件中
|
||||||
@@ -162,24 +142,58 @@ task <file_path> conc <env_name> <account_number>(可选的)
|
|||||||
task <file_path> desi <env_name> <account_number>
|
task <file_path> desi <env_name> <account_number>
|
||||||
# 设置任务超时时间
|
# 设置任务超时时间
|
||||||
task -m <max_time> <file_path>
|
task -m <max_time> <file_path>
|
||||||
# 实时打印任务日志,创建定时任务时,不用携带此参数
|
# 使用 -- 分割,-- 后面的参数会传给脚本,下面的例子,脚本就可接收到参数 -u whyour -p password
|
||||||
task -l <file_path>
|
task <file_path> -- -u whyour -p password
|
||||||
```
|
```
|
||||||
|
|
||||||
2. 参数说明
|
- ql
|
||||||
|
|
||||||
* file_url: 脚本地址
|
```bash
|
||||||
* repo_url: 仓库地址
|
# 更新并重启青龙
|
||||||
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串,多个竖线分割
|
ql update
|
||||||
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串,多个竖线分割
|
# 运行自定义脚本extra.sh
|
||||||
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响,多个竖线分割
|
ql extra
|
||||||
* extensions: 拉取仓库的文件后缀,多个竖线分割
|
# 添加单个脚本文件
|
||||||
* branch: 拉取仓库的分支
|
ql raw <file_url>
|
||||||
* days: 需要保留的日志的天数
|
# 添加单个仓库的指定脚本
|
||||||
* file_path: 任务执行时的文件路径
|
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch> <extensions>
|
||||||
* env_name: 任务执行时需要并发或者指定时的环境变量名称
|
# 删除旧日志
|
||||||
* account_number: 任务执行时指定某个环境变量需要执行的账号序号
|
ql rmlog <days>
|
||||||
* max_time: 超时时间,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
|
# 启动tg-bot
|
||||||
|
ql bot
|
||||||
|
# 检测青龙环境并修复
|
||||||
|
ql check
|
||||||
|
# 重置登录错误次数
|
||||||
|
ql resetlet
|
||||||
|
# 禁用两步登录
|
||||||
|
ql resettfa
|
||||||
|
```
|
||||||
|
|
||||||
|
| **参数** | **说明** |
|
||||||
|
|------------|---------------------------------------------------------------------------------------------|
|
||||||
|
| file_url | 脚本地址 |
|
||||||
|
| repo_url | 仓库地址 |
|
||||||
|
| whitelist | 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串,多个竖线分割 |
|
||||||
|
| blacklist | 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串,多个竖线分割 |
|
||||||
|
| dependence | 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响,多个竖线分割 |
|
||||||
|
| extensions | 拉取仓库的文件后缀,多个竖线分割 |
|
||||||
|
| branch | 拉取仓库的分支 |
|
||||||
|
| days | 需要保留的日志的天数 |
|
||||||
|
| file_path | 任务执行时的文件路径 |
|
||||||
|
|
||||||
|
## 开发
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/whyour/qinglong.git
|
||||||
|
cd qinglong
|
||||||
|
cp .env.example .env
|
||||||
|
# 推荐使用 pnpm https://pnpm.io/zh/installation
|
||||||
|
npm install -g pnpm@8.3.1
|
||||||
|
pnpm install
|
||||||
|
pnpm start
|
||||||
|
```
|
||||||
|
|
||||||
|
打开你的浏览器,访问 <http://127.0.0.1:5700>
|
||||||
|
|
||||||
## 链接
|
## 链接
|
||||||
|
|
||||||
@@ -191,24 +205,6 @@ task -l <file_path>
|
|||||||
- [darkreader](https://github.com/darkreader/darkreader)
|
- [darkreader](https://github.com/darkreader/darkreader)
|
||||||
- [admin-server](https://github.com/sunpu007/admin-server)
|
- [admin-server](https://github.com/sunpu007/admin-server)
|
||||||
|
|
||||||
## 开发
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ git clone git@github.com:whyour/qinglong.git
|
|
||||||
$ cd qinglong
|
|
||||||
$ cp .env.example .env
|
|
||||||
# 推荐使用 pnpm https://pnpm.io/zh/installation
|
|
||||||
$ npm install -g pnpm
|
|
||||||
$ pnpm install
|
|
||||||
$ pnpm start
|
|
||||||
```
|
|
||||||
|
|
||||||
打开你的浏览器,访问 http://127.0.0.1:5700
|
|
||||||
|
|
||||||
## 交流
|
|
||||||
|
|
||||||
[telegram频道](https://t.me/jiao_long)
|
|
||||||
|
|
||||||
## 名称来源
|
## 名称来源
|
||||||
|
|
||||||
青龙,又名苍龙,在中国传统文化中是四象之一、[天之四灵](https://zh.wikipedia.org/wiki/%E5%A4%A9%E4%B9%8B%E5%9B%9B%E7%81%B5)之一,根据五行学说,它是代表东方的灵兽,为青色的龙,五行属木,代表的季节是春季,八卦主震。苍龙与应龙一样,都是身具羽翼。《张果星宗》称“又有辅翼,方为真龙”。
|
青龙,又名苍龙,在中国传统文化中是四象之一、[天之四灵](https://zh.wikipedia.org/wiki/%E5%A4%A9%E4%B9%8B%E5%9B%9B%E7%81%B5)之一,根据五行学说,它是代表东方的灵兽,为青色的龙,五行属木,代表的季节是春季,八卦主震。苍龙与应龙一样,都是身具羽翼。《张果星宗》称“又有辅翼,方为真龙”。
|
||||||
|
|||||||
@@ -3,19 +3,36 @@ import { Router, Request, Response, NextFunction } from 'express';
|
|||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs/promises';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { SAMPLE_FILES } from '../config/const';
|
||||||
|
import ConfigService from '../services/config';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/configs', route);
|
app.use('/configs', route);
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/sample',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
res.send({
|
||||||
|
code: 200,
|
||||||
|
data: SAMPLE_FILES,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/files',
|
'/files',
|
||||||
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 fileList = fs.readdirSync(config.configPath, 'utf-8');
|
const fileList = await fs.readdir(config.configPath, 'utf-8');
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
data: fileList
|
data: fileList
|
||||||
@@ -31,24 +48,11 @@ export default (app: Router) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/:file',
|
'/detail',
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
try {
|
||||||
let content = '';
|
const configService = Container.get(ConfigService);
|
||||||
if (config.blackFileList.includes(req.params.file)) {
|
await configService.getFile(req.query.path as string, res);
|
||||||
res.send({ code: 403, message: '文件无法访问' });
|
|
||||||
}
|
|
||||||
if (req.params.file.includes('sample')) {
|
|
||||||
content = getFileContentByName(
|
|
||||||
`${config.samplePath}${req.params.file}`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
content = getFileContentByName(
|
|
||||||
`${config.configPath}${req.params.file}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
res.send({ code: 200, data: content });
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
@@ -70,12 +74,27 @@ 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 = `${config.configPath}${name}`;
|
let path = join(config.configPath, name);
|
||||||
fs.writeFileSync(path, content);
|
if (name.startsWith('data/scripts/')) {
|
||||||
|
path = join(config.rootPath, name);
|
||||||
|
}
|
||||||
|
await fs.writeFile(path, content);
|
||||||
res.send({ code: 200, message: '保存成功' });
|
res.send({ code: 200, message: '保存成功' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/:file',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const configService = Container.get(ConfigService);
|
||||||
|
await configService.getFile(req.params.file, res);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
};
|
};
|
||||||
@@ -152,6 +152,21 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/detail',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const cronService = Container.get(CronService);
|
||||||
|
const data = await cronService.find(req.query as any);
|
||||||
|
return res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
'/',
|
'/',
|
||||||
celebrate({
|
celebrate({
|
||||||
@@ -160,6 +175,10 @@ 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) => {
|
||||||
@@ -316,6 +335,10 @@ 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(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -435,13 +458,12 @@ 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: parseInt(req.body.status),
|
status: req.body.status ? parseInt(req.body.status) : undefined,
|
||||||
pid: parseInt(req.body.pid) || '',
|
pid: req.body.pid ? parseInt(req.body.pid) : undefined,
|
||||||
});
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -134,4 +134,20 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/cancel',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.array().items(Joi.number().required()),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const dependenceService = Container.get(DependenceService);
|
||||||
|
await dependenceService.cancel(req.body);
|
||||||
|
return res.send({ code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
};
|
};
|
||||||
@@ -6,6 +6,7 @@ import { celebrate, Joi } from 'celebrate';
|
|||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
import { safeJSONParse } from '../config/util';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@@ -50,6 +51,9 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
|
if (!req.body?.length) {
|
||||||
|
return res.send({ code: 400, message: '参数不正确' });
|
||||||
|
}
|
||||||
const data = await envService.create(req.body);
|
const data = await envService.create(req.body);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -200,7 +204,7 @@ export default (app: Router) => {
|
|||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const fileContent = await fs.promises.readFile(req!.file!.path, 'utf8');
|
const fileContent = await fs.promises.readFile(req!.file!.path, 'utf8');
|
||||||
const parseContent = JSON.parse(fileContent);
|
const parseContent = safeJSONParse(fileContent);
|
||||||
const data = Array.isArray(parseContent)
|
const data = Array.isArray(parseContent)
|
||||||
? parseContent
|
? parseContent
|
||||||
: [parseContent];
|
: [parseContent];
|
||||||
@@ -216,7 +220,7 @@ export default (app: Router) => {
|
|||||||
} else {
|
} else {
|
||||||
return res.send({
|
return res.send({
|
||||||
code: 400,
|
code: 400,
|
||||||
message: '文件缺少name或者value字段,参考导出文件格式',
|
message: '每条数据 name 或者 value 字段不能为空,参考导出文件格式',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -3,7 +3,7 @@ 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, rmPath } from '../config/util';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
@@ -15,7 +15,7 @@ export default (app: Router) => {
|
|||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const result = readDirs(config.logPath, config.logPath, blacklist);
|
const result = await readDirs(config.logPath, config.logPath, blacklist);
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
data: result,
|
data: result,
|
||||||
@@ -26,10 +26,29 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/detail',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
if (blacklist.includes(req.path)) {
|
||||||
|
return res.send({ code: 403, message: '暂无权限' });
|
||||||
|
}
|
||||||
|
const filePath = join(
|
||||||
|
config.logPath,
|
||||||
|
(req.query.path || '') as string,
|
||||||
|
req.query.file as string,
|
||||||
|
);
|
||||||
|
const content = await getFileContentByName(filePath);
|
||||||
|
res.send({ code: 200, data: content });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/:file',
|
'/:file',
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
try {
|
||||||
if (blacklist.includes(req.path)) {
|
if (blacklist.includes(req.path)) {
|
||||||
return res.send({ code: 403, message: '暂无权限' });
|
return res.send({ code: 403, message: '暂无权限' });
|
||||||
@@ -39,7 +58,7 @@ export default (app: Router) => {
|
|||||||
(req.query.path || '') as string,
|
(req.query.path || '') as string,
|
||||||
req.params.file,
|
req.params.file,
|
||||||
);
|
);
|
||||||
const content = getFileContentByName(filePath);
|
const content = await getFileContentByName(filePath);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -64,11 +83,7 @@ export default (app: Router) => {
|
|||||||
type: string;
|
type: string;
|
||||||
};
|
};
|
||||||
const filePath = join(config.logPath, path, filename);
|
const filePath = join(config.logPath, path, filename);
|
||||||
if (type === 'directory') {
|
await rmPath(filePath);
|
||||||
emptyDir(filePath);
|
|
||||||
} else {
|
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
}
|
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -4,13 +4,13 @@ import {
|
|||||||
readDirs,
|
readDirs,
|
||||||
getLastModifyFilePath,
|
getLastModifyFilePath,
|
||||||
readDir,
|
readDir,
|
||||||
emptyDir,
|
rmPath,
|
||||||
} 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';
|
||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs/promises';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import path, { join, parse } from 'path';
|
import path, { join, parse } from 'path';
|
||||||
import ScriptService from '../services/script';
|
import ScriptService from '../services/script';
|
||||||
@@ -34,15 +34,33 @@ 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'];
|
const blacklist = [
|
||||||
|
'node_modules',
|
||||||
|
'.git',
|
||||||
|
'.pnpm',
|
||||||
|
'pnpm-lock.yaml',
|
||||||
|
'yarn.lock',
|
||||||
|
'package-lock.json',
|
||||||
|
];
|
||||||
if (req.query.path) {
|
if (req.query.path) {
|
||||||
const targetPath = path.join(
|
const targetPath = path.join(
|
||||||
config.scriptPath,
|
config.scriptPath,
|
||||||
req.query.path as string,
|
req.query.path as string,
|
||||||
);
|
);
|
||||||
result = readDir(targetPath, config.scriptPath, blacklist);
|
result = await readDir(targetPath, config.scriptPath, blacklist);
|
||||||
} else {
|
} else {
|
||||||
result = readDirs(config.scriptPath, config.scriptPath, blacklist);
|
result = await readDirs(
|
||||||
|
config.scriptPath,
|
||||||
|
config.scriptPath,
|
||||||
|
blacklist,
|
||||||
|
(a, b) => {
|
||||||
|
if (a.type === b.type) {
|
||||||
|
return a.title.localeCompare(b.title);
|
||||||
|
} else {
|
||||||
|
return a.type === 'directory' ? -1 : 1;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
@@ -54,17 +72,31 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/detail',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const scriptService = Container.get(ScriptService);
|
||||||
|
const content = await scriptService.getFile(
|
||||||
|
req.query.path as string,
|
||||||
|
req.query.file as string,
|
||||||
|
);
|
||||||
|
res.send({ code: 200, data: content });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/:file',
|
'/:file',
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
try {
|
||||||
const filePath = join(
|
const scriptService = Container.get(ScriptService);
|
||||||
config.scriptPath,
|
const content = await scriptService.getFile(
|
||||||
req.query.path as string,
|
req.query.path as string,
|
||||||
req.params.file,
|
req.params.file,
|
||||||
);
|
);
|
||||||
const content = getFileContentByName(filePath);
|
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -94,7 +126,7 @@ export default (app: Router) => {
|
|||||||
path += '/';
|
path += '/';
|
||||||
}
|
}
|
||||||
if (!path.startsWith('/')) {
|
if (!path.startsWith('/')) {
|
||||||
path = `${config.scriptPath}${path}`;
|
path = join(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({
|
||||||
@@ -104,12 +136,12 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (req.file) {
|
if (req.file) {
|
||||||
fs.renameSync(req.file.path, join(path, req.file.filename));
|
await fs.rename(req.file.path, join(path, filename));
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (directory) {
|
if (directory) {
|
||||||
fs.mkdirSync(join(path, directory), { recursive: true });
|
await fs.mkdir(join(path, directory), { recursive: true });
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,16 +153,17 @@ export default (app: Router) => {
|
|||||||
`${originFilename.replace(/\//g, '')}`,
|
`${originFilename.replace(/\//g, '')}`,
|
||||||
);
|
);
|
||||||
const filePath = join(path, `${filename.replace(/\//g, '')}`);
|
const filePath = join(path, `${filename.replace(/\//g, '')}`);
|
||||||
if (fs.existsSync(originFilePath)) {
|
const fileExists = await fileExist(filePath);
|
||||||
fs.copyFileSync(
|
if (fileExists) {
|
||||||
|
await fs.copyFile(
|
||||||
originFilePath,
|
originFilePath,
|
||||||
`${config.bakPath}${originFilename.replace(/\//g, '')}`,
|
join(config.bakPath, originFilename.replace(/\//g, '')),
|
||||||
);
|
);
|
||||||
if (filename !== originFilename) {
|
if (filename !== originFilename) {
|
||||||
fs.unlinkSync(originFilePath);
|
await rmPath(originFilePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fs.writeFileSync(filePath, content);
|
await fs.writeFile(filePath, content);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -156,7 +189,7 @@ export default (app: Router) => {
|
|||||||
path: string;
|
path: string;
|
||||||
};
|
};
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
const filePath = join(config.scriptPath, path, filename);
|
||||||
fs.writeFileSync(filePath, content);
|
await fs.writeFile(filePath, content);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -182,11 +215,7 @@ export default (app: Router) => {
|
|||||||
type: string;
|
type: string;
|
||||||
};
|
};
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
const filePath = join(config.scriptPath, path, filename);
|
||||||
if (type === 'directory') {
|
await rmPath(filePath);
|
||||||
emptyDir(filePath);
|
|
||||||
} else {
|
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
}
|
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -207,7 +236,7 @@ export default (app: Router) => {
|
|||||||
let { filename } = req.body as {
|
let { filename } = req.body as {
|
||||||
filename: string;
|
filename: string;
|
||||||
};
|
};
|
||||||
const filePath = `${config.scriptPath}${filename}`;
|
const filePath = join(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', //告诉浏览器这是一个二进制文件
|
||||||
@@ -239,7 +268,7 @@ export default (app: Router) => {
|
|||||||
let { filename, content, path } = 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}`);
|
||||||
fs.writeFileSync(filePath, content || '', { encoding: 'utf8' });
|
await fs.writeFile(filePath, content || '', { encoding: 'utf8' });
|
||||||
|
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const result = await scriptService.runScript(filePath);
|
const result = await scriptService.runScript(filePath);
|
||||||
@@ -260,14 +289,17 @@ 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 {
|
||||||
let { filename, path, pid } = req.body;
|
let { filename, path, pid } = 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, pid);
|
||||||
|
setTimeout(() => {
|
||||||
|
rmPath(logPath);
|
||||||
|
}, 3000);
|
||||||
res.send(result);
|
res.send(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -294,7 +326,7 @@ export default (app: Router) => {
|
|||||||
};
|
};
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
const filePath = join(config.scriptPath, path, filename);
|
||||||
const newPath = join(config.scriptPath, path, newFilename);
|
const newPath = join(config.scriptPath, path, newFilename);
|
||||||
fs.renameSync(filePath, newPath);
|
await fs.rename(filePath, newPath);
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -50,6 +50,8 @@ export default (app: Router) => {
|
|||||||
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),
|
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) => {
|
||||||
@@ -179,6 +181,8 @@ export default (app: Router) => {
|
|||||||
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),
|
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(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -206,12 +210,16 @@ 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);
|
const data = await subscriptionService.remove(req.body, req.query);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
|
import { Container } from 'typedi';
|
||||||
|
import { Logger } from 'winston';
|
||||||
|
import * as fs from 'fs/promises';
|
||||||
|
import config from '../config';
|
||||||
|
import SystemService from '../services/system';
|
||||||
|
import { celebrate, Joi } from 'celebrate';
|
||||||
|
import UserService from '../services/user';
|
||||||
|
import {
|
||||||
|
getUniqPath,
|
||||||
|
handleLogPath,
|
||||||
|
parseVersion,
|
||||||
|
promiseExec,
|
||||||
|
} from '../config/util';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import multer from 'multer';
|
||||||
|
|
||||||
|
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) => {
|
||||||
|
app.use('/system', route);
|
||||||
|
|
||||||
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const userService = Container.get(UserService);
|
||||||
|
const authInfo = await userService.getUserInfo();
|
||||||
|
const { version, changeLog, changeLogLink, publishTime } =
|
||||||
|
await parseVersion(config.versionFile);
|
||||||
|
|
||||||
|
let isInitialized = true;
|
||||||
|
if (
|
||||||
|
Object.keys(authInfo).length === 2 &&
|
||||||
|
authInfo.username === 'admin' &&
|
||||||
|
authInfo.password === 'admin'
|
||||||
|
) {
|
||||||
|
isInitialized = false;
|
||||||
|
}
|
||||||
|
res.send({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
isInitialized,
|
||||||
|
version,
|
||||||
|
publishTime: dayjs(publishTime).unix(),
|
||||||
|
branch: process.env.QL_BRANCH || 'master',
|
||||||
|
changeLog,
|
||||||
|
changeLogLink,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/config',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const data = await systemService.getSystemConfig();
|
||||||
|
res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/log-remove-frequency',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
logRemoveFrequency: Joi.number().allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.updateLogRemoveFrequency(req.body);
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/cron-concurrency',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
cronConcurrency: Joi.number().allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.updateCronConcurrency(req.body);
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/dependence-proxy',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
dependenceProxy: Joi.string().allow('').allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.updateDependenceProxy(req.body);
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/node-mirror',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
nodeMirror: Joi.string().allow('').allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
res.setHeader('Content-type', 'application/octet-stream');
|
||||||
|
await systemService.updateNodeMirror(req.body, res);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/python-mirror',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
pythonMirror: Joi.string().allow('').allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.updatePythonMirror(req.body);
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/linux-mirror',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
linuxMirror: Joi.string().allow('').allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
res.setHeader('Content-type', 'application/octet-stream');
|
||||||
|
await systemService.updateLinuxMirror(req.body, res);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/update-check',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.checkUpdate();
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/update',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.updateSystem();
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/reload',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
type: Joi.string().optional().allow('').allow(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
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(
|
||||||
|
'/notify',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
title: Joi.string().required(),
|
||||||
|
content: 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.notify(req.body);
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
|
await fs.appendFile(absolutePath, `\n${message}`);
|
||||||
|
},
|
||||||
|
onLog: async (message: string) => {
|
||||||
|
res.write(`\n${message}`);
|
||||||
|
const absolutePath = await handleLogPath(logPath);
|
||||||
|
await fs.appendFile(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,6 +6,7 @@ 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();
|
||||||
|
|
||||||
@@ -26,6 +27,10 @@ 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(),
|
||||||
@@ -69,6 +74,9 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
|
if (process.env.DeployEnv === 'demo') {
|
||||||
|
return res.send({ code: 450, message: '未知错误' });
|
||||||
|
}
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
await userService.updateUsernameAndPassword(req.body);
|
await userService.updateUsernameAndPassword(req.body);
|
||||||
res.send({ code: 200, message: '更新成功' });
|
res.send({ code: 200, message: '更新成功' });
|
||||||
@@ -2,7 +2,6 @@ import 'reflect-metadata'; // We need this in order to use @Decorators
|
|||||||
import config from './config';
|
import config from './config';
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
import Logger from './loaders/logger';
|
import Logger from './loaders/logger';
|
||||||
import path from 'path';
|
|
||||||
|
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -16,11 +15,14 @@ async function startServer() {
|
|||||||
await require('./loaders/app').default({ expressApp: app });
|
await require('./loaders/app').default({ expressApp: app });
|
||||||
|
|
||||||
const server = app
|
const server = app
|
||||||
.listen(config.port, () => {
|
.listen(config.port, '0.0.0.0', () => {
|
||||||
Logger.debug(`✌️ 后端服务启动成功!`);
|
Logger.debug(`✌️ 后端服务启动成功!`);
|
||||||
|
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,25 @@
|
|||||||
|
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} `;
|
||||||
|
|
||||||
|
export const SAMPLE_FILES = [
|
||||||
|
{
|
||||||
|
title: 'config.sample.sh',
|
||||||
|
value: 'sample/config.sample.sh',
|
||||||
|
target: 'config.sh',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'notify.js',
|
||||||
|
value: 'sample/notify.js',
|
||||||
|
target: 'data/scripts/sendNotify.js',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'notify.py',
|
||||||
|
value: 'sample/notify.py',
|
||||||
|
target: 'data/scripts/notify.py',
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { createRandomString } from './util';
|
import { createRandomString } from './share';
|
||||||
|
|
||||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||||
|
|
||||||
if (!process.env.QL_DIR) {
|
if (!process.env.QL_DIR) {
|
||||||
// 声明QL_DIR环境变量
|
// 声明QL_DIR环境变量
|
||||||
let qlHomePath = path.join(__dirname, '../../../../');
|
let qlHomePath = path.join(__dirname, '../../');
|
||||||
// 生产环境
|
// 生产环境
|
||||||
if (qlHomePath.endsWith('/static/')) {
|
if (qlHomePath.endsWith('/static/')) {
|
||||||
qlHomePath = path.join(qlHomePath, '../');
|
qlHomePath = path.join(qlHomePath, '../');
|
||||||
@@ -19,7 +19,14 @@ const lastVersionFile = `https://qn.whyour.cn/version.yaml`;
|
|||||||
const rootPath = process.env.QL_DIR as string;
|
const rootPath = process.env.QL_DIR as string;
|
||||||
const envFound = dotenv.config({ path: path.join(rootPath, '.env') });
|
const envFound = dotenv.config({ path: path.join(rootPath, '.env') });
|
||||||
|
|
||||||
const dataPath = path.join(rootPath, 'data/');
|
let dataPath = path.join(rootPath, 'data/');
|
||||||
|
|
||||||
|
if (process.env.QL_DATA_DIR) {
|
||||||
|
dataPath = process.env.QL_DATA_DIR.replace(/\/$/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
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/');
|
||||||
@@ -27,8 +34,12 @@ 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 jsEnvFile = path.join(configPath, 'env.js');
|
||||||
|
const pyEnvFile = path.join(configPath, 'env.py');
|
||||||
const confFile = path.join(configPath, 'config.sh');
|
const confFile = path.join(configPath, 'config.sh');
|
||||||
const crontabFile = path.join(configPath, 'crontab.list');
|
const crontabFile = path.join(configPath, 'crontab.list');
|
||||||
const authConfigFile = path.join(configPath, 'auth.json');
|
const authConfigFile = path.join(configPath, 'auth.json');
|
||||||
@@ -41,6 +52,9 @@ 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, 'version.yaml');
|
||||||
|
const dataTgzFile = path.join(tmpPath, 'data.tgz');
|
||||||
|
const shareShellFile = path.join(shellPath, 'share.sh');
|
||||||
|
const dependenceProxyFile = path.join(configPath, 'dependence-proxy.sh');
|
||||||
|
|
||||||
if (envFound.error) {
|
if (envFound.error) {
|
||||||
throw new Error("⚠️ Couldn't find .env file ⚠️");
|
throw new Error("⚠️ Couldn't find .env file ⚠️");
|
||||||
@@ -50,6 +64,7 @@ export default {
|
|||||||
port: parseInt(process.env.BACK_PORT as string, 10),
|
port: parseInt(process.env.BACK_PORT as string, 10),
|
||||||
cronPort: parseInt(process.env.CRON_PORT as string, 10),
|
cronPort: parseInt(process.env.CRON_PORT as string, 10),
|
||||||
publicPort: parseInt(process.env.PUBLIC_PORT as string, 10),
|
publicPort: parseInt(process.env.PUBLIC_PORT as string, 10),
|
||||||
|
updatePort: parseInt(process.env.UPDATE_PORT as string, 10),
|
||||||
secret: process.env.SECRET || createRandomString(16, 32),
|
secret: process.env.SECRET || createRandomString(16, 32),
|
||||||
logs: {
|
logs: {
|
||||||
level: process.env.LOG_LEVEL || 'silly',
|
level: process.env.LOG_LEVEL || 'silly',
|
||||||
@@ -58,6 +73,11 @@ export default {
|
|||||||
prefix: '/api',
|
prefix: '/api',
|
||||||
},
|
},
|
||||||
rootPath,
|
rootPath,
|
||||||
|
tmpPath,
|
||||||
|
dataPath,
|
||||||
|
dataTgzFile,
|
||||||
|
shareShellFile,
|
||||||
|
dependenceProxyFile,
|
||||||
configString,
|
configString,
|
||||||
loginFaild,
|
loginFaild,
|
||||||
authError,
|
authError,
|
||||||
@@ -69,6 +89,8 @@ export default {
|
|||||||
sampleFile,
|
sampleFile,
|
||||||
confFile,
|
confFile,
|
||||||
envFile,
|
envFile,
|
||||||
|
jsEnvFile,
|
||||||
|
pyEnvFile,
|
||||||
dbPath,
|
dbPath,
|
||||||
uploadPath,
|
uploadPath,
|
||||||
configPath,
|
configPath,
|
||||||
@@ -79,7 +101,10 @@ export default {
|
|||||||
'config.sh.sample',
|
'config.sh.sample',
|
||||||
'cookie.sh',
|
'cookie.sh',
|
||||||
'crontab.list',
|
'crontab.list',
|
||||||
|
'dependence-proxy.sh',
|
||||||
'env.sh',
|
'env.sh',
|
||||||
|
'env.js',
|
||||||
|
'env.py',
|
||||||
'token.json',
|
'token.json',
|
||||||
],
|
],
|
||||||
writePathList: [configPath, scriptPath],
|
writePathList: [configPath, scriptPath],
|
||||||
@@ -91,8 +116,15 @@ 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,
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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'),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
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('');
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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}" "${proxy || ''}" "${
|
||||||
|
isNil(autoAddCron) ? true : Boolean(autoAddCron)
|
||||||
|
}" "${isNil(autoDelCron) ? true : Boolean(autoDelCron)}"`;
|
||||||
|
} else {
|
||||||
|
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${
|
||||||
|
dependences || ''
|
||||||
|
}" "${branch || ''}" "${extensions || ''}" "${proxy || ''}" "${
|
||||||
|
isNil(autoAddCron) ? true : Boolean(autoAddCron)
|
||||||
|
}" "${isNil(autoDelCron) ? true : Boolean(autoDelCron)}"`;
|
||||||
|
}
|
||||||
|
return command;
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as fs from 'fs';
|
import * as fs from 'fs/promises';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import got from 'got';
|
import got from 'got';
|
||||||
import iconv from 'iconv-lite';
|
import iconv from 'iconv-lite';
|
||||||
@@ -7,23 +7,30 @@ import FormData from 'form-data';
|
|||||||
import psTreeFun from 'pstree.remy';
|
import psTreeFun from 'pstree.remy';
|
||||||
import { promisify } from 'util';
|
import { promisify } from 'util';
|
||||||
import { load } from 'js-yaml';
|
import { load } from 'js-yaml';
|
||||||
|
import config from './index';
|
||||||
|
import { TASK_COMMAND } from './const';
|
||||||
|
import Logger from '../loaders/logger';
|
||||||
|
|
||||||
export function getFileContentByName(fileName: string) {
|
export * from './share';
|
||||||
if (fs.existsSync(fileName)) {
|
|
||||||
return fs.readFileSync(fileName, 'utf8');
|
export async function getFileContentByName(fileName: string) {
|
||||||
|
const _exsit = await fileExist(fileName);
|
||||||
|
if (_exsit) {
|
||||||
|
return await fs.readFile(fileName, 'utf8');
|
||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getLastModifyFilePath(dir: string) {
|
export async function getLastModifyFilePath(dir: string) {
|
||||||
let filePath = '';
|
let filePath = '';
|
||||||
|
|
||||||
if (fs.existsSync(dir)) {
|
const _exsit = await fileExist(dir);
|
||||||
const arr = fs.readdirSync(dir);
|
if (_exsit) {
|
||||||
|
const arr = await fs.readdir(dir);
|
||||||
|
|
||||||
arr.forEach((item) => {
|
arr.forEach(async (item) => {
|
||||||
const fullpath = path.join(dir, item);
|
const fullpath = path.join(dir, item);
|
||||||
const stats = fs.statSync(fullpath);
|
const stats = await fs.lstat(fullpath);
|
||||||
if (stats.isFile()) {
|
if (stats.isFile()) {
|
||||||
if (stats.mtimeMs >= 0) {
|
if (stats.mtimeMs >= 0) {
|
||||||
filePath = fullpath;
|
filePath = fullpath;
|
||||||
@@ -34,91 +41,6 @@ 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') {
|
||||||
@@ -139,7 +61,8 @@ export async function getNetIp(req: any) {
|
|||||||
...req.ips,
|
...req.ips,
|
||||||
req.socket.remoteAddress,
|
req.socket.remoteAddress,
|
||||||
]),
|
]),
|
||||||
];
|
].filter(Boolean);
|
||||||
|
|
||||||
let ip = ipArray[0];
|
let ip = ipArray[0];
|
||||||
|
|
||||||
if (ipArray.length > 1) {
|
if (ipArray.length > 1) {
|
||||||
@@ -160,34 +83,42 @@ export async function getNetIp(req: any) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);
|
ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);
|
||||||
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 csdnApi = got
|
||||||
.get(`https://www.cip.cc/${ip}`, { timeout: 10000, retry: 0 })
|
.get(`https://searchplugin.csdn.net/api/v1/ip/get?ip=${ip}`, {
|
||||||
|
timeout: 10000,
|
||||||
|
retry: 0,
|
||||||
|
})
|
||||||
.text();
|
.text();
|
||||||
const ipApi = got
|
const pconlineApi = got
|
||||||
.get(`https://whois.pconline.com.cn/ipJson.jsp?ip=${ip}&json=true`, {
|
.get(`https://whois.pconline.com.cn/ipJson.jsp?ip=${ip}&json=true`, {
|
||||||
timeout: 10000,
|
timeout: 10000,
|
||||||
retry: 0,
|
retry: 0,
|
||||||
})
|
})
|
||||||
.buffer();
|
.buffer();
|
||||||
const [data, ipApiBody] = await await Promise.all<any>([baiduApi, ipApi]);
|
const [csdnBody, pconlineBody] = await await Promise.all<any>([
|
||||||
|
csdnApi,
|
||||||
const ipRegx = /.*IP :(.*)\n/;
|
pconlineApi,
|
||||||
const addrRegx = /.*数据二 :(.*)\n/;
|
]);
|
||||||
if (data && ipRegx.test(data) && addrRegx.test(data)) {
|
const csdnRes = JSON.parse(csdnBody);
|
||||||
const ip = data.match(ipRegx)[1];
|
const pconlineRes = JSON.parse(iconv.decode(pconlineBody, 'GBK'));
|
||||||
const addr = data.match(addrRegx)[1];
|
let address = '';
|
||||||
return { address: addr, ip };
|
if (csdnBody && csdnRes.code == 200) {
|
||||||
} else if (ipApiBody) {
|
address = csdnRes.data.address;
|
||||||
const { addr, ip } = JSON.parse(iconv.decode(ipApiBody, 'GBK'));
|
} else if (pconlineRes && pconlineRes.addr) {
|
||||||
return { address: `${addr}`, ip };
|
address = pconlineRes.addr;
|
||||||
} else {
|
|
||||||
return { address: `获取失败`, ip };
|
|
||||||
}
|
}
|
||||||
|
return { address, ip };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { address: `获取失败`, ip };
|
return { address: `获取失败`, ip };
|
||||||
}
|
}
|
||||||
@@ -227,22 +158,29 @@ export function getPlatform(userAgent: string): 'mobile' | 'desktop' {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function fileExist(file: any) {
|
export async function fileExist(file: any) {
|
||||||
return new Promise((resolve) => {
|
try {
|
||||||
try {
|
await fs.access(file);
|
||||||
fs.accessSync(file);
|
return true;
|
||||||
resolve(true);
|
} catch (error) {
|
||||||
} catch (error) {
|
return false;
|
||||||
resolve(false);
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createFile(file: string, data: string = '') {
|
export async function createFile(file: string, data: string = '') {
|
||||||
return new Promise((resolve) => {
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
await fs.writeFile(file, data);
|
||||||
fs.writeFileSync(file, data);
|
}
|
||||||
resolve(true);
|
|
||||||
});
|
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(
|
||||||
@@ -293,61 +231,76 @@ interface IFile {
|
|||||||
type: 'directory' | 'file';
|
type: 'directory' | 'file';
|
||||||
parent: string;
|
parent: string;
|
||||||
mtime: number;
|
mtime: number;
|
||||||
|
size?: number;
|
||||||
children?: IFile[];
|
children?: IFile[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dirSort(a: IFile, b: IFile) {
|
export function dirSort(a: IFile, b: IFile): number {
|
||||||
if (a.type !== b.type) return FileType[a.type] < FileType[b.type] ? -1 : 1;
|
if (a.type === 'file' && b.type === 'file') {
|
||||||
else if (a.mtime !== b.mtime) return a.mtime > b.mtime ? -1 : 1;
|
return b.mtime - a.mtime;
|
||||||
|
} else if (a.type === 'directory' && b.type === 'directory') {
|
||||||
|
return a.title.localeCompare(b.title);
|
||||||
|
} else {
|
||||||
|
return a.type === 'directory' ? -1 : 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readDirs(
|
export async function readDirs(
|
||||||
dir: string,
|
dir: string,
|
||||||
baseDir: string = '',
|
baseDir: string = '',
|
||||||
blacklist: string[] = [],
|
blacklist: string[] = [],
|
||||||
) {
|
sort: (a: IFile, b: IFile) => number = dirSort,
|
||||||
|
): Promise<IFile[]> {
|
||||||
const relativePath = path.relative(baseDir, dir);
|
const relativePath = path.relative(baseDir, dir);
|
||||||
const files = fs.readdirSync(dir);
|
const files = await fs.readdir(dir);
|
||||||
const result: any = files
|
const result: IFile[] = [];
|
||||||
.filter((x) => !blacklist.includes(x))
|
|
||||||
.map((file: string) => {
|
for (const file of files) {
|
||||||
const subPath = path.join(dir, file);
|
const subPath = path.join(dir, file);
|
||||||
const stats = fs.statSync(subPath);
|
const stats = await fs.lstat(subPath);
|
||||||
const key = path.join(relativePath, file);
|
const key = path.join(relativePath, file);
|
||||||
if (stats.isDirectory()) {
|
|
||||||
return {
|
if (blacklist.includes(file) || stats.isSymbolicLink()) {
|
||||||
title: file,
|
continue;
|
||||||
key,
|
}
|
||||||
type: 'directory',
|
|
||||||
parent: relativePath,
|
if (stats.isDirectory()) {
|
||||||
mtime: stats.mtime.getTime(),
|
const children = await readDirs(subPath, baseDir, blacklist, sort);
|
||||||
children: readDirs(subPath, baseDir).sort(dirSort),
|
result.push({
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
title: file,
|
title: file,
|
||||||
type: 'file',
|
|
||||||
isLeaf: true,
|
|
||||||
key,
|
key,
|
||||||
|
type: 'directory',
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
mtime: stats.mtime.getTime(),
|
mtime: stats.mtime.getTime(),
|
||||||
};
|
children: children.sort(sort),
|
||||||
});
|
});
|
||||||
return result.sort(dirSort);
|
} else {
|
||||||
|
result.push({
|
||||||
|
title: file,
|
||||||
|
type: 'file',
|
||||||
|
key,
|
||||||
|
parent: relativePath,
|
||||||
|
size: stats.size,
|
||||||
|
mtime: stats.mtime.getTime(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.sort(sort);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readDir(
|
export async function readDir(
|
||||||
dir: string,
|
dir: string,
|
||||||
baseDir: string = '',
|
baseDir: string = '',
|
||||||
blacklist: string[] = [],
|
blacklist: string[] = [],
|
||||||
) {
|
) {
|
||||||
const relativePath = path.relative(baseDir, dir);
|
const relativePath = path.relative(baseDir, dir);
|
||||||
const files = fs.readdirSync(dir);
|
const files = await fs.readdir(dir);
|
||||||
const result: any = files
|
const result: any = files
|
||||||
.filter((x) => !blacklist.includes(x))
|
.filter((x) => !blacklist.includes(x))
|
||||||
.map((file: string) => {
|
.map(async (file: string) => {
|
||||||
const subPath = path.join(dir, file);
|
const subPath = path.join(dir, file);
|
||||||
const stats = fs.statSync(subPath);
|
const stats = await fs.lstat(subPath);
|
||||||
const key = path.join(relativePath, file);
|
const key = path.join(relativePath, file);
|
||||||
return {
|
return {
|
||||||
title: file,
|
title: file,
|
||||||
@@ -359,30 +312,28 @@ export function readDir(
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function emptyDir(path: string) {
|
export async function promiseExec(command: string): Promise<string> {
|
||||||
const files = fs.readdirSync(path);
|
try {
|
||||||
files.forEach((file) => {
|
const { stderr, stdout } = await promisify(exec)(command, {
|
||||||
const filePath = `${path}/${file}`;
|
maxBuffer: 200 * 1024 * 1024,
|
||||||
const stats = fs.statSync(filePath);
|
encoding: 'utf8',
|
||||||
if (stats.isDirectory()) {
|
});
|
||||||
emptyDir(filePath);
|
return stdout || stderr;
|
||||||
} else {
|
} catch (error) {
|
||||||
fs.unlinkSync(filePath);
|
return JSON.stringify(error);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
fs.rmdirSync(path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function promiseExec(command: string): Promise<string> {
|
export async function promiseExecSuccess(command: string): Promise<string> {
|
||||||
return new Promise((resolve, reject) => {
|
try {
|
||||||
exec(
|
const { stdout } = await promisify(exec)(command, {
|
||||||
command,
|
maxBuffer: 200 * 1024 * 1024,
|
||||||
{ maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' },
|
encoding: 'utf8',
|
||||||
(err, stdout, stderr) => {
|
});
|
||||||
resolve(stdout || stderr || JSON.stringify(err));
|
return stdout || '';
|
||||||
},
|
} catch (error) {
|
||||||
);
|
return '';
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseHeaders(headers: string) {
|
export function parseHeaders(headers: string) {
|
||||||
@@ -409,37 +360,49 @@ export function parseHeaders(headers: string) {
|
|||||||
return parsed;
|
return parsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseString(
|
||||||
|
input: string,
|
||||||
|
valueFormatFn?: (v: string) => string,
|
||||||
|
): Record<string, string> {
|
||||||
|
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
|
||||||
|
const matches: Record<string, string> = {};
|
||||||
|
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(input)) !== null) {
|
||||||
|
const [, key, value] = match;
|
||||||
|
const _key = key.trim();
|
||||||
|
if (!_key || matches[_key]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let _value = value.trim();
|
||||||
|
|
||||||
|
try {
|
||||||
|
_value = valueFormatFn ? valueFormatFn(_value) : _value;
|
||||||
|
const jsonValue = JSON.parse(_value);
|
||||||
|
matches[_key] = jsonValue;
|
||||||
|
} catch (error) {
|
||||||
|
matches[_key] = _value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
export function parseBody(
|
export function parseBody(
|
||||||
body: string,
|
body: string,
|
||||||
contentType:
|
contentType:
|
||||||
| 'application/json'
|
| 'application/json'
|
||||||
| 'multipart/form-data'
|
| 'multipart/form-data'
|
||||||
| 'application/x-www-form-urlencoded',
|
| 'application/x-www-form-urlencoded'
|
||||||
|
| 'text/plain',
|
||||||
|
valueFormatFn?: (v: string) => string,
|
||||||
) {
|
) {
|
||||||
if (!body) return '';
|
if (contentType === 'text/plain' || !body) {
|
||||||
|
return valueFormatFn && body ? valueFormatFn(body) : body;
|
||||||
|
}
|
||||||
|
|
||||||
const parsed: any = {};
|
const parsed = parseString(body, valueFormatFn);
|
||||||
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) {
|
switch (contentType) {
|
||||||
case 'multipart/form-data':
|
case 'multipart/form-data':
|
||||||
@@ -469,31 +432,96 @@ export function psTree(pid: number): Promise<number[]> {
|
|||||||
|
|
||||||
export async function killTask(pid: number) {
|
export async function killTask(pid: number) {
|
||||||
const pids = await psTree(pid);
|
const pids = await psTree(pid);
|
||||||
// SIGALRM 14 时钟信号
|
|
||||||
if (pids.length) {
|
if (pids.length) {
|
||||||
process.kill(pids[0], 14);
|
try {
|
||||||
|
[pid, ...pids].reverse().forEach((x) => {
|
||||||
|
process.kill(x, 15);
|
||||||
|
});
|
||||||
|
} catch (error) {}
|
||||||
} else {
|
} else {
|
||||||
process.kill(pid, 14);
|
process.kill(pid, 2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPid(name: string) {
|
export async function getPid(cmd: string) {
|
||||||
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
const taskCommand = `ps -eo pid,command | grep "${cmd}" | grep -v grep | awk '{print $1}' | head -1 | xargs echo -n`;
|
||||||
const execAsync = promisify(exec);
|
const pid = await promiseExec(taskCommand);
|
||||||
let pid = (await execAsync(taskCommand)).stdout;
|
return pid ? Number(pid) : undefined;
|
||||||
return Number(pid);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IVersion {
|
interface IVersion {
|
||||||
version: string;
|
version: string;
|
||||||
changeLogLink: string;
|
changeLogLink: string;
|
||||||
changeLog: string;
|
changeLog: string;
|
||||||
|
publishTime: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function parseVersion(path: string): Promise<IVersion> {
|
export async function parseVersion(path: string): Promise<IVersion> {
|
||||||
return load(await promisify(fs.readFile)(path, 'utf8')) as IVersion;
|
return load(await fs.readFile(path, 'utf8')) as IVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function parseContentVersion(content: string): Promise<IVersion> {
|
export async function parseContentVersion(content: string): Promise<IVersion> {
|
||||||
return load(content) as 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 {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rmPath(path: string) {
|
||||||
|
try {
|
||||||
|
const _exsit = await fileExist(path);
|
||||||
|
if (_exsit) {
|
||||||
|
await fs.rm(path, { force: true, recursive: true, maxRetries: 5 });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
Logger.error('[rmPath失败]', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,15 +17,19 @@ 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;
|
this.command = options.command.trim();
|
||||||
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 =
|
||||||
options.status && CrontabStatus[options.status]
|
typeof options.status === 'number' && CrontabStatus[options.status]
|
||||||
? options.status
|
? options.status
|
||||||
: CrontabStatus.idle;
|
: CrontabStatus.idle;
|
||||||
this.timestamp = new Date().toString();
|
this.timestamp = new Date().toString();
|
||||||
@@ -37,17 +41,21 @@ 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',
|
'running' = 0,
|
||||||
'idle',
|
'queued' = 0.5,
|
||||||
|
'idle' = 1,
|
||||||
'disabled',
|
'disabled',
|
||||||
'queued',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
|
export 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',
|
||||||
@@ -72,4 +80,8 @@ 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,
|
||||||
});
|
});
|
||||||
@@ -39,7 +39,7 @@ export class CrontabView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CronViewInstance
|
export interface CronViewInstance
|
||||||
extends Model<CrontabView, CrontabView>,
|
extends Model<CrontabView, CrontabView>,
|
||||||
CrontabView {}
|
CrontabView {}
|
||||||
export const CrontabViewModel = sequelize.define<CronViewInstance>(
|
export const CrontabViewModel = sequelize.define<CronViewInstance>(
|
||||||
@@ -4,18 +4,21 @@ 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?: number;
|
name: string;
|
||||||
log?: string[];
|
log?: string[];
|
||||||
remark?: string;
|
remark?: string;
|
||||||
|
|
||||||
constructor(options: Dependence) {
|
constructor(options: Dependence) {
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
this.status = options.status || DependenceStatus.installing;
|
this.status =
|
||||||
|
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;
|
this.name = options.name.trim();
|
||||||
this.log = options.log || [];
|
this.log = options.log || [];
|
||||||
this.remark = options.remark || '';
|
this.remark = options.remark || '';
|
||||||
}
|
}
|
||||||
@@ -28,6 +31,8 @@ export enum DependenceStatus {
|
|||||||
'removing',
|
'removing',
|
||||||
'removed',
|
'removed',
|
||||||
'removeFailed',
|
'removeFailed',
|
||||||
|
'queued',
|
||||||
|
'cancelled',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum DependenceTypes {
|
export enum DependenceTypes {
|
||||||
@@ -38,17 +43,29 @@ export enum DependenceTypes {
|
|||||||
|
|
||||||
export enum InstallDependenceCommandTypes {
|
export enum InstallDependenceCommandTypes {
|
||||||
'pnpm add -g',
|
'pnpm add -g',
|
||||||
'pip3 install',
|
'pip3 install --disable-pip-version-check --root-user-action=ignore',
|
||||||
'apk add',
|
'apk add --no-check-certificate',
|
||||||
|
}
|
||||||
|
|
||||||
|
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 -y',
|
'pip3 uninstall --disable-pip-version-check --root-user-action=ignore -y',
|
||||||
'apk del',
|
'apk del',
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DependenceInstance
|
export interface DependenceInstance
|
||||||
extends Model<Dependence, Dependence>,
|
extends Model<Dependence, Dependence>,
|
||||||
Dependence {}
|
Dependence {}
|
||||||
export const DependenceModel = sequelize.define<DependenceInstance>(
|
export const DependenceModel = sequelize.define<DependenceInstance>(
|
||||||
@@ -13,7 +13,10 @@ 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 = options.status || EnvStatus.normal;
|
this.status =
|
||||||
|
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;
|
||||||
@@ -28,10 +31,10 @@ export enum EnvStatus {
|
|||||||
|
|
||||||
export const maxPosition = 9000000000000000;
|
export const maxPosition = 9000000000000000;
|
||||||
export const initPosition = 4500000000000000;
|
export const initPosition = 4500000000000000;
|
||||||
export const stepPosition = 10000000;
|
export const stepPosition = 10000000000;
|
||||||
export const minPosition = 100;
|
export const minPosition = 100;
|
||||||
|
|
||||||
interface EnvInstance extends Model<Env, Env>, Env {}
|
export 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,
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Sequelize, Transaction } from 'sequelize';
|
import { Sequelize, Transaction } 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: `${config.dbPath}database.sqlite`,
|
storage: join(config.dbPath, 'database.sqlite'),
|
||||||
logging: false,
|
logging: false,
|
||||||
retry: {
|
retry: {
|
||||||
max: 10,
|
max: 10,
|
||||||
@@ -14,9 +14,12 @@ export enum NotificationMode {
|
|||||||
'aibotk' = 'aibotk',
|
'aibotk' = 'aibotk',
|
||||||
'iGot' = 'iGot',
|
'iGot' = 'iGot',
|
||||||
'pushPlus' = 'pushPlus',
|
'pushPlus' = 'pushPlus',
|
||||||
|
'wePlusBot' = 'wePlusBot',
|
||||||
'email' = 'email',
|
'email' = 'email',
|
||||||
|
'pushMe' = 'pushMe',
|
||||||
'feishu' = 'feishu',
|
'feishu' = 'feishu',
|
||||||
'webhook' = 'webhook',
|
'webhook' = 'webhook',
|
||||||
|
'chronocat' = 'Chronocat',
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class NotificationBaseInfo {
|
abstract class NotificationBaseInfo {
|
||||||
@@ -54,6 +57,9 @@ export class BarkNotification extends NotificationBaseInfo {
|
|||||||
public barkIcon = 'https://qn.whyour.cn/logo.png';
|
public barkIcon = 'https://qn.whyour.cn/logo.png';
|
||||||
public barkSound = '';
|
public barkSound = '';
|
||||||
public barkGroup = 'qinglong';
|
public barkGroup = 'qinglong';
|
||||||
|
public barkLevel = 'active';
|
||||||
|
public barkUrl = '';
|
||||||
|
public barkArchive=""
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TelegramBotNotification extends NotificationBaseInfo {
|
export class TelegramBotNotification extends NotificationBaseInfo {
|
||||||
@@ -62,7 +68,7 @@ export class TelegramBotNotification extends NotificationBaseInfo {
|
|||||||
public telegramBotProxyHost = '';
|
public telegramBotProxyHost = '';
|
||||||
public telegramBotProxyPort = '';
|
public telegramBotProxyPort = '';
|
||||||
public telegramBotProxyAuth = '';
|
public telegramBotProxyAuth = '';
|
||||||
public telegramBotApiHost = 'api.telegram.org';
|
public telegramBotApiHost = 'https://api.telegram.org';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class DingtalkBotNotification extends NotificationBaseInfo {
|
export class DingtalkBotNotification extends NotificationBaseInfo {
|
||||||
@@ -72,10 +78,12 @@ 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 {
|
export class AibotkNotification extends NotificationBaseInfo {
|
||||||
@@ -93,12 +101,29 @@ export class PushPlusNotification extends NotificationBaseInfo {
|
|||||||
public pushPlusUser = '';
|
public pushPlusUser = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class WePlusBotNotification extends NotificationBaseInfo {
|
||||||
|
public wePlusBotToken = '';
|
||||||
|
public wePlusBotReceiver = '';
|
||||||
|
public wePlusBotVersion = '';
|
||||||
|
}
|
||||||
|
|
||||||
export class EmailNotification extends NotificationBaseInfo {
|
export class EmailNotification extends NotificationBaseInfo {
|
||||||
public emailService: string = '';
|
public emailService: string = '';
|
||||||
public emailUser: string = '';
|
public emailUser: string = '';
|
||||||
public emailPass: string = '';
|
public emailPass: string = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class PushMeNotification extends NotificationBaseInfo {
|
||||||
|
public pushMeKey: string = '';
|
||||||
|
public pushMeUrl: string = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ChronocatNotification extends NotificationBaseInfo {
|
||||||
|
public chronocatURL: string = '';
|
||||||
|
public chronocatQQ: string = '';
|
||||||
|
public chronocatToken: string = '';
|
||||||
|
}
|
||||||
|
|
||||||
export class WebhookNotification extends NotificationBaseInfo {
|
export class WebhookNotification extends NotificationBaseInfo {
|
||||||
public webhookHeaders: string = '';
|
public webhookHeaders: string = '';
|
||||||
public webhookBody: string = '';
|
public webhookBody: string = '';
|
||||||
@@ -128,6 +153,10 @@ export interface NotificationInfo
|
|||||||
AibotkNotification,
|
AibotkNotification,
|
||||||
IGotNotification,
|
IGotNotification,
|
||||||
PushPlusNotification,
|
PushPlusNotification,
|
||||||
|
WePlusBotNotification,
|
||||||
EmailNotification,
|
EmailNotification,
|
||||||
|
PushMeNotification,
|
||||||
WebhookNotification,
|
WebhookNotification,
|
||||||
|
ChronocatNotification,
|
||||||
LarkNotification {}
|
LarkNotification {}
|
||||||
|
|
||||||
@@ -26,14 +26,7 @@ export interface AppToken {
|
|||||||
|
|
||||||
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs';
|
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs';
|
||||||
|
|
||||||
export enum CrontabStatus {
|
export interface AppInstance extends Model<App, App>, App {}
|
||||||
'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,
|
||||||
@@ -16,4 +16,7 @@ export type SockMessageType =
|
|||||||
| 'uninstallDependence'
|
| 'uninstallDependence'
|
||||||
| 'updateSystemVersion'
|
| 'updateSystemVersion'
|
||||||
| 'manuallyRunScript'
|
| 'manuallyRunScript'
|
||||||
| 'runSubscriptionEnd';
|
| 'runSubscriptionEnd'
|
||||||
|
| 'reloadSystem'
|
||||||
|
| 'updateNodeMirror'
|
||||||
|
| 'updateLinuxMirror';
|
||||||
@@ -29,14 +29,16 @@ export class Subscription {
|
|||||||
sub_before?: string;
|
sub_before?: string;
|
||||||
sub_after?: string;
|
sub_after?: string;
|
||||||
proxy?: 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 =
|
||||||
options.status && SubscriptionStatus[options.status]
|
typeof options.status === 'number' && SubscriptionStatus[options.status]
|
||||||
? options.status
|
? options.status
|
||||||
: SubscriptionStatus.idle;
|
: SubscriptionStatus.idle;
|
||||||
this.url = options.url;
|
this.url = options.url;
|
||||||
@@ -56,6 +58,8 @@ export class Subscription {
|
|||||||
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.proxy = options.proxy;
|
||||||
|
this.autoAddCron = options.autoAddCron ? 1 : 0;
|
||||||
|
this.autoDelCron = options.autoDelCron ? 1 : 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +70,7 @@ export enum SubscriptionStatus {
|
|||||||
'queued',
|
'queued',
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SubscriptionInstance
|
export interface SubscriptionInstance
|
||||||
extends Model<Subscription, Subscription>,
|
extends Model<Subscription, Subscription>,
|
||||||
Subscription {}
|
Subscription {}
|
||||||
export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
||||||
@@ -105,5 +109,7 @@ export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
|||||||
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 },
|
proxy: { type: DataTypes.STRING, allowNull: true },
|
||||||
|
autoAddCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
|
autoDelCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { sequelize } from '.';
|
||||||
|
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||||
|
import { NotificationInfo } from './notify';
|
||||||
|
|
||||||
|
export class SystemInfo {
|
||||||
|
ip?: string;
|
||||||
|
type: AuthDataType;
|
||||||
|
info?: SystemModelInfo;
|
||||||
|
id?: number;
|
||||||
|
|
||||||
|
constructor(options: SystemInfo) {
|
||||||
|
this.ip = options.ip;
|
||||||
|
this.info = options.info;
|
||||||
|
this.type = options.type;
|
||||||
|
this.id = options.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum LoginStatus {
|
||||||
|
'success',
|
||||||
|
'fail',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum AuthDataType {
|
||||||
|
'loginLog' = 'loginLog',
|
||||||
|
'authToken' = 'authToken',
|
||||||
|
'notification' = 'notification',
|
||||||
|
'removeLogFrequency' = 'removeLogFrequency',
|
||||||
|
'systemConfig' = 'systemConfig',
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SystemConfigInfo {
|
||||||
|
logRemoveFrequency?: number;
|
||||||
|
cronConcurrency?: number;
|
||||||
|
dependenceProxy?: string;
|
||||||
|
nodeMirror?: string;
|
||||||
|
pythonMirror?: string;
|
||||||
|
linuxMirror?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginLogInfo {
|
||||||
|
timestamp?: number;
|
||||||
|
address?: string;
|
||||||
|
ip?: string;
|
||||||
|
platform?: string;
|
||||||
|
status?: LoginStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SystemModelInfo = SystemConfigInfo &
|
||||||
|
Partial<NotificationInfo> &
|
||||||
|
LoginLogInfo;
|
||||||
|
|
||||||
|
export interface SystemInstance extends Model<SystemInfo, SystemInfo>, SystemInfo { }
|
||||||
|
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
|
||||||
|
ip: DataTypes.STRING,
|
||||||
|
type: DataTypes.STRING,
|
||||||
|
info: {
|
||||||
|
type: DataTypes.JSON,
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -3,3 +3,5 @@ declare namespace Express {
|
|||||||
platform: 'desktop' | 'mobile';
|
platform: 'desktop' | 'mobile';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
declare module 'pstree.remy';
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import expressLoader from './express';
|
||||||
|
import depInjectorLoader from './depInjector';
|
||||||
|
import Logger from './logger';
|
||||||
|
import initData from './initData';
|
||||||
|
import { Application } from 'express';
|
||||||
|
import linkDeps from './deps';
|
||||||
|
import initTask from './initTask';
|
||||||
|
|
||||||
|
export default async ({ expressApp }: { expressApp: Application }) => {
|
||||||
|
depInjectorLoader();
|
||||||
|
Logger.info('✌️ Dependency loaded');
|
||||||
|
console.log('✌️ Dependency loaded');
|
||||||
|
|
||||||
|
await initData();
|
||||||
|
Logger.info('✌️ Init data loaded');
|
||||||
|
console.log('✌️ Init data loaded');
|
||||||
|
|
||||||
|
await linkDeps();
|
||||||
|
Logger.info('✌️ Link deps loaded');
|
||||||
|
console.log('✌️ Link deps loaded');
|
||||||
|
|
||||||
|
initTask();
|
||||||
|
Logger.info('✌️ Init task loaded');
|
||||||
|
console.log('✌️ Init task loaded');
|
||||||
|
|
||||||
|
expressLoader({ app: expressApp });
|
||||||
|
Logger.info('✌️ Express loaded');
|
||||||
|
console.log('✌️ Express loaded');
|
||||||
|
};
|
||||||
@@ -5,7 +5,7 @@ import { EnvModel } from '../data/env';
|
|||||||
import { CrontabModel } from '../data/cron';
|
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 { SystemModel } from '../data/system';
|
||||||
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 { CrontabViewModel } from '../data/cronView';
|
||||||
@@ -17,7 +17,7 @@ export default async () => {
|
|||||||
await CrontabModel.sync();
|
await CrontabModel.sync();
|
||||||
await DependenceModel.sync();
|
await DependenceModel.sync();
|
||||||
await AppModel.sync();
|
await AppModel.sync();
|
||||||
await AuthModel.sync();
|
await SystemModel.sync();
|
||||||
await EnvModel.sync();
|
await EnvModel.sync();
|
||||||
await SubscriptionModel.sync();
|
await SubscriptionModel.sync();
|
||||||
await CrontabViewModel.sync();
|
await CrontabViewModel.sync();
|
||||||
@@ -36,6 +36,28 @@ export default async () => {
|
|||||||
try {
|
try {
|
||||||
await sequelize.query('alter table CrontabViews add column type NUMBER');
|
await sequelize.query('alter table CrontabViews add column type NUMBER');
|
||||||
} catch (error) {}
|
} 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');
|
||||||
@@ -53,7 +75,7 @@ export default async () => {
|
|||||||
const dependenceCount = await DependenceModel.count();
|
const dependenceCount = await DependenceModel.count();
|
||||||
const envCount = await EnvModel.count();
|
const envCount = await EnvModel.count();
|
||||||
const appCount = await AppModel.count();
|
const appCount = await AppModel.count();
|
||||||
const authCount = await AuthModel.count();
|
const authCount = await SystemModel.count();
|
||||||
if (crondbExist && cronCount === 0) {
|
if (crondbExist && cronCount === 0) {
|
||||||
const cronDb = new DataStore({
|
const cronDb = new DataStore({
|
||||||
filename: cronDbFile,
|
filename: cronDbFile,
|
||||||
@@ -105,13 +127,14 @@ export default async () => {
|
|||||||
});
|
});
|
||||||
authDb.persistence.compactDatafile();
|
authDb.persistence.compactDatafile();
|
||||||
authDb.find({}).exec(async (err, docs) => {
|
authDb.find({}).exec(async (err, docs) => {
|
||||||
await AuthModel.bulkCreate(docs, { ignoreDuplicates: true });
|
await SystemModel.bulkCreate(docs, { ignoreDuplicates: true });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('✌️ DB loaded');
|
||||||
Logger.info('✌️ DB loaded');
|
Logger.info('✌️ DB loaded');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.info('✌️ DB load failed');
|
console.error('✌️ DB load failed');
|
||||||
Logger.info(error);
|
Logger.error(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,20 +1,19 @@
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs/promises';
|
||||||
import chokidar from 'chokidar';
|
import chokidar from 'chokidar';
|
||||||
import config from '../config/index';
|
import config from '../config/index';
|
||||||
import { promiseExec } from '../config/util';
|
import { fileExist, promiseExec, rmPath } from '../config/util';
|
||||||
|
|
||||||
function linkToNodeModule(src: string, dst?: string) {
|
async function linkToNodeModule(src: string, dst?: string) {
|
||||||
const target = path.join(config.rootPath, 'node_modules', dst || src);
|
const target = path.join(config.rootPath, 'node_modules', dst || src);
|
||||||
const source = path.join(config.rootPath, src);
|
const source = path.join(config.rootPath, src);
|
||||||
|
|
||||||
fs.lstat(target, (err, stat) => {
|
try {
|
||||||
if (!stat) {
|
const stats = await fs.lstat(target);
|
||||||
fs.symlink(source, target, 'dir', (err) => {
|
if (!stats) {
|
||||||
if (err) throw err;
|
await fs.symlink(source, target, 'dir');
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
} catch (error) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function linkCommand() {
|
async function linkCommand() {
|
||||||
@@ -24,26 +23,27 @@ async function linkCommand() {
|
|||||||
{
|
{
|
||||||
src: 'update.sh',
|
src: 'update.sh',
|
||||||
dest: 'ql',
|
dest: 'ql',
|
||||||
|
tmp: 'ql_tmp',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
src: 'task.sh',
|
src: 'task.sh',
|
||||||
dest: 'task',
|
dest: 'task',
|
||||||
|
tmp: 'task_tmp',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const link of linkShell) {
|
for (const link of linkShell) {
|
||||||
const source = path.join(config.rootPath, 'shell', link.src);
|
const source = path.join(config.rootPath, 'shell', link.src);
|
||||||
const target = path.join(commandDir, link.dest);
|
const target = path.join(commandDir, link.dest);
|
||||||
if (fs.existsSync(target)) {
|
const tmpTarget = path.join(commandDir, link.tmp);
|
||||||
fs.unlinkSync(target);
|
await fs.symlink(source, tmpTarget);
|
||||||
}
|
await fs.rename(tmpTarget, target);
|
||||||
fs.symlink(source, target, (err) => {});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async (src: string = 'deps') => {
|
export default async (src: string = 'deps') => {
|
||||||
await linkCommand();
|
await linkCommand();
|
||||||
linkToNodeModule(src);
|
await linkToNodeModule(src);
|
||||||
|
|
||||||
const source = path.join(config.rootPath, src);
|
const source = path.join(config.rootPath, src);
|
||||||
const watcher = chokidar.watch(source, {
|
const watcher = chokidar.watch(source, {
|
||||||
@@ -4,38 +4,41 @@ 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, { UnauthorizedError } from 'express-jwt';
|
||||||
import fs from 'fs';
|
import fs from 'fs/promises';
|
||||||
import { getPlatform, getToken } from '../config/util';
|
import { getPlatform, getToken, safeJSONParse } 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.set('trust proxy', 'loopback');
|
||||||
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((req, res, next) => {
|
app.use(
|
||||||
if (req.path.startsWith('/api') || req.path.startsWith('/open')) {
|
'/api/public',
|
||||||
next();
|
createProxyMiddleware({
|
||||||
} else {
|
target: `http://0.0.0.0:${config.publicPort}/api`,
|
||||||
return handler(req, res, {
|
changeOrigin: true,
|
||||||
public: 'static/dist',
|
pathRewrite: { '/api/public': '' },
|
||||||
rewrites: [{ source: '**', destination: '/index.html' }],
|
logProvider: () => Logger,
|
||||||
});
|
}),
|
||||||
}
|
);
|
||||||
});
|
|
||||||
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 as string,
|
secret: config.secret,
|
||||||
algorithms: ['HS384'],
|
algorithms: ['HS384'],
|
||||||
}).unless({
|
}).unless({
|
||||||
path: [...config.apiWhiteList, /^\/open\//],
|
path: [...config.apiWhiteList, /^\/open\//],
|
||||||
@@ -80,9 +83,9 @@ export default ({ app }: { app: Application }) => {
|
|||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
const data = await fs.readFile(config.authConfigFile, 'utf8');
|
||||||
if (data && headerToken) {
|
if (data && headerToken) {
|
||||||
const { token = '', tokens = {} } = JSON.parse(data);
|
const { token = '', tokens = {} } = safeJSONParse(data);
|
||||||
if (headerToken === token || tokens[req.platform] === headerToken) {
|
if (headerToken === token || tokens[req.platform] === headerToken) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
@@ -102,14 +105,12 @@ export default ({ app }: { app: Application }) => {
|
|||||||
}
|
}
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
const authInfo = await userService.getUserInfo();
|
const authInfo = await userService.getUserInfo();
|
||||||
const envCount = await EnvModel.count();
|
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -170,18 +171,6 @@ export default ({ app }: { app: Application }) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
app.use(
|
|
||||||
Sentry.Handlers.errorHandler({
|
|
||||||
shouldHandleError(error) {
|
|
||||||
// 排除 SequelizeUniqueConstraintError / NotFound
|
|
||||||
return (
|
|
||||||
!['SequelizeUniqueConstraintError'].includes(error.name) ||
|
|
||||||
!['Not Found'].includes(error.message)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
err: Error & { status: number },
|
err: Error & { status: number },
|
||||||
@@ -4,17 +4,67 @@ import { Container } from 'typedi';
|
|||||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||||
import CronService from '../services/cron';
|
import CronService from '../services/cron';
|
||||||
import EnvService from '../services/env';
|
import EnvService from '../services/env';
|
||||||
import groupBy from 'lodash/groupBy';
|
import { DependenceModel, DependenceStatus } from '../data/dependence';
|
||||||
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 { CrontabViewModel, CronViewType } from '../data/cronView';
|
||||||
import { initPosition } from '../data/env';
|
import { initPosition } from '../data/env';
|
||||||
|
import { AuthDataType, SystemModel } from '../data/system';
|
||||||
|
import SystemService from '../services/system';
|
||||||
|
|
||||||
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);
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
|
||||||
|
// 初始化增加系统配置
|
||||||
|
await SystemModel.upsert({ type: AuthDataType.systemConfig });
|
||||||
|
await SystemModel.upsert({ type: AuthDataType.notification });
|
||||||
|
|
||||||
|
const installDependencies = () => {
|
||||||
|
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
||||||
|
DependenceModel.findAll({
|
||||||
|
where: {},
|
||||||
|
order: [
|
||||||
|
['type', 'DESC'],
|
||||||
|
['createdAt', 'DESC'],
|
||||||
|
],
|
||||||
|
raw: true,
|
||||||
|
}).then(async (docs) => {
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ status: DependenceStatus.queued, log: [] },
|
||||||
|
{ where: { id: docs.map((x) => x.id!) } },
|
||||||
|
);
|
||||||
|
setTimeout(() => {
|
||||||
|
dependenceService.installDependenceOneByOne(docs);
|
||||||
|
}, 5000);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 初始化更新 linux/python/nodejs 镜像源配置
|
||||||
|
const systemConfig = await systemService.getSystemConfig();
|
||||||
|
if (systemConfig.info?.pythonMirror) {
|
||||||
|
systemService.updatePythonMirror({
|
||||||
|
pythonMirror: systemConfig.info?.pythonMirror,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (systemConfig.info?.linuxMirror) {
|
||||||
|
systemService.updateLinuxMirror(
|
||||||
|
{
|
||||||
|
linuxMirror: systemConfig.info?.linuxMirror,
|
||||||
|
},
|
||||||
|
undefined,
|
||||||
|
() => installDependencies(),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
installDependencies();
|
||||||
|
}
|
||||||
|
if (systemConfig.info?.nodeMirror) {
|
||||||
|
systemService.updateNodeMirror({
|
||||||
|
nodeMirror: systemConfig.info?.nodeMirror,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 初始化新增默认全部任务视图
|
// 初始化新增默认全部任务视图
|
||||||
CrontabViewModel.findAll({
|
CrontabViewModel.findAll({
|
||||||
@@ -31,27 +81,9 @@ export default async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 初始化更新所有任务状态为空闲
|
// 初始化更新所有任务状态为空闲
|
||||||
await CrontabModel.update(
|
await CrontabModel.update({ status: CrontabStatus.idle }, { where: {} });
|
||||||
{ status: CrontabStatus.idle },
|
|
||||||
{ where: { status: [CrontabStatus.running, CrontabStatus.queued] } },
|
|
||||||
);
|
|
||||||
|
|
||||||
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
// 初始化时执行一次所有的 ql repo 任务
|
||||||
DependenceModel.findAll({
|
|
||||||
where: {},
|
|
||||||
order: [['type', 'DESC']],
|
|
||||||
raw: true,
|
|
||||||
}).then(async (docs) => {
|
|
||||||
const groups = groupBy(docs, 'type');
|
|
||||||
const keys = Object.keys(groups).sort((a, b) => parseInt(b) - parseInt(a));
|
|
||||||
for (const key of keys) {
|
|
||||||
const group = groups[key];
|
|
||||||
const depIds = group.map((x) => x.id);
|
|
||||||
await dependenceService.reInstall(depIds as number[]);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 初始化时执行一次所有的ql repo 任务
|
|
||||||
CrontabModel.findAll({
|
CrontabModel.findAll({
|
||||||
where: {
|
where: {
|
||||||
isDisabled: { [Op.ne]: 1 },
|
isDisabled: { [Op.ne]: 1 },
|
||||||
@@ -93,7 +125,7 @@ export default async () => {
|
|||||||
if (doc.command.includes(`${config.rootPath}/log/`)) {
|
if (doc.command.includes(`${config.rootPath}/log/`)) {
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{
|
{
|
||||||
command: `${config.rootPath}/data/log/${doc.command.replace(
|
command: `${config.dataPath}/log/${doc.command.replace(
|
||||||
`${config.rootPath}/log/`,
|
`${config.rootPath}/log/`,
|
||||||
'',
|
'',
|
||||||
)}`,
|
)}`,
|
||||||
@@ -104,7 +136,7 @@ export default async () => {
|
|||||||
if (doc.command.includes(`${config.rootPath}/config/`)) {
|
if (doc.command.includes(`${config.rootPath}/config/`)) {
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{
|
{
|
||||||
command: `${config.rootPath}/data/config/${doc.command.replace(
|
command: `${config.dataPath}/config/${doc.command.replace(
|
||||||
`${config.rootPath}/config/`,
|
`${config.rootPath}/config/`,
|
||||||
'',
|
'',
|
||||||
)}`,
|
)}`,
|
||||||
@@ -115,7 +147,7 @@ export default async () => {
|
|||||||
if (doc.command.includes(`${config.rootPath}/db/`)) {
|
if (doc.command.includes(`${config.rootPath}/db/`)) {
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{
|
{
|
||||||
command: `${config.rootPath}/data/db/${doc.command.replace(
|
command: `${config.dataPath}/db/${doc.command.replace(
|
||||||
`${config.rootPath}/db/`,
|
`${config.rootPath}/db/`,
|
||||||
'',
|
'',
|
||||||
)}`,
|
)}`,
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import fs from 'fs/promises';
|
||||||
|
import path from 'path';
|
||||||
|
import os from 'os';
|
||||||
|
import Logger from './logger';
|
||||||
|
import { fileExist } from '../config/util';
|
||||||
|
|
||||||
|
const rootPath = process.env.QL_DIR as string;
|
||||||
|
let dataPath = path.join(rootPath, 'data/');
|
||||||
|
|
||||||
|
if (process.env.QL_DATA_DIR) {
|
||||||
|
dataPath = process.env.QL_DATA_DIR.replace(/\/$/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
const configPath = path.join(dataPath, 'config/');
|
||||||
|
const scriptPath = path.join(dataPath, 'scripts/');
|
||||||
|
const logPath = path.join(dataPath, 'log/');
|
||||||
|
const uploadPath = path.join(dataPath, 'upload/');
|
||||||
|
const bakPath = path.join(dataPath, 'bak/');
|
||||||
|
const samplePath = path.join(rootPath, 'sample/');
|
||||||
|
const tmpPath = path.join(logPath, '.tmp/');
|
||||||
|
const confFile = path.join(configPath, 'config.sh');
|
||||||
|
const authConfigFile = path.join(configPath, 'auth.json');
|
||||||
|
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
||||||
|
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 sshPath = path.resolve(homedir, '.ssh');
|
||||||
|
const sshdPath = path.join(dataPath, 'ssh.d');
|
||||||
|
const systemLogPath = path.join(dataPath, 'syslog');
|
||||||
|
|
||||||
|
export default async () => {
|
||||||
|
const authFileExist = await fileExist(authConfigFile);
|
||||||
|
const confFileExist = await fileExist(confFile);
|
||||||
|
const scriptDirExist = await fileExist(scriptPath);
|
||||||
|
const logDirExist = await fileExist(logPath);
|
||||||
|
const configDirExist = await fileExist(configPath);
|
||||||
|
const uploadDirExist = await fileExist(uploadPath);
|
||||||
|
const sshDirExist = await fileExist(sshPath);
|
||||||
|
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) {
|
||||||
|
await fs.mkdir(configPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!scriptDirExist) {
|
||||||
|
await fs.mkdir(scriptPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!logDirExist) {
|
||||||
|
await fs.mkdir(logPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tmpDirExist) {
|
||||||
|
await fs.mkdir(tmpPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!uploadDirExist) {
|
||||||
|
await fs.mkdir(uploadPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sshDirExist) {
|
||||||
|
await fs.mkdir(sshPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!bakDirExist) {
|
||||||
|
await fs.mkdir(bakPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sshdDirExist) {
|
||||||
|
await fs.mkdir(sshdPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!systemLogDirExist) {
|
||||||
|
await fs.mkdir(systemLogPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化文件
|
||||||
|
if (!authFileExist) {
|
||||||
|
await fs.writeFile(authConfigFile, await fs.readFile(sampleAuthFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!confFileExist) {
|
||||||
|
await fs.writeFile(confFile, await fs.readFile(sampleConfigFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!scriptNotifyJsFileExist) {
|
||||||
|
await fs.writeFile(
|
||||||
|
scriptNotifyJsFile,
|
||||||
|
await fs.readFile(sampleNotifyJsFile),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!scriptNotifyPyFileExist) {
|
||||||
|
await fs.writeFile(
|
||||||
|
scriptNotifyPyFile,
|
||||||
|
await fs.readFile(sampleNotifyPyFile),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TaskBeforeFileExist) {
|
||||||
|
await fs.writeFile(TaskBeforeFile, await fs.readFile(sampleTaskShellFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TaskAfterFileExist) {
|
||||||
|
await fs.writeFile(TaskAfterFile, await fs.readFile(sampleTaskShellFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.info('✌️ Init file down');
|
||||||
|
console.log('✌️ Init file down');
|
||||||
|
};
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import SystemService from '../services/system';
|
import SystemService from '../services/system';
|
||||||
import ScheduleService from '../services/schedule';
|
import ScheduleService, { ScheduleTaskType } from '../services/schedule';
|
||||||
import SubscriptionService from '../services/subscription';
|
import SubscriptionService from '../services/subscription';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { fileExist } from '../config/util';
|
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);
|
||||||
@@ -11,8 +12,9 @@ export default async () => {
|
|||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
|
|
||||||
// 生成内置token
|
// 生成内置token
|
||||||
let tokenCommand = `ts-node-transpile-only ${config.rootPath}/back/token.ts`;
|
let tokenCommand = `tsx ${join(config.rootPath, 'back/token.ts')}`;
|
||||||
const tokenFile = `${config.rootPath}static/build/token.js`;
|
const tokenFile = join(config.rootPath, 'static/build/token.js');
|
||||||
|
|
||||||
if (await fileExist(tokenFile)) {
|
if (await fileExist(tokenFile)) {
|
||||||
tokenCommand = `node ${tokenFile}`;
|
tokenCommand = `node ${tokenFile}`;
|
||||||
}
|
}
|
||||||
@@ -20,32 +22,30 @@ export default async () => {
|
|||||||
id: NaN,
|
id: NaN,
|
||||||
name: '生成token',
|
name: '生成token',
|
||||||
command: tokenCommand,
|
command: tokenCommand,
|
||||||
};
|
} as ScheduleTaskType;
|
||||||
|
await scheduleService.cancelIntervalTask(cron);
|
||||||
scheduleService.createIntervalTask(cron, {
|
scheduleService.createIntervalTask(cron, {
|
||||||
days: 28,
|
days: 28,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 运行删除日志任务
|
// 运行删除日志任务
|
||||||
const data = await systemService.getLogRemoveFrequency();
|
const data = await systemService.getSystemConfig();
|
||||||
if (data && data.info && data.info.frequency) {
|
if (data && data.info && data.info.logRemoveFrequency) {
|
||||||
const cron = {
|
const rmlogCron = {
|
||||||
id: data.id,
|
id: data.id as number,
|
||||||
name: '删除日志',
|
name: '删除日志',
|
||||||
command: `ql rmlog ${data.info.frequency}`,
|
command: `ql rmlog ${data.info.logRemoveFrequency}`,
|
||||||
};
|
};
|
||||||
scheduleService.createIntervalTask(cron, {
|
await scheduleService.cancelIntervalTask(rmlogCron);
|
||||||
days: data.info.frequency,
|
scheduleService.createIntervalTask(rmlogCron, {
|
||||||
|
days: data.info.logRemoveFrequency,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 运行所有订阅
|
// 运行所有订阅
|
||||||
|
await subscriptionService.setSshConfig();
|
||||||
const subs = await subscriptionService.list();
|
const subs = await subscriptionService.list();
|
||||||
for (const sub of subs) {
|
for (const sub of subs) {
|
||||||
await subscriptionService.handleTask(
|
subscriptionService.handleTask(sub, !sub.is_disabled, !sub.is_disabled);
|
||||||
sub,
|
|
||||||
!sub.is_disabled,
|
|
||||||
true,
|
|
||||||
!sub.is_disabled,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import winston from 'winston';
|
||||||
|
import 'winston-daily-rotate-file';
|
||||||
|
import config from '../config';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
const levelMap: Record<string, string> = {
|
||||||
|
info: '🔵',
|
||||||
|
warn: '🟡',
|
||||||
|
error: '🔴',
|
||||||
|
debug: '🔶'
|
||||||
|
}
|
||||||
|
|
||||||
|
const customFormat = winston.format.combine(
|
||||||
|
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({
|
||||||
|
level: config.logs.level,
|
||||||
|
levels: winston.config.npm.levels,
|
||||||
|
transports: [
|
||||||
|
new winston.transports.DailyRotateFile({
|
||||||
|
filename: path.join(config.systemLogPath, '%DATE%.log'),
|
||||||
|
...defaultOptions,
|
||||||
|
})
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
export default LoggerInstance;
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import { Application } from 'express';
|
import { Application } from 'express';
|
||||||
import * as Sentry from '@sentry/node';
|
import * as Sentry from '@sentry/node';
|
||||||
import * as Tracing from '@sentry/tracing';
|
|
||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
@@ -10,12 +9,18 @@ export default async ({ expressApp }: { expressApp: Application }) => {
|
|||||||
const { version } = await parseVersion(config.versionFile);
|
const { version } = await parseVersion(config.versionFile);
|
||||||
|
|
||||||
Sentry.init({
|
Sentry.init({
|
||||||
dsn: 'https://f4b5b55fb3c645b29a5dc2d70a1a4ef4@o1098464.ingest.sentry.io/6122819',
|
ignoreErrors: [
|
||||||
|
/SequelizeUniqueConstraintError/i,
|
||||||
|
/Validation error/i,
|
||||||
|
/UnauthorizedError/i,
|
||||||
|
/celebrate request validation failed/i,
|
||||||
|
],
|
||||||
|
dsn: 'https://8b5c84cfef3e22541bc84de0ed00497b@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 Sentry.Integrations.Express({ app: expressApp }),
|
||||||
],
|
],
|
||||||
tracesSampleRate: 0.1,
|
tracesSampleRate: 0.8,
|
||||||
release: version,
|
release: version,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -23,4 +28,5 @@ export default async ({ expressApp }: { expressApp: Application }) => {
|
|||||||
expressApp.use(Sentry.Handlers.tracingHandler());
|
expressApp.use(Sentry.Handlers.tracingHandler());
|
||||||
|
|
||||||
Logger.info('✌️ Sentry loaded');
|
Logger.info('✌️ Sentry loaded');
|
||||||
|
console.log('✌️ Sentry loaded');
|
||||||
};
|
};
|
||||||
@@ -6,11 +6,11 @@ export default async ({ server }: { server: Server }) => {
|
|||||||
await Sock({ server });
|
await Sock({ server });
|
||||||
Logger.info('✌️ Sock loaded');
|
Logger.info('✌️ Sock loaded');
|
||||||
|
|
||||||
process.on('SIGINT', () => {
|
process.on('uncaughtException', (error) => {
|
||||||
Logger.info('✌️ Server need close');
|
Logger.error('Uncaught exception:', error);
|
||||||
server.close(() => {
|
});
|
||||||
Logger.info('✌️ Server closed');
|
|
||||||
process.exit(0);
|
process.on('unhandledRejection', (reason, promise) => {
|
||||||
});
|
Logger.error('Unhandled rejection:', reason, promise);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -1,26 +1,25 @@
|
|||||||
import sockJs from 'sockjs';
|
import sockJs from 'sockjs';
|
||||||
import { Server } from 'http';
|
import { Server } from 'http';
|
||||||
import Logger from './logger';
|
|
||||||
import { Container } from 'typedi';
|
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/promises';
|
||||||
import { getPlatform } from '../config/util';
|
import { getPlatform, safeJSONParse } 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: () => {} });
|
||||||
const sockService = Container.get(SockService);
|
const sockService = Container.get(SockService);
|
||||||
|
|
||||||
echo.on('connection', (conn) => {
|
echo.on('connection', async (conn) => {
|
||||||
if (!conn.headers || !conn.url || !conn.pathname) {
|
if (!conn.headers || !conn.url || !conn.pathname) {
|
||||||
conn.close('404');
|
conn.close('404');
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
const data = await fs.readFile(config.authConfigFile, 'utf8');
|
||||||
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 = {} } = JSON.parse(data);
|
const { token = '', tokens = {} } = safeJSONParse(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);
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import bodyParser from 'body-parser';
|
||||||
|
import { errors } from 'celebrate';
|
||||||
|
import cors from 'cors';
|
||||||
|
import { Application, NextFunction, Request, Response } from 'express';
|
||||||
|
import jwt from 'express-jwt';
|
||||||
|
import Container from 'typedi';
|
||||||
|
import config from '../config';
|
||||||
|
import SystemService from '../services/system';
|
||||||
|
import Logger from './logger';
|
||||||
|
|
||||||
|
export default ({ app }: { app: Application }) => {
|
||||||
|
app.set('trust proxy', 'loopback');
|
||||||
|
app.use(cors());
|
||||||
|
|
||||||
|
app.use(bodyParser.json({ limit: '50mb' }));
|
||||||
|
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
jwt({
|
||||||
|
secret: config.secret,
|
||||||
|
algorithms: ['HS384'],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
app.put(
|
||||||
|
'/api/reload',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.reloadSystem();
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
Logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.put(
|
||||||
|
'/api/system',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.reloadSystem('system');
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
Logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.put(
|
||||||
|
'/api/data',
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.reloadSystem('data');
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
Logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
const err: any = new Error('Not Found');
|
||||||
|
err['status'] = 404;
|
||||||
|
next(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use(errors());
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
(
|
||||||
|
err: Error & { status: number },
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction,
|
||||||
|
) => {
|
||||||
|
if (err.name === 'UnauthorizedError') {
|
||||||
|
return res
|
||||||
|
.status(err.status)
|
||||||
|
.send({ code: 401, message: err.message })
|
||||||
|
.end();
|
||||||
|
}
|
||||||
|
return next(err);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
(
|
||||||
|
err: Error & { status: number },
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction,
|
||||||
|
) => {
|
||||||
|
res.status(err.status || 500);
|
||||||
|
res.json({
|
||||||
|
code: err.status || 500,
|
||||||
|
message: err.message,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
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 {}
|
||||||
@@ -0,0 +1,502 @@
|
|||||||
|
/* 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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
/* 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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import Logger from './loaders/logger';
|
||||||
|
import config from './config';
|
||||||
|
import { HealthClient } from './protos/health';
|
||||||
|
import { credentials } from '@grpc/grpc-js';
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const client = new HealthClient(
|
||||||
|
`0.0.0.0:${config.cronPort}`,
|
||||||
|
credentials.createInsecure(),
|
||||||
|
{ 'grpc.enable_http_proxy': 0 },
|
||||||
|
);
|
||||||
|
|
||||||
|
app.get('/api/health', (req, res) => {
|
||||||
|
client.check({ service: 'cron' }, (err, response) => {
|
||||||
|
if (err) {
|
||||||
|
return res.status(200).send({ code: 500, error: err });
|
||||||
|
}
|
||||||
|
return res.status(200).send({ code: 200, data: response });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app
|
||||||
|
.listen(config.publicPort, '0.0.0.0', async () => {
|
||||||
|
await require('./loaders/sentry').default({ expressApp: app });
|
||||||
|
await require('./loaders/db').default();
|
||||||
|
|
||||||
|
Logger.debug(`✌️ 公共服务启动成功!`);
|
||||||
|
console.debug(`✌️ 公共服务启动成功!`);
|
||||||
|
process.send?.('ready');
|
||||||
|
})
|
||||||
|
.on('error', (err) => {
|
||||||
|
Logger.error(err);
|
||||||
|
console.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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 };
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
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(),
|
||||||
|
{ 'grpc.enable_http_proxy': 0 },
|
||||||
|
);
|
||||||
|
|
||||||
|
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();
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import nodeSchedule from 'node-schedule';
|
||||||
|
import { ToadScheduler } from 'toad-scheduler';
|
||||||
|
|
||||||
|
export const scheduleStacks = new Map<string, nodeSchedule.Job[]>();
|
||||||
|
|
||||||
|
export const intervalSchedule = new ToadScheduler();
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
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 };
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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 --noproxy '*' 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 };
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
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({ 'grpc.enable_http_proxy': 0 });
|
||||||
|
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');
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import path, { join } from 'path';
|
||||||
|
import config from '../config';
|
||||||
|
import { getFileContentByName } from '../config/util';
|
||||||
|
import { Response } from 'express';
|
||||||
|
import got from 'got';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class ConfigService {
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
public async getFile(filePath: string, res: Response) {
|
||||||
|
let content = '';
|
||||||
|
if (config.blackFileList.includes(filePath) || !filePath) {
|
||||||
|
res.send({ code: 403, message: '文件无法访问' });
|
||||||
|
}
|
||||||
|
if (filePath.startsWith('sample/')) {
|
||||||
|
const res = await got.get(
|
||||||
|
`https://gitlab.com/whyour/qinglong/-/raw/master/${filePath}`,
|
||||||
|
);
|
||||||
|
content = res.body;
|
||||||
|
} else if (filePath.startsWith('data/scripts/')) {
|
||||||
|
content = await getFileContentByName(join(config.rootPath, filePath));
|
||||||
|
} else {
|
||||||
|
content = await getFileContentByName(join(config.configPath, filePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
res.send({ code: 200, data: content });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,26 +2,33 @@ 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, spawn } from 'child_process';
|
import { exec, execSync } from 'child_process';
|
||||||
import fs from 'fs';
|
import fs from 'fs/promises';
|
||||||
import cron_parser from 'cron-parser';
|
import cron_parser from 'cron-parser';
|
||||||
import {
|
import {
|
||||||
getFileContentByName,
|
getFileContentByName,
|
||||||
concurrentRun,
|
|
||||||
fileExist,
|
fileExist,
|
||||||
killTask,
|
killTask,
|
||||||
|
getUniqPath,
|
||||||
|
safeJSONParse,
|
||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import { promises, existsSync } from 'fs';
|
import { Op, where, col as colFn, FindOptions, fn } from 'sequelize';
|
||||||
import { Op, where, col as colFn } 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 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 isNodeCron(cron: Crontab) {
|
||||||
const { schedule } = cron;
|
const { schedule, extra_schedules } = cron;
|
||||||
if (schedule?.split(/ +/).length === 6) {
|
if (Number(schedule?.split(/ +/).length) > 5 || extra_schedules?.length) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -31,7 +38,18 @@ 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);
|
||||||
await this.set_crontab(this.isSixCron(doc));
|
if (this.isNodeCron(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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,9 +58,28 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: Crontab): Promise<Crontab> {
|
public async update(payload: Crontab): Promise<Crontab> {
|
||||||
payload.saved = false;
|
const doc = await this.getDb({ id: payload.id });
|
||||||
const newDoc = await this.updateDb(payload);
|
const tab = new Crontab({ ...doc, ...payload });
|
||||||
await this.set_crontab(this.isSixCron(newDoc));
|
tab.saved = false;
|
||||||
|
const newDoc = await this.updateDb(tab);
|
||||||
|
if (doc.isDisabled === 1) {
|
||||||
|
return newDoc;
|
||||||
|
}
|
||||||
|
if (this.isNodeCron(doc)) {
|
||||||
|
await cronClient.delCron([String(doc.id)]);
|
||||||
|
}
|
||||||
|
if (this.isNodeCron(newDoc)) {
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +103,7 @@ export default class CronService {
|
|||||||
last_running_time: number;
|
last_running_time: number;
|
||||||
last_execution_time: number;
|
last_execution_time: number;
|
||||||
}) {
|
}) {
|
||||||
const options: any = {
|
let options: any = {
|
||||||
status,
|
status,
|
||||||
pid,
|
pid,
|
||||||
log_path,
|
log_path,
|
||||||
@@ -76,12 +113,28 @@ export default class CronService {
|
|||||||
options.last_running_time = last_running_time;
|
options.last_running_time = last_running_time;
|
||||||
}
|
}
|
||||||
|
|
||||||
return await CrontabModel.update({ ...options }, { where: { id: ids } });
|
for (const id of ids) {
|
||||||
|
let cron;
|
||||||
|
try {
|
||||||
|
cron = await this.getDb({ id });
|
||||||
|
} catch (err) {}
|
||||||
|
if (!cron) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
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 this.set_crontab(true);
|
await cronClient.delCron(ids.map(String));
|
||||||
|
await this.set_crontab();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async pin(ids: number[]) {
|
public async pin(ids: number[]) {
|
||||||
@@ -139,7 +192,7 @@ export default class CronService {
|
|||||||
case 'In':
|
case 'In':
|
||||||
q[Op.or] = [
|
q[Op.or] = [
|
||||||
{
|
{
|
||||||
[property]: value,
|
[property]: Array.isArray(value) ? value : [value],
|
||||||
},
|
},
|
||||||
property === 'status' && value.includes(2)
|
property === 'status' && value.includes(2)
|
||||||
? { isDisabled: 1 }
|
? { isDisabled: 1 }
|
||||||
@@ -150,7 +203,7 @@ export default class CronService {
|
|||||||
q[Op.and] = [
|
q[Op.and] = [
|
||||||
{
|
{
|
||||||
[property]: {
|
[property]: {
|
||||||
[Op.notIn]: value,
|
[Op.notIn]: Array.isArray(value) ? value : [value],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
property === 'status' && value.includes(2)
|
property === 'status' && value.includes(2)
|
||||||
@@ -167,17 +220,13 @@ export default class CronService {
|
|||||||
{
|
{
|
||||||
[operate2]: [
|
[operate2]: [
|
||||||
{ [operate]: `%${value}%` },
|
{ [operate]: `%${value}%` },
|
||||||
{ [operate]: `%${encodeURIComponent(value)}%` },
|
{ [operate]: `%${encodeURI(value)}%` },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
[operate2]: [
|
[operate2]: [
|
||||||
where(colFn(property), operate, `%${value}%`),
|
where(colFn(property), operate, `%${value}%`),
|
||||||
where(
|
where(colFn(property), operate, `%${encodeURI(value)}%`),
|
||||||
colFn(property),
|
|
||||||
operate,
|
|
||||||
`%${encodeURIComponent(value)}%`,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -204,7 +253,7 @@ export default class CronService {
|
|||||||
q[column] = {
|
q[column] = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${textArray[1]}%` },
|
{ [Op.like]: `%${textArray[1]}%` },
|
||||||
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
{ [Op.like]: `%${encodeURI(textArray[1])}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
break;
|
break;
|
||||||
@@ -212,7 +261,7 @@ export default class CronService {
|
|||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
{ [Op.like]: `%${encodeURI(searchText)}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
q[Op.or] = [
|
q[Op.or] = [
|
||||||
@@ -243,8 +292,15 @@ export default class CronService {
|
|||||||
const filterKeys: any = Object.keys(filterQuery);
|
const filterKeys: any = Object.keys(filterQuery);
|
||||||
for (const key of filterKeys) {
|
for (const key of filterKeys) {
|
||||||
let q: any = {};
|
let q: any = {};
|
||||||
if (filterKeys[key]) {
|
if (!filterQuery[key]) continue;
|
||||||
q[key] = filterKeys[key];
|
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);
|
query[Op.and].push(q);
|
||||||
}
|
}
|
||||||
@@ -259,6 +315,19 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async find({
|
||||||
|
log_path,
|
||||||
|
}: {
|
||||||
|
log_path: string;
|
||||||
|
}): Promise<Crontab | null> {
|
||||||
|
try {
|
||||||
|
const result = await CrontabModel.findOne({ where: { log_path } });
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async crontabs(params?: {
|
public async crontabs(params?: {
|
||||||
searchValue: string;
|
searchValue: string;
|
||||||
page: string;
|
page: string;
|
||||||
@@ -270,9 +339,9 @@ export default class CronService {
|
|||||||
const searchText = params?.searchValue;
|
const searchText = params?.searchValue;
|
||||||
const page = Number(params?.page || '0');
|
const page = Number(params?.page || '0');
|
||||||
const size = Number(params?.size || '0');
|
const size = Number(params?.size || '0');
|
||||||
const viewQuery = JSON.parse(params?.queryString || '{}');
|
const viewQuery = safeJSONParse(params?.queryString);
|
||||||
const filterQuery = JSON.parse(params?.filters || '{}');
|
const filterQuery = safeJSONParse(params?.filters);
|
||||||
const sorterQuery = JSON.parse(params?.sorter || '{}');
|
const sorterQuery = safeJSONParse(params?.sorter);
|
||||||
|
|
||||||
let query: any = {};
|
let query: any = {};
|
||||||
let order = [
|
let order = [
|
||||||
@@ -310,9 +379,12 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<Crontab> {
|
public async getDb(query: FindOptions<Crontab>['where']): 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);
|
if (!doc) {
|
||||||
|
throw new Error(`Cron ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async run(ids: number[]) {
|
public async run(ids: number[]) {
|
||||||
@@ -320,10 +392,9 @@ export default class CronService {
|
|||||||
{ status: CrontabStatus.queued },
|
{ status: CrontabStatus.queued },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
);
|
);
|
||||||
concurrentRun(
|
ids.forEach((id) => {
|
||||||
ids.map((id) => async () => await this.runSingle(id)),
|
this.runSingle(id);
|
||||||
10,
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop(ids: number[]) {
|
public async stop(ids: number[]) {
|
||||||
@@ -333,7 +404,7 @@ export default class CronService {
|
|||||||
try {
|
try {
|
||||||
await killTask(doc.pid);
|
await killTask(doc.pid);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.silly(error);
|
this.logger.error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -344,76 +415,87 @@ export default class CronService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runSingle(cronId: number): Promise<number> {
|
private async runSingle(cronId: number): Promise<number | void> {
|
||||||
return new Promise(async (resolve: any) => {
|
return taskLimit.manualRunWithCronLimit(() => {
|
||||||
const cron = await this.getDb({ id: cronId });
|
return new Promise(async (resolve: any) => {
|
||||||
if (cron.status !== CrontabStatus.queued) {
|
const cron = await this.getDb({ id: cronId });
|
||||||
resolve();
|
const params = {
|
||||||
return;
|
name: cron.name,
|
||||||
}
|
command: cron.command,
|
||||||
|
schedule: cron.schedule,
|
||||||
let { id, command, log_path } = cron;
|
extraSchedules: cron.extra_schedules,
|
||||||
const absolutePath = path.resolve(config.logPath, `${log_path}`);
|
};
|
||||||
const logFileExist = log_path && (await fileExist(absolutePath));
|
if (cron.status !== CrontabStatus.queued) {
|
||||||
|
resolve(params);
|
||||||
this.logger.silly('Running job');
|
return;
|
||||||
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.endsWith('.py') ||
|
|
||||||
cmdStr.endsWith('.pyc') ||
|
|
||||||
cmdStr.endsWith('.sh') ||
|
|
||||||
cmdStr.endsWith('.ts')
|
|
||||||
) {
|
|
||||||
cmdStr = `${cmdStr} now`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cp = spawn(`ID=${id} ${cmdStr}`, { shell: '/bin/bash' });
|
|
||||||
|
|
||||||
await CrontabModel.update(
|
|
||||||
{ status: CrontabStatus.running, pid: cp.pid },
|
|
||||||
{ where: { id } },
|
|
||||||
);
|
|
||||||
cp.stderr.on('data', (data) => {
|
|
||||||
if (logFileExist) {
|
|
||||||
fs.appendFileSync(`${absolutePath}`, `${data.toString()}`);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
cp.on('error', (err) => {
|
|
||||||
if (logFileExist) {
|
|
||||||
fs.appendFileSync(`${absolutePath}`, `${JSON.stringify(err)}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.on('exit', async (code, signal) => {
|
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`任务 ${command} 进程id: ${cp.pid} 退出,退出码 ${code}`,
|
`[panel][开始执行任务] 参数 ${JSON.stringify(params)}`,
|
||||||
);
|
);
|
||||||
});
|
|
||||||
cp.on('close', async (code) => {
|
let { id, command, log_path } = cron;
|
||||||
|
const uniqPath = await getUniqPath(command, `${id}`);
|
||||||
|
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
||||||
|
const logDirPath = path.resolve(config.logPath, `${uniqPath}`);
|
||||||
|
if (log_path?.split('/')?.every((x) => x !== uniqPath)) {
|
||||||
|
await fs.mkdir(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,
|
||||||
|
true,
|
||||||
|
)}`,
|
||||||
|
{ shell: '/bin/bash' },
|
||||||
|
);
|
||||||
|
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{ status: CrontabStatus.idle, pid: undefined },
|
{ status: CrontabStatus.running, pid: cp.pid, log_path: logPath },
|
||||||
{ where: { id } },
|
{ where: { id } },
|
||||||
);
|
);
|
||||||
resolve();
|
cp.stdout.on('data', async (data) => {
|
||||||
|
await fs.appendFile(absolutePath, data.toString());
|
||||||
|
});
|
||||||
|
cp.stderr.on('data', async (data) => {
|
||||||
|
await fs.appendFile(absolutePath, data.toString());
|
||||||
|
});
|
||||||
|
cp.on('error', async (err) => {
|
||||||
|
await fs.appendFile(absolutePath, JSON.stringify(err));
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('exit', async (code) => {
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.idle, pid: undefined },
|
||||||
|
{ where: { id } },
|
||||||
|
);
|
||||||
|
resolve({ ...params, pid: cp.pid, code });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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 this.set_crontab(true);
|
await cronClient.delCron(ids.map(String));
|
||||||
|
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 } });
|
||||||
await this.set_crontab(true);
|
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
||||||
|
const sixCron = docs
|
||||||
|
.filter((x) => this.isNodeCron(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) {
|
||||||
@@ -425,130 +507,86 @@ export default class CronService {
|
|||||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||||
if (logFileExist) {
|
if (logFileExist) {
|
||||||
return getFileContentByName(`${absolutePath}`);
|
return await 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) {
|
if (!doc || !doc.log_path) {
|
||||||
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);
|
const dirExist = await fileExist(dir);
|
||||||
if (existsSync(dir)) {
|
if (dirExist) {
|
||||||
let files = await promises.readdir(dir);
|
let files = await fs.readdir(dir);
|
||||||
return files
|
return (
|
||||||
.map((x) => ({
|
await Promise.all(
|
||||||
|
files.map(async (x) => ({
|
||||||
filename: x,
|
filename: x,
|
||||||
directory: relativeDir.replace(config.logPath, ''),
|
directory: relativeDir.replace(config.logPath, ''),
|
||||||
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
time: (await fs.lstat(`${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 getKey(command: string): string {
|
private makeCommand(tab: Crontab, realTime?: boolean) {
|
||||||
const start =
|
let command = tab.command.trim();
|
||||||
command.lastIndexOf('/') !== -1 ? command.lastIndexOf('/') + 1 : 0;
|
if (!command.startsWith(TASK_PREFIX) && !command.startsWith(QL_PREFIX)) {
|
||||||
const end =
|
command = `${TASK_PREFIX}${tab.command}`;
|
||||||
command.lastIndexOf('.') !== -1
|
|
||||||
? command.lastIndexOf('.')
|
|
||||||
: command.length;
|
|
||||||
|
|
||||||
const tmpStr = command.substring(0, start - 1);
|
|
||||||
let index = 0;
|
|
||||||
if (tmpStr.lastIndexOf('/') !== -1 && tmpStr.startsWith('http')) {
|
|
||||||
index = tmpStr.lastIndexOf('/');
|
|
||||||
} else if (tmpStr.lastIndexOf(':') !== -1 && tmpStr.startsWith('git@')) {
|
|
||||||
index = tmpStr.lastIndexOf(':');
|
|
||||||
}
|
}
|
||||||
if (index) {
|
let commandVariable = `real_time=${Boolean(realTime)} no_tee=true ID=${
|
||||||
return `${tmpStr.substring(index + 1)}_${command.substring(start, end)}`;
|
tab.id
|
||||||
} else {
|
} `;
|
||||||
return command.substring(start, end);
|
if (tab.task_before) {
|
||||||
|
commandVariable += `task_before='${tab.task_before
|
||||||
|
.replace(/'/g, "'\\''")
|
||||||
|
.trim()}' `;
|
||||||
|
}
|
||||||
|
if (tab.task_after) {
|
||||||
|
commandVariable += `task_after='${tab.task_after
|
||||||
|
.replace(/'/g, "'\\''")
|
||||||
|
.trim()}' `;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private make_command(tab: Crontab) {
|
const crontab_job_string = `${commandVariable}${command}`;
|
||||||
const crontab_job_string = `ID=${tab.id} ${tab.command}`;
|
|
||||||
return crontab_job_string;
|
return crontab_job_string;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async set_crontab(needReloadSchedule: boolean = false) {
|
private async set_crontab(data?: { data: Crontab[]; total: number }) {
|
||||||
const tabs = await this.crontabs();
|
const tabs = data ?? (await this.crontabs());
|
||||||
var crontab_string = '';
|
var crontab_string = '';
|
||||||
tabs.data.forEach((tab) => {
|
tabs.data.forEach((tab) => {
|
||||||
const _schedule = tab.schedule && tab.schedule.split(/ +/);
|
const _schedule = tab.schedule && tab.schedule.split(/ +/);
|
||||||
if (tab.isDisabled === 1 || _schedule!.length !== 5) {
|
if (
|
||||||
|
tab.isDisabled === 1 ||
|
||||||
|
_schedule!.length !== 5 ||
|
||||||
|
tab.extra_schedules?.length
|
||||||
|
) {
|
||||||
crontab_string += '# ';
|
crontab_string += '# ';
|
||||||
crontab_string += tab.schedule;
|
crontab_string += tab.schedule;
|
||||||
crontab_string += ' ';
|
crontab_string += ' ';
|
||||||
crontab_string += this.make_command(tab);
|
crontab_string += this.makeCommand(tab);
|
||||||
crontab_string += '\n';
|
crontab_string += '\n';
|
||||||
} else {
|
} else {
|
||||||
crontab_string += tab.schedule;
|
crontab_string += tab.schedule;
|
||||||
crontab_string += ' ';
|
crontab_string += ' ';
|
||||||
crontab_string += this.make_command(tab);
|
crontab_string += this.makeCommand(tab);
|
||||||
crontab_string += '\n';
|
crontab_string += '\n';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.logger.silly(crontab_string);
|
await fs.writeFile(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: {} });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -586,7 +624,19 @@ export default class CronService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public autosave_crontab() {
|
public async autosave_crontab() {
|
||||||
return this.set_crontab();
|
const tabs = await this.crontabs();
|
||||||
|
this.set_crontab(tabs);
|
||||||
|
|
||||||
|
const sixCron = tabs.data
|
||||||
|
.filter((x) => this.isNodeCron(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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
minPosition,
|
minPosition,
|
||||||
stepPosition,
|
stepPosition,
|
||||||
} from '../data/env';
|
} from '../data/env';
|
||||||
|
import { FindOptions } from 'sequelize';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class CronViewService {
|
export default class CronViewService {
|
||||||
@@ -31,7 +32,9 @@ export default class CronViewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: CrontabView): Promise<CrontabView> {
|
public async update(payload: CrontabView): Promise<CrontabView> {
|
||||||
const newDoc = await this.updateDb(payload);
|
const doc = await this.getDb({ id: payload.id });
|
||||||
|
const tab = new CrontabView({ ...doc, ...payload });
|
||||||
|
const newDoc = await this.updateDb(tab);
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,9 +59,14 @@ export default class CronViewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<CrontabView> {
|
public async getDb(
|
||||||
|
query: FindOptions<CrontabView>['where'],
|
||||||
|
): Promise<CrontabView> {
|
||||||
const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
|
const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
|
||||||
return doc && (doc.get({ plain: true }) as CrontabView);
|
if (!doc) {
|
||||||
|
throw new Error(`CronView ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
public async disabled(ids: number[]) {
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import winston from 'winston';
|
||||||
|
import config from '../config';
|
||||||
|
import {
|
||||||
|
Dependence,
|
||||||
|
InstallDependenceCommandTypes,
|
||||||
|
DependenceStatus,
|
||||||
|
DependenceTypes,
|
||||||
|
unInstallDependenceCommandTypes,
|
||||||
|
DependenceModel,
|
||||||
|
GetDependenceCommandTypes,
|
||||||
|
versionDependenceCommandTypes,
|
||||||
|
} from '../data/dependence';
|
||||||
|
import { spawn } from 'cross-spawn';
|
||||||
|
import SockService from './sock';
|
||||||
|
import { FindOptions, Op } from 'sequelize';
|
||||||
|
import {
|
||||||
|
fileExist,
|
||||||
|
getPid,
|
||||||
|
killTask,
|
||||||
|
promiseExecSuccess,
|
||||||
|
} from '../config/util';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import taskLimit from '../shared/pLimit';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class DependenceService {
|
||||||
|
constructor(
|
||||||
|
@Inject('logger') private logger: winston.Logger,
|
||||||
|
private sockService: SockService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async create(payloads: Dependence[]): Promise<Dependence[]> {
|
||||||
|
const tabs = payloads.map((x) => {
|
||||||
|
const tab = new Dependence({ ...x, status: DependenceStatus.queued });
|
||||||
|
return tab;
|
||||||
|
});
|
||||||
|
const docs = await this.insert(tabs);
|
||||||
|
this.installDependenceOneByOne(docs);
|
||||||
|
return docs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async insert(payloads: Dependence[]): Promise<Dependence[]> {
|
||||||
|
const docs = await DependenceModel.bulkCreate(payloads);
|
||||||
|
return docs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async update(
|
||||||
|
payload: Dependence & { id: string },
|
||||||
|
): Promise<Dependence> {
|
||||||
|
const { id, ...other } = payload;
|
||||||
|
const doc = await this.getDb({ id });
|
||||||
|
const tab = new Dependence({
|
||||||
|
...doc,
|
||||||
|
...other,
|
||||||
|
status: DependenceStatus.queued,
|
||||||
|
});
|
||||||
|
const newDoc = await this.updateDb(tab);
|
||||||
|
this.installDependenceOneByOne([newDoc]);
|
||||||
|
return newDoc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateDb(payload: Dependence): Promise<Dependence> {
|
||||||
|
await DependenceModel.update(payload, { where: { id: payload.id } });
|
||||||
|
return await this.getDb({ id: payload.id });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
||||||
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
|
const unInstalledDeps = docs.filter(
|
||||||
|
(x) => x.status !== DependenceStatus.installed,
|
||||||
|
);
|
||||||
|
const installedDeps = docs.filter(
|
||||||
|
(x) => x.status === DependenceStatus.installed,
|
||||||
|
);
|
||||||
|
await this.removeDb(unInstalledDeps.map((x) => x.id!));
|
||||||
|
|
||||||
|
if (installedDeps.length) {
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ status: DependenceStatus.queued, log: [] },
|
||||||
|
{ where: { id: ids } },
|
||||||
|
);
|
||||||
|
|
||||||
|
this.installDependenceOneByOne(docs, false, force);
|
||||||
|
}
|
||||||
|
return docs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async removeDb(ids: number[]) {
|
||||||
|
await DependenceModel.destroy({ where: { id: ids } });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async dependencies(
|
||||||
|
{
|
||||||
|
searchValue,
|
||||||
|
type,
|
||||||
|
status,
|
||||||
|
}: { searchValue: string; type: string; status: string },
|
||||||
|
sort: any = [],
|
||||||
|
query: any = {},
|
||||||
|
): Promise<Dependence[]> {
|
||||||
|
let condition = {
|
||||||
|
...query,
|
||||||
|
type: DependenceTypes[type as any],
|
||||||
|
};
|
||||||
|
if (status) {
|
||||||
|
condition.status = status.split(',').map(Number);
|
||||||
|
}
|
||||||
|
if (searchValue) {
|
||||||
|
const encodeText = encodeURI(searchValue);
|
||||||
|
const reg = {
|
||||||
|
[Op.or]: [
|
||||||
|
{ [Op.like]: `%${searchValue}%` },
|
||||||
|
{ [Op.like]: `%${encodeText}%` },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
condition = {
|
||||||
|
...condition,
|
||||||
|
name: reg,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await this.find(condition, sort);
|
||||||
|
return result as any;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public installDependenceOneByOne(
|
||||||
|
docs: Dependence[],
|
||||||
|
isInstall: boolean = true,
|
||||||
|
force: boolean = false,
|
||||||
|
) {
|
||||||
|
docs.forEach((dep) => {
|
||||||
|
this.installOrUninstallDependency(dep, isInstall, force);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async reInstall(ids: number[]): Promise<Dependence[]> {
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ status: DependenceStatus.queued, log: [] },
|
||||||
|
{ where: { id: ids } },
|
||||||
|
);
|
||||||
|
|
||||||
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
|
this.installDependenceOneByOne(docs, true, true);
|
||||||
|
return docs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async cancel(ids: number[]) {
|
||||||
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
|
for (const doc of docs) {
|
||||||
|
taskLimit.removeQueuedDependency(doc);
|
||||||
|
const depInstallCommand = InstallDependenceCommandTypes[doc.type];
|
||||||
|
const depUnInstallCommand = unInstallDependenceCommandTypes[doc.type];
|
||||||
|
const installCmd = `${depInstallCommand} ${doc.name.trim()}`;
|
||||||
|
const unInstallCmd = `${depUnInstallCommand} ${doc.name.trim()}`;
|
||||||
|
const pids = await Promise.all([
|
||||||
|
getPid(installCmd),
|
||||||
|
getPid(unInstallCmd),
|
||||||
|
]);
|
||||||
|
for (const pid of pids) {
|
||||||
|
pid && (await killTask(pid));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ status: DependenceStatus.cancelled },
|
||||||
|
{ where: { id: ids } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async find(query: any, sort: any = []): Promise<Dependence[]> {
|
||||||
|
const docs = await DependenceModel.findAll({
|
||||||
|
where: { ...query },
|
||||||
|
order: [...sort, ['createdAt', 'DESC']],
|
||||||
|
});
|
||||||
|
return docs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getDb(
|
||||||
|
query: FindOptions<Dependence>['where'],
|
||||||
|
): Promise<Dependence> {
|
||||||
|
const doc: any = await DependenceModel.findOne({ where: { ...query } });
|
||||||
|
if (!doc) {
|
||||||
|
throw new Error(`Dependency ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateLog(ids: number[], log: string): Promise<void> {
|
||||||
|
taskLimit.updateDepLog(async () => {
|
||||||
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
|
for (const doc of docs) {
|
||||||
|
const newLog = doc?.log ? [...doc.log, log] : [log];
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ log: newLog },
|
||||||
|
{ where: { id: doc.id } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public installOrUninstallDependency(
|
||||||
|
dependency: Dependence,
|
||||||
|
isInstall: boolean = true,
|
||||||
|
force: boolean = false,
|
||||||
|
) {
|
||||||
|
return taskLimit.runDependeny(dependency, () => {
|
||||||
|
return new Promise(async (resolve) => {
|
||||||
|
if (taskLimit.firstDependencyId !== dependency.id) {
|
||||||
|
return resolve(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
taskLimit.removeQueuedDependency(dependency);
|
||||||
|
|
||||||
|
const depIds = [dependency.id!];
|
||||||
|
const status = isInstall
|
||||||
|
? DependenceStatus.installing
|
||||||
|
: DependenceStatus.removing;
|
||||||
|
await DependenceModel.update({ status }, { where: { id: depIds } });
|
||||||
|
|
||||||
|
const socketMessageType = isInstall
|
||||||
|
? 'installDependence'
|
||||||
|
: 'uninstallDependence';
|
||||||
|
let depName = dependency.name.trim();
|
||||||
|
const depRunCommand = (
|
||||||
|
isInstall
|
||||||
|
? InstallDependenceCommandTypes
|
||||||
|
: unInstallDependenceCommandTypes
|
||||||
|
)[dependency.type];
|
||||||
|
const actionText = isInstall ? '安装' : '删除';
|
||||||
|
const startTime = dayjs();
|
||||||
|
|
||||||
|
const message = `开始${actionText}依赖 ${depName},开始时间 ${startTime.format(
|
||||||
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
|
)}\n\n`;
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: socketMessageType,
|
||||||
|
message,
|
||||||
|
references: depIds,
|
||||||
|
});
|
||||||
|
this.updateLog(depIds, message);
|
||||||
|
|
||||||
|
// 判断是否已经安装过依赖
|
||||||
|
if (isInstall && !force) {
|
||||||
|
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 dependenceProxyFileExist = await fileExist(
|
||||||
|
config.dependenceProxyFile,
|
||||||
|
);
|
||||||
|
const proxyStr = dependenceProxyFileExist
|
||||||
|
? `source ${config.dependenceProxyFile} &&`
|
||||||
|
: '';
|
||||||
|
const cp = spawn(
|
||||||
|
`${proxyStr} ${depRunCommand} ${dependency.name.trim()}`,
|
||||||
|
{
|
||||||
|
shell: '/bin/bash',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
cp.stdout.on('data', async (data) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: socketMessageType,
|
||||||
|
message: data.toString(),
|
||||||
|
references: depIds,
|
||||||
|
});
|
||||||
|
this.updateLog(depIds, data.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.stderr.on('data', async (data) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: socketMessageType,
|
||||||
|
message: data.toString(),
|
||||||
|
references: depIds,
|
||||||
|
});
|
||||||
|
this.updateLog(depIds, data.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('error', async (err) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: socketMessageType,
|
||||||
|
message: JSON.stringify(err),
|
||||||
|
references: depIds,
|
||||||
|
});
|
||||||
|
this.updateLog(depIds, JSON.stringify(err));
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('exit', async (code) => {
|
||||||
|
const endTime = dayjs();
|
||||||
|
const isSucceed = code === 0;
|
||||||
|
const resultText = isSucceed ? '成功' : '失败';
|
||||||
|
|
||||||
|
const message = `\n依赖${actionText}${resultText},结束时间 ${endTime.format(
|
||||||
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
|
)},耗时 ${endTime.diff(startTime, 'second')} 秒`;
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: socketMessageType,
|
||||||
|
message,
|
||||||
|
references: depIds,
|
||||||
|
});
|
||||||
|
this.updateLog(depIds, message);
|
||||||
|
|
||||||
|
let status = null;
|
||||||
|
if (isSucceed) {
|
||||||
|
status = isInstall
|
||||||
|
? DependenceStatus.installed
|
||||||
|
: DependenceStatus.removed;
|
||||||
|
} else {
|
||||||
|
status = isInstall
|
||||||
|
? DependenceStatus.installFailed
|
||||||
|
: DependenceStatus.removeFailed;
|
||||||
|
}
|
||||||
|
const docs = await DependenceModel.findAll({ where: { id: depIds } });
|
||||||
|
const _docIds = docs
|
||||||
|
.filter((x) => x.status !== DependenceStatus.cancelled)
|
||||||
|
.map((x) => x.id!);
|
||||||
|
|
||||||
|
if (_docIds.length > 0) {
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ status },
|
||||||
|
{ where: { id: _docIds } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果删除依赖成功或者强制删除
|
||||||
|
if ((isSucceed || force) && !isInstall) {
|
||||||
|
this.removeDb(depIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
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 * as fs from 'fs';
|
import * as fs from 'fs/promises';
|
||||||
import {
|
import {
|
||||||
Env,
|
Env,
|
||||||
EnvModel,
|
EnvModel,
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
stepPosition,
|
stepPosition,
|
||||||
} from '../data/env';
|
} from '../data/env';
|
||||||
import groupBy from 'lodash/groupBy';
|
import groupBy from 'lodash/groupBy';
|
||||||
import { Op } from 'sequelize';
|
import { FindOptions, Op } from 'sequelize';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class EnvService {
|
export default class EnvService {
|
||||||
@@ -49,7 +49,9 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: Env): Promise<Env> {
|
public async update(payload: Env): Promise<Env> {
|
||||||
const newDoc = await this.updateDb(payload);
|
const doc = await this.getDb({ id: payload.id });
|
||||||
|
const tab = new Env({ ...doc, ...payload });
|
||||||
|
const newDoc = await this.updateDb(tab);
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
@@ -92,13 +94,17 @@ export default class EnvService {
|
|||||||
position: this.getPrecisionPosition(targetPosition),
|
position: this.getPrecisionPosition(targetPosition),
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.checkPosition(targetPosition);
|
await this.checkPosition(targetPosition, envs[toIndex].position!);
|
||||||
return newDoc;
|
return newDoc;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async checkPosition(position: number) {
|
private async checkPosition(position: number, edge: number = 0) {
|
||||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
const precisionPosition = parseFloat(position.toPrecision(16));
|
||||||
if (precisionPosition < minPosition || precisionPosition > maxPosition) {
|
if (
|
||||||
|
precisionPosition < minPosition ||
|
||||||
|
precisionPosition > maxPosition ||
|
||||||
|
Math.abs(precisionPosition - edge) < minPosition
|
||||||
|
) {
|
||||||
const envs = await this.envs();
|
const envs = await this.envs();
|
||||||
let position = initPosition;
|
let position = initPosition;
|
||||||
for (const env of envs) {
|
for (const env of envs) {
|
||||||
@@ -115,7 +121,7 @@ export default class EnvService {
|
|||||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const encodeText = encodeURIComponent(searchText);
|
const encodeText = encodeURI(searchText);
|
||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
@@ -140,7 +146,6 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.find(condition, [
|
const result = await this.find(condition, [
|
||||||
['status', 'ASC'],
|
|
||||||
['position', 'DESC'],
|
['position', 'DESC'],
|
||||||
['createdAt', 'ASC'],
|
['createdAt', 'ASC'],
|
||||||
]);
|
]);
|
||||||
@@ -158,9 +163,12 @@ export default class EnvService {
|
|||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<Env> {
|
public async getDb(query: FindOptions<Env>['where']): 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);
|
if (!doc) {
|
||||||
|
throw new Error(`Env ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: string[]) {
|
public async disabled(ids: string[]) {
|
||||||
@@ -188,6 +196,8 @@ export default class EnvService {
|
|||||||
});
|
});
|
||||||
const groups = groupBy(envs, 'name');
|
const groups = groupBy(envs, 'name');
|
||||||
let env_string = '';
|
let env_string = '';
|
||||||
|
let js_env_string = '';
|
||||||
|
let py_env_string = 'import os\n';
|
||||||
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];
|
||||||
@@ -197,14 +207,21 @@ export default class EnvService {
|
|||||||
let value = group
|
let value = group
|
||||||
.map((x) => x.value)
|
.map((x) => x.value)
|
||||||
.join('&')
|
.join('&')
|
||||||
.replace(/(\\)[^n]/g, '\\\\')
|
.replace(/'/g, "'\\''")
|
||||||
.replace(/(\\$)/, '\\\\')
|
|
||||||
.replace(/"/g, '\\"')
|
|
||||||
.trim();
|
.trim();
|
||||||
env_string += `export ${key}="${value}"\n`;
|
env_string += `export ${key}='${value}'\n`;
|
||||||
|
const _env_value = `'${group
|
||||||
|
.map((x) => x.value)
|
||||||
|
.join('&')
|
||||||
|
.replace(/\\/g, '\\\\')
|
||||||
|
.replace(/'/g, "\\'")}'`;
|
||||||
|
js_env_string += `process.env.${key}=${_env_value};\n`;
|
||||||
|
py_env_string += `os.environ['${key}']=${_env_value}\n`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fs.writeFileSync(config.envFile, env_string);
|
await fs.writeFile(config.envFile, env_string);
|
||||||
|
await fs.writeFile(config.jsEnvFile, js_env_string);
|
||||||
|
await fs.writeFile(config.pyEnvFile, py_env_string);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,751 @@
|
|||||||
|
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 UserService from './user';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class NotificationService {
|
||||||
|
@Inject((type) => UserService)
|
||||||
|
private userService!: UserService;
|
||||||
|
|
||||||
|
private modeMap = new Map([
|
||||||
|
['gotify', this.gotify],
|
||||||
|
['goCqHttpBot', this.goCqHttpBot],
|
||||||
|
['serverChan', this.serverChan],
|
||||||
|
['pushDeer', this.pushDeer],
|
||||||
|
['chat', this.chat],
|
||||||
|
['bark', this.bark],
|
||||||
|
['telegramBot', this.telegramBot],
|
||||||
|
['dingtalkBot', this.dingtalkBot],
|
||||||
|
['weWorkBot', this.weWorkBot],
|
||||||
|
['weWorkApp', this.weWorkApp],
|
||||||
|
['aibotk', this.aibotk],
|
||||||
|
['iGot', this.iGot],
|
||||||
|
['pushPlus', this.pushPlus],
|
||||||
|
['wePlusBot', this.wePlusBot],
|
||||||
|
['email', this.email],
|
||||||
|
['pushMe', this.pushMe],
|
||||||
|
['webhook', this.webhook],
|
||||||
|
['lark', this.lark],
|
||||||
|
['chronocat', this.chronocat],
|
||||||
|
]);
|
||||||
|
|
||||||
|
private title = '';
|
||||||
|
private content = '';
|
||||||
|
private params!: Omit<NotificationInfo, 'type'>;
|
||||||
|
private gotOption = {
|
||||||
|
timeout: 10000,
|
||||||
|
retry: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
|
public async notify(
|
||||||
|
title: string,
|
||||||
|
content: string,
|
||||||
|
): Promise<boolean | undefined> {
|
||||||
|
const { type, ...rest } = await this.userService.getNotificationMode();
|
||||||
|
if (type) {
|
||||||
|
this.title = title;
|
||||||
|
this.content = content;
|
||||||
|
this.params = rest;
|
||||||
|
const notificationModeAction = this.modeMap.get(type);
|
||||||
|
try {
|
||||||
|
return await notificationModeAction?.call(this);
|
||||||
|
} catch (error: any) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async testNotify(
|
||||||
|
info: NotificationInfo,
|
||||||
|
title: string,
|
||||||
|
content: string,
|
||||||
|
) {
|
||||||
|
const { type, ...rest } = info;
|
||||||
|
if (type) {
|
||||||
|
this.title = title;
|
||||||
|
this.content = content;
|
||||||
|
this.params = rest;
|
||||||
|
const notificationModeAction = this.modeMap.get(type);
|
||||||
|
return await notificationModeAction?.call(this);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async gotify() {
|
||||||
|
const { gotifyUrl, gotifyToken, gotifyPriority = 1 } = this.params;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(`${gotifyUrl}/message?token=${gotifyToken}`, {
|
||||||
|
...this.gotOption,
|
||||||
|
body: `title=${encodeURIComponent(
|
||||||
|
this.title,
|
||||||
|
)}&message=${encodeURIComponent(
|
||||||
|
this.content,
|
||||||
|
)}&priority=${gotifyPriority}`,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: { message: `${this.title}\n${this.content}` },
|
||||||
|
headers: { Authorization: 'Bearer ' + goCqHttpBotToken },
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const { serverChanKey } = this.params;
|
||||||
|
const url = serverChanKey.startsWith('SCT')
|
||||||
|
? `https://sctapi.ftqq.com/${serverChanKey}.send`
|
||||||
|
: `https://sc.ftqq.com/${serverChanKey}.send`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
body: `title=${this.title}&desp=${this.content}`,
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const { pushDeerKey, pushDeerUrl } = this.params;
|
||||||
|
const url = pushDeerUrl || `https://api2.pushdeer.com/message/push`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
body: `pushkey=${pushDeerKey}&text=${encodeURIComponent(
|
||||||
|
this.title,
|
||||||
|
)}&desp=${encodeURIComponent(this.content)}&type=markdown`,
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (
|
||||||
|
res.content.result.length !== undefined &&
|
||||||
|
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() {
|
||||||
|
let {
|
||||||
|
barkPush,
|
||||||
|
barkIcon = '',
|
||||||
|
barkSound = '',
|
||||||
|
barkGroup = '',
|
||||||
|
barkLevel = '',
|
||||||
|
barkUrl = '',
|
||||||
|
barkArchive = '',
|
||||||
|
} = this.params;
|
||||||
|
if (!barkPush.startsWith('http')) {
|
||||||
|
barkPush = `https://api.day.app/${barkPush}`;
|
||||||
|
}
|
||||||
|
const url = `${barkPush}`;
|
||||||
|
const body = {
|
||||||
|
title: this.title,
|
||||||
|
body: this.content,
|
||||||
|
icon: barkIcon,
|
||||||
|
sound: barkSound,
|
||||||
|
group: barkGroup,
|
||||||
|
isArchive: barkArchive,
|
||||||
|
level: barkLevel,
|
||||||
|
url: barkUrl,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: body,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const {
|
||||||
|
telegramBotApiHost,
|
||||||
|
telegramBotProxyAuth,
|
||||||
|
telegramBotProxyHost,
|
||||||
|
telegramBotProxyPort,
|
||||||
|
telegramBotToken,
|
||||||
|
telegramBotUserId,
|
||||||
|
} = this.params;
|
||||||
|
const authStr = telegramBotProxyAuth ? `${telegramBotProxyAuth}@` : '';
|
||||||
|
const url = `${
|
||||||
|
telegramBotApiHost ? telegramBotApiHost : 'https://api.telegram.org'
|
||||||
|
}/bot${telegramBotToken}/sendMessage`;
|
||||||
|
let agent;
|
||||||
|
if (telegramBotProxyHost && telegramBotProxyPort) {
|
||||||
|
const options: any = {
|
||||||
|
keepAlive: true,
|
||||||
|
keepAliveMsecs: 1000,
|
||||||
|
maxSockets: 256,
|
||||||
|
maxFreeSockets: 256,
|
||||||
|
proxy: `http://${authStr}${telegramBotProxyHost}:${telegramBotProxyPort}`,
|
||||||
|
};
|
||||||
|
const httpAgent = new HttpProxyAgent(options);
|
||||||
|
const httpsAgent = new HttpsProxyAgent(options);
|
||||||
|
agent = {
|
||||||
|
http: httpAgent,
|
||||||
|
https: httpsAgent,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
body: `chat_id=${telegramBotUserId}&text=${this.title}\n\n${this.content}&disable_web_page_preview=true`,
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
agent,
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const { dingtalkBotSecret, dingtalkBotToken } = this.params;
|
||||||
|
let secretParam = '';
|
||||||
|
if (dingtalkBotSecret) {
|
||||||
|
const dateNow = Date.now();
|
||||||
|
const hmac = crypto.createHmac('sha256', dingtalkBotSecret);
|
||||||
|
hmac.update(`${dateNow}\n${dingtalkBotSecret}`);
|
||||||
|
const result = encodeURIComponent(hmac.digest('base64'));
|
||||||
|
secretParam = `×tamp=${dateNow}&sign=${result}`;
|
||||||
|
}
|
||||||
|
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
msgtype: 'text',
|
||||||
|
text: {
|
||||||
|
content: ` ${this.title}\n\n${this.content}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const { weWorkBotKey, weWorkOrigin = 'https://qyapi.weixin.qq.com' } =
|
||||||
|
this.params;
|
||||||
|
const url = `${weWorkOrigin}/cgi-bin/webhook/send?key=${weWorkBotKey}`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
msgtype: 'text',
|
||||||
|
text: {
|
||||||
|
content: ` ${this.title}\n\n${this.content}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
if (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() {
|
||||||
|
const { weWorkAppKey, weWorkOrigin = 'https://qyapi.weixin.qq.com' } =
|
||||||
|
this.params;
|
||||||
|
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
||||||
|
weWorkAppKey.split(',');
|
||||||
|
const url = `${weWorkOrigin}/cgi-bin/gettoken`;
|
||||||
|
const tokenRes: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
corpid,
|
||||||
|
corpsecret,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
|
||||||
|
let options: any = {
|
||||||
|
msgtype: 'mpnews',
|
||||||
|
mpnews: {
|
||||||
|
articles: [
|
||||||
|
{
|
||||||
|
title: `${this.title}`,
|
||||||
|
thumb_media_id,
|
||||||
|
author: `智能助手`,
|
||||||
|
content_source_url: ``,
|
||||||
|
content: `${this.content.replace(/\n/g, '<br/>')}`,
|
||||||
|
digest: `${this.content}`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
switch (thumb_media_id) {
|
||||||
|
case '0':
|
||||||
|
options = {
|
||||||
|
msgtype: 'textcard',
|
||||||
|
textcard: {
|
||||||
|
title: `${this.title}`,
|
||||||
|
description: `${this.content}`,
|
||||||
|
url: 'https://github.com/whyour/qinglong',
|
||||||
|
btntxt: '更多',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
|
||||||
|
case '1':
|
||||||
|
options = {
|
||||||
|
msgtype: 'text',
|
||||||
|
text: {
|
||||||
|
content: `${this.title}\n\n${this.content}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(
|
||||||
|
`${weWorkOrigin}/cgi-bin/message/send?access_token=${tokenRes.access_token}`,
|
||||||
|
{
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
touser,
|
||||||
|
agentid,
|
||||||
|
safe: '0',
|
||||||
|
...options,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.json();
|
||||||
|
|
||||||
|
if (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() {
|
||||||
|
const { iGotPushKey } = this.params;
|
||||||
|
const url = `https://push.hellyw.com/${iGotPushKey.toLowerCase()}`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
body: `title=${this.title}&content=${this.content}`,
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
|
||||||
|
if (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() {
|
||||||
|
const { pushPlusToken, pushPlusUser } = this.params;
|
||||||
|
const url = `https://www.pushplus.plus/send`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
token: `${pushPlusToken}`,
|
||||||
|
title: `${this.title}`,
|
||||||
|
content: `${this.content.replace(/[\n\r]/g, '<br>')}`,
|
||||||
|
topic: `${pushPlusUser || ''}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
|
||||||
|
if (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 wePlusBot() {
|
||||||
|
const { wePlusBotToken, wePlusBotReceiver, wePlusBotVersion } = this.params;
|
||||||
|
|
||||||
|
let content = this.content;
|
||||||
|
let template = 'txt';
|
||||||
|
if (this.content.length > 800) {
|
||||||
|
template = 'html';
|
||||||
|
content = content.replace(/[\n\r]/g, '<br>');
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = `https://www.weplusbot.com/send`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
token: `${wePlusBotToken}`,
|
||||||
|
title: `${this.title}`,
|
||||||
|
template: `${template}`,
|
||||||
|
content: `${content}`,
|
||||||
|
receiver: `${wePlusBotReceiver || ''}`,
|
||||||
|
version: `${wePlusBotVersion || 'pro'}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
|
||||||
|
if (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 || 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 email() {
|
||||||
|
const { emailPass, emailService, emailUser } = this.params;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
service: emailService,
|
||||||
|
auth: {
|
||||||
|
user: emailUser,
|
||||||
|
pass: emailPass,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const info = await transporter.sendMail({
|
||||||
|
from: `"青龙快讯" <${emailUser}>`,
|
||||||
|
to: `${emailUser}`,
|
||||||
|
subject: `${this.title}`,
|
||||||
|
html: `${this.content.replace(/\n/g, '<br/>')}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
transporter.close();
|
||||||
|
|
||||||
|
if (info.messageId) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
throw new Error(JSON.stringify(info));
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pushMe() {
|
||||||
|
const { pushMeKey, pushMeUrl } = this.params;
|
||||||
|
try {
|
||||||
|
const res: any = await got.post(pushMeUrl || 'https://push.i-i.me/', {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
push_key: pushMeKey,
|
||||||
|
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, chronocatToken } = 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 ${chronocatToken}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
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.statusCode === 200) {
|
||||||
|
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;
|
||||||
|
|
||||||
|
if (!webhookUrl.includes('$title') && !webhookBody.includes('$title')) {
|
||||||
|
throw new Error('Url 或者 Body 中必须包含 $title');
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = parseHeaders(webhookHeaders);
|
||||||
|
const body = parseBody(webhookBody, webhookContentType, (v) =>
|
||||||
|
v?.replaceAll('$title', this.title)?.replaceAll('$content', this.content),
|
||||||
|
);
|
||||||
|
const bodyParam = this.formatBody(webhookContentType, body);
|
||||||
|
const options = {
|
||||||
|
method: webhookMethod,
|
||||||
|
headers,
|
||||||
|
...this.gotOption,
|
||||||
|
allowGetBody: true,
|
||||||
|
...bodyParam,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const formatUrl = webhookUrl
|
||||||
|
?.replaceAll('$title', encodeURIComponent(this.title))
|
||||||
|
?.replaceAll('$content', encodeURIComponent(this.content));
|
||||||
|
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':
|
||||||
|
case 'text/plain':
|
||||||
|
return { body };
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ export default class OpenService {
|
|||||||
|
|
||||||
public async insert(payload: App): Promise<App> {
|
public async insert(payload: App): Promise<App> {
|
||||||
const doc = await AppModel.create(payload, { returning: true });
|
const doc = await AppModel.create(payload, { returning: true });
|
||||||
return doc.get({ plain: true }) as App;
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: App): Promise<App> {
|
public async update(payload: App): Promise<App> {
|
||||||
@@ -45,7 +45,10 @@ export default class OpenService {
|
|||||||
|
|
||||||
public async getDb(query: any): Promise<App> {
|
public async getDb(query: any): Promise<App> {
|
||||||
const doc: any = await AppModel.findOne({ where: query });
|
const doc: any = await AppModel.findOne({ where: query });
|
||||||
return doc && (doc.get({ plain: true }) as App);
|
if (!doc) {
|
||||||
|
throw new Error(`App ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[]) {
|
public async remove(ids: number[]) {
|
||||||
@@ -75,7 +78,7 @@ export default class OpenService {
|
|||||||
): Promise<App[]> {
|
): Promise<App[]> {
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const encodeText = encodeURIComponent(searchText);
|
const encodeText = encodeURI(searchText);
|
||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import winston from 'winston';
|
||||||
|
import nodeSchedule from 'node-schedule';
|
||||||
|
import { ChildProcessWithoutNullStreams } from 'child_process';
|
||||||
|
import {
|
||||||
|
ToadScheduler,
|
||||||
|
LongIntervalJob,
|
||||||
|
SimpleIntervalSchedule,
|
||||||
|
Task,
|
||||||
|
} from 'toad-scheduler';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import taskLimit from '../shared/pLimit';
|
||||||
|
import { spawn } from 'cross-spawn';
|
||||||
|
|
||||||
|
export interface ScheduleTaskType {
|
||||||
|
id?: number;
|
||||||
|
command: string;
|
||||||
|
name?: string;
|
||||||
|
schedule?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskCallbacks {
|
||||||
|
onBefore?: (startTime: dayjs.Dayjs) => Promise<void>;
|
||||||
|
onStart?: (
|
||||||
|
cp: ChildProcessWithoutNullStreams,
|
||||||
|
startTime: dayjs.Dayjs,
|
||||||
|
) => Promise<void>;
|
||||||
|
onEnd?: (
|
||||||
|
cp: ChildProcessWithoutNullStreams,
|
||||||
|
endTime: dayjs.Dayjs,
|
||||||
|
diff: number,
|
||||||
|
) => Promise<void>;
|
||||||
|
onLog?: (message: string) => Promise<void>;
|
||||||
|
onError?: (message: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class ScheduleService {
|
||||||
|
private scheduleStacks = new Map<string, nodeSchedule.Job>();
|
||||||
|
|
||||||
|
private intervalSchedule = new ToadScheduler();
|
||||||
|
|
||||||
|
private maxBuffer = 200 * 1024 * 1024;
|
||||||
|
|
||||||
|
constructor(@Inject('logger') private logger: winston.Logger) { }
|
||||||
|
|
||||||
|
async runTask(
|
||||||
|
command: string,
|
||||||
|
callbacks: TaskCallbacks = {},
|
||||||
|
params: {
|
||||||
|
schedule?: string;
|
||||||
|
name?: string;
|
||||||
|
command?: string;
|
||||||
|
},
|
||||||
|
completionTime: 'start' | 'end' = 'end',
|
||||||
|
) {
|
||||||
|
return taskLimit.runWithCronLimit(() => {
|
||||||
|
return new Promise(async (resolve, reject) => {
|
||||||
|
this.logger.info(`[panel][开始执行任务] 参数 ${JSON.stringify({ ...params, command })}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const startTime = dayjs();
|
||||||
|
await callbacks.onBefore?.(startTime);
|
||||||
|
|
||||||
|
const cp = spawn(command, { shell: '/bin/bash' });
|
||||||
|
|
||||||
|
callbacks.onStart?.(cp, startTime);
|
||||||
|
completionTime === 'start' && resolve(cp.pid);
|
||||||
|
|
||||||
|
cp.stdout.on('data', async (data) => {
|
||||||
|
await callbacks.onLog?.(data.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.stderr.on('data', async (data) => {
|
||||||
|
this.logger.info(
|
||||||
|
'[panel][执行任务失败] 命令: %s, 错误信息: %j',
|
||||||
|
command,
|
||||||
|
data.toString(),
|
||||||
|
);
|
||||||
|
await callbacks.onError?.(data.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('error', async (err) => {
|
||||||
|
this.logger.error(
|
||||||
|
'[panel][创建任务失败] 命令: %s, 错误信息: %j',
|
||||||
|
command,
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
await callbacks.onError?.(JSON.stringify(err));
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('exit', async (code) => {
|
||||||
|
const endTime = dayjs();
|
||||||
|
await callbacks.onEnd?.(
|
||||||
|
cp,
|
||||||
|
endTime,
|
||||||
|
endTime.diff(startTime, 'seconds'),
|
||||||
|
);
|
||||||
|
resolve({ ...params, pid: cp.pid, code });
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
'[panel][执行任务失败] 命令: %s, 错误信息: %j',
|
||||||
|
command,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
await callbacks.onError?.(JSON.stringify(error));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async createCronTask(
|
||||||
|
{ id = 0, command, name, schedule = '' }: ScheduleTaskType,
|
||||||
|
callbacks?: TaskCallbacks,
|
||||||
|
runImmediately = false,
|
||||||
|
) {
|
||||||
|
const _id = this.formatId(id);
|
||||||
|
this.logger.info(
|
||||||
|
'[panel][创建cron任务], 任务ID: %s, cron: %s, 任务名: %s, 执行命令: %s',
|
||||||
|
_id,
|
||||||
|
schedule,
|
||||||
|
name,
|
||||||
|
command,
|
||||||
|
);
|
||||||
|
|
||||||
|
this.scheduleStacks.set(
|
||||||
|
_id,
|
||||||
|
nodeSchedule.scheduleJob(_id, schedule, async () => {
|
||||||
|
this.runTask(command, callbacks, {
|
||||||
|
name,
|
||||||
|
schedule,
|
||||||
|
command,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (runImmediately) {
|
||||||
|
this.runTask(command, callbacks, {
|
||||||
|
name,
|
||||||
|
schedule,
|
||||||
|
command,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
|
||||||
|
const _id = this.formatId(id);
|
||||||
|
this.logger.info('[panel][取消定时任务], 任务名: %s', name);
|
||||||
|
if (this.scheduleStacks.has(_id)) {
|
||||||
|
this.scheduleStacks.get(_id)?.cancel();
|
||||||
|
this.scheduleStacks.delete(_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async createIntervalTask(
|
||||||
|
{ id = 0, command, name = '' }: ScheduleTaskType,
|
||||||
|
schedule: SimpleIntervalSchedule,
|
||||||
|
runImmediately = true,
|
||||||
|
callbacks?: TaskCallbacks,
|
||||||
|
) {
|
||||||
|
const _id = this.formatId(id);
|
||||||
|
this.logger.info(
|
||||||
|
'[panel][创建interval任务], 任务ID: %s, 任务名: %s, 执行命令: %s',
|
||||||
|
_id,
|
||||||
|
name,
|
||||||
|
command,
|
||||||
|
);
|
||||||
|
const task = new Task(
|
||||||
|
name,
|
||||||
|
() => {
|
||||||
|
this.runTask(command, callbacks, {
|
||||||
|
name,
|
||||||
|
command,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
|
this.logger.error(
|
||||||
|
'[执行任务失败] 命令: %s, 错误信息: %j',
|
||||||
|
command,
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const job = new LongIntervalJob(
|
||||||
|
{ runImmediately: false, ...schedule },
|
||||||
|
task,
|
||||||
|
_id,
|
||||||
|
);
|
||||||
|
|
||||||
|
this.intervalSchedule.addIntervalJob(job);
|
||||||
|
|
||||||
|
if (runImmediately) {
|
||||||
|
this.runTask(command, callbacks, {
|
||||||
|
name,
|
||||||
|
command,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelIntervalTask({ id = 0, name }: ScheduleTaskType) {
|
||||||
|
const _id = this.formatId(id);
|
||||||
|
this.logger.info('[取消interval任务], 任务ID: %s, 任务名: %s', _id, name);
|
||||||
|
this.intervalSchedule.removeById(_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatId(id: number): string {
|
||||||
|
return String(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import fs from 'fs';
|
import path, { join } from 'path';
|
||||||
import path from 'path';
|
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
import CronService from './cron';
|
import CronService from './cron';
|
||||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { LOG_END_SYMBOL } from '../config/const';
|
import { TASK_COMMAND } from '../config/const';
|
||||||
import { getPid, killTask } from '../config/util';
|
import { getFileContentByName, getPid, killTask, rmPath } from '../config/util';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class ScriptService {
|
export default class ScriptService {
|
||||||
@@ -21,9 +20,7 @@ export default class ScriptService {
|
|||||||
private taskCallbacks(filePath: string): TaskCallbacks {
|
private taskCallbacks(filePath: string): TaskCallbacks {
|
||||||
return {
|
return {
|
||||||
onEnd: async (cp, endTime, diff) => {
|
onEnd: async (cp, endTime, diff) => {
|
||||||
try {
|
await rmPath(filePath);
|
||||||
fs.unlinkSync(filePath);
|
|
||||||
} catch (error) {}
|
|
||||||
},
|
},
|
||||||
onError: async (message: string) => {
|
onError: async (message: string) => {
|
||||||
this.sockService.sendMessage({
|
this.sockService.sendMessage({
|
||||||
@@ -42,10 +39,11 @@ 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 -l ${relativePath} now`;
|
const command = `${TASK_COMMAND} ${relativePath} now`;
|
||||||
const pid = await this.scheduleService.runTask(
|
const pid = await this.scheduleService.runTask(
|
||||||
command,
|
`real_time=true ${command}`,
|
||||||
this.taskCallbacks(filePath),
|
this.taskCallbacks(filePath),
|
||||||
|
{ command },
|
||||||
'start',
|
'start',
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -53,10 +51,9 @@ export default class ScriptService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async stopScript(filePath: string, pid: number) {
|
public async stopScript(filePath: string, pid: number) {
|
||||||
let str = '';
|
|
||||||
if (!pid) {
|
if (!pid) {
|
||||||
const relativePath = path.relative(config.scriptPath, filePath);
|
const relativePath = path.relative(config.scriptPath, filePath);
|
||||||
pid = await getPid(`task -l ${relativePath} now`);
|
pid = (await getPid(`${TASK_COMMAND} ${relativePath} now`)) as number;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await killTask(pid);
|
await killTask(pid);
|
||||||
@@ -64,4 +61,13 @@ export default class ScriptService {
|
|||||||
|
|
||||||
return { code: 200 };
|
return { code: 200 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async getFile(filePath: string, fileName: string) {
|
||||||
|
let _filePath = join(config.scriptPath, filePath, fileName);
|
||||||
|
if (filePath.startsWith(config.dataPath)) {
|
||||||
|
_filePath = join(filePath, fileName);
|
||||||
|
}
|
||||||
|
const content = await getFileContentByName(_filePath);
|
||||||
|
return content;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import winston from 'winston';
|
||||||
|
import fs from 'fs/promises';
|
||||||
|
import os from 'os';
|
||||||
|
import path from 'path';
|
||||||
|
import { Subscription } from '../data/subscription';
|
||||||
|
import { formatUrl } from '../config/subscription';
|
||||||
|
import config from '../config';
|
||||||
|
import { fileExist, rmPath } from '../config/util';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class SshKeyService {
|
||||||
|
private homedir = os.homedir();
|
||||||
|
private sshPath = config.sshdPath;
|
||||||
|
private sshConfigFilePath = path.resolve(this.homedir, '.ssh', 'config');
|
||||||
|
private sshConfigHeader = `Include ${path.join(this.sshPath, '*.config')}`;
|
||||||
|
|
||||||
|
constructor(@Inject('logger') private logger: winston.Logger) {
|
||||||
|
this.initSshConfigFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async initSshConfigFile() {
|
||||||
|
let config = '';
|
||||||
|
const _exist = await fileExist(this.sshConfigFilePath);
|
||||||
|
if (_exist) {
|
||||||
|
config = await fs.readFile(this.sshConfigFilePath, { encoding: 'utf-8' });
|
||||||
|
} else {
|
||||||
|
await fs.writeFile(this.sshConfigFilePath, '');
|
||||||
|
}
|
||||||
|
if (!config.includes(this.sshConfigHeader)) {
|
||||||
|
await fs.writeFile(
|
||||||
|
this.sshConfigFilePath,
|
||||||
|
`${this.sshConfigHeader}\n\n${config}`,
|
||||||
|
{ encoding: 'utf-8' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async generatePrivateKeyFile(
|
||||||
|
alias: string,
|
||||||
|
key: string,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
await fs.writeFile(path.join(this.sshPath, alias), `${key}${os.EOL}`, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
mode: '400',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('生成私钥文件失败', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async removePrivateKeyFile(alias: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const filePath = path.join(this.sshPath, alias);
|
||||||
|
await rmPath(filePath);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('删除私钥文件失败', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async generateSingleSshConfig(
|
||||||
|
alias: string,
|
||||||
|
host: string,
|
||||||
|
proxy?: string,
|
||||||
|
) {
|
||||||
|
if (host === 'github.com') {
|
||||||
|
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`
|
||||||
|
: '';
|
||||||
|
const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${path.join(
|
||||||
|
this.sshPath,
|
||||||
|
alias,
|
||||||
|
)}\n StrictHostKeyChecking no\n${proxyStr}`;
|
||||||
|
await fs.writeFile(
|
||||||
|
`${path.join(this.sshPath, `${alias}.config`)}`,
|
||||||
|
config,
|
||||||
|
{
|
||||||
|
encoding: 'utf8',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async removeSshConfig(alias: string) {
|
||||||
|
try {
|
||||||
|
const filePath = path.join(this.sshPath, `${alias}.config`);
|
||||||
|
await rmPath(filePath);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`删除ssh配置文件${alias}失败`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async addSSHKey(
|
||||||
|
key: string,
|
||||||
|
alias: string,
|
||||||
|
host: string,
|
||||||
|
proxy?: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.generatePrivateKeyFile(alias, key);
|
||||||
|
await this.generateSingleSshConfig(alias, host, proxy);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async removeSSHKey(alias: string, host: string, proxy?: string): Promise<void> {
|
||||||
|
await this.removePrivateKeyFile(alias);
|
||||||
|
await this.removeSshConfig(alias);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async 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);
|
||||||
|
await this.removePrivateKeyFile(alias);
|
||||||
|
await this.removeSshConfig(alias);
|
||||||
|
await this.generatePrivateKeyFile(
|
||||||
|
alias,
|
||||||
|
(doc.pull_option as any).private_key,
|
||||||
|
);
|
||||||
|
await this.generateSingleSshConfig(alias, host, proxy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,30 +6,29 @@ import {
|
|||||||
SubscriptionModel,
|
SubscriptionModel,
|
||||||
SubscriptionStatus,
|
SubscriptionStatus,
|
||||||
} from '../data/subscription';
|
} from '../data/subscription';
|
||||||
import {
|
import { ChildProcessWithoutNullStreams } from 'child_process';
|
||||||
ChildProcessWithoutNullStreams,
|
|
||||||
exec,
|
|
||||||
execSync,
|
|
||||||
spawn,
|
|
||||||
} from 'child_process';
|
|
||||||
import fs from 'fs';
|
|
||||||
import cron_parser from 'cron-parser';
|
|
||||||
import {
|
import {
|
||||||
getFileContentByName,
|
getFileContentByName,
|
||||||
concurrentRun,
|
concurrentRun,
|
||||||
fileExist,
|
fileExist,
|
||||||
createFile,
|
createFile,
|
||||||
killTask,
|
killTask,
|
||||||
|
handleLogPath,
|
||||||
|
promiseExec,
|
||||||
|
rmPath,
|
||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import { promises, existsSync } from 'fs';
|
import fs from 'fs/promises';
|
||||||
import { Op } from 'sequelize';
|
import { FindOptions, Op } from 'sequelize';
|
||||||
import path from 'path';
|
import path, { join } 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 { 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,6 +37,7 @@ 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[]> {
|
||||||
@@ -46,7 +46,7 @@ export default class SubscriptionService {
|
|||||||
const reg = {
|
const reg = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchText}%` },
|
{ [Op.like]: `%${searchText}%` },
|
||||||
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
{ [Op.like]: `%${encodeURI(searchText)}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
query = {
|
query = {
|
||||||
@@ -68,71 +68,20 @@ export default class SubscriptionService {
|
|||||||
['createdAt', 'DESC'],
|
['createdAt', 'DESC'],
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
return result as any;
|
return result;
|
||||||
} 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,
|
|
||||||
proxy,
|
|
||||||
} = doc;
|
|
||||||
if (type === 'file') {
|
|
||||||
command += `raw "${_url}"`;
|
|
||||||
} else {
|
|
||||||
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${
|
|
||||||
dependences || ''
|
|
||||||
}" "${branch || ''}" "${extensions || ''}" "${proxy || ''}"`;
|
|
||||||
}
|
|
||||||
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, host } = this.formatUrl(doc);
|
const { url } = 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,
|
|
||||||
doc.proxy,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
this.sshKeyService.removeSSHKey(doc.alias, host, doc.proxy);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
doc.command = this.formatCommand(doc, url as string);
|
doc.command = 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);
|
||||||
@@ -142,9 +91,9 @@ export default class SubscriptionService {
|
|||||||
this.taskCallbacks(doc),
|
this.taskCallbacks(doc),
|
||||||
runImmediately,
|
runImmediately,
|
||||||
));
|
));
|
||||||
} else {
|
} else if (doc.interval_schedule) {
|
||||||
this.scheduleService.cancelIntervalTask(doc as any);
|
this.scheduleService.cancelIntervalTask(doc as any);
|
||||||
const { type, value } = doc.interval_schedule as any;
|
const { type, value } = doc.interval_schedule;
|
||||||
needCreate &&
|
needCreate &&
|
||||||
(await this.scheduleService.createIntervalTask(
|
(await this.scheduleService.createIntervalTask(
|
||||||
doc as any,
|
doc as any,
|
||||||
@@ -155,28 +104,9 @@ export default class SubscriptionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async promiseExec(command: string): Promise<string> {
|
public async setSshConfig() {
|
||||||
return new Promise((resolve, reject) => {
|
const docs = await SubscriptionModel.findAll();
|
||||||
exec(
|
await this.sshKeyService.setSshConfig(docs);
|
||||||
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 {
|
||||||
@@ -191,7 +121,7 @@ export default class SubscriptionService {
|
|||||||
},
|
},
|
||||||
{ where: { id: doc.id } },
|
{ where: { id: doc.id } },
|
||||||
);
|
);
|
||||||
const absolutePath = await this.handleLogPath(
|
const absolutePath = await 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`,
|
||||||
);
|
);
|
||||||
@@ -200,15 +130,15 @@ export default class SubscriptionService {
|
|||||||
let beforeStr = '';
|
let beforeStr = '';
|
||||||
try {
|
try {
|
||||||
if (doc.sub_before) {
|
if (doc.sub_before) {
|
||||||
fs.appendFileSync(absolutePath, `\n## 执行before命令...\n\n`);
|
await fs.appendFile(absolutePath, `\n## 执行before命令...\n\n`);
|
||||||
beforeStr = await this.promiseExec(doc.sub_before);
|
beforeStr = await promiseExec(doc.sub_before);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
beforeStr =
|
beforeStr =
|
||||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||||
}
|
}
|
||||||
if (beforeStr) {
|
if (beforeStr) {
|
||||||
fs.appendFileSync(absolutePath, `${beforeStr}\n`);
|
await fs.appendFile(absolutePath, `${beforeStr}\n`);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onStart: async (cp: ChildProcessWithoutNullStreams, startTime) => {
|
onStart: async (cp: ChildProcessWithoutNullStreams, startTime) => {
|
||||||
@@ -221,24 +151,24 @@ 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 this.handleLogPath(sub.log_path as string);
|
const absolutePath = await 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`);
|
await fs.appendFile(absolutePath, `\n\n## 执行after命令...\n\n`);
|
||||||
afterStr = await this.promiseExec(sub.sub_after);
|
afterStr = await promiseExec(sub.sub_after);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
afterStr =
|
afterStr =
|
||||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||||
}
|
}
|
||||||
if (afterStr) {
|
if (afterStr) {
|
||||||
fs.appendFileSync(absolutePath, `${afterStr}\n`);
|
await fs.appendFile(absolutePath, `${afterStr}\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.appendFileSync(
|
await fs.appendFile(
|
||||||
absolutePath,
|
absolutePath,
|
||||||
`\n## 执行结束... ${endTime.format(
|
`\n## 执行结束... ${endTime.format(
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
@@ -258,13 +188,13 @@ 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 this.handleLogPath(sub.log_path as string);
|
const absolutePath = await handleLogPath(sub.log_path as string);
|
||||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
await fs.appendFile(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 this.handleLogPath(sub.log_path as string);
|
const absolutePath = await handleLogPath(sub.log_path as string);
|
||||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
await fs.appendFile(absolutePath, `\n${message}`);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -273,6 +203,7 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,8 +212,11 @@ export default class SubscriptionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async update(payload: Subscription): Promise<Subscription> {
|
public async update(payload: Subscription): Promise<Subscription> {
|
||||||
const newDoc = await this.updateDb(payload);
|
const doc = await this.getDb({ id: payload.id });
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,17 +256,34 @@ export default class SubscriptionService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[]) {
|
public async remove(ids: number[], query: { force?: boolean }) {
|
||||||
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, false);
|
await this.handleTask(doc, 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);
|
||||||
|
await rmPath(filePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<Subscription> {
|
public async getDb(
|
||||||
const doc: any = await SubscriptionModel.findOne({ where: { ...query } });
|
query: FindOptions<Subscription>['where'],
|
||||||
return doc && (doc.get({ plain: true }) as Subscription);
|
): Promise<Subscription> {
|
||||||
|
const doc = await SubscriptionModel.findOne({ where: { ...query } });
|
||||||
|
if (!doc) {
|
||||||
|
throw new Error(`Subscription ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async run(ids: number[]) {
|
public async run(ids: number[]) {
|
||||||
@@ -340,10 +291,9 @@ export default class SubscriptionService {
|
|||||||
{ status: SubscriptionStatus.queued },
|
{ status: SubscriptionStatus.queued },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
);
|
);
|
||||||
concurrentRun(
|
ids.forEach((id) => {
|
||||||
ids.map((id) => async () => await this.runSingle(id)),
|
this.runSingle(id);
|
||||||
10,
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop(ids: number[]) {
|
public async stop(ids: number[]) {
|
||||||
@@ -353,17 +303,9 @@ export default class SubscriptionService {
|
|||||||
try {
|
try {
|
||||||
await killTask(doc.pid);
|
await killTask(doc.pid);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.silly(error);
|
this.logger.error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
|
||||||
|
|
||||||
fs.appendFileSync(
|
|
||||||
`${absolutePath}`,
|
|
||||||
`\n## 执行结束... ${dayjs().format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
)}${LOG_END_SYMBOL}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await SubscriptionModel.update(
|
await SubscriptionModel.update(
|
||||||
@@ -378,28 +320,31 @@ export default class SubscriptionService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const command = this.formatCommand(subscription);
|
const command = formatCommand(subscription);
|
||||||
|
|
||||||
await this.scheduleService.runTask(
|
this.scheduleService.runTask(command, this.taskCallbacks(subscription), {
|
||||||
|
name: subscription.name,
|
||||||
|
schedule: subscription.schedule,
|
||||||
command,
|
command,
|
||||||
this.taskCallbacks(subscription),
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
@@ -408,8 +353,8 @@ export default class SubscriptionService {
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
const absolutePath = await handleLogPath(doc.log_path as string);
|
||||||
return getFileContentByName(absolutePath);
|
return await getFileContentByName(absolutePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async logs(id: number) {
|
public async logs(id: number) {
|
||||||
@@ -421,15 +366,18 @@ export default class SubscriptionService {
|
|||||||
if (doc.log_path) {
|
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)) {
|
const _exist = await fileExist(dir);
|
||||||
let files = await promises.readdir(dir);
|
if (_exist) {
|
||||||
return files
|
let files = await fs.readdir(dir);
|
||||||
.map((x) => ({
|
return (
|
||||||
filename: x,
|
await Promise.all(
|
||||||
directory: relativeDir.replace(config.logPath, ''),
|
files.map(async (x) => ({
|
||||||
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
filename: x,
|
||||||
}))
|
directory: relativeDir.replace(config.logPath, ''),
|
||||||
.sort((a, b) => b.time - a.time);
|
time: (await fs.lstat(`${dir}/${x}`)).mtime.getTime(),
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
).sort((a, b) => b.time - a.time);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
import { spawn } from 'cross-spawn';
|
||||||
|
import { Response } from 'express';
|
||||||
|
import fs from 'fs';
|
||||||
|
import got from 'got';
|
||||||
|
import sum from 'lodash/sum';
|
||||||
|
import path from 'path';
|
||||||
|
import { Inject, Service } from 'typedi';
|
||||||
|
import winston from 'winston';
|
||||||
|
import config from '../config';
|
||||||
|
import { TASK_COMMAND } from '../config/const';
|
||||||
|
import {
|
||||||
|
getPid,
|
||||||
|
killTask,
|
||||||
|
parseContentVersion,
|
||||||
|
parseVersion,
|
||||||
|
promiseExec,
|
||||||
|
readDirs,
|
||||||
|
} from '../config/util';
|
||||||
|
import {
|
||||||
|
DependenceModel,
|
||||||
|
DependenceStatus,
|
||||||
|
DependenceTypes,
|
||||||
|
} from '../data/dependence';
|
||||||
|
import { NotificationInfo } from '../data/notify';
|
||||||
|
import {
|
||||||
|
AuthDataType,
|
||||||
|
SystemInfo,
|
||||||
|
SystemInstance,
|
||||||
|
SystemModel,
|
||||||
|
SystemModelInfo,
|
||||||
|
} from '../data/system';
|
||||||
|
import taskLimit from '../shared/pLimit';
|
||||||
|
import NotificationService from './notify';
|
||||||
|
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||||
|
import SockService from './sock';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class SystemService {
|
||||||
|
@Inject((type) => NotificationService)
|
||||||
|
private notificationService!: NotificationService;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@Inject('logger') private logger: winston.Logger,
|
||||||
|
private scheduleService: ScheduleService,
|
||||||
|
private sockService: SockService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async getSystemConfig() {
|
||||||
|
const doc = await this.getDb({ type: AuthDataType.systemConfig });
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateAuthDb(payload: SystemInfo): Promise<SystemInfo> {
|
||||||
|
await SystemModel.upsert({ ...payload });
|
||||||
|
const doc = await this.getDb({ type: payload.type });
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getDb(query: any): Promise<SystemInfo> {
|
||||||
|
const doc = await SystemModel.findOne({ where: { ...query } });
|
||||||
|
if (!doc) {
|
||||||
|
throw new Error(`System ${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
||||||
|
const code = Math.random().toString().slice(-6);
|
||||||
|
const isSuccess = await this.notificationService.testNotify(
|
||||||
|
notificationInfo,
|
||||||
|
'青龙',
|
||||||
|
`【蛟龙】测试通知 https://t.me/jiao_long`,
|
||||||
|
);
|
||||||
|
if (isSuccess) {
|
||||||
|
const result = await this.updateAuthDb({
|
||||||
|
type: AuthDataType.notification,
|
||||||
|
info: { ...notificationInfo },
|
||||||
|
});
|
||||||
|
return { code: 200, data: { ...result, code } };
|
||||||
|
} else {
|
||||||
|
return { code: 400, message: '通知发送失败,请检查参数' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateLogRemoveFrequency(info: SystemModelInfo) {
|
||||||
|
const oDoc = await this.getSystemConfig();
|
||||||
|
const result = await this.updateAuthDb({
|
||||||
|
...oDoc,
|
||||||
|
info: { ...oDoc.info, ...info },
|
||||||
|
});
|
||||||
|
const cron = {
|
||||||
|
id: result.id || NaN,
|
||||||
|
name: '删除日志',
|
||||||
|
command: `ql rmlog ${info.logRemoveFrequency}`,
|
||||||
|
};
|
||||||
|
if (oDoc.info?.logRemoveFrequency) {
|
||||||
|
await this.scheduleService.cancelIntervalTask(cron);
|
||||||
|
}
|
||||||
|
if (info.logRemoveFrequency && info.logRemoveFrequency > 0) {
|
||||||
|
this.scheduleService.createIntervalTask(cron, {
|
||||||
|
days: info.logRemoveFrequency,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { code: 200, data: info };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateCronConcurrency(info: SystemModelInfo) {
|
||||||
|
const oDoc = await this.getSystemConfig();
|
||||||
|
await this.updateAuthDb({
|
||||||
|
...oDoc,
|
||||||
|
info: { ...oDoc.info, ...info },
|
||||||
|
});
|
||||||
|
if (info.cronConcurrency) {
|
||||||
|
await taskLimit.setCustomLimit(info.cronConcurrency);
|
||||||
|
}
|
||||||
|
return { code: 200, data: info };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateDependenceProxy(info: SystemModelInfo) {
|
||||||
|
const oDoc = await this.getSystemConfig();
|
||||||
|
await this.updateAuthDb({
|
||||||
|
...oDoc,
|
||||||
|
info: { ...oDoc.info, ...info },
|
||||||
|
});
|
||||||
|
if (info.dependenceProxy) {
|
||||||
|
await fs.promises.writeFile(
|
||||||
|
config.dependenceProxyFile,
|
||||||
|
`export http_proxy="${info.dependenceProxy}"\nexport https_proxy="${info.dependenceProxy}"`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await fs.promises.rm(config.dependenceProxyFile);
|
||||||
|
}
|
||||||
|
return { code: 200, data: info };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateNodeMirror(info: SystemModelInfo, res?: Response) {
|
||||||
|
const oDoc = await this.getSystemConfig();
|
||||||
|
await this.updateAuthDb({
|
||||||
|
...oDoc,
|
||||||
|
info: { ...oDoc.info, ...info },
|
||||||
|
});
|
||||||
|
let cmd = 'pnpm config delete registry';
|
||||||
|
if (info.nodeMirror) {
|
||||||
|
cmd = `pnpm config set registry ${info.nodeMirror}`;
|
||||||
|
}
|
||||||
|
let command = `cd && ${cmd}`;
|
||||||
|
const docs = await DependenceModel.findAll({
|
||||||
|
where: {
|
||||||
|
type: DependenceTypes.nodejs,
|
||||||
|
status: DependenceStatus.installed,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (docs.length > 0) {
|
||||||
|
command += ` && pnpm i -g`;
|
||||||
|
}
|
||||||
|
this.scheduleService.runTask(
|
||||||
|
command,
|
||||||
|
{
|
||||||
|
onStart: async (cp) => {
|
||||||
|
res?.setHeader('QL-Task-Pid', `${cp.pid}`);
|
||||||
|
res?.end();
|
||||||
|
},
|
||||||
|
onEnd: async () => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'updateNodeMirror',
|
||||||
|
message: 'update node mirror end',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: async (message: string) => {
|
||||||
|
this.sockService.sendMessage({ type: 'updateNodeMirror', message });
|
||||||
|
},
|
||||||
|
onLog: async (message: string) => {
|
||||||
|
this.sockService.sendMessage({ type: 'updateNodeMirror', message });
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updatePythonMirror(info: SystemModelInfo) {
|
||||||
|
const oDoc = await this.getSystemConfig();
|
||||||
|
await this.updateAuthDb({
|
||||||
|
...oDoc,
|
||||||
|
info: { ...oDoc.info, ...info },
|
||||||
|
});
|
||||||
|
let cmd = 'pip config unset global.index-url';
|
||||||
|
if (info.pythonMirror) {
|
||||||
|
cmd = `pip3 config set global.index-url ${info.pythonMirror}`;
|
||||||
|
}
|
||||||
|
await promiseExec(cmd);
|
||||||
|
return { code: 200, data: info };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateLinuxMirror(
|
||||||
|
info: SystemModelInfo,
|
||||||
|
res?: Response,
|
||||||
|
onEnd?: () => void,
|
||||||
|
) {
|
||||||
|
const oDoc = await this.getSystemConfig();
|
||||||
|
await this.updateAuthDb({
|
||||||
|
...oDoc,
|
||||||
|
info: { ...oDoc.info, ...info },
|
||||||
|
});
|
||||||
|
let defaultDomain = 'https://dl-cdn.alpinelinux.org';
|
||||||
|
let targetDomain = 'https://dl-cdn.alpinelinux.org';
|
||||||
|
const content = await fs.promises.readFile('/etc/apk/repositories', {
|
||||||
|
encoding: 'utf-8',
|
||||||
|
});
|
||||||
|
const domainMatch = content.match(/(http.*)\/alpine\/.*/);
|
||||||
|
if (domainMatch) {
|
||||||
|
defaultDomain = domainMatch[1];
|
||||||
|
}
|
||||||
|
if (info.linuxMirror) {
|
||||||
|
targetDomain = info.linuxMirror;
|
||||||
|
}
|
||||||
|
const command = `sed -i 's/${defaultDomain.replace(
|
||||||
|
/\//g,
|
||||||
|
'\\/',
|
||||||
|
)}/${targetDomain.replace(
|
||||||
|
/\//g,
|
||||||
|
'\\/',
|
||||||
|
)}/g' /etc/apk/repositories && apk update -f`;
|
||||||
|
|
||||||
|
this.scheduleService.runTask(
|
||||||
|
command,
|
||||||
|
{
|
||||||
|
onStart: async (cp) => {
|
||||||
|
res?.setHeader('QL-Task-Pid', `${cp.pid}`);
|
||||||
|
res?.end();
|
||||||
|
},
|
||||||
|
onEnd: async () => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'updateLinuxMirror',
|
||||||
|
message: 'update linux mirror end',
|
||||||
|
});
|
||||||
|
onEnd?.();
|
||||||
|
},
|
||||||
|
onError: async (message: string) => {
|
||||||
|
this.sockService.sendMessage({ type: 'updateLinuxMirror', message });
|
||||||
|
},
|
||||||
|
onLog: async (message: string) => {
|
||||||
|
this.sockService.sendMessage({ type: 'updateLinuxMirror', message });
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async checkUpdate() {
|
||||||
|
try {
|
||||||
|
const currentVersionContent = await parseVersion(config.versionFile);
|
||||||
|
|
||||||
|
let lastVersionContent;
|
||||||
|
try {
|
||||||
|
const result = await got.get(
|
||||||
|
`${config.lastVersionFile}?t=${Date.now()}`,
|
||||||
|
{
|
||||||
|
timeout: 30000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
lastVersionContent = await parseContentVersion(result.body);
|
||||||
|
} catch (error) {}
|
||||||
|
|
||||||
|
if (!lastVersionContent) {
|
||||||
|
lastVersionContent = currentVersionContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
hasNewVersion: this.checkHasNewVersion(
|
||||||
|
currentVersionContent.version,
|
||||||
|
lastVersionContent.version,
|
||||||
|
),
|
||||||
|
lastVersion: lastVersionContent.version,
|
||||||
|
lastLog: lastVersionContent.changeLog,
|
||||||
|
lastLogLink: lastVersionContent.changeLogLink,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
code: 400,
|
||||||
|
message: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private checkHasNewVersion(curVersion: string, lastVersion: string) {
|
||||||
|
const curArr = curVersion.split('.').map((x) => parseInt(x, 10));
|
||||||
|
const lastArr = lastVersion.split('.').map((x) => parseInt(x, 10));
|
||||||
|
if (curArr[0] < lastArr[0]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (curArr[0] === lastArr[0] && curArr[1] < lastArr[1]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
curArr[0] === lastArr[0] &&
|
||||||
|
curArr[1] === lastArr[1] &&
|
||||||
|
curArr[2] < lastArr[2]
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateSystem() {
|
||||||
|
const cp = spawn('real_time=true ql update false', { shell: '/bin/bash' });
|
||||||
|
|
||||||
|
cp.stdout.on('data', (data) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'updateSystemVersion',
|
||||||
|
message: data.toString(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.stderr.on('data', (data) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'updateSystemVersion',
|
||||||
|
message: data.toString(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
cp.on('error', (err) => {
|
||||||
|
this.sockService.sendMessage({
|
||||||
|
type: 'updateSystemVersion',
|
||||||
|
message: JSON.stringify(err),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return { code: 200 };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async reloadSystem(target?: 'system' | 'data') {
|
||||||
|
const cmd = `real_time=true ql reload ${target || ''}`;
|
||||||
|
const cp = spawn(cmd, { shell: '/bin/bash' });
|
||||||
|
cp.unref();
|
||||||
|
return { code: 200 };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async notify({ title, content }: { title: string; content: string }) {
|
||||||
|
const isSuccess = await this.notificationService.notify(title, content);
|
||||||
|
if (isSuccess) {
|
||||||
|
return { code: 200, message: '通知发送成功' };
|
||||||
|
} else {
|
||||||
|
return { code: 400, message: '通知发送失败,请检查系统设置/通知配置' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async run({ command }: { command: string }, callback: TaskCallbacks) {
|
||||||
|
if (!command.startsWith(TASK_COMMAND)) {
|
||||||
|
command = `${TASK_COMMAND} ${command}`;
|
||||||
|
}
|
||||||
|
this.scheduleService.runTask(`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 promiseExec(
|
||||||
|
`cd ${config.rootPath} && tar -zcvf ${config.dataTgzFile} 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')}`);
|
||||||
|
const res = await promiseExec(
|
||||||
|
`cd ${config.tmpPath} && tar -zxvf data.tgz`,
|
||||||
|
);
|
||||||
|
return { code: 200, data: res };
|
||||||
|
} catch (error: any) {
|
||||||
|
return { code: 400, message: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getSystemLog(res: Response) {
|
||||||
|
const result = await 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,33 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import { createRandomString, getNetIp, getPlatform } from '../config/util';
|
import {
|
||||||
|
createFile,
|
||||||
|
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/promises';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
import { authenticator } from '@otplib/preset-default';
|
import { authenticator } from '@otplib/preset-default';
|
||||||
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
|
import {
|
||||||
|
AuthDataType,
|
||||||
|
SystemInfo,
|
||||||
|
SystemModel,
|
||||||
|
SystemModelInfo,
|
||||||
|
LoginStatus,
|
||||||
|
} from '../data/system';
|
||||||
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';
|
||||||
|
import IP2Region from 'ip2region';
|
||||||
|
import requestIp from 'request-ip';
|
||||||
|
import uniq from 'lodash/uniq';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class UserService {
|
export default class UserService {
|
||||||
@@ -33,12 +48,13 @@ export default class UserService {
|
|||||||
req: Request,
|
req: Request,
|
||||||
needTwoFactor = true,
|
needTwoFactor = true,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
if (!fs.existsSync(config.authConfigFile)) {
|
const _exist = await fileExist(config.authConfigFile);
|
||||||
|
if (!_exist) {
|
||||||
return this.initAuthInfo();
|
return this.initAuthInfo();
|
||||||
}
|
}
|
||||||
|
|
||||||
let { username, password } = payloads;
|
let { username, password } = payloads;
|
||||||
const content = this.getAuthInfo();
|
const content = await this.getAuthInfo();
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
if (content) {
|
if (content) {
|
||||||
let {
|
let {
|
||||||
@@ -91,7 +107,16 @@ export default class UserService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const { ip, address } = await getNetIp(req);
|
const ip = requestIp.getClientIp(req) || '';
|
||||||
|
const query = new IP2Region();
|
||||||
|
const ipAddress = query.search(ip);
|
||||||
|
let address = '';
|
||||||
|
if (ipAddress) {
|
||||||
|
const { country, province, city, isp } = ipAddress;
|
||||||
|
address = uniq([country, province, city, isp])
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
|
}
|
||||||
if (username === cUsername && password === cPassword) {
|
if (username === cUsername && password === cPassword) {
|
||||||
const data = createRandomString(50, 100);
|
const data = createRandomString(50, 100);
|
||||||
const expiration = twoFactorActivated ? 60 : 20;
|
const expiration = twoFactorActivated ? 60 : 20;
|
||||||
@@ -113,13 +138,12 @@ export default class UserService {
|
|||||||
platform: req.platform,
|
platform: req.platform,
|
||||||
isTwoFactorChecking: false,
|
isTwoFactorChecking: false,
|
||||||
});
|
});
|
||||||
await this.notificationService.notify(
|
this.notificationService.notify(
|
||||||
'登录通知',
|
'登录通知',
|
||||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||||
req.platform
|
req.platform
|
||||||
}端 登录成功,ip地址 ${ip}`,
|
}端 登录成功,ip地址 ${ip}`,
|
||||||
);
|
);
|
||||||
await this.getLoginLog();
|
|
||||||
await this.insertDb({
|
await this.insertDb({
|
||||||
type: AuthDataType.loginLog,
|
type: AuthDataType.loginLog,
|
||||||
info: {
|
info: {
|
||||||
@@ -142,13 +166,12 @@ export default class UserService {
|
|||||||
lastaddr: address,
|
lastaddr: address,
|
||||||
platform: req.platform,
|
platform: req.platform,
|
||||||
});
|
});
|
||||||
await this.notificationService.notify(
|
this.notificationService.notify(
|
||||||
'登录通知',
|
'登录通知',
|
||||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||||
req.platform
|
req.platform
|
||||||
}端 登录失败,ip地址 ${ip}`,
|
}端 登录失败,ip地址 ${ip}`,
|
||||||
);
|
);
|
||||||
await this.getLoginLog();
|
|
||||||
await this.insertDb({
|
await this.insertDb({
|
||||||
type: AuthDataType.loginLog,
|
type: AuthDataType.loginLog,
|
||||||
info: {
|
info: {
|
||||||
@@ -176,21 +199,23 @@ export default class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async logout(platform: string): Promise<any> {
|
public async logout(platform: string): Promise<any> {
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, {
|
this.updateAuthInfo(authInfo, {
|
||||||
token: '',
|
token: '',
|
||||||
tokens: { ...authInfo.tokens, [platform]: '' },
|
tokens: { ...authInfo.tokens, [platform]: '' },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getLoginLog(): Promise<AuthInfo[]> {
|
public async getLoginLog(): Promise<Array<SystemModelInfo | undefined>> {
|
||||||
const docs = await AuthModel.findAll({
|
const docs = await SystemModel.findAll({
|
||||||
where: { type: AuthDataType.loginLog },
|
where: { type: AuthDataType.loginLog },
|
||||||
});
|
});
|
||||||
if (docs && docs.length > 0) {
|
if (docs && docs.length > 0) {
|
||||||
const result = docs.sort((a, b) => b.info.timestamp - a.info.timestamp);
|
const result = docs.sort(
|
||||||
|
(a, b) => b.info!.timestamp! - a.info!.timestamp!,
|
||||||
|
);
|
||||||
if (result.length > 100) {
|
if (result.length > 100) {
|
||||||
await AuthModel.destroy({
|
await SystemModel.destroy({
|
||||||
where: { id: result[result.length - 1].id },
|
where: { id: result[result.length - 1].id },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -199,23 +224,22 @@ export default class UserService {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
private async insertDb(payload: AuthInfo): Promise<AuthInfo> {
|
private async insertDb(payload: SystemInfo): Promise<SystemInfo> {
|
||||||
const doc = await AuthModel.create({ ...payload }, { returning: true });
|
const doc = await SystemModel.create({ ...payload }, { returning: true });
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
private initAuthInfo() {
|
private async initAuthInfo() {
|
||||||
const newPassword = createRandomString(16, 22);
|
await fs.writeFile(
|
||||||
fs.writeFileSync(
|
|
||||||
config.authConfigFile,
|
config.authConfigFile,
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
username: 'admin',
|
username: 'admin',
|
||||||
password: newPassword,
|
password: 'admin',
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
code: 100,
|
code: 100,
|
||||||
message: '已初始化密码,请前往auth.json查看并重新登录',
|
message: '未找到认证文件,重新初始化',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,36 +253,41 @@ export default class UserService {
|
|||||||
if (password === 'admin') {
|
if (password === 'admin') {
|
||||||
return { code: 400, message: '密码不能设置为admin' };
|
return { code: 400, message: '密码不能设置为admin' };
|
||||||
}
|
}
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, { username, password });
|
this.updateAuthInfo(authInfo, { username, password });
|
||||||
return { code: 200, message: '更新成功' };
|
return { code: 200, message: '更新成功' };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateAvatar(avatar: string) {
|
public async updateAvatar(avatar: string) {
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, { avatar });
|
this.updateAuthInfo(authInfo, { avatar });
|
||||||
return { code: 200, data: avatar, message: '更新成功' };
|
return { code: 200, data: avatar, message: '更新成功' };
|
||||||
}
|
}
|
||||||
|
|
||||||
public getUserInfo(): Promise<any> {
|
public async getUserInfo(): Promise<any> {
|
||||||
return new Promise((resolve) => {
|
const authFileExist = await fileExist(config.authConfigFile);
|
||||||
fs.readFile(config.authConfigFile, 'utf8', (err, data) => {
|
if (!authFileExist) {
|
||||||
if (err) console.log(err);
|
await createFile(
|
||||||
resolve(JSON.parse(data));
|
config.authConfigFile,
|
||||||
});
|
JSON.stringify({
|
||||||
});
|
username: 'admin',
|
||||||
|
password: 'admin',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return await this.getAuthInfo();
|
||||||
}
|
}
|
||||||
|
|
||||||
public initTwoFactor() {
|
public async initTwoFactor() {
|
||||||
const secret = authenticator.generateSecret();
|
const secret = authenticator.generateSecret();
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
const otpauth = authenticator.keyuri(authInfo.username, 'qinglong', secret);
|
const otpauth = authenticator.keyuri(authInfo.username, 'qinglong', secret);
|
||||||
this.updateAuthInfo(authInfo, { twoFactorSecret: secret });
|
this.updateAuthInfo(authInfo, { twoFactorSecret: secret });
|
||||||
return { secret, url: otpauth };
|
return { secret, url: otpauth };
|
||||||
}
|
}
|
||||||
|
|
||||||
public activeTwoFactor(code: string) {
|
public async activeTwoFactor(code: string) {
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
const isValid = authenticator.verify({
|
const isValid = authenticator.verify({
|
||||||
token: code,
|
token: code,
|
||||||
secret: authInfo.twoFactorSecret,
|
secret: authInfo.twoFactorSecret,
|
||||||
@@ -277,7 +306,7 @@ export default class UserService {
|
|||||||
}: { username: string; password: string; code: string },
|
}: { username: string; password: string; code: string },
|
||||||
req: any,
|
req: any,
|
||||||
) {
|
) {
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
const { isTwoFactorChecking, twoFactorSecret } = authInfo;
|
const { isTwoFactorChecking, twoFactorSecret } = authInfo;
|
||||||
if (!isTwoFactorChecking) {
|
if (!isTwoFactorChecking) {
|
||||||
return { code: 450, message: '未知错误' };
|
return { code: 450, message: '未知错误' };
|
||||||
@@ -299,8 +328,8 @@ export default class UserService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public deactiveTwoFactor() {
|
public async deactiveTwoFactor() {
|
||||||
const authInfo = this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, {
|
this.updateAuthInfo(authInfo, {
|
||||||
twoFactorActivated: false,
|
twoFactorActivated: false,
|
||||||
twoFactorActived: false,
|
twoFactorActived: false,
|
||||||
@@ -309,13 +338,13 @@ export default class UserService {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getAuthInfo() {
|
private async getAuthInfo() {
|
||||||
const content = fs.readFileSync(config.authConfigFile, 'utf8');
|
const content = await fs.readFile(config.authConfigFile, 'utf8');
|
||||||
return JSON.parse(content || '{}');
|
return safeJSONParse(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateAuthInfo(authInfo: any, info: any) {
|
private async updateAuthInfo(authInfo: any, info: any) {
|
||||||
fs.writeFileSync(
|
await fs.writeFile(
|
||||||
config.authConfigFile,
|
config.authConfigFile,
|
||||||
JSON.stringify({ ...authInfo, ...info }),
|
JSON.stringify({ ...authInfo, ...info }),
|
||||||
);
|
);
|
||||||
@@ -323,26 +352,29 @@ export default class UserService {
|
|||||||
|
|
||||||
public async getNotificationMode(): Promise<NotificationInfo> {
|
public async getNotificationMode(): Promise<NotificationInfo> {
|
||||||
const doc = await this.getDb({ type: AuthDataType.notification });
|
const doc = await this.getDb({ type: AuthDataType.notification });
|
||||||
return (doc && doc.info) || {};
|
return (doc.info || {}) as NotificationInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateAuthDb(payload: AuthInfo): Promise<any> {
|
private async updateAuthDb(payload: SystemInfo): Promise<any> {
|
||||||
let doc = await AuthModel.findOne({ type: payload.type });
|
let doc = await SystemModel.findOne({ type: payload.type });
|
||||||
if (doc) {
|
if (doc) {
|
||||||
const updateResult = await AuthModel.update(payload, {
|
const updateResult = await SystemModel.update(payload, {
|
||||||
where: { id: doc.id },
|
where: { id: doc.id },
|
||||||
returning: true,
|
returning: true,
|
||||||
});
|
});
|
||||||
doc = updateResult[1][0];
|
doc = updateResult[1][0];
|
||||||
} else {
|
} else {
|
||||||
doc = await AuthModel.create(payload, { returning: true });
|
doc = await SystemModel.create(payload, { returning: true });
|
||||||
}
|
}
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<any> {
|
public async getDb(query: any): Promise<SystemInfo> {
|
||||||
const doc: any = await AuthModel.findOne({ where: { ...query } });
|
const doc = await SystemModel.findOne({ where: { ...query } });
|
||||||
return doc && (doc.get({ plain: true }) as any);
|
if (!doc) {
|
||||||
|
throw new Error(`${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||||
|
import os from 'os';
|
||||||
|
import { AuthDataType, SystemModel } from '../data/system';
|
||||||
|
import Logger from '../loaders/logger';
|
||||||
|
import { Dependence } from '../data/dependence';
|
||||||
|
|
||||||
|
interface IDependencyFn<T> {
|
||||||
|
(): Promise<T>;
|
||||||
|
dependency?: Dependence;
|
||||||
|
}
|
||||||
|
class TaskLimit {
|
||||||
|
private dependenyLimit = new PQueue({ concurrency: 1 });
|
||||||
|
private queuedDependencyIds = new Set<number>([]);
|
||||||
|
private updateLogLimit = new PQueue({ concurrency: 1 });
|
||||||
|
private cronLimit = new PQueue({
|
||||||
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
|
});
|
||||||
|
private manualCronoLimit = new PQueue({
|
||||||
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
|
});
|
||||||
|
|
||||||
|
get cronLimitActiveCount() {
|
||||||
|
return this.cronLimit.pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
get cronLimitPendingCount() {
|
||||||
|
return this.cronLimit.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
get firstDependencyId() {
|
||||||
|
return [...this.queuedDependencyIds.values()][0];
|
||||||
|
}
|
||||||
|
|
||||||
|
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 removeQueuedDependency(dependency: Dependence) {
|
||||||
|
if (this.queuedDependencyIds.has(dependency.id!)) {
|
||||||
|
this.queuedDependencyIds.delete(dependency.id!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async setCustomLimit(limit?: number) {
|
||||||
|
if (limit) {
|
||||||
|
this.cronLimit.concurrency = limit;
|
||||||
|
this.manualCronoLimit.concurrency = limit;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await SystemModel.sync();
|
||||||
|
const doc = await SystemModel.findOne({
|
||||||
|
where: { type: AuthDataType.systemConfig },
|
||||||
|
});
|
||||||
|
if (doc?.info?.cronConcurrency) {
|
||||||
|
this.cronLimit.concurrency = doc.info.cronConcurrency;
|
||||||
|
this.manualCronoLimit.concurrency = doc.info.cronConcurrency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async runWithCronLimit<T>(
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
options?: Partial<QueueAddOptions>,
|
||||||
|
): Promise<T | void> {
|
||||||
|
return this.cronLimit.add(fn, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async manualRunWithCronLimit<T>(
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
options?: Partial<QueueAddOptions>,
|
||||||
|
): Promise<T | void> {
|
||||||
|
return this.manualCronoLimit.add(fn, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public runDependeny<T>(
|
||||||
|
dependency: Dependence,
|
||||||
|
fn: IDependencyFn<T>,
|
||||||
|
options?: Partial<QueueAddOptions>,
|
||||||
|
): Promise<T | void> {
|
||||||
|
this.queuedDependencyIds.add(dependency.id!);
|
||||||
|
fn.dependency = dependency;
|
||||||
|
return this.dependenyLimit.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();
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
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 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import 'reflect-metadata'; // We need this in order to use @Decorators
|
||||||
|
import config from './config';
|
||||||
|
import express from 'express';
|
||||||
|
import depInjectorLoader from './loaders/depInjector';
|
||||||
|
import Logger from './loaders/logger';
|
||||||
|
|
||||||
|
|
||||||
|
async function startServer() {
|
||||||
|
const app = express();
|
||||||
|
depInjectorLoader();
|
||||||
|
|
||||||
|
await require('./loaders/update').default({ app });
|
||||||
|
|
||||||
|
app
|
||||||
|
.listen(config.updatePort, '0.0.0.0', () => {
|
||||||
|
Logger.debug(`✌️ 更新服务启动成功!`);
|
||||||
|
console.debug(`✌️ 更新服务启动成功!`);
|
||||||
|
process.send?.('ready');
|
||||||
|
})
|
||||||
|
.on('error', (err) => {
|
||||||
|
Logger.error(err);
|
||||||
|
console.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
startServer();
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
FROM python:3.10-alpine3.18 as builder
|
||||||
|
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||||
|
RUN set -x \
|
||||||
|
&& apk update \
|
||||||
|
&& apk add nodejs npm git \
|
||||||
|
&& npm i -g pnpm@8.3.1 pm2 tsx \
|
||||||
|
&& cd /tmp/build \
|
||||||
|
&& pnpm install --prod
|
||||||
|
|
||||||
|
FROM python:3.10-alpine
|
||||||
|
|
||||||
|
ARG QL_MAINTAINER="whyour"
|
||||||
|
LABEL maintainer="${QL_MAINTAINER}"
|
||||||
|
ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
||||||
|
ARG QL_BRANCH=develop
|
||||||
|
|
||||||
|
ENV PNPM_HOME=/root/.local/share/pnpm \
|
||||||
|
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/share/pnpm:/root/.local/share/pnpm/global/5/node_modules:$PNPM_HOME \
|
||||||
|
NODE_PATH=/usr/local/bin:/usr/local/pnpm-global/5/node_modules:/usr/local/lib/node_modules:/root/.local/share/pnpm/global/5/node_modules \
|
||||||
|
LANG=C.UTF-8 \
|
||||||
|
SHELL=/bin/bash \
|
||||||
|
PS1="\u@\h:\w \$ " \
|
||||||
|
QL_DIR=/ql \
|
||||||
|
QL_BRANCH=${QL_BRANCH}
|
||||||
|
|
||||||
|
VOLUME /ql/data
|
||||||
|
|
||||||
|
EXPOSE 5700
|
||||||
|
|
||||||
|
COPY --from=builder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||||
|
COPY --from=builder /usr/local/bin/. /usr/local/bin/
|
||||||
|
|
||||||
|
RUN set -x \
|
||||||
|
&& apk update -f \
|
||||||
|
&& apk upgrade \
|
||||||
|
&& apk --no-cache add -f bash \
|
||||||
|
coreutils \
|
||||||
|
git \
|
||||||
|
curl \
|
||||||
|
wget \
|
||||||
|
tzdata \
|
||||||
|
perl \
|
||||||
|
openssl \
|
||||||
|
nginx \
|
||||||
|
nodejs \
|
||||||
|
jq \
|
||||||
|
openssh \
|
||||||
|
procps \
|
||||||
|
netcat-openbsd \
|
||||||
|
unzip \
|
||||||
|
npm \
|
||||||
|
&& rm -rf /var/cache/apk/* \
|
||||||
|
&& apk update \
|
||||||
|
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||||
|
&& echo "Asia/Shanghai" > /etc/timezone \
|
||||||
|
&& git config --global user.email "qinglong@@users.noreply.github.com" \
|
||||||
|
&& git config --global user.name "qinglong" \
|
||||||
|
&& git config --global http.postBuffer 524288000 \
|
||||||
|
&& rm -rf /root/.pnpm-store \
|
||||||
|
&& rm -rf /root/.local/share/pnpm/store \
|
||||||
|
&& rm -rf /root/.cache \
|
||||||
|
&& ulimit -c 0
|
||||||
|
|
||||||
|
ARG SOURCE_COMMIT
|
||||||
|
RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||||
|
&& cd ${QL_DIR} \
|
||||||
|
&& cp -f .env.example .env \
|
||||||
|
&& chmod 777 ${QL_DIR}/shell/*.sh \
|
||||||
|
&& chmod 777 ${QL_DIR}/docker/*.sh \
|
||||||
|
&& git clone --depth=1 -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
|
||||||
|
&& mkdir -p ${QL_DIR}/static \
|
||||||
|
&& cp -rf /static/* ${QL_DIR}/static \
|
||||||
|
&& rm -rf /static
|
||||||
|
|
||||||
|
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||||
|
|
||||||
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||||
|
CMD curl -sf --noproxy '*' http://127.0.0.1:5400/api/health || exit 1
|
||||||
|
|
||||||
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
+71
-49
@@ -1,4 +1,13 @@
|
|||||||
FROM python:3.10-alpine
|
FROM python:3.11-alpine3.18 as builder
|
||||||
|
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||||
|
RUN set -x \
|
||||||
|
&& apk update \
|
||||||
|
&& apk add nodejs npm git \
|
||||||
|
&& npm i -g pnpm@8.3.1 pm2 tsx \
|
||||||
|
&& cd /tmp/build \
|
||||||
|
&& pnpm install --prod
|
||||||
|
|
||||||
|
FROM python:3.11-alpine
|
||||||
|
|
||||||
ARG QL_MAINTAINER="whyour"
|
ARG QL_MAINTAINER="whyour"
|
||||||
LABEL maintainer="${QL_MAINTAINER}"
|
LABEL maintainer="${QL_MAINTAINER}"
|
||||||
@@ -6,55 +15,68 @@ ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
|||||||
ARG QL_BRANCH=develop
|
ARG QL_BRANCH=develop
|
||||||
|
|
||||||
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 \
|
||||||
LANG=zh_CN.UTF-8 \
|
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 \
|
||||||
SHELL=/bin/bash \
|
LANG=C.UTF-8 \
|
||||||
PS1="\u@\h:\w \$ " \
|
SHELL=/bin/bash \
|
||||||
QL_DIR=/ql \
|
PS1="\u@\h:\w \$ " \
|
||||||
QL_BRANCH=${QL_BRANCH}
|
QL_DIR=/ql \
|
||||||
|
QL_BRANCH=${QL_BRANCH}
|
||||||
|
|
||||||
|
VOLUME /ql/data
|
||||||
|
|
||||||
|
EXPOSE 5700
|
||||||
|
|
||||||
|
COPY --from=builder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||||
|
COPY --from=builder /usr/local/bin/. /usr/local/bin/
|
||||||
|
|
||||||
|
RUN set -x \
|
||||||
|
&& apk update -f \
|
||||||
|
&& apk upgrade \
|
||||||
|
&& apk --no-cache add -f bash \
|
||||||
|
coreutils \
|
||||||
|
git \
|
||||||
|
curl \
|
||||||
|
wget \
|
||||||
|
tzdata \
|
||||||
|
perl \
|
||||||
|
openssl \
|
||||||
|
nginx \
|
||||||
|
nodejs \
|
||||||
|
jq \
|
||||||
|
openssh \
|
||||||
|
procps \
|
||||||
|
netcat-openbsd \
|
||||||
|
unzip \
|
||||||
|
npm \
|
||||||
|
&& rm -rf /var/cache/apk/* \
|
||||||
|
&& apk update \
|
||||||
|
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||||
|
&& echo "Asia/Shanghai" > /etc/timezone \
|
||||||
|
&& git config --global user.email "qinglong@@users.noreply.github.com" \
|
||||||
|
&& git config --global user.name "qinglong" \
|
||||||
|
&& git config --global http.postBuffer 524288000 \
|
||||||
|
&& rm -rf /root/.pnpm-store \
|
||||||
|
&& rm -rf /root/.local/share/pnpm/store \
|
||||||
|
&& rm -rf /root/.cache \
|
||||||
|
&& ulimit -c 0
|
||||||
|
|
||||||
|
ARG SOURCE_COMMIT
|
||||||
|
RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||||
|
&& cd ${QL_DIR} \
|
||||||
|
&& cp -f .env.example .env \
|
||||||
|
&& chmod 777 ${QL_DIR}/shell/*.sh \
|
||||||
|
&& chmod 777 ${QL_DIR}/docker/*.sh \
|
||||||
|
&& git clone --depth=1 -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
|
||||||
|
&& mkdir -p ${QL_DIR}/static \
|
||||||
|
&& cp -rf /static/* ${QL_DIR}/static \
|
||||||
|
&& rm -rf /static
|
||||||
|
|
||||||
|
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||||
|
|
||||||
WORKDIR ${QL_DIR}
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
RUN set -x \
|
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||||
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
CMD curl -sf --noproxy '*' http://127.0.0.1:5400/api/health || exit 1
|
||||||
&& apk update -f \
|
|
||||||
&& apk upgrade \
|
|
||||||
&& apk --no-cache add -f bash \
|
|
||||||
coreutils \
|
|
||||||
moreutils \
|
|
||||||
git \
|
|
||||||
curl \
|
|
||||||
wget \
|
|
||||||
tzdata \
|
|
||||||
perl \
|
|
||||||
openssl \
|
|
||||||
nginx \
|
|
||||||
nodejs \
|
|
||||||
jq \
|
|
||||||
openssh \
|
|
||||||
npm \
|
|
||||||
&& rm -rf /var/cache/apk/* \
|
|
||||||
&& apk update \
|
|
||||||
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
|
||||||
&& echo "Asia/Shanghai" > /etc/timezone \
|
|
||||||
&& git config --global user.email "qinglong@@users.noreply.github.com" \
|
|
||||||
&& git config --global user.name "qinglong" \
|
|
||||||
&& git config --global http.postBuffer 524288000 \
|
|
||||||
&& npm install -g pnpm \
|
|
||||||
&& pnpm add -g pm2 ts-node typescript tslib \
|
|
||||||
&& git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
|
||||||
&& cd ${QL_DIR} \
|
|
||||||
&& cp -f .env.example .env \
|
|
||||||
&& chmod 777 ${QL_DIR}/shell/*.sh \
|
|
||||||
&& chmod 777 ${QL_DIR}/docker/*.sh \
|
|
||||||
&& pnpm install --prod \
|
|
||||||
&& rm -rf /root/.pnpm-store \
|
|
||||||
&& rm -rf /root/.local/share/pnpm/store \
|
|
||||||
&& rm -rf /root/.cache \
|
|
||||||
&& rm -rf /root/.npm \
|
|
||||||
&& git clone -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
|
|
||||||
&& mkdir -p ${QL_DIR}/static \
|
|
||||||
&& cp -rf /static/* ${QL_DIR}/static \
|
|
||||||
&& rm -rf /static
|
|
||||||
|
|
||||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
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
|
||||||
|
|||||||
+10
-28
@@ -1,60 +1,42 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
dir_shell=/ql/shell
|
dir_shell=/ql/shell
|
||||||
|
. $dir_shell/env.sh
|
||||||
. $dir_shell/share.sh
|
. $dir_shell/share.sh
|
||||||
link_shell
|
|
||||||
|
|
||||||
export isFirstStartServer=true
|
|
||||||
|
|
||||||
echo -e "======================1. 检测配置文件========================\n"
|
echo -e "======================1. 检测配置文件========================\n"
|
||||||
make_dir /etc/nginx/conf.d
|
make_dir /etc/nginx/conf.d
|
||||||
make_dir /run/nginx
|
make_dir /run/nginx
|
||||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
init_nginx
|
||||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
fix_config
|
||||||
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
|
|
||||||
pm2 l &>/dev/null
|
pm2 l &>/dev/null
|
||||||
|
|
||||||
patch_version &>/dev/null
|
|
||||||
echo
|
|
||||||
|
|
||||||
echo -e "======================2. 安装依赖========================\n"
|
echo -e "======================2. 安装依赖========================\n"
|
||||||
update_depend
|
patch_version
|
||||||
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. 启动面板监控========================\n"
|
echo -e "======================4. 启动pm2服务========================\n"
|
||||||
pm2 delete public &>/dev/null
|
reload_update
|
||||||
pm2 start $dir_static/build/public.js -n public --source-map-support --time
|
reload_pm2
|
||||||
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 "======================7. 启动bot========================\n"
|
echo -e "======================5. 启动bot========================\n"
|
||||||
nohup ql bot >$dir_log/bot.log 2>&1 &
|
nohup ql bot >$dir_log/bot.log 2>&1 &
|
||||||
echo -e "bot后台启动中...\n"
|
echo -e "bot后台启动中...\n"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ $EnableExtraShell == true ]]; then
|
if [[ $EnableExtraShell == true ]]; then
|
||||||
echo -e "======================8. 执行自定义脚本========================\n"
|
echo -e "====================6. 执行自定义脚本========================\n"
|
||||||
nohup ql extra >$dir_log/extra.log 2>&1 &
|
nohup ql extra >$dir_log/extra.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
|
||||||
|
|||||||
+41
-8
@@ -6,38 +6,69 @@ upstream publicApi {
|
|||||||
server 0.0.0.0:5400;
|
server 0.0.0.0:5400;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
upstream updateApi {
|
||||||
|
server 0.0.0.0:5300;
|
||||||
|
}
|
||||||
|
|
||||||
map $http_upgrade $connection_upgrade {
|
map $http_upgrade $connection_upgrade {
|
||||||
default keep-alive;
|
default keep-alive;
|
||||||
'websocket' upgrade;
|
'websocket' upgrade;
|
||||||
}
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
listen 5700;
|
IPV4_CONFIG
|
||||||
root /ql/static/dist;
|
IPV6_CONFIG
|
||||||
ssl_session_timeout 5m;
|
ssl_session_timeout 5m;
|
||||||
|
|
||||||
location QL_BASE_URL/api/public/ {
|
location QL_BASE_URLapi/update/ {
|
||||||
proxy_set_header Host $http_host;
|
proxy_set_header Host $http_host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_pass http://publicApi/api/public/;
|
proxy_pass http://updateApi/api/;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_redirect default;
|
||||||
|
proxy_connect_timeout 1800;
|
||||||
|
proxy_send_timeout 1800;
|
||||||
|
proxy_read_timeout 1800;
|
||||||
}
|
}
|
||||||
|
|
||||||
location QL_BASE_URL/api/ {
|
location QL_BASE_URLapi/public/ {
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_pass http://publicApi/api/;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_redirect default;
|
||||||
|
proxy_connect_timeout 1800;
|
||||||
|
proxy_send_timeout 1800;
|
||||||
|
proxy_read_timeout 1800;
|
||||||
|
}
|
||||||
|
|
||||||
|
location QL_BASE_URLapi/ {
|
||||||
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://baseApi/api/;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_redirect default;
|
||||||
|
proxy_connect_timeout 1800;
|
||||||
|
proxy_send_timeout 1800;
|
||||||
|
proxy_read_timeout 1800;
|
||||||
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection $connection_upgrade;
|
proxy_set_header Connection $connection_upgrade;
|
||||||
}
|
}
|
||||||
|
|
||||||
location QL_BASE_URL/open/ {
|
location QL_BASE_URLopen/ {
|
||||||
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://baseApi/open/;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_redirect default;
|
||||||
|
proxy_connect_timeout 1800;
|
||||||
|
proxy_send_timeout 1800;
|
||||||
|
proxy_read_timeout 1800;
|
||||||
}
|
}
|
||||||
|
|
||||||
gzip on;
|
gzip on;
|
||||||
@@ -48,10 +79,12 @@ 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 QL_BASE_URL_LOCATION {
|
||||||
|
QL_ALIAS_CONFIG
|
||||||
index index.html index.htm;
|
index index.html index.htm;
|
||||||
try_files $uri $uri/ QL_BASE_URL/index.html;
|
try_files $uri QL_BASE_URLindex.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ~ .*\.(html)$ {
|
location ~ .*\.(html)$ {
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ http {
|
|||||||
|
|
||||||
server_tokens off;
|
server_tokens off;
|
||||||
|
|
||||||
client_max_body_size 20m;
|
client_max_body_size 4096m;
|
||||||
client_body_buffer_size 20m;
|
client_body_buffer_size 20m;
|
||||||
|
|
||||||
keepalive_timeout 65;
|
keepalive_timeout 65;
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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',
|
||||||
|
env: {
|
||||||
|
http_proxy: '',
|
||||||
|
https_proxy: '',
|
||||||
|
HTTP_PROXY: '',
|
||||||
|
HTTPS_PROXY: '',
|
||||||
|
all_proxy: '',
|
||||||
|
ALL_PROXY: '',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"watch": ["back", ".env"],
|
||||||
|
"ext": "js,ts,json",
|
||||||
|
"exec": "ts-node -P tsconfig.back.json ./back/app.ts"
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'update',
|
||||||
|
max_restarts: 10,
|
||||||
|
kill_timeout: 15000,
|
||||||
|
wait_ready: true,
|
||||||
|
listen_timeout: 10000,
|
||||||
|
time: true,
|
||||||
|
script: 'static/build/update.js',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
+48
-21
@@ -2,15 +2,18 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "concurrently -n w: npm:start:*",
|
"start": "concurrently -n w: npm:start:*",
|
||||||
"start:env": "pnpm run --filter @qinglong/env start",
|
"start:front": "max dev",
|
||||||
"start:front": "pnpm run --filter @qinglong/web start",
|
"start:back": "nodemon",
|
||||||
"start:back": "pnpm run --filter @qinglong/back start",
|
"start:update": "ts-node -P tsconfig.back.json ./back/update.ts",
|
||||||
"start:public": "pnpm run --filter @qinglong/public start",
|
"start:public": "ts-node -P tsconfig.back.json ./back/public.ts",
|
||||||
|
"start:rpc": "ts-node -P tsconfig.back.json ./back/schedule/index.ts",
|
||||||
"build:front": "max 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.js",
|
"schedule": "npm run build:back && node static/build/schedule/index.js",
|
||||||
"public": "npm run build:back && node static/build/public.js",
|
"public": "npm run build:back && node static/build/public.js",
|
||||||
|
"update": "npm run build:back && node static/build/update.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": "max setup 2>/dev/null || true",
|
||||||
"test": "umi-test",
|
"test": "umi-test",
|
||||||
@@ -43,7 +46,8 @@
|
|||||||
"monaco-editor",
|
"monaco-editor",
|
||||||
"rc-field-form",
|
"rc-field-form",
|
||||||
"@types/lodash.merge",
|
"@types/lodash.merge",
|
||||||
"rollup"
|
"rollup",
|
||||||
|
"styled-components"
|
||||||
],
|
],
|
||||||
"allowedVersions": {
|
"allowedVersions": {
|
||||||
"react": "18",
|
"react": "18",
|
||||||
@@ -53,52 +57,63 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"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.12.1",
|
||||||
"@sentry/tracing": "^7.12.1",
|
|
||||||
"body-parser": "^1.19.2",
|
"body-parser": "^1.19.2",
|
||||||
"celebrate": "^15.0.1",
|
"celebrate": "^15.0.1",
|
||||||
"chokidar": "^3.5.3",
|
"chokidar": "^3.5.3",
|
||||||
"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",
|
"form-data": "^4.0.0",
|
||||||
"got": "^11.8.2",
|
"got": "^11.8.2",
|
||||||
"hpagent": "^0.1.2",
|
"hpagent": "^1.2.0",
|
||||||
|
"http-proxy-middleware": "^2.0.6",
|
||||||
"iconv-lite": "^0.6.3",
|
"iconv-lite": "^0.6.3",
|
||||||
"js-yaml": "^4.1.0",
|
"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.5-lts.1",
|
||||||
"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",
|
||||||
|
"protobufjs": "^7.3.0",
|
||||||
"pstree.remy": "^1.1.8",
|
"pstree.remy": "^1.1.8",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"sequelize": "^6.25.5",
|
"sequelize": "^6.25.5",
|
||||||
"serve-handler": "^6.1.3",
|
"serve-handler": "^6.1.3",
|
||||||
"sockjs": "^0.3.24",
|
"sockjs": "^0.3.24",
|
||||||
"sqlite3": "npm:@louislam/sqlite3@^15.0.6",
|
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
||||||
"toad-scheduler": "^1.6.0",
|
"toad-scheduler": "^1.6.0",
|
||||||
"typedi": "^0.10.0",
|
"typedi": "^0.10.0",
|
||||||
"uuid": "^8.3.2",
|
"uuid": "^8.3.2",
|
||||||
"winston": "^3.6.0",
|
"winston": "^3.6.0",
|
||||||
"yargs": "^17.3.1"
|
"winston-daily-rotate-file": "^4.7.1",
|
||||||
|
"yargs": "^17.3.1",
|
||||||
|
"tough-cookie": "^4.0.0",
|
||||||
|
"request-ip": "3.3.0",
|
||||||
|
"ip2region": "2.3.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ant-design/icons": "^4.7.0",
|
"@ant-design/icons": "^4.7.0",
|
||||||
"@ant-design/pro-layout": "^6.33.1",
|
"@ant-design/pro-layout": "6.38.22",
|
||||||
"@monaco-editor/react": "4.4.6",
|
"@monaco-editor/react": "4.2.1",
|
||||||
"@react-hook/resize-observer": "^1.2.6",
|
"@react-hook/resize-observer": "^1.2.6",
|
||||||
"@sentry/react": "^7.12.1",
|
"@sentry/react": "^7.12.1",
|
||||||
"@types/body-parser": "^1.19.2",
|
"@types/body-parser": "^1.19.2",
|
||||||
"@types/cors": "^2.8.12",
|
"@types/cors": "^2.8.12",
|
||||||
|
"@types/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.2",
|
||||||
"@types/js-yaml": "^4.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.185",
|
||||||
@@ -109,40 +124,52 @@
|
|||||||
"@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": "^18.0.20",
|
||||||
|
"@types/react-copy-to-clipboard": "^5.0.4",
|
||||||
"@types/react-dom": "^18.0.6",
|
"@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/uuid": "^8.3.4",
|
"@types/uuid": "^8.3.4",
|
||||||
"@umijs/max": "^4.0.21",
|
"@types/request-ip": "0.0.41",
|
||||||
|
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
||||||
|
"@uiw/react-codemirror": "^4.21.9",
|
||||||
|
"@umijs/max": "^4.0.72",
|
||||||
"@umijs/ssr-darkreader": "^4.9.45",
|
"@umijs/ssr-darkreader": "^4.9.45",
|
||||||
|
"ahooks": "^3.7.8",
|
||||||
"ansi-to-react": "^6.1.6",
|
"ansi-to-react": "^6.1.6",
|
||||||
"antd": "^4.23.0",
|
"antd": "^4.24.8",
|
||||||
"antd-img-crop": "^4.2.3",
|
"antd-img-crop": "^4.2.3",
|
||||||
"codemirror": "^5.65.2",
|
"axios": "^1.4.0",
|
||||||
"compression-webpack-plugin": "9.2.0",
|
"compression-webpack-plugin": "9.2.0",
|
||||||
"concurrently": "^7.0.0",
|
"concurrently": "^7.0.0",
|
||||||
|
"react-hotkeys-hook": "^4.4.1",
|
||||||
|
"file-saver": "2.0.2",
|
||||||
"lint-staged": "^13.0.3",
|
"lint-staged": "^13.0.3",
|
||||||
"monaco-editor": "^0.34.1",
|
"monaco-editor": "0.33.0",
|
||||||
"nodemon": "^2.0.15",
|
"nodemon": "^3.0.1",
|
||||||
"prettier": "^2.5.1",
|
"prettier": "^2.5.1",
|
||||||
|
"pretty-bytes": "6.1.1",
|
||||||
"qiniu": "^7.4.0",
|
"qiniu": "^7.4.0",
|
||||||
"qrcode.react": "^1.0.1",
|
"qrcode.react": "^1.0.1",
|
||||||
"query-string": "^7.1.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": "18.2.0",
|
"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": "18.2.0",
|
||||||
|
"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",
|
||||||
"tslib": "^2.4.0",
|
"tslib": "^2.4.0",
|
||||||
"typescript": "4.8.4",
|
"tsx": "^4.7.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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"watch": ["src", ".env"],
|
|
||||||
"ext": "js,ts,json",
|
|
||||||
"ignore": ["src/**/*.spec.ts"],
|
|
||||||
"exec": "ts-node --transpile-only ./src/app.ts"
|
|
||||||
}
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@qinglong/back",
|
|
||||||
"private": true,
|
|
||||||
"scripts": {
|
|
||||||
"start": "nodemon",
|
|
||||||
"build": "tsc"
|
|
||||||
},
|
|
||||||
"gitHooks": {
|
|
||||||
"pre-commit": "lint-staged"
|
|
||||||
},
|
|
||||||
"lint-staged": {
|
|
||||||
"*.{js,jsx,less,md,json}": [
|
|
||||||
"prettier --write"
|
|
||||||
],
|
|
||||||
"*.ts?(x)": [
|
|
||||||
"prettier --parser=typescript --write"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"pnpm": {
|
|
||||||
"peerDependencyRules": {
|
|
||||||
"ignoreMissing": [
|
|
||||||
"react",
|
|
||||||
"react-dom",
|
|
||||||
"antd",
|
|
||||||
"dva",
|
|
||||||
"postcss",
|
|
||||||
"webpack",
|
|
||||||
"eslint",
|
|
||||||
"stylelint",
|
|
||||||
"redux",
|
|
||||||
"@babel/core",
|
|
||||||
"monaco-editor",
|
|
||||||
"rc-field-form",
|
|
||||||
"@types/lodash.merge",
|
|
||||||
"rollup"
|
|
||||||
],
|
|
||||||
"allowedVersions": {
|
|
||||||
"react": "18",
|
|
||||||
"react-dom": "18",
|
|
||||||
"dva-core": "2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@otplib/preset-default": "^12.0.1",
|
|
||||||
"@sentry/node": "^7.12.1",
|
|
||||||
"@sentry/tracing": "^7.12.1",
|
|
||||||
"body-parser": "^1.19.2",
|
|
||||||
"celebrate": "^15.0.1",
|
|
||||||
"chokidar": "^3.5.3",
|
|
||||||
"cors": "^2.8.5",
|
|
||||||
"cron-parser": "^4.2.1",
|
|
||||||
"dayjs": "^1.11.2",
|
|
||||||
"dotenv": "^16.0.0",
|
|
||||||
"express": "^4.17.3",
|
|
||||||
"express-jwt": "^6.1.1",
|
|
||||||
"express-urlrewrite": "^1.4.0",
|
|
||||||
"form-data": "^4.0.0",
|
|
||||||
"got": "^11.8.2",
|
|
||||||
"hpagent": "^0.1.2",
|
|
||||||
"iconv-lite": "^0.6.3",
|
|
||||||
"js-yaml": "^4.1.0",
|
|
||||||
"jsonwebtoken": "^8.5.1",
|
|
||||||
"lodash": "^4.17.21",
|
|
||||||
"multer": "^1.4.4",
|
|
||||||
"nedb": "^1.8.0",
|
|
||||||
"node-schedule": "^2.1.0",
|
|
||||||
"nodemailer": "^6.7.2",
|
|
||||||
"pstree.remy": "^1.1.8",
|
|
||||||
"reflect-metadata": "^0.1.13",
|
|
||||||
"sequelize": "^6.25.5",
|
|
||||||
"serve-handler": "^6.1.3",
|
|
||||||
"sockjs": "^0.3.24",
|
|
||||||
"sqlite3": "npm:@louislam/sqlite3@^15.0.6",
|
|
||||||
"toad-scheduler": "^1.6.0",
|
|
||||||
"typedi": "^0.10.0",
|
|
||||||
"uuid": "^8.3.2",
|
|
||||||
"winston": "^3.6.0",
|
|
||||||
"yargs": "^17.3.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@ant-design/icons": "^4.7.0",
|
|
||||||
"@ant-design/pro-layout": "^6.33.1",
|
|
||||||
"@monaco-editor/react": "4.4.6",
|
|
||||||
"@react-hook/resize-observer": "^1.2.6",
|
|
||||||
"@sentry/react": "^7.12.1",
|
|
||||||
"@types/body-parser": "^1.19.2",
|
|
||||||
"@types/cors": "^2.8.12",
|
|
||||||
"@types/express": "^4.17.13",
|
|
||||||
"@types/express-jwt": "^6.0.4",
|
|
||||||
"@types/js-yaml": "^4.0.5",
|
|
||||||
"@types/jsonwebtoken": "^8.5.8",
|
|
||||||
"@types/lodash": "^4.14.185",
|
|
||||||
"@types/multer": "^1.4.7",
|
|
||||||
"@types/nedb": "^1.8.12",
|
|
||||||
"@types/node": "^17.0.21",
|
|
||||||
"@types/node-schedule": "^1.3.2",
|
|
||||||
"@types/nodemailer": "^6.4.4",
|
|
||||||
"@types/qrcode.react": "^1.0.2",
|
|
||||||
"@types/react": "^18.0.20",
|
|
||||||
"@types/react-dom": "^18.0.6",
|
|
||||||
"@types/serve-handler": "^6.1.1",
|
|
||||||
"@types/sockjs": "^0.3.33",
|
|
||||||
"@types/sockjs-client": "^1.5.1",
|
|
||||||
"@types/uuid": "^8.3.4",
|
|
||||||
"@umijs/max": "^4.0.21",
|
|
||||||
"@umijs/ssr-darkreader": "^4.9.45",
|
|
||||||
"ansi-to-react": "^6.1.6",
|
|
||||||
"antd": "^4.23.0",
|
|
||||||
"antd-img-crop": "^4.2.3",
|
|
||||||
"codemirror": "^5.65.2",
|
|
||||||
"compression-webpack-plugin": "9.2.0",
|
|
||||||
"concurrently": "^7.0.0",
|
|
||||||
"lint-staged": "^13.0.3",
|
|
||||||
"monaco-editor": "^0.34.1",
|
|
||||||
"nodemon": "^2.0.15",
|
|
||||||
"prettier": "^2.5.1",
|
|
||||||
"qiniu": "^7.4.0",
|
|
||||||
"qrcode.react": "^1.0.1",
|
|
||||||
"query-string": "^7.1.1",
|
|
||||||
"rc-tween-one": "^3.0.6",
|
|
||||||
"react": "18.2.0",
|
|
||||||
"react-codemirror2": "^7.2.1",
|
|
||||||
"react-diff-viewer": "^3.1.1",
|
|
||||||
"react-dnd": "^14.0.2",
|
|
||||||
"react-dnd-html5-backend": "^14.0.0",
|
|
||||||
"react-dom": "18.2.0",
|
|
||||||
"react-split-pane": "^0.1.92",
|
|
||||||
"sockjs-client": "^1.6.0",
|
|
||||||
"ts-node": "^10.6.0",
|
|
||||||
"tslib": "^2.4.0",
|
|
||||||
"typescript": "4.8.4",
|
|
||||||
"umi-request": "^1.4.0",
|
|
||||||
"vh-check": "^2.0.5",
|
|
||||||
"webpack": "^5.70.0",
|
|
||||||
"yorkie": "^2.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
import { Router, Request, Response, NextFunction } from 'express';
|
|
||||||
import { Container } from 'typedi';
|
|
||||||
import { Logger } from 'winston';
|
|
||||||
import * as fs from 'fs';
|
|
||||||
import config from '../config';
|
|
||||||
import SystemService from '../services/system';
|
|
||||||
import { celebrate, Joi } from 'celebrate';
|
|
||||||
import UserService from '../services/user';
|
|
||||||
import { EnvModel } from '../data/env';
|
|
||||||
import { parseVersion, promiseExec } from '../config/util';
|
|
||||||
import dayjs from 'dayjs';
|
|
||||||
|
|
||||||
const route = Router();
|
|
||||||
|
|
||||||
export default (app: Router) => {
|
|
||||||
app.use('/system', route);
|
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const userService = Container.get(UserService);
|
|
||||||
const authInfo = await userService.getUserInfo();
|
|
||||||
const envCount = await EnvModel.count();
|
|
||||||
const { version, changeLog, changeLogLink } = await parseVersion(
|
|
||||||
config.versionFile,
|
|
||||||
);
|
|
||||||
const lastCommitTime = (
|
|
||||||
await promiseExec(
|
|
||||||
`cd ${config.rootPath} && git show -s --format=%ai | head -1`,
|
|
||||||
)
|
|
||||||
).replace('\n', '');
|
|
||||||
const lastCommitId = (
|
|
||||||
await promiseExec(`cd ${config.rootPath} && git rev-parse --short HEAD`)
|
|
||||||
).replace('\n', '');
|
|
||||||
const branch = (
|
|
||||||
await promiseExec(
|
|
||||||
`cd ${config.rootPath} && git symbolic-ref --short HEAD`,
|
|
||||||
)
|
|
||||||
).replace('\n', '');
|
|
||||||
|
|
||||||
let isInitialized = true;
|
|
||||||
if (
|
|
||||||
Object.keys(authInfo).length === 2 &&
|
|
||||||
authInfo.username === 'admin' &&
|
|
||||||
authInfo.password === 'admin' &&
|
|
||||||
envCount === 0
|
|
||||||
) {
|
|
||||||
isInitialized = false;
|
|
||||||
}
|
|
||||||
res.send({
|
|
||||||
code: 200,
|
|
||||||
data: {
|
|
||||||
isInitialized,
|
|
||||||
version,
|
|
||||||
lastCommitTime: dayjs(lastCommitTime).unix(),
|
|
||||||
lastCommitId,
|
|
||||||
branch,
|
|
||||||
changeLog,
|
|
||||||
changeLogLink,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
logger.error('🔥 error: %o', e);
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/log/remove',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const data = await systemService.getLogRemoveFrequency();
|
|
||||||
res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/log/remove',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
frequency: Joi.number().required(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const result = await systemService.updateLogRemoveFrequency(
|
|
||||||
req.body.frequency,
|
|
||||||
);
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/update-check',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const result = await systemService.checkUpdate();
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/update',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const logger: Logger = Container.get('logger');
|
|
||||||
try {
|
|
||||||
const systemService = Container.get(SystemService);
|
|
||||||
const result = await systemService.updateSystem();
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.put(
|
|
||||||
'/notify',
|
|
||||||
celebrate({
|
|
||||||
body: Joi.object({
|
|
||||||
title: Joi.string().required(),
|
|
||||||
content: 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.notify(req.body);
|
|
||||||
res.send(result);
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export const LOG_END_SYMBOL = '\n ';
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import { sequelize } from '.';
|
|
||||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
|
||||||
|
|
||||||
export class AuthInfo {
|
|
||||||
ip?: string;
|
|
||||||
type: AuthDataType;
|
|
||||||
info?: any;
|
|
||||||
id?: number;
|
|
||||||
|
|
||||||
constructor(options: AuthInfo) {
|
|
||||||
this.ip = options.ip;
|
|
||||||
this.info = options.info;
|
|
||||||
this.type = options.type;
|
|
||||||
this.id = options.id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum LoginStatus {
|
|
||||||
'success',
|
|
||||||
'fail',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum AuthDataType {
|
|
||||||
'loginLog' = 'loginLog',
|
|
||||||
'authToken' = 'authToken',
|
|
||||||
'notification' = 'notification',
|
|
||||||
'removeLogFrequency' = 'removeLogFrequency',
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AuthInstance extends Model<AuthInfo, AuthInfo>, AuthInfo {}
|
|
||||||
export const AuthModel = sequelize.define<AuthInstance>('Auth', {
|
|
||||||
ip: DataTypes.STRING,
|
|
||||||
type: DataTypes.STRING,
|
|
||||||
info: {
|
|
||||||
type: DataTypes.JSON,
|
|
||||||
allowNull: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import expressLoader from './express';
|
|
||||||
import depInjectorLoader from './depInjector';
|
|
||||||
import Logger from './logger';
|
|
||||||
import initData from './initData';
|
|
||||||
import { Application } from 'express';
|
|
||||||
import linkDeps from './deps';
|
|
||||||
import initTask from './initTask';
|
|
||||||
|
|
||||||
export default async ({ expressApp }: { expressApp: Application }) => {
|
|
||||||
await depInjectorLoader();
|
|
||||||
Logger.info('✌️ Dependency Injector loaded');
|
|
||||||
|
|
||||||
await expressLoader({ app: expressApp });
|
|
||||||
Logger.info('✌️ Express loaded');
|
|
||||||
|
|
||||||
await initData();
|
|
||||||
Logger.info('✌️ init data loaded');
|
|
||||||
|
|
||||||
await linkDeps();
|
|
||||||
Logger.info('✌️ link deps loaded');
|
|
||||||
|
|
||||||
initTask();
|
|
||||||
Logger.info('✌️ init task loaded');
|
|
||||||
};
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import fs from 'fs';
|
|
||||||
import path from 'path';
|
|
||||||
import os from 'os';
|
|
||||||
import dotenv from 'dotenv';
|
|
||||||
import Logger from './logger';
|
|
||||||
import { fileExist } from '../config/util';
|
|
||||||
const rootPath = process.env.QL_DIR as string;
|
|
||||||
const dataPath = path.join(rootPath, 'data/');
|
|
||||||
const configPath = path.join(dataPath, 'config/');
|
|
||||||
const scriptPath = path.join(dataPath, 'scripts/');
|
|
||||||
const logPath = path.join(dataPath, 'log/');
|
|
||||||
const uploadPath = path.join(dataPath, 'upload/');
|
|
||||||
const bakPath = path.join(dataPath, 'bak/');
|
|
||||||
const samplePath = path.join(rootPath, 'sample/');
|
|
||||||
const confFile = path.join(configPath, 'config.sh');
|
|
||||||
const authConfigFile = path.join(configPath, 'auth.json');
|
|
||||||
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
|
||||||
const sampleAuthFile = path.join(samplePath, 'auth.sample.json');
|
|
||||||
const homedir = os.homedir();
|
|
||||||
const sshPath = path.resolve(homedir, '.ssh');
|
|
||||||
|
|
||||||
export default async () => {
|
|
||||||
const authFileExist = await fileExist(authConfigFile);
|
|
||||||
const confFileExist = await fileExist(confFile);
|
|
||||||
const scriptDirExist = await fileExist(scriptPath);
|
|
||||||
const logDirExist = await fileExist(logPath);
|
|
||||||
const configDirExist = await fileExist(configPath);
|
|
||||||
const uploadDirExist = await fileExist(uploadPath);
|
|
||||||
const sshDirExist = await fileExist(sshPath);
|
|
||||||
const bakDirExist = await fileExist(bakPath);
|
|
||||||
|
|
||||||
if (!configDirExist) {
|
|
||||||
fs.mkdirSync(configPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!authFileExist) {
|
|
||||||
fs.writeFileSync(authConfigFile, fs.readFileSync(sampleAuthFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!confFileExist) {
|
|
||||||
fs.writeFileSync(confFile, fs.readFileSync(sampleConfigFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!scriptDirExist) {
|
|
||||||
fs.mkdirSync(scriptPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!logDirExist) {
|
|
||||||
fs.mkdirSync(logPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!uploadDirExist) {
|
|
||||||
fs.mkdirSync(uploadPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!sshDirExist) {
|
|
||||||
fs.mkdirSync(sshPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!bakDirExist) {
|
|
||||||
fs.mkdirSync(bakPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
dotenv.config({ path: confFile });
|
|
||||||
|
|
||||||
Logger.info('✌️ Init file down');
|
|
||||||
};
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import winston from 'winston';
|
|
||||||
import config from '../config';
|
|
||||||
|
|
||||||
const transports = [];
|
|
||||||
if (process.env.NODE_ENV !== 'development') {
|
|
||||||
transports.push(new winston.transports.Console());
|
|
||||||
} else {
|
|
||||||
transports.push(
|
|
||||||
new winston.transports.Console({
|
|
||||||
format: winston.format.combine(
|
|
||||||
winston.format.cli(),
|
|
||||||
winston.format.splat(),
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const LoggerInstance = winston.createLogger({
|
|
||||||
level: config.logs.level,
|
|
||||||
levels: winston.config.npm.levels,
|
|
||||||
format: winston.format.combine(
|
|
||||||
winston.format.timestamp({
|
|
||||||
format: 'YYYY-MM-DD HH:mm:ss',
|
|
||||||
}),
|
|
||||||
winston.format.errors({ stack: true }),
|
|
||||||
winston.format.splat(),
|
|
||||||
winston.format.json(),
|
|
||||||
),
|
|
||||||
transports,
|
|
||||||
});
|
|
||||||
|
|
||||||
export default LoggerInstance;
|
|
||||||
@@ -1,245 +0,0 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
|
||||||
import winston from 'winston';
|
|
||||||
import config from '../config';
|
|
||||||
import {
|
|
||||||
Dependence,
|
|
||||||
InstallDependenceCommandTypes,
|
|
||||||
DependenceStatus,
|
|
||||||
DependenceTypes,
|
|
||||||
unInstallDependenceCommandTypes,
|
|
||||||
DependenceModel,
|
|
||||||
} from '../data/dependence';
|
|
||||||
import { spawn } from 'child_process';
|
|
||||||
import SockService from './sock';
|
|
||||||
import { Op } from 'sequelize';
|
|
||||||
import { concurrentRun } from '../config/util';
|
|
||||||
import dayjs from 'dayjs';
|
|
||||||
|
|
||||||
@Service()
|
|
||||||
export default class DependenceService {
|
|
||||||
constructor(
|
|
||||||
@Inject('logger') private logger: winston.Logger,
|
|
||||||
private sockService: SockService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public async create(payloads: Dependence[]): Promise<Dependence[]> {
|
|
||||||
const tabs = payloads.map((x) => {
|
|
||||||
const tab = new Dependence({ ...x, status: DependenceStatus.installing });
|
|
||||||
return tab;
|
|
||||||
});
|
|
||||||
const docs = await this.insert(tabs);
|
|
||||||
this.installDependenceOneByOne(docs);
|
|
||||||
return docs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async insert(payloads: Dependence[]): Promise<Dependence[]> {
|
|
||||||
const docs = await DependenceModel.bulkCreate(payloads);
|
|
||||||
return docs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async update(
|
|
||||||
payload: Dependence & { id: string },
|
|
||||||
): Promise<Dependence> {
|
|
||||||
const { id, ...other } = payload;
|
|
||||||
const doc = await this.getDb({ id });
|
|
||||||
const tab = new Dependence({
|
|
||||||
...doc,
|
|
||||||
...other,
|
|
||||||
status: DependenceStatus.installing,
|
|
||||||
});
|
|
||||||
const newDoc = await this.updateDb(tab);
|
|
||||||
this.installDependenceOneByOne([newDoc]);
|
|
||||||
return newDoc;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async updateDb(payload: Dependence): Promise<Dependence> {
|
|
||||||
await DependenceModel.update(payload, { where: { id: payload.id } });
|
|
||||||
return await this.getDb({ id: payload.id });
|
|
||||||
}
|
|
||||||
|
|
||||||
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
|
||||||
await DependenceModel.update(
|
|
||||||
{ status: DependenceStatus.removing, log: [] },
|
|
||||||
{ where: { id: ids } },
|
|
||||||
);
|
|
||||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
|
||||||
this.installDependenceOneByOne(docs, false, force);
|
|
||||||
return docs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async removeDb(ids: number[]) {
|
|
||||||
await DependenceModel.destroy({ where: { id: ids } });
|
|
||||||
}
|
|
||||||
|
|
||||||
public async dependencies(
|
|
||||||
{ searchValue, type }: { searchValue: string; type: string },
|
|
||||||
sort: any = { position: -1 },
|
|
||||||
query: any = {},
|
|
||||||
): Promise<Dependence[]> {
|
|
||||||
let condition = { ...query, type: DependenceTypes[type as any] };
|
|
||||||
if (searchValue) {
|
|
||||||
const encodeText = encodeURIComponent(searchValue);
|
|
||||||
const reg = {
|
|
||||||
[Op.or]: [
|
|
||||||
{ [Op.like]: `%${searchValue}%` },
|
|
||||||
{ [Op.like]: `%${encodeText}%` },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
condition = {
|
|
||||||
...condition,
|
|
||||||
name: reg,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const result = await this.find(condition);
|
|
||||||
return result as any;
|
|
||||||
} catch (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private installDependenceOneByOne(
|
|
||||||
docs: Dependence[],
|
|
||||||
isInstall: boolean = true,
|
|
||||||
force: boolean = false,
|
|
||||||
) {
|
|
||||||
concurrentRun(
|
|
||||||
docs.map(
|
|
||||||
(dep) => async () =>
|
|
||||||
await this.installOrUninstallDependencies([dep], isInstall, force),
|
|
||||||
),
|
|
||||||
1,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async reInstall(ids: number[]): Promise<Dependence[]> {
|
|
||||||
await DependenceModel.update(
|
|
||||||
{ status: DependenceStatus.installing, log: [] },
|
|
||||||
{ where: { id: ids } },
|
|
||||||
);
|
|
||||||
|
|
||||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
|
||||||
this.installDependenceOneByOne(docs);
|
|
||||||
return docs;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async find(query: any, sort: any = []): Promise<Dependence[]> {
|
|
||||||
const docs = await DependenceModel.findAll({
|
|
||||||
where: { ...query },
|
|
||||||
order: [...sort, ['createdAt', 'DESC']],
|
|
||||||
});
|
|
||||||
return docs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getDb(query: any): Promise<Dependence> {
|
|
||||||
const doc: any = await DependenceModel.findOne({ where: { ...query } });
|
|
||||||
return doc && (doc.get({ plain: true }) as Dependence);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async updateLog(ids: number[], log: string): Promise<void> {
|
|
||||||
const doc = await DependenceModel.findOne({ where: { id: ids } });
|
|
||||||
const newLog = doc?.log ? [...doc.log, log] : [log];
|
|
||||||
await DependenceModel.update({ log: newLog }, { where: { id: ids } });
|
|
||||||
}
|
|
||||||
|
|
||||||
public installOrUninstallDependencies(
|
|
||||||
dependencies: Dependence[],
|
|
||||||
isInstall: boolean = true,
|
|
||||||
force: boolean = false,
|
|
||||||
) {
|
|
||||||
return new Promise(async (resolve) => {
|
|
||||||
if (dependencies.length === 0) {
|
|
||||||
resolve(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const socketMessageType = !force
|
|
||||||
? 'installDependence'
|
|
||||||
: 'uninstallDependence';
|
|
||||||
const depNames = dependencies.map((x) => x.name).join(' ');
|
|
||||||
const depRunCommand = (
|
|
||||||
isInstall
|
|
||||||
? InstallDependenceCommandTypes
|
|
||||||
: unInstallDependenceCommandTypes
|
|
||||||
)[dependencies[0].type as any];
|
|
||||||
const actionText = isInstall ? '安装' : '删除';
|
|
||||||
const depIds = dependencies.map((x) => x.id) as number[];
|
|
||||||
const startTime = dayjs();
|
|
||||||
|
|
||||||
const message = `开始${actionText}依赖 ${depNames},开始时间 ${startTime.format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
)}\n\n`;
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: socketMessageType,
|
|
||||||
message,
|
|
||||||
references: depIds,
|
|
||||||
});
|
|
||||||
await this.updateLog(depIds, message);
|
|
||||||
|
|
||||||
const cp = spawn(`${depRunCommand} ${depNames}`, { shell: '/bin/bash' });
|
|
||||||
|
|
||||||
cp.stdout.on('data', async (data) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: socketMessageType,
|
|
||||||
message: data.toString(),
|
|
||||||
references: depIds,
|
|
||||||
});
|
|
||||||
await this.updateLog(depIds, data.toString());
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.stderr.on('data', async (data) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: socketMessageType,
|
|
||||||
message: data.toString(),
|
|
||||||
references: depIds,
|
|
||||||
});
|
|
||||||
await this.updateLog(depIds, data.toString());
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.on('error', async (err) => {
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: socketMessageType,
|
|
||||||
message: JSON.stringify(err),
|
|
||||||
references: depIds,
|
|
||||||
});
|
|
||||||
await this.updateLog(depIds, JSON.stringify(err));
|
|
||||||
resolve(null);
|
|
||||||
});
|
|
||||||
|
|
||||||
cp.on('close', async (code) => {
|
|
||||||
const endTime = dayjs();
|
|
||||||
const isSucceed = code === 0;
|
|
||||||
const resultText = isSucceed ? '成功' : '失败';
|
|
||||||
|
|
||||||
const message = `\n依赖${actionText}${resultText},结束时间 ${endTime.format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
)},耗时 ${endTime.diff(startTime, 'second')} 秒`;
|
|
||||||
this.sockService.sendMessage({
|
|
||||||
type: socketMessageType,
|
|
||||||
message,
|
|
||||||
references: depIds,
|
|
||||||
});
|
|
||||||
await this.updateLog(depIds, message);
|
|
||||||
|
|
||||||
let status = null;
|
|
||||||
if (isSucceed) {
|
|
||||||
status = isInstall
|
|
||||||
? DependenceStatus.installed
|
|
||||||
: DependenceStatus.removed;
|
|
||||||
} else {
|
|
||||||
status = isInstall
|
|
||||||
? DependenceStatus.installFailed
|
|
||||||
: DependenceStatus.removeFailed;
|
|
||||||
}
|
|
||||||
await DependenceModel.update({ status }, { where: { id: depIds } });
|
|
||||||
|
|
||||||
// 如果删除依赖成功或者强制删除
|
|
||||||
if ((isSucceed || force) && !isInstall) {
|
|
||||||
this.removeDb(depIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
resolve(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user