mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
201f578bbc | ||
|
|
ce9aa369d2 | ||
|
|
c5c41c0859 | ||
|
|
d3009f82dd | ||
|
|
0eb9a1fdb0 | ||
|
|
83f6d9926a | ||
|
|
14134842b0 | ||
|
|
4c094c4710 | ||
|
|
3ac41075fd | ||
|
|
fdc97773d1 | ||
|
|
917a739595 | ||
|
|
21475f81ae | ||
|
|
a2a9a0560c | ||
|
|
b879846cdb | ||
|
|
a24011cd72 | ||
|
|
410dd2ecdc | ||
|
|
96b111b894 | ||
|
|
630572c8f9 | ||
|
|
6a381a6366 | ||
|
|
fd04f12677 | ||
|
|
86b8cd17a4 | ||
|
|
bb8ee01693 | ||
|
|
5fb0bca3af | ||
|
|
1e4d1f373d | ||
|
|
87c78d0fcc | ||
|
|
041d2b7947 | ||
|
|
5e7b90d995 | ||
|
|
fadc3dcb55 | ||
|
|
4eea091944 | ||
|
|
9f8d46f395 | ||
|
|
2c54a057c9 | ||
|
|
e1e5cacc6d | ||
|
|
edf9066967 | ||
|
|
7097d12b87 | ||
|
|
08aaeb6372 | ||
|
|
4310f80ec0 | ||
|
|
01577f6494 | ||
|
|
9aa570b2c6 | ||
|
|
d611d7d698 | ||
|
|
f05549b06c | ||
|
|
8c4db8dd40 | ||
|
|
ddee69d291 | ||
|
|
28960c9fab | ||
|
|
449301e519 | ||
|
|
28dab3dc2f | ||
|
|
7995d98db5 | ||
|
|
1f319f3533 | ||
|
|
7d2dbaa62d | ||
|
|
ed5999526b | ||
|
|
2409f75491 | ||
|
|
0c840095d1 | ||
|
|
3eaf0b4856 | ||
|
|
394735a5d9 | ||
|
|
5bfa10bfe7 | ||
|
|
3f12d9cbd5 | ||
|
|
54d89754df | ||
|
|
9470524615 | ||
|
|
b5faa6eaaa | ||
|
|
eab476cfe8 | ||
|
|
b773def012 | ||
|
|
a9f8b23a7a | ||
|
|
61bb6535fb | ||
|
|
eb0bdffe06 | ||
|
|
e129485285 | ||
|
|
aac7de172e | ||
|
|
e19d2412fc | ||
|
|
7cba2cf76c | ||
|
|
55d7a49dbc | ||
|
|
f695864fd8 | ||
|
|
ae4883fbe7 | ||
|
|
836dfd2861 | ||
|
|
6e0523c6d7 | ||
|
|
cd9ba084ae | ||
|
|
c8a0c0de67 | ||
|
|
5dd8d9df91 | ||
|
|
2dbee94e85 | ||
|
|
9001797037 | ||
|
|
5e7104d5a3 | ||
|
|
7c33b22d63 | ||
|
|
b7cb1e379c | ||
|
|
274a6ce52e | ||
|
|
8079e4e7b8 | ||
|
|
920efb8fab | ||
|
|
92aeb2b9da | ||
|
|
ced76cf343 | ||
|
|
3750d6ecd5 | ||
|
|
7444f30384 | ||
|
|
b0fd5ba47f | ||
|
|
cc098bc2e5 | ||
|
|
1cfcf8d194 | ||
|
|
d1e9f741d0 | ||
|
|
0cde9d07ee | ||
|
|
a266425348 | ||
|
|
6dbe02e321 | ||
|
|
39979879c9 | ||
|
|
ba3f604a5c | ||
|
|
9572582401 | ||
|
|
2bcef0ba75 | ||
|
|
31cd7c4007 | ||
|
|
1c4c1799b0 | ||
|
|
2d558df15e | ||
|
|
7b769da4e2 | ||
|
|
4e95d62933 | ||
|
|
83255280b9 | ||
|
|
2546cebdea | ||
|
|
f14a3fe0f1 | ||
|
|
c3eb845be4 | ||
|
|
1eef77dca5 | ||
|
|
d7d9f47fe5 | ||
|
|
fce6a996d9 | ||
|
|
48a484d7de | ||
|
|
4b81d3c612 | ||
|
|
21b6edd7eb | ||
|
|
9a43e022e9 | ||
|
|
62bef3f13d | ||
|
|
c87f5fa004 | ||
|
|
8d99f3ffbb | ||
|
|
100ca7b54b | ||
|
|
4a2624f12a | ||
|
|
21b01a85a8 | ||
|
|
e039ae436e | ||
|
|
b13a1a45f8 | ||
|
|
667fe2bbba | ||
|
|
f083871ca0 | ||
|
|
782e1ba235 | ||
|
|
b92c6edc4e | ||
|
|
bdf4657c73 | ||
|
|
8559438611 | ||
|
|
04045fd410 | ||
|
|
1c71a9d8a8 | ||
|
|
9a9ae9782c | ||
|
|
da2569850b | ||
|
|
b475035415 | ||
|
|
7baee27585 | ||
|
|
2cb2f1ce0a | ||
|
|
8c1407e2a9 | ||
|
|
7bcb113085 | ||
|
|
42dc27addf | ||
|
|
aac30398c4 | ||
|
|
ceae888372 | ||
|
|
61df7050db | ||
|
|
af5561cbbf | ||
|
|
bce30f922d | ||
|
|
d6ed394557 | ||
|
|
7b512a1681 | ||
|
|
7af0597cd5 | ||
|
|
2f5cf6d93c | ||
|
|
d672d2d104 | ||
|
|
c0d1fb1ef4 | ||
|
|
3c882ad0ce | ||
|
|
58acd2eb68 | ||
|
|
590473e7d2 | ||
|
|
21139157c8 | ||
|
|
8f8296ab64 | ||
|
|
40bf07d2a4 | ||
|
|
fd2b4fb86d | ||
|
|
783e867ef6 | ||
|
|
3873d9f978 | ||
|
|
7dece938c8 | ||
|
|
0842d66c79 | ||
|
|
d071e50d62 | ||
|
|
337f01aff1 | ||
|
|
5614e41eb0 | ||
|
|
4f0fdbe453 | ||
|
|
49c068db78 | ||
|
|
fbba44d482 | ||
|
|
10c07b0a09 | ||
|
|
20893698ba | ||
|
|
31de659ed3 | ||
|
|
6c08a16c66 | ||
|
|
21e7178f48 | ||
|
|
aefd267eb2 | ||
|
|
fb1a3980d4 | ||
|
|
cfc467f8a5 | ||
|
|
48120f012d | ||
|
|
c907a78437 | ||
|
|
915c0d09a9 | ||
|
|
80638862cc | ||
|
|
a7350948cd | ||
|
|
1e1be013b5 | ||
|
|
4062584eae | ||
|
|
abedddffa6 | ||
|
|
38858ccdb2 | ||
|
|
d56e6359d0 | ||
|
|
5886991464 | ||
|
|
838326616b | ||
|
|
fcf80fe946 | ||
|
|
2e63a7056c | ||
|
|
7c807e3ec8 | ||
|
|
b558aa0934 | ||
|
|
38757758cb | ||
|
|
84dd3d8fd1 | ||
|
|
19423c2d30 | ||
|
|
98bba7d7fa | ||
|
|
dcaa9ce000 | ||
|
|
3cae44a136 | ||
|
|
df8a3d2692 | ||
|
|
56e43f1808 | ||
|
|
2f6b95cccf | ||
|
|
ad9f6b2b64 | ||
|
|
165c3dc976 | ||
|
|
cbe6390b41 | ||
|
|
026eaf6606 | ||
|
|
ee184f8e62 | ||
|
|
5745231dc9 | ||
|
|
cbdc3a9861 | ||
|
|
ba5c42ad6d | ||
|
|
b056a731a1 | ||
|
|
b4cd94f2d9 | ||
|
|
3b8cb43f02 | ||
|
|
82cb11c3c4 | ||
|
|
eb7522a90b | ||
|
|
3898201b1e | ||
|
|
bb6ab0c17b | ||
|
|
652c40ab1f | ||
|
|
ca0d6215a9 | ||
|
|
61d155257c | ||
|
|
91399f1a1f | ||
|
|
2e738c5977 | ||
|
|
c0bd51cf03 | ||
|
|
ca5afe04f8 | ||
|
|
47db0b9f4e | ||
|
|
27f17a377a | ||
|
|
ecaf731ecf | ||
|
|
9fba2a85f6 | ||
|
|
93f75be182 | ||
|
|
d537901f59 | ||
|
|
260c1ed4a4 | ||
|
|
ac2bd52463 | ||
|
|
16c6f8fee1 | ||
|
|
8a0db21f17 | ||
|
|
9ab08a71c0 | ||
|
|
381c32a3b4 | ||
|
|
350c0f10c4 | ||
|
|
d5b982f813 | ||
|
|
6587375ff2 | ||
|
|
f5ecb81bad | ||
|
|
0141cd81c4 | ||
|
|
ff412c7497 | ||
|
|
623f239f91 | ||
|
|
c7ba304c6a | ||
|
|
c8393604d1 | ||
|
|
c5d47a67aa | ||
|
|
3a1423cd59 | ||
|
|
d57f4cf6cd | ||
|
|
af420942c4 | ||
|
|
eac4e5e66f | ||
|
|
b8822a98f7 | ||
|
|
95322b42c0 | ||
|
|
33f5a06d32 | ||
|
|
a7e5126c92 | ||
|
|
c62f3e5b8e | ||
|
|
5d3f413a05 | ||
|
|
644154ca38 | ||
|
|
cccce5ff74 | ||
|
|
aa1fe98188 | ||
|
|
b6a78550d6 | ||
|
|
70b7f2c493 | ||
|
|
ea44e5f209 | ||
|
|
41ef87d9f8 | ||
|
|
c0b4a70aa0 | ||
|
|
955875cb7a | ||
|
|
827e8571aa | ||
|
|
aed08b0f59 | ||
|
|
3ddaf41e27 | ||
|
|
38a9cce6bf | ||
|
|
ae255ef381 | ||
|
|
4316bef01e | ||
|
|
8491c5706d | ||
|
|
7b7fab1f32 | ||
|
|
5a6fccdc2f | ||
|
|
23668be46d | ||
|
|
f92f2c1666 | ||
|
|
895740a3cb | ||
|
|
4c76c3231f | ||
|
|
ca9d3f9559 | ||
|
|
3ca3c5e75c | ||
|
|
c2c0b1dfdc | ||
|
|
c633774487 | ||
|
|
c2d86fc517 | ||
|
|
d7c8d150ca | ||
|
|
6b8a4e65f2 | ||
|
|
482e43dd1f | ||
|
|
1437babc6c | ||
|
|
5ed882943a | ||
|
|
e678b3fb3a | ||
|
|
a5770bc4e4 | ||
|
|
59821bb939 | ||
|
|
b58040be44 | ||
|
|
be3b8ad52e | ||
|
|
0fdaf97461 | ||
|
|
f5f036372f | ||
|
|
3fceb983e6 | ||
|
|
ae6a39196d | ||
|
|
2810ff2753 | ||
|
|
205c0cf8d3 | ||
|
|
d9c801a091 | ||
|
|
0833aa3b30 | ||
|
|
9c90bbc146 | ||
|
|
231b387076 | ||
|
|
3de432652f | ||
|
|
cad714493e | ||
|
|
6a690a6108 | ||
|
|
1b85c52557 | ||
|
|
b37be92ea9 | ||
|
|
f95979f445 | ||
|
|
09e07218ae | ||
|
|
085f5a9451 | ||
|
|
eb4e935554 | ||
|
|
57986cf425 | ||
|
|
7bf14b9acc | ||
|
|
3ba0be34d9 | ||
|
|
0f828a3c75 | ||
|
|
16a768a142 | ||
|
|
f380d20279 | ||
|
|
be908ab36c | ||
|
|
b545454537 | ||
|
|
a5ff8dd1d6 | ||
|
|
59f23e518b | ||
|
|
858b3f0176 | ||
|
|
89b8494ad0 | ||
|
|
64ecd75bd5 | ||
|
|
138eb3393d | ||
|
|
1ad51d2925 | ||
|
|
317e175bca | ||
|
|
0e287aa7d1 | ||
|
|
28018b705b | ||
|
|
46ec72d6be | ||
|
|
82494a87af | ||
|
|
95c19b447a | ||
|
|
9c6eae936a | ||
|
|
77605a9360 | ||
|
|
82880c3f06 | ||
|
|
11143c771b | ||
|
|
0968eaa5a8 | ||
|
|
0687f9d472 | ||
|
|
25f0f5951a | ||
|
|
eec0ce65ad | ||
|
|
be4e100168 | ||
|
|
59e4f1063c | ||
|
|
359e21f02b | ||
|
|
6894bd9c0e | ||
|
|
7040f02823 | ||
|
|
41408de337 | ||
|
|
72e243dce8 | ||
|
|
77d4840e2a | ||
|
|
0d5961821c | ||
|
|
f34980b173 | ||
|
|
5b21a6e529 | ||
|
|
6dbb737d4b | ||
|
|
76ecfbaaa2 | ||
|
|
d9aacbcb92 | ||
|
|
e088325d95 | ||
|
|
b29dd2c580 | ||
|
|
89e82fd5b0 | ||
|
|
9f0b671d42 | ||
|
|
7de7c724dc | ||
|
|
3525b1d92a | ||
|
|
30cea84886 | ||
|
|
0c2cc7f575 |
+4
-7
@@ -1,12 +1,9 @@
|
||||
PUBLIC_PORT=5400
|
||||
MONGODB_URI='mongodb://'
|
||||
YIYAN_MONGODB_URI=''
|
||||
|
||||
CRON_PORT=5500
|
||||
BACK_PORT=5600
|
||||
PORT=5700
|
||||
PORT=5600
|
||||
|
||||
LOG_LEVEL='debug'
|
||||
|
||||
SECRET='whyour'
|
||||
|
||||
QINIU_AK=''
|
||||
QINIU_SK=''
|
||||
QINIU_SCOPE=''
|
||||
@@ -1,42 +0,0 @@
|
||||
name: "\U0001F41E Bug report"
|
||||
description: Create a report to help us improve
|
||||
body:
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Qinglong version
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps-to-reproduce
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: |
|
||||
What do we need to do after opening your repro in order to make the bug happen? Clear and concise reproduction instructions are important for us to be able to triage your issue in a timely manner. Note that you can use [Markdown](https://guides.github.com/features/mastering-markdown/) to format lists and code.
|
||||
placeholder: Steps to reproduce
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: What is expected?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: actually-happening
|
||||
attributes:
|
||||
label: What is actually happening?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: system-info
|
||||
attributes:
|
||||
label: System Info
|
||||
description: Output of `npx envinfo --system --binaries --browsers`
|
||||
render: shell
|
||||
placeholder: System, Binaries, Browsers
|
||||
- type: textarea
|
||||
id: additional-comments
|
||||
attributes:
|
||||
label: Any additional comments?
|
||||
description: e.g. some background/context of how you ran into this bug.
|
||||
@@ -1,8 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Telegram Chat
|
||||
url: https://t.me/jiao_long
|
||||
about: Ask questions and discuss with other Qinglong users in real time.
|
||||
- name: Questions & Discussions
|
||||
url: https://github.com/whyour/qinglong/discussions/new?category=q-a
|
||||
about: Use GitHub discussions for message-board style questions and discussions.
|
||||
@@ -1,40 +0,0 @@
|
||||
name: "\U0001F680 New feature proposal"
|
||||
description: Suggest an idea for this project
|
||||
labels: [":sparkles: feature request"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for your interest in the project and taking the time to fill out this feature report!
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
attributes:
|
||||
label: Clear and concise description of the problem
|
||||
description: "Explain your use case, context, and rationale behind this feature request. More importantly, what is the **end user experience** you are trying to build that led to the need for this feature?"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: suggested-solution
|
||||
attributes:
|
||||
label: Suggested solution
|
||||
description: "In module [xy] we could provide following implementation..."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternative
|
||||
attributes:
|
||||
label: Alternative
|
||||
description: Clear and concise description of any alternative solutions or features you've considered.
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Any other context or screenshots about the feature request here.
|
||||
- type: checkboxes
|
||||
id: checkboxes
|
||||
attributes:
|
||||
label: Validations
|
||||
description: Before submitting the issue, please make sure you do the following
|
||||
options:
|
||||
- label: Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
|
||||
required: true
|
||||
@@ -1,31 +0,0 @@
|
||||
## PR Type
|
||||
What kind of change does this PR introduce?
|
||||
|
||||
<!-- Please check the one that applies to this PR using "x". -->
|
||||
|
||||
- [ ] Bugfix
|
||||
- [ ] Feature
|
||||
- [ ] Code style update (formatting, local variables)
|
||||
- [ ] Refactoring (no functional changes, no api changes)
|
||||
- [ ] Other... Please describe:
|
||||
|
||||
|
||||
## What is the current behavior?
|
||||
<!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->
|
||||
|
||||
Issue Number: N/A
|
||||
|
||||
|
||||
## What is the new behavior?
|
||||
|
||||
|
||||
## Does this PR introduce a breaking change?
|
||||
|
||||
- [ ] Yes
|
||||
- [ ] No
|
||||
|
||||
|
||||
<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->
|
||||
|
||||
|
||||
## Other information
|
||||
@@ -1,7 +0,0 @@
|
||||
# Comment to be posted to on PRs from first time contributors in your repository
|
||||
newPRWelcomeComment: |
|
||||
💖 Thanks for opening this pull request! 💖
|
||||
Please be patient and we will get back to you as soon as we can.
|
||||
# Comment to be posted to on pull requests merged by a first time user
|
||||
firstPRMergeComment: >
|
||||
Congrats on merging your first pull request! 🎉🎉🎉
|
||||
@@ -20,24 +20,25 @@ jobs:
|
||||
build-static:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '14'
|
||||
|
||||
- name: build front and back
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm install
|
||||
pnpm build:front
|
||||
pnpm build:back
|
||||
yarn install
|
||||
yarn build
|
||||
yarn build-back
|
||||
|
||||
- name: copy to static repo
|
||||
env:
|
||||
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
||||
GITHUB_BRANCH: ${{ github.ref_name }}
|
||||
run: |
|
||||
mkdir -p tmp
|
||||
cd ./tmp
|
||||
cp -rf ../static/* ./
|
||||
mkdir -p static
|
||||
cd ./static
|
||||
cp -rf ../dist ./ && cp -rf ../build ./
|
||||
git init -b ${GITHUB_BRANCH} && git add .
|
||||
git config --local user.name 'github-actions[bot]'
|
||||
git config --local user.email 'github-actions[bot]@users.noreply.github.com'
|
||||
@@ -54,8 +55,10 @@ jobs:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '14'
|
||||
|
||||
- name: Set time zone
|
||||
uses: szenius/set-timezone@v1.0
|
||||
@@ -65,13 +68,13 @@ jobs:
|
||||
timezoneWindows: "China Standard Time"
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -79,7 +82,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
uses: docker/metadata-action@v3
|
||||
with:
|
||||
images: |
|
||||
${{ github.repository }}
|
||||
@@ -96,20 +99,19 @@ jobs:
|
||||
type=semver,pattern={{major}}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
uses: docker/setup-qemu-action@v1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v1
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
build-args: |
|
||||
MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
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/s390x
|
||||
context: docker/
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
name: PublishDockerImage
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
|
||||
- name: Docker login
|
||||
env:
|
||||
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||
run: |
|
||||
echo "${DOCKER_PASSWORD}" | docker login --username "${DOCKER_USERNAME}" --password-stdin
|
||||
|
||||
- name: Docker buildx image and push on master branch
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
run: |
|
||||
docker buildx build --build-arg SSH_PRIVATE_KEY="${SSH_PRIVATE_KEY}" --output "type=image,push=true" --platform=linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/s390x --tag whyour/qinglong:latest docker/
|
||||
+2
-3
@@ -4,13 +4,12 @@
|
||||
/node_modules
|
||||
/npm-debug.log*
|
||||
/yarn-error.log
|
||||
/yarn.lock
|
||||
/pnpm-lock.yaml
|
||||
/package-lock.json
|
||||
|
||||
# production
|
||||
/static
|
||||
/data
|
||||
/dist
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
sentrycli_cdnurl=https://npmmirror.com/mirrors/sentry-cli/
|
||||
strict-peer-dependencies=false
|
||||
sentrycli_cdnurl=https://cdn.npm.taobao.org/dist/sentry-cli
|
||||
@@ -4,22 +4,15 @@ const CompressionPlugin = require('compression-webpack-plugin');
|
||||
export default defineConfig({
|
||||
hash: true,
|
||||
layout: false,
|
||||
outputPath: 'static/dist',
|
||||
nodeModulesTransform: {
|
||||
type: 'none',
|
||||
},
|
||||
fastRefresh: {},
|
||||
esbuild: {},
|
||||
webpack5: {},
|
||||
dynamicImport: {
|
||||
loading: '@/components/pageLoading',
|
||||
},
|
||||
favicon: '/images/favicon.svg',
|
||||
favicon: '/images/g5.ico',
|
||||
proxy: {
|
||||
'/api/public': {
|
||||
target: 'http://127.0.0.1:5400/',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:5600/',
|
||||
changeOrigin: true,
|
||||
@@ -39,9 +32,18 @@ export default defineConfig({
|
||||
externals: {
|
||||
react: 'window.React',
|
||||
'react-dom': 'window.ReactDOM',
|
||||
darkreader: 'window.DarkReader',
|
||||
codemirror: 'window.CodeMirror',
|
||||
'sockjs-client': 'window.SockJS',
|
||||
},
|
||||
scripts: [
|
||||
'https://gw.alipayobjects.com/os/lib/react/16.13.1/umd/react.production.min.js',
|
||||
'https://gw.alipayobjects.com/os/lib/react-dom/16.13.1/umd/react-dom.production.min.js',
|
||||
'https://unpkg.zhimg.com/darkreader@4.9.40/darkreader.js',
|
||||
'https://unpkg.zhimg.com/codemirror@5/lib/codemirror.js',
|
||||
'https://unpkg.zhimg.com/codemirror@5/mode/shell/shell.js',
|
||||
'https://unpkg.zhimg.com/codemirror@5/mode/python/python.js',
|
||||
'https://unpkg.zhimg.com/codemirror@5/mode/javascript/javascript.js',
|
||||
'https://unpkg.zhimg.com/sockjs-client@1/dist/sockjs.min.js',
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,201 +1,22 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
MIT LICENSE
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
Copyright (c) 2021-present whyour
|
||||
|
||||
1. Definitions.
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021 WHYOUR <https://github.com/whyour>.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-214
@@ -1,214 +0,0 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/whyour/qinglong">
|
||||
<img width="150" src="https://z3.ax1x.com/2021/11/18/I7MpAe.png">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h1 align="center">Green Dragon</h1>
|
||||
|
||||
<div align="center">
|
||||
|
||||
Timed task management panel with python3, javaScript, shell, typescript support
|
||||
|
||||
[![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]
|
||||
|
||||
[docker-pulls-image]: https://img.shields.io/docker/pulls/whyour/qinglong?style=flat
|
||||
[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-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-url]: https://hub.docker.com/r/whyour/qinglong
|
||||
</div>
|
||||
|
||||
[](https://whyour.cn)
|
||||
|
||||
[简体中文](./README.md) | English
|
||||
|
||||
## Features
|
||||
|
||||
- Support for multiple scripting languages (python3, javaScript, shell, typescript)
|
||||
- Support online management of scripts, environment variables, configuration files
|
||||
- Support online view task log
|
||||
- Support second-level task setting
|
||||
- Support system level notification
|
||||
- Support dark mode
|
||||
- Support cell phone operation
|
||||
|
||||
## Deployment
|
||||
|
||||
### Local Deployment
|
||||
|
||||
```bash
|
||||
# To be completed
|
||||
```
|
||||
|
||||
### 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 \
|
||||
--restart unless-stopped \
|
||||
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
|
||||
docker run -dit \
|
||||
-v $PWD/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--name qinglong \
|
||||
--hostname qinglong \
|
||||
--restart unless-stopped \
|
||||
whyour/qinglong:latest
|
||||
```
|
||||
|
||||
### Docker-compose Deployment
|
||||
|
||||
1. docker-compose installation
|
||||
|
||||
```bash
|
||||
sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
||||
```
|
||||
|
||||
2. start the container
|
||||
|
||||
```bash
|
||||
mkdir qinglong
|
||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
||||
|
||||
# start
|
||||
docker-compose up -d
|
||||
# stop
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
3. access
|
||||
|
||||
Open your browser and visit http://{ip}:5700
|
||||
|
||||
## Use
|
||||
|
||||
1. built-in commands
|
||||
|
||||
```bash
|
||||
# Update and restart Green Dragon
|
||||
ql update
|
||||
# Run custom scripts extra.sh
|
||||
ql extra
|
||||
# Adding a single script file
|
||||
ql raw <file_url>
|
||||
# Add a specific script for a single repository
|
||||
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch>
|
||||
# Delete old logs
|
||||
ql rmlog <days>
|
||||
# Start bot
|
||||
ql bot
|
||||
# Detecting the Green Dragon environment and repairing it
|
||||
ql check
|
||||
# Reset the number of login errors
|
||||
ql resetlet
|
||||
# Disable two-step login
|
||||
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>
|
||||
```
|
||||
|
||||
2. 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
|
||||
* branch: Pull the branch of the repository
|
||||
* days: Number of days of logs to be kept
|
||||
* file_path: File path for task execution
|
||||
* env_name: The name of the environment variable that needs to be concurrent or specified at the time of task execution
|
||||
* account_number: Specify the account number of an environment variable to be executed when the task is executed
|
||||
|
||||
## Links
|
||||
|
||||
- [nevinee](https://gitee.com/evine)
|
||||
- [crontab-ui](https://github.com/alseambusher/crontab-ui)
|
||||
- [Ant Design](https://ant.design)
|
||||
- [Ant Design Pro](https://pro.ant.design/)
|
||||
- [Umijs3.0](https://umijs.org)
|
||||
- [darkreader](https://github.com/darkreader/darkreader)
|
||||
- [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
|
||||
|
||||
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)
|
||||
|
||||
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.
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
支持python3、javaScript、shell、typescript 的定时任务管理面板
|
||||
支持python3、javaScript、shell、typescript 的定时任务管理面板(A timed task management panel that supports typescript, javaScript, python3, and shell.)
|
||||
|
||||
[![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]
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||
</div>
|
||||
|
||||
[](https://whyour.cn)
|
||||
[](https://whyour.cn)
|
||||
|
||||
简体中文 | [English](./README-en.md)
|
||||
|
||||
@@ -44,27 +44,6 @@
|
||||
# 待完善
|
||||
```
|
||||
|
||||
### 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 \
|
||||
--restart unless-stopped \
|
||||
docker.io/whyour/qinglong:latest
|
||||
```
|
||||
|
||||
### docker 部署
|
||||
|
||||
1. docker 安装
|
||||
@@ -73,31 +52,16 @@ podman run -dit \
|
||||
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. 启动容器
|
||||
2. 启动容器
|
||||
|
||||
```bash
|
||||
docker run -dit \
|
||||
-v $PWD/ql/data:/ql/data \
|
||||
-v $PWD/ql/config:/ql/config \
|
||||
-v $PWD/ql/log:/ql/log \
|
||||
-v $PWD/ql/db:/ql/db \
|
||||
-v $PWD/ql/repo:/ql/repo \
|
||||
-v $PWD/ql/raw:/ql/raw \
|
||||
-v $PWD/ql/scripts:/ql/scripts \
|
||||
-p 5700:5700 \
|
||||
--name qinglong \
|
||||
--hostname qinglong \
|
||||
@@ -117,7 +81,7 @@ sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-c
|
||||
|
||||
```bash
|
||||
mkdir qinglong
|
||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker-compose.yml
|
||||
|
||||
# 启动
|
||||
docker-compose up -d
|
||||
@@ -125,10 +89,6 @@ docker-compose up -d
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
3. 访问
|
||||
|
||||
打开你的浏览器,访问 http://{ip}:5700
|
||||
|
||||
## 使用
|
||||
|
||||
1. 内置命令
|
||||
@@ -141,7 +101,7 @@ ql extra
|
||||
# 添加单个脚本文件
|
||||
ql raw <file_url>
|
||||
# 添加单个仓库的指定脚本
|
||||
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch> <extensions>
|
||||
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch>
|
||||
# 删除旧日志
|
||||
ql rmlog <days>
|
||||
# 启动tg-bot
|
||||
@@ -167,10 +127,9 @@ task <file_path> desi <env_name> <account_number>
|
||||
|
||||
* file_url: 脚本地址
|
||||
* repo_url: 仓库地址
|
||||
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串,多个竖线分割
|
||||
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串,多个竖线分割
|
||||
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响,多个竖线分割
|
||||
* extensions: 拉取仓库的文件后缀,多个竖线分割
|
||||
* whitelist: 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串
|
||||
* blacklist: 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串
|
||||
* dependence: 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响
|
||||
* branch: 拉取仓库的分支
|
||||
* days: 需要保留的日志的天数
|
||||
* file_path: 任务执行时的文件路径
|
||||
@@ -193,13 +152,12 @@ task <file_path> desi <env_name> <account_number>
|
||||
$ 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
|
||||
$ yarn install
|
||||
$ yarn start-back
|
||||
$ yarn start
|
||||
```
|
||||
|
||||
打开你的浏览器,访问 http://127.0.0.1:5700
|
||||
打开你的浏览器,访问 http://127.0.0.1:5601
|
||||
|
||||
## 交流
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ export default (app: Router) => {
|
||||
}),
|
||||
});
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -50,6 +51,7 @@ export default (app: Router) => {
|
||||
}
|
||||
res.send({ code: 200, data: content });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -74,6 +76,7 @@ export default (app: Router) => {
|
||||
fs.writeFileSync(path, content);
|
||||
res.send({ code: 200, message: '保存成功' });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+23
-152
@@ -2,7 +2,6 @@ import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import CronService from '../services/cron';
|
||||
import CronViewService from '../services/cronView';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import cron_parser from 'cron-parser';
|
||||
const route = Router();
|
||||
@@ -10,135 +9,11 @@ const route = Router();
|
||||
export default (app: Router) => {
|
||||
app.use('/crons', route);
|
||||
|
||||
route.get(
|
||||
'/views',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.list();
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/views',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().required(),
|
||||
sorts: Joi.array().optional().allow(null),
|
||||
filters: Joi.array().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().required(),
|
||||
id: Joi.number().required(),
|
||||
sorts: Joi.array().optional().allow(null),
|
||||
filters: Joi.array().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.delete(
|
||||
'/views',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views/move',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
fromIndex: Joi.number().required(),
|
||||
toIndex: Joi.number().required(),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.move(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views/disable',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.disabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/views/enable',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
const data = await cronViewService.enabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.crontabs(req.query as any);
|
||||
const data = await cronService.crontabs(req.query.searchValue as string);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
@@ -167,6 +42,7 @@ export default (app: Router) => {
|
||||
return res.send({ code: 400, message: 'param schedule error' });
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -184,6 +60,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.run(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -201,6 +78,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.stop(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -224,6 +102,7 @@ export default (app: Router) => {
|
||||
);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -244,6 +123,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.addLabels(req.body.ids, req.body.labels);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -261,6 +141,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.disabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -278,6 +159,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.enabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -297,6 +179,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.log(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -307,9 +190,9 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
labels: Joi.array().optional().allow(null),
|
||||
command: Joi.string().required(),
|
||||
schedule: Joi.string().required(),
|
||||
name: Joi.string().optional().allow(null),
|
||||
command: Joi.string().optional(),
|
||||
schedule: Joi.string().optional(),
|
||||
name: Joi.string().optional(),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
@@ -327,6 +210,7 @@ export default (app: Router) => {
|
||||
return res.send({ code: 400, message: 'param schedule error' });
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -344,6 +228,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -361,6 +246,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.pin(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -378,6 +264,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.unPin(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -392,6 +279,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.import_crontab();
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -411,6 +299,7 @@ export default (app: Router) => {
|
||||
const data = await cronService.getDb({ id: req.params.id });
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -422,10 +311,10 @@ export default (app: Router) => {
|
||||
body: Joi.object({
|
||||
ids: Joi.array().items(Joi.number().required()),
|
||||
status: Joi.string().required(),
|
||||
pid: Joi.string().optional().allow(null),
|
||||
log_path: Joi.string().optional().allow(null),
|
||||
last_running_time: Joi.number().optional().allow(null),
|
||||
last_execution_time: Joi.number().optional().allow(null),
|
||||
pid: Joi.string().optional(),
|
||||
log_path: Joi.string().optional(),
|
||||
last_running_time: Joi.number().optional(),
|
||||
last_execution_time: Joi.number().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -439,25 +328,7 @@ export default (app: Router) => {
|
||||
});
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:id/logs',
|
||||
celebrate({
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.logs(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -38,6 +38,7 @@ export default (app: Router) => {
|
||||
const data = await dependenceService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -60,6 +61,7 @@ export default (app: Router) => {
|
||||
const data = await dependenceService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -77,6 +79,7 @@ export default (app: Router) => {
|
||||
const data = await dependenceService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -91,9 +94,10 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
const data = await dependenceService.remove(req.body, true);
|
||||
const data = await dependenceService.removeDb(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -113,6 +117,7 @@ export default (app: Router) => {
|
||||
const data = await dependenceService.getDb({ id: req.params.id });
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -130,6 +135,7 @@ export default (app: Router) => {
|
||||
const data = await dependenceService.reInstall(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+9
-1
@@ -38,6 +38,7 @@ export default (app: Router) => {
|
||||
const data = await envService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -60,6 +61,7 @@ export default (app: Router) => {
|
||||
const data = await envService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -77,6 +79,7 @@ export default (app: Router) => {
|
||||
const data = await envService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -100,6 +103,7 @@ export default (app: Router) => {
|
||||
const data = await envService.move(req.params.id, req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -117,6 +121,7 @@ export default (app: Router) => {
|
||||
const data = await envService.disabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -134,6 +139,7 @@ export default (app: Router) => {
|
||||
const data = await envService.enabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -154,6 +160,7 @@ export default (app: Router) => {
|
||||
const data = await envService.updateNames(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -170,9 +177,10 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.getDb({ id: req.params.id });
|
||||
const data = await envService.getDb(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -8,7 +8,6 @@ import script from './script';
|
||||
import open from './open';
|
||||
import dependence from './dependence';
|
||||
import system from './system';
|
||||
import subscription from './subscription';
|
||||
|
||||
export default () => {
|
||||
const app = Router();
|
||||
@@ -21,7 +20,6 @@ export default () => {
|
||||
open(app);
|
||||
dependence(app);
|
||||
system(app);
|
||||
subscription(app);
|
||||
|
||||
return app;
|
||||
};
|
||||
|
||||
+43
-16
@@ -3,10 +3,8 @@ import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import * as fs from 'fs';
|
||||
import config from '../config';
|
||||
import { getFileContentByName, readDirs } from '../config/util';
|
||||
import { join } from 'path';
|
||||
import { getFileContentByName } from '../config/util';
|
||||
const route = Router();
|
||||
const blacklist = ['.tmp'];
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/logs', route);
|
||||
@@ -14,33 +12,62 @@ export default (app: Router) => {
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const result = readDirs(config.logPath, config.logPath, blacklist);
|
||||
res.send({
|
||||
code: 200,
|
||||
data: result,
|
||||
const fileList = fs.readdirSync(config.logPath, 'utf-8');
|
||||
const dirs = [];
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const stat = fs.lstatSync(config.logPath + fileList[i]);
|
||||
if (stat.isDirectory()) {
|
||||
const fileListTmp = fs.readdirSync(
|
||||
`${config.logPath}/${fileList[i]}`,
|
||||
'utf-8',
|
||||
);
|
||||
dirs.push({
|
||||
name: fileList[i],
|
||||
isDir: true,
|
||||
files: fileListTmp.reverse(),
|
||||
});
|
||||
} else {
|
||||
dirs.push({
|
||||
name: fileList[i],
|
||||
isDir: false,
|
||||
files: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
res.send({ code: 200, dirs });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/:dir/:file',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const { dir, file } = req.params;
|
||||
const content = getFileContentByName(
|
||||
`${config.logPath}/${dir}/${file}`,
|
||||
);
|
||||
res.send({ code: 200, data: content });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:file',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
if (blacklist.includes(req.path)) {
|
||||
return res.send({ code: 403, message: '暂无权限' });
|
||||
}
|
||||
const filePath = join(
|
||||
config.logPath,
|
||||
(req.query.path || '') as string,
|
||||
req.params.file,
|
||||
);
|
||||
const content = getFileContentByName(filePath);
|
||||
const { file } = req.params;
|
||||
const content = getFileContentByName(`${config.logPath}/${file}`);
|
||||
res.send({ code: 200, data: content });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+7
-1
@@ -16,6 +16,7 @@ export default (app: Router) => {
|
||||
const data = await openService.list();
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -25,7 +26,7 @@ export default (app: Router) => {
|
||||
'/apps',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().optional().allow('').disallow('system'),
|
||||
name: Joi.string().optional().allow(''),
|
||||
scopes: Joi.array().items(Joi.string().required()),
|
||||
}),
|
||||
}),
|
||||
@@ -36,6 +37,7 @@ export default (app: Router) => {
|
||||
const data = await openService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -57,6 +59,7 @@ export default (app: Router) => {
|
||||
const data = await openService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -74,6 +77,7 @@ export default (app: Router) => {
|
||||
const data = await openService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -93,6 +97,7 @@ export default (app: Router) => {
|
||||
const data = await openService.resetSecret(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -113,6 +118,7 @@ export default (app: Router) => {
|
||||
const result = await openService.authToken(req.query as any);
|
||||
return res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+81
-46
@@ -1,9 +1,7 @@
|
||||
import {
|
||||
fileExist,
|
||||
getFileContentByName,
|
||||
readDirs,
|
||||
getLastModifyFilePath,
|
||||
readDir,
|
||||
} from '../config/util';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
@@ -11,38 +9,65 @@ import { Logger } from 'winston';
|
||||
import config from '../config';
|
||||
import * as fs from 'fs';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import path, { join, parse } from 'path';
|
||||
import path, { join } from 'path';
|
||||
import ScriptService from '../services/script';
|
||||
import multer from 'multer';
|
||||
const route = Router();
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, config.scriptPath);
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, file.originalname);
|
||||
},
|
||||
});
|
||||
const upload = multer({ storage: storage });
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/scripts', route);
|
||||
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
route.get(
|
||||
'/files',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const fileList = fs.readdirSync(config.scriptPath, 'utf-8');
|
||||
|
||||
let result = [];
|
||||
const blacklist = ['node_modules', '.git'];
|
||||
if (req.query.path) {
|
||||
const targetPath = path.join(
|
||||
config.scriptPath,
|
||||
req.query.path as string,
|
||||
);
|
||||
result = readDir(targetPath, config.scriptPath, blacklist);
|
||||
} else {
|
||||
result = readDirs(config.scriptPath, config.scriptPath, blacklist);
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const fileOrDir = fileList[i];
|
||||
const fPath = path.join(config.scriptPath, fileOrDir);
|
||||
const dirStat = fs.statSync(fPath);
|
||||
if (['node_modules'].includes(fileOrDir)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dirStat.isDirectory()) {
|
||||
const childFileList = fs.readdirSync(fPath, 'utf-8');
|
||||
let children = [];
|
||||
for (let j = 0; j < childFileList.length; j++) {
|
||||
const childFile = childFileList[j];
|
||||
const sPath = path.join(config.scriptPath, fileOrDir, childFile);
|
||||
const _fileExist = await fileExist(sPath);
|
||||
if (_fileExist && fs.statSync(sPath).isFile()) {
|
||||
const statObj = fs.statSync(sPath);
|
||||
children.push({
|
||||
title: childFile,
|
||||
value: childFile,
|
||||
key: `${fileOrDir}/${childFile}`,
|
||||
mtime: statObj.mtimeMs,
|
||||
parent: fileOrDir,
|
||||
});
|
||||
}
|
||||
}
|
||||
result.push({
|
||||
title: fileOrDir,
|
||||
value: fileOrDir,
|
||||
key: fileOrDir,
|
||||
mtime: dirStat.mtimeMs,
|
||||
disabled: true,
|
||||
children: children.sort((a, b) => b.mtime - a.mtime),
|
||||
});
|
||||
} else {
|
||||
result.push({
|
||||
title: fileOrDir,
|
||||
value: fileOrDir,
|
||||
key: fileOrDir,
|
||||
mtime: dirStat.mtimeMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.send({
|
||||
code: 200,
|
||||
data: result,
|
||||
@@ -51,7 +76,8 @@ export default (app: Router) => {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:file',
|
||||
@@ -66,6 +92,7 @@ export default (app: Router) => {
|
||||
const content = getFileContentByName(filePath);
|
||||
res.send({ code: 200, data: content });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -73,7 +100,14 @@ export default (app: Router) => {
|
||||
|
||||
route.post(
|
||||
'/',
|
||||
upload.single('file'),
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
path: Joi.string().optional().allow(''),
|
||||
content: Joi.string().allow(''),
|
||||
originFilename: Joi.string().allow(''),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
@@ -83,7 +117,6 @@ export default (app: Router) => {
|
||||
content: string;
|
||||
originFilename: string;
|
||||
};
|
||||
|
||||
if (!path) {
|
||||
path = config.scriptPath;
|
||||
}
|
||||
@@ -96,21 +129,18 @@ export default (app: Router) => {
|
||||
if (config.writePathList.every((x) => !path.startsWith(x))) {
|
||||
return res.send({
|
||||
code: 430,
|
||||
message: '文件路径禁止访问',
|
||||
data: '文件路径禁止访问',
|
||||
});
|
||||
}
|
||||
|
||||
if (req.file) {
|
||||
fs.renameSync(req.file.path, join(path, req.file.filename));
|
||||
return res.send({ code: 200 });
|
||||
}
|
||||
|
||||
if (!originFilename) {
|
||||
originFilename = filename;
|
||||
}
|
||||
const originFilePath = `${path}${originFilename.replace(/\//g, '')}`;
|
||||
const filePath = `${path}${filename.replace(/\//g, '')}`;
|
||||
if (fs.existsSync(originFilePath)) {
|
||||
if (!fs.existsSync(config.bakPath)) {
|
||||
fs.mkdirSync(config.bakPath);
|
||||
}
|
||||
fs.copyFileSync(
|
||||
originFilePath,
|
||||
`${config.bakPath}${originFilename.replace(/\//g, '')}`,
|
||||
@@ -122,6 +152,7 @@ export default (app: Router) => {
|
||||
fs.writeFileSync(filePath, content);
|
||||
return res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -133,7 +164,7 @@ export default (app: Router) => {
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
path: Joi.string().optional().allow(''),
|
||||
content: Joi.string().required().allow(''),
|
||||
content: Joi.string().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -148,6 +179,7 @@ export default (app: Router) => {
|
||||
fs.writeFileSync(filePath, content);
|
||||
return res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -172,6 +204,7 @@ export default (app: Router) => {
|
||||
fs.unlinkSync(filePath);
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -202,6 +235,7 @@ export default (app: Router) => {
|
||||
return next(err);
|
||||
});
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -212,22 +246,22 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
content: Joi.string().optional().allow(''),
|
||||
path: Joi.string().optional().allow(''),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let { filename, content, path } = req.body;
|
||||
const { name, ext } = parse(filename);
|
||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||
fs.writeFileSync(filePath, content || '', { encoding: 'utf8' });
|
||||
|
||||
let { filename, path } = req.body as {
|
||||
filename: string;
|
||||
path: string;
|
||||
};
|
||||
const filePath = join(path, filename);
|
||||
const scriptService = Container.get(ScriptService);
|
||||
const result = await scriptService.runScript(filePath);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -238,21 +272,22 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
filename: Joi.string().required(),
|
||||
content: Joi.string().optional().allow(''),
|
||||
path: Joi.string().optional().allow(''),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let { filename, content, path } = req.body;
|
||||
const { name, ext } = parse(filename);
|
||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||
|
||||
let { filename, path } = req.body as {
|
||||
filename: string;
|
||||
path: string;
|
||||
};
|
||||
const filePath = join(path, filename);
|
||||
const scriptService = Container.get(ScriptService);
|
||||
const result = await scriptService.stopScript(filePath);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import SubscriptionService from '../services/subscription';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import cron_parser from 'cron-parser';
|
||||
const route = Router();
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/subscriptions', route);
|
||||
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.list(
|
||||
req.query.searchValue as string,
|
||||
);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
});
|
||||
|
||||
route.post(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
type: Joi.string().required(),
|
||||
schedule: Joi.string().optional().allow('').allow(null),
|
||||
interval_schedule: Joi.object({
|
||||
type: Joi.string().required(),
|
||||
value: Joi.number().min(1).required(),
|
||||
})
|
||||
.optional()
|
||||
.allow('')
|
||||
.allow(null),
|
||||
name: Joi.string().optional().allow('').allow(null),
|
||||
url: Joi.string().required(),
|
||||
whitelist: Joi.string().optional().allow('').allow(null),
|
||||
blacklist: Joi.string().optional().allow('').allow(null),
|
||||
branch: Joi.string().optional().allow('').allow(null),
|
||||
dependences: Joi.string().optional().allow('').allow(null),
|
||||
pull_type: Joi.string().optional().allow('').allow(null),
|
||||
pull_option: Joi.object().optional().allow('').allow(null),
|
||||
extensions: Joi.string().optional().allow('').allow(null),
|
||||
sub_before: Joi.string().optional().allow('').allow(null),
|
||||
sub_after: Joi.string().optional().allow('').allow(null),
|
||||
schedule_type: Joi.string().required(),
|
||||
alias: Joi.string().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
if (
|
||||
!req.body.schedule ||
|
||||
cron_parser.parseExpression(req.body.schedule).hasNext()
|
||||
) {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} else {
|
||||
return res.send({ code: 400, message: 'param schedule error' });
|
||||
}
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/run',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.run(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/stop',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.stop(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/disable',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.disabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/enable',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.enabled(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:id/log',
|
||||
celebrate({
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.log(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
type: Joi.string().required(),
|
||||
schedule: Joi.string().optional().allow('').allow(null),
|
||||
interval_schedule: Joi.object().optional().allow('').allow(null),
|
||||
name: Joi.string().optional().allow('').allow(null),
|
||||
url: Joi.string().required(),
|
||||
whitelist: Joi.string().optional().allow('').allow(null),
|
||||
blacklist: Joi.string().optional().allow('').allow(null),
|
||||
branch: Joi.string().optional().allow('').allow(null),
|
||||
dependences: Joi.string().optional().allow('').allow(null),
|
||||
pull_type: Joi.string().optional().allow('').allow(null),
|
||||
pull_option: Joi.object().optional().allow('').allow(null),
|
||||
schedule_type: Joi.string().optional().allow('').allow(null),
|
||||
extensions: Joi.string().optional().allow('').allow(null),
|
||||
sub_before: Joi.string().optional().allow('').allow(null),
|
||||
sub_after: Joi.string().optional().allow('').allow(null),
|
||||
alias: Joi.string().required(),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
if (
|
||||
!req.body.schedule ||
|
||||
typeof req.body.schedule === 'object' ||
|
||||
cron_parser.parseExpression(req.body.schedule).hasNext()
|
||||
) {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} else {
|
||||
return res.send({ code: 400, message: 'param schedule error' });
|
||||
}
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.delete(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.remove(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:id',
|
||||
celebrate({
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.getDb({ id: req.params.id });
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/status',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
ids: Joi.array().items(Joi.number().required()),
|
||||
status: Joi.string().required(),
|
||||
pid: Joi.string().optional(),
|
||||
log_path: Joi.string().optional(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.status({
|
||||
...req.body,
|
||||
status: parseInt(req.body.status),
|
||||
pid: parseInt(req.body.pid) || '',
|
||||
});
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:id/logs',
|
||||
celebrate({
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const data = await subscriptionService.logs(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
+7
-23
@@ -5,8 +5,8 @@ import * as fs from 'fs';
|
||||
import config from '../config';
|
||||
import SystemService from '../services/system';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { getFileContentByName } from '../config/util';
|
||||
import UserService from '../services/user';
|
||||
import { EnvModel } from '../data/env';
|
||||
const route = Router();
|
||||
|
||||
export default (app: Router) => {
|
||||
@@ -17,7 +17,7 @@ export default (app: Router) => {
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const authInfo = await userService.getUserInfo();
|
||||
const envCount = await EnvModel.count();
|
||||
const envDbContent = getFileContentByName(config.envDbFile);
|
||||
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
||||
|
||||
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||
@@ -28,7 +28,7 @@ export default (app: Router) => {
|
||||
Object.keys(authInfo).length === 2 &&
|
||||
authInfo.username === 'admin' &&
|
||||
authInfo.password === 'admin' &&
|
||||
envCount === 0
|
||||
envDbContent.length === 0
|
||||
) {
|
||||
isInitialized = false;
|
||||
}
|
||||
@@ -54,6 +54,7 @@ export default (app: Router) => {
|
||||
const data = await systemService.getLogRemoveFrequency();
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -75,6 +76,7 @@ export default (app: Router) => {
|
||||
);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -89,6 +91,7 @@ export default (app: Router) => {
|
||||
const result = await systemService.checkUpdate();
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -103,26 +106,7 @@ export default (app: Router) => {
|
||||
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) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+15
-32
@@ -1,26 +1,13 @@
|
||||
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 UserService from '../services/user';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import { v4 as uuidV4 } from 'uuid';
|
||||
import config from '../config';
|
||||
import { getFileContentByName } from '../config/util';
|
||||
const route = Router();
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, config.uploadPath);
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
const ext = path.parse(file.originalname).ext;
|
||||
const key = uuidV4();
|
||||
cb(null, key + ext);
|
||||
},
|
||||
});
|
||||
const upload = multer({ storage: storage });
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/user', route);
|
||||
|
||||
@@ -39,6 +26,7 @@ export default (app: Router) => {
|
||||
const data = await userService.login({ ...req.body }, req);
|
||||
return res.send(data);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -53,6 +41,7 @@ export default (app: Router) => {
|
||||
await userService.logout(req.platform);
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -73,6 +62,7 @@ export default (app: Router) => {
|
||||
await userService.updateUsernameAndPassword(req.body);
|
||||
res.send({ code: 200, message: '更新成功' });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -87,7 +77,6 @@ export default (app: Router) => {
|
||||
code: 200,
|
||||
data: {
|
||||
username: authInfo.username,
|
||||
avatar: authInfo.avatar,
|
||||
twoFactorActivated: authInfo.twoFactorActivated,
|
||||
},
|
||||
});
|
||||
@@ -106,6 +95,7 @@ export default (app: Router) => {
|
||||
const data = await userService.initTwoFactor();
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -125,6 +115,7 @@ export default (app: Router) => {
|
||||
const data = await userService.activeTwoFactor(req.body.code);
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -139,6 +130,7 @@ export default (app: Router) => {
|
||||
const data = await userService.deactiveTwoFactor();
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -160,6 +152,7 @@ export default (app: Router) => {
|
||||
const data = await userService.twoFactorLogin(req.body, req);
|
||||
res.send(data);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -174,6 +167,7 @@ export default (app: Router) => {
|
||||
const data = await userService.getLoginLog();
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -188,6 +182,7 @@ export default (app: Router) => {
|
||||
const data = await userService.getNotificationMode();
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -202,6 +197,7 @@ export default (app: Router) => {
|
||||
const result = await userService.updateNotificationMode(req.body);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -222,6 +218,7 @@ export default (app: Router) => {
|
||||
await userService.updateUsernameAndPassword(req.body);
|
||||
res.send({ code: 200, message: '更新成功' });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -236,21 +233,7 @@ export default (app: Router) => {
|
||||
const result = await userService.updateNotificationMode(req.body);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/avatar',
|
||||
upload.single('avatar'),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const result = await userService.updateAvatar(req.file!.filename);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+10
-4
@@ -1,23 +1,29 @@
|
||||
import 'reflect-metadata'; // We need this in order to use @Decorators
|
||||
|
||||
import config from './config';
|
||||
|
||||
import express from 'express';
|
||||
|
||||
import Logger from './loaders/logger';
|
||||
import path from 'path';
|
||||
|
||||
async function startServer() {
|
||||
const app = express();
|
||||
|
||||
await require('./loaders/db').default();
|
||||
|
||||
await require('./loaders/initFile').default();
|
||||
|
||||
await require('./loaders/sentry').default({ expressApp: app });
|
||||
|
||||
await require('./loaders/db').default();
|
||||
|
||||
await require('./loaders/app').default({ expressApp: app });
|
||||
|
||||
const server = app
|
||||
.listen(config.port, () => {
|
||||
Logger.debug(`✌️ Back server launched on port ${config.port}`);
|
||||
Logger.info(`
|
||||
################################################
|
||||
🛡️ Server listening on port: ${config.port} 🛡️
|
||||
################################################
|
||||
`);
|
||||
})
|
||||
.on('error', (err) => {
|
||||
Logger.error(err);
|
||||
|
||||
+27
-36
@@ -4,42 +4,32 @@ import { createRandomString } from './util';
|
||||
|
||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
if (!process.env.QL_DIR) {
|
||||
// 声明QL_DIR环境变量
|
||||
let qlHomePath = path.join(__dirname, '../../');
|
||||
// 生产环境
|
||||
if (qlHomePath.endsWith('/static/')) {
|
||||
qlHomePath = path.join(qlHomePath, '../');
|
||||
}
|
||||
process.env.QL_DIR = qlHomePath;
|
||||
}
|
||||
const lastVersionFile =
|
||||
'https://raw.githubusercontent.com/whyour/qinglong/master/src/version.ts';
|
||||
|
||||
const lastVersionFile = `http://qn.whyour.cn/version.ts?v=${Date.now()}`;
|
||||
|
||||
const rootPath = process.env.QL_DIR as string;
|
||||
const envFound = dotenv.config({ path: path.join(rootPath, '.env') });
|
||||
|
||||
const dataPath = path.join(rootPath, 'data/');
|
||||
const envFound = dotenv.config();
|
||||
const rootPath = process.cwd();
|
||||
const envFile = path.join(rootPath, 'config/env.sh');
|
||||
const confFile = path.join(rootPath, 'config/config.sh');
|
||||
const sampleFile = path.join(rootPath, 'sample/config.sample.sh');
|
||||
const crontabFile = path.join(rootPath, 'config/crontab.list');
|
||||
const confBakDir = path.join(rootPath, 'config/bak/');
|
||||
const authConfigFile = path.join(rootPath, 'config/auth.json');
|
||||
const extraFile = path.join(rootPath, 'config/extra.sh');
|
||||
const configPath = path.join(rootPath, 'config/');
|
||||
const scriptPath = path.join(rootPath, 'scripts/');
|
||||
const bakPath = path.join(rootPath, 'bak/');
|
||||
const samplePath = path.join(rootPath, 'sample/');
|
||||
const configPath = path.join(dataPath, 'config/');
|
||||
const scriptPath = path.join(dataPath, 'scripts/');
|
||||
const bakPath = path.join(dataPath, 'bak/');
|
||||
const logPath = path.join(dataPath, 'log/');
|
||||
const dbPath = path.join(dataPath, 'db/');
|
||||
const uploadPath = path.join(dataPath, 'upload/');
|
||||
|
||||
const envFile = path.join(configPath, 'env.sh');
|
||||
const confFile = path.join(configPath, 'config.sh');
|
||||
const crontabFile = path.join(configPath, 'crontab.list');
|
||||
const authConfigFile = path.join(configPath, 'auth.json');
|
||||
const extraFile = path.join(configPath, 'extra.sh');
|
||||
const confBakDir = path.join(dataPath, 'config/bak/');
|
||||
const sampleFile = path.join(samplePath, 'config.sample.sh');
|
||||
const sqliteFile = path.join(samplePath, 'database.sqlite');
|
||||
|
||||
const logPath = path.join(rootPath, 'log/');
|
||||
const authError = '错误的用户名密码,请重试';
|
||||
const loginFaild = '请先登录!';
|
||||
const configString = 'config sample crontab shareCode diy';
|
||||
const dbPath = path.join(rootPath, 'db/');
|
||||
const cronDbFile = path.join(rootPath, 'db/crontab.db');
|
||||
const envDbFile = path.join(rootPath, 'db/env.db');
|
||||
const appDbFile = path.join(rootPath, 'db/app.db');
|
||||
const authDbFile = path.join(rootPath, 'db/auth.db');
|
||||
const dependenceDbFile = path.join(rootPath, 'db/dependence.db');
|
||||
const versionFile = path.join(rootPath, 'src/version.ts');
|
||||
|
||||
if (envFound.error) {
|
||||
@@ -47,9 +37,8 @@ if (envFound.error) {
|
||||
}
|
||||
|
||||
export default {
|
||||
port: parseInt(process.env.BACK_PORT as string, 10),
|
||||
port: parseInt(process.env.PORT as string, 10),
|
||||
cronPort: parseInt(process.env.CRON_PORT as string, 10),
|
||||
publicPort: parseInt(process.env.PUBLIC_PORT as string, 10),
|
||||
secret: process.env.SECRET || createRandomString(16, 32),
|
||||
logs: {
|
||||
level: process.env.LOG_LEVEL || 'silly',
|
||||
@@ -70,7 +59,11 @@ export default {
|
||||
confFile,
|
||||
envFile,
|
||||
dbPath,
|
||||
uploadPath,
|
||||
cronDbFile,
|
||||
envDbFile,
|
||||
appDbFile,
|
||||
authDbFile,
|
||||
dependenceDbFile,
|
||||
configPath,
|
||||
scriptPath,
|
||||
samplePath,
|
||||
@@ -80,7 +73,6 @@ export default {
|
||||
'cookie.sh',
|
||||
'crontab.list',
|
||||
'env.sh',
|
||||
'token.json',
|
||||
],
|
||||
writePathList: [configPath, scriptPath],
|
||||
bakPath,
|
||||
@@ -94,5 +86,4 @@ export default {
|
||||
],
|
||||
versionFile,
|
||||
lastVersionFile,
|
||||
sqliteFile,
|
||||
};
|
||||
|
||||
+1
-88
@@ -2,7 +2,6 @@ import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import got from 'got';
|
||||
import iconv from 'iconv-lite';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
export function getFileContentByName(fileName: string) {
|
||||
if (fs.existsSync(fileName)) {
|
||||
@@ -108,7 +107,7 @@ export function createRandomString(min: number, max: number): string {
|
||||
newArr.push(arr.splice(Math.random() * arr.length, 1)[0]);
|
||||
}
|
||||
|
||||
function getOne(arr: any[]) {
|
||||
function getOne(arr) {
|
||||
return arr[Math.floor(Math.random() * arr.length)];
|
||||
}
|
||||
|
||||
@@ -233,14 +232,6 @@ export async function fileExist(file: any) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function createFile(file: string, data: string = '') {
|
||||
return new Promise((resolve) => {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, data);
|
||||
resolve(true);
|
||||
});
|
||||
}
|
||||
|
||||
export async function concurrentRun(
|
||||
fnList: Array<() => Promise<any>> = [],
|
||||
max = 5,
|
||||
@@ -277,81 +268,3 @@ export async function concurrentRun(
|
||||
|
||||
return replyList;
|
||||
}
|
||||
|
||||
enum FileType {
|
||||
'directory',
|
||||
'file',
|
||||
}
|
||||
|
||||
export function readDirs(
|
||||
dir: string,
|
||||
baseDir: string = '',
|
||||
blacklist: string[] = [],
|
||||
) {
|
||||
const relativePath = path.relative(baseDir, dir);
|
||||
const files = fs.readdirSync(dir);
|
||||
const result: any = files
|
||||
.filter((x) => !blacklist.includes(x))
|
||||
.map((file: string) => {
|
||||
const subPath = path.join(dir, file);
|
||||
const stats = fs.statSync(subPath);
|
||||
const key = path.join(relativePath, file);
|
||||
if (stats.isDirectory()) {
|
||||
return {
|
||||
title: file,
|
||||
key,
|
||||
type: 'directory',
|
||||
disabled: true,
|
||||
parent: relativePath,
|
||||
children: readDirs(subPath, baseDir).sort(
|
||||
(a: any, b: any) =>
|
||||
(FileType as any)[a.type] - (FileType as any)[b.type],
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: file,
|
||||
type: 'file',
|
||||
key,
|
||||
parent: relativePath,
|
||||
};
|
||||
});
|
||||
return result.sort(
|
||||
(a: any, b: any) => (FileType as any)[a.type] - (FileType as any)[b.type],
|
||||
);
|
||||
}
|
||||
|
||||
export function readDir(
|
||||
dir: string,
|
||||
baseDir: string = '',
|
||||
blacklist: string[] = [],
|
||||
) {
|
||||
const relativePath = path.relative(baseDir, dir);
|
||||
const files = fs.readdirSync(dir);
|
||||
const result: any = files
|
||||
.filter((x) => !blacklist.includes(x))
|
||||
.map((file: string) => {
|
||||
const subPath = path.join(dir, file);
|
||||
const stats = fs.statSync(subPath);
|
||||
const key = path.join(relativePath, file);
|
||||
return {
|
||||
title: file,
|
||||
type: stats.isDirectory() ? 'directory' : 'file',
|
||||
key,
|
||||
parent: relativePath,
|
||||
};
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export function promiseExec(command: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(
|
||||
command,
|
||||
{ maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' },
|
||||
(err, stdout, stderr) => {
|
||||
resolve(stdout || stderr || JSON.stringify(err));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
+5
-11
@@ -4,7 +4,7 @@ import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
export class Crontab {
|
||||
name?: string;
|
||||
command: string;
|
||||
schedule?: string;
|
||||
schedule: string;
|
||||
timestamp?: string;
|
||||
saved?: boolean;
|
||||
id?: number;
|
||||
@@ -34,7 +34,7 @@ export class Crontab {
|
||||
this.isDisabled = options.isDisabled || 0;
|
||||
this.log_path = options.log_path || '';
|
||||
this.isPinned = options.isPinned || 0;
|
||||
this.labels = options.labels || [];
|
||||
this.labels = options.labels || [''];
|
||||
this.last_running_time = options.last_running_time || 0;
|
||||
this.last_execution_time = options.last_execution_time || 0;
|
||||
}
|
||||
@@ -49,18 +49,12 @@ export enum CrontabStatus {
|
||||
|
||||
interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
|
||||
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||
name: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
name: DataTypes.STRING,
|
||||
command: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
schedule: {
|
||||
unique: 'compositeIndex',
|
||||
unique: 'command',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
schedule: DataTypes.STRING,
|
||||
timestamp: DataTypes.STRING,
|
||||
saved: DataTypes.BOOLEAN,
|
||||
status: DataTypes.NUMBER,
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
|
||||
interface SortType {
|
||||
type: 'ASC' | 'DESC';
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface FilterType {
|
||||
type: 'or' | 'and';
|
||||
value: string;
|
||||
}
|
||||
|
||||
export class CrontabView {
|
||||
name?: string;
|
||||
id?: number;
|
||||
position?: number;
|
||||
isDisabled?: 1 | 0;
|
||||
filters?: FilterType[];
|
||||
sorts?: SortType[];
|
||||
|
||||
constructor(options: CrontabView) {
|
||||
this.name = options.name;
|
||||
this.id = options.id;
|
||||
this.position = options.position;
|
||||
this.isDisabled = options.isDisabled || 0;
|
||||
this.filters = options.filters;
|
||||
this.sorts = options.sorts;
|
||||
}
|
||||
}
|
||||
|
||||
interface CronViewInstance
|
||||
extends Model<CrontabView, CrontabView>,
|
||||
CrontabView {}
|
||||
export const CrontabViewModel = sequelize.define<CronViewInstance>(
|
||||
'CrontabView',
|
||||
{
|
||||
name: {
|
||||
unique: 'name',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
position: DataTypes.NUMBER,
|
||||
isDisabled: DataTypes.NUMBER,
|
||||
filters: DataTypes.JSON,
|
||||
sorts: DataTypes.JSON,
|
||||
},
|
||||
);
|
||||
@@ -37,15 +37,15 @@ export enum DependenceTypes {
|
||||
}
|
||||
|
||||
export enum InstallDependenceCommandTypes {
|
||||
'pnpm add -g',
|
||||
'npm i -g --force',
|
||||
'pip3 install',
|
||||
'apk add',
|
||||
'apk add --no-cache -f',
|
||||
}
|
||||
|
||||
export enum unInstallDependenceCommandTypes {
|
||||
'pnpm remove -g',
|
||||
'npm uninstall -g --force',
|
||||
'pip3 uninstall -y',
|
||||
'apk del',
|
||||
'apk del -f',
|
||||
}
|
||||
|
||||
interface DependenceInstance
|
||||
|
||||
+2
-2
@@ -30,10 +30,10 @@ export const initEnvPosition = 9999999999;
|
||||
|
||||
interface EnvInstance extends Model<Env, Env>, Env {}
|
||||
export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
||||
value: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||
value: DataTypes.STRING,
|
||||
timestamp: DataTypes.STRING,
|
||||
status: DataTypes.NUMBER,
|
||||
position: DataTypes.NUMBER,
|
||||
name: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||
name: DataTypes.STRING,
|
||||
remarks: DataTypes.STRING,
|
||||
});
|
||||
|
||||
@@ -5,11 +5,4 @@ export const sequelize = new Sequelize({
|
||||
dialect: 'sqlite',
|
||||
storage: `${config.dbPath}database.sqlite`,
|
||||
logging: false,
|
||||
pool: {
|
||||
max: 6,
|
||||
min: 0,
|
||||
idle: 30000,
|
||||
},
|
||||
});
|
||||
|
||||
export type ResponseType<T> = { code: number; data?: T; message?: string };
|
||||
|
||||
@@ -2,9 +2,7 @@ export enum NotificationMode {
|
||||
'gotify' = 'gotify',
|
||||
'goCqHttpBot' = 'goCqHttpBot',
|
||||
'serverChan' = 'serverChan',
|
||||
'pushDeer' = 'pushDeer',
|
||||
'bark' = 'bark',
|
||||
'chat' = 'chat',
|
||||
'telegramBot' = 'telegramBot',
|
||||
'dingtalkBot' = 'dingtalkBot',
|
||||
'weWorkBot' = 'weWorkBot',
|
||||
@@ -34,18 +32,8 @@ export class ServerChanNotification extends NotificationBaseInfo {
|
||||
public serverChanKey = '';
|
||||
}
|
||||
|
||||
export class PushDeerNotification extends NotificationBaseInfo {
|
||||
public pushDeerKey = '';
|
||||
}
|
||||
|
||||
export class ChatNotification extends NotificationBaseInfo {
|
||||
public chatUrl = '';
|
||||
public chatToken = '';
|
||||
}
|
||||
|
||||
export class BarkNotification extends NotificationBaseInfo {
|
||||
public barkPush = '';
|
||||
public barkIcon = 'http://qn.whyour.cn/logo.png';
|
||||
public barkSound = '';
|
||||
public barkGroup = 'qinglong';
|
||||
}
|
||||
@@ -91,8 +79,6 @@ export interface NotificationInfo
|
||||
extends GoCqHttpBotNotification,
|
||||
GotifyNotification,
|
||||
ServerChanNotification,
|
||||
PushDeerNotification,
|
||||
ChatNotification,
|
||||
BarkNotification,
|
||||
TelegramBotNotification,
|
||||
DingtalkBotNotification,
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ export enum CrontabStatus {
|
||||
|
||||
interface AppInstance extends Model<App, App>, App {}
|
||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||
name: { type: DataTypes.STRING, unique: 'name' },
|
||||
name: DataTypes.STRING,
|
||||
scopes: DataTypes.JSON,
|
||||
client_id: DataTypes.STRING,
|
||||
client_secret: DataTypes.STRING,
|
||||
|
||||
+1
-3
@@ -13,7 +13,5 @@ export class SockMessage {
|
||||
export type SockMessageType =
|
||||
| 'ping'
|
||||
| 'installDependence'
|
||||
| 'uninstallDependence'
|
||||
| 'updateSystemVersion'
|
||||
| 'manuallyRunScript'
|
||||
| 'runSubscriptionEnd';
|
||||
| 'manuallyRunScript';
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||
|
||||
type SimpleIntervalScheduleUnit = keyof SimpleIntervalSchedule;
|
||||
export class Subscription {
|
||||
id?: number;
|
||||
name?: string;
|
||||
type?: 'public-repo' | 'private-repo' | 'file';
|
||||
schedule_type?: 'crontab' | 'interval';
|
||||
schedule?: string;
|
||||
interval_schedule?: { type: SimpleIntervalScheduleUnit; value: number };
|
||||
url?: string;
|
||||
whitelist?: string;
|
||||
blacklist?: string;
|
||||
dependences?: string;
|
||||
branch?: string;
|
||||
status?: SubscriptionStatus;
|
||||
pull_type?: 'ssh-key' | 'user-pwd';
|
||||
pull_option?:
|
||||
| { private_key: string }
|
||||
| { username: string; password: string };
|
||||
pid?: number;
|
||||
is_disabled?: 1 | 0;
|
||||
log_path?: string;
|
||||
alias: string;
|
||||
command?: string;
|
||||
extensions?: string;
|
||||
sub_before?: string;
|
||||
sub_after?: string;
|
||||
|
||||
constructor(options: Subscription) {
|
||||
this.id = options.id;
|
||||
this.name = options.name || options.alias;
|
||||
this.type = options.type;
|
||||
this.schedule = options.schedule;
|
||||
this.status =
|
||||
options.status && SubscriptionStatus[options.status]
|
||||
? options.status
|
||||
: SubscriptionStatus.idle;
|
||||
this.url = options.url;
|
||||
this.whitelist = options.whitelist;
|
||||
this.blacklist = options.blacklist;
|
||||
this.dependences = options.dependences;
|
||||
this.branch = options.branch;
|
||||
this.pull_type = options.pull_type;
|
||||
this.pull_option = options.pull_option;
|
||||
this.pid = options.pid;
|
||||
this.is_disabled = options.is_disabled;
|
||||
this.log_path = options.log_path;
|
||||
this.schedule_type = options.schedule_type;
|
||||
this.alias = options.alias;
|
||||
this.interval_schedule = options.interval_schedule;
|
||||
this.extensions = options.extensions;
|
||||
this.sub_before = options.sub_before;
|
||||
this.sub_after = options.sub_after;
|
||||
}
|
||||
}
|
||||
|
||||
export enum SubscriptionStatus {
|
||||
'running',
|
||||
'idle',
|
||||
'disabled',
|
||||
'queued',
|
||||
}
|
||||
|
||||
interface SubscriptionInstance
|
||||
extends Model<Subscription, Subscription>,
|
||||
Subscription {}
|
||||
export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
||||
'Subscription',
|
||||
{
|
||||
name: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
url: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
schedule: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
interval_schedule: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.JSON,
|
||||
},
|
||||
type: DataTypes.STRING,
|
||||
whitelist: DataTypes.STRING,
|
||||
blacklist: DataTypes.STRING,
|
||||
status: DataTypes.NUMBER,
|
||||
dependences: DataTypes.STRING,
|
||||
extensions: DataTypes.STRING,
|
||||
sub_before: DataTypes.STRING,
|
||||
sub_after: DataTypes.STRING,
|
||||
branch: DataTypes.STRING,
|
||||
pull_type: DataTypes.STRING,
|
||||
pull_option: DataTypes.JSON,
|
||||
pid: DataTypes.NUMBER,
|
||||
is_disabled: DataTypes.NUMBER,
|
||||
log_path: DataTypes.STRING,
|
||||
schedule_type: DataTypes.STRING,
|
||||
alias: { type: DataTypes.STRING, unique: 'alias' },
|
||||
},
|
||||
);
|
||||
+5
-7
@@ -1,13 +1,14 @@
|
||||
import expressLoader from './express';
|
||||
import depInjectorLoader from './depInjector';
|
||||
import dependencyInjectorLoader from './dependencyInjector';
|
||||
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();
|
||||
await dependencyInjectorLoader({
|
||||
models: [],
|
||||
});
|
||||
Logger.info('✌️ Dependency Injector loaded');
|
||||
|
||||
await expressLoader({ app: expressApp });
|
||||
@@ -17,8 +18,5 @@ export default async ({ expressApp }: { expressApp: Application }) => {
|
||||
Logger.info('✌️ init data loaded');
|
||||
|
||||
await linkDeps();
|
||||
Logger.info('✌️ link deps loaded');
|
||||
|
||||
initTask();
|
||||
Logger.info('✌️ init task loaded');
|
||||
Logger.info('✌️ link deps');
|
||||
};
|
||||
|
||||
+15
-36
@@ -1,44 +1,23 @@
|
||||
import Logger from './logger';
|
||||
import path from 'path';
|
||||
import DataStore from 'nedb';
|
||||
import config from '../config';
|
||||
import Logger from './logger';
|
||||
import { fileExist } from '../config/util';
|
||||
import { EnvModel } from '../data/env';
|
||||
import { CrontabModel } from '../data/cron';
|
||||
import { DependenceModel } from '../data/dependence';
|
||||
import { AppModel } from '../data/open';
|
||||
import { AuthModel } from '../data/auth';
|
||||
import { fileExist } from '../config/util';
|
||||
import { SubscriptionModel } from '../data/subscription';
|
||||
import { CrontabViewModel } from '../data/cronView';
|
||||
import config from '../config';
|
||||
import { sequelize } from '../data';
|
||||
|
||||
export default async () => {
|
||||
try {
|
||||
await CrontabModel.sync();
|
||||
await DependenceModel.sync();
|
||||
await AppModel.sync();
|
||||
await AuthModel.sync();
|
||||
await EnvModel.sync();
|
||||
await SubscriptionModel.sync();
|
||||
await CrontabViewModel.sync();
|
||||
await sequelize.sync({ alter: true });
|
||||
|
||||
// try {
|
||||
// const queryInterface = sequelize.getQueryInterface();
|
||||
// await queryInterface.addIndex('Crontabs', ['command'], { unique: true });
|
||||
// await queryInterface.addIndex('Envs', ['name', 'value'], { unique: true });
|
||||
// await queryInterface.addIndex('Apps', ['name'], { unique: true });
|
||||
// } catch (error) { }
|
||||
|
||||
// 2.10-2.11 升级
|
||||
const cronDbFile = path.join(config.rootPath, 'db/crontab.db');
|
||||
const envDbFile = path.join(config.rootPath, 'db/env.db');
|
||||
const appDbFile = path.join(config.rootPath, 'db/app.db');
|
||||
const authDbFile = path.join(config.rootPath, 'db/auth.db');
|
||||
const dependenceDbFile = path.join(config.rootPath, 'db/dependence.db');
|
||||
const crondbExist = await fileExist(cronDbFile);
|
||||
const dependenceDbExist = await fileExist(dependenceDbFile);
|
||||
const envDbExist = await fileExist(envDbFile);
|
||||
const appDbExist = await fileExist(appDbFile);
|
||||
const authDbExist = await fileExist(authDbFile);
|
||||
const crondbExist = await fileExist(config.cronDbFile);
|
||||
const dependenceDbExist = await fileExist(config.dependenceDbFile);
|
||||
const envDbExist = await fileExist(config.envDbFile);
|
||||
const appDbExist = await fileExist(config.appDbFile);
|
||||
const authDbExist = await fileExist(config.authDbFile);
|
||||
|
||||
const cronCount = await CrontabModel.count();
|
||||
const dependenceCount = await DependenceModel.count();
|
||||
@@ -47,7 +26,7 @@ export default async () => {
|
||||
const authCount = await AuthModel.count();
|
||||
if (crondbExist && cronCount === 0) {
|
||||
const cronDb = new DataStore({
|
||||
filename: cronDbFile,
|
||||
filename: config.cronDbFile,
|
||||
autoload: true,
|
||||
});
|
||||
cronDb.persistence.compactDatafile();
|
||||
@@ -58,7 +37,7 @@ export default async () => {
|
||||
|
||||
if (dependenceDbExist && dependenceCount === 0) {
|
||||
const dependenceDb = new DataStore({
|
||||
filename: dependenceDbFile,
|
||||
filename: config.dependenceDbFile,
|
||||
autoload: true,
|
||||
});
|
||||
dependenceDb.persistence.compactDatafile();
|
||||
@@ -69,7 +48,7 @@ export default async () => {
|
||||
|
||||
if (envDbExist && envCount === 0) {
|
||||
const envDb = new DataStore({
|
||||
filename: envDbFile,
|
||||
filename: config.envDbFile,
|
||||
autoload: true,
|
||||
});
|
||||
envDb.persistence.compactDatafile();
|
||||
@@ -80,7 +59,7 @@ export default async () => {
|
||||
|
||||
if (appDbExist && appCount === 0) {
|
||||
const appDb = new DataStore({
|
||||
filename: appDbFile,
|
||||
filename: config.appDbFile,
|
||||
autoload: true,
|
||||
});
|
||||
appDb.persistence.compactDatafile();
|
||||
@@ -91,7 +70,7 @@ export default async () => {
|
||||
|
||||
if (authDbExist && authCount === 0) {
|
||||
const authDb = new DataStore({
|
||||
filename: authDbFile,
|
||||
filename: config.authDbFile,
|
||||
autoload: true,
|
||||
});
|
||||
authDb.persistence.compactDatafile();
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Container } from 'typedi';
|
||||
import LoggerInstance from './logger';
|
||||
|
||||
export default () => {
|
||||
export default ({ models }: { models: { name: string; model: any }[] }) => {
|
||||
try {
|
||||
models.forEach((m) => {
|
||||
Container.set(m.name, m.model);
|
||||
});
|
||||
|
||||
Container.set('logger', LoggerInstance);
|
||||
} catch (e) {
|
||||
LoggerInstance.error('🔥 Error on dependency injector loader: %o', e);
|
||||
@@ -2,7 +2,6 @@ import path from 'path';
|
||||
import fs from 'fs';
|
||||
import chokidar from 'chokidar';
|
||||
import config from '../config/index';
|
||||
import { promiseExec } from '../config/util';
|
||||
|
||||
function linkToNodeModule(src: string, dst?: string) {
|
||||
const target = path.join(config.rootPath, 'node_modules', dst || src);
|
||||
@@ -17,32 +16,7 @@ function linkToNodeModule(src: string, dst?: string) {
|
||||
});
|
||||
}
|
||||
|
||||
async function linkCommand() {
|
||||
const commandPath = await promiseExec('which node');
|
||||
const commandDir = path.dirname(commandPath);
|
||||
const linkShell = [
|
||||
{
|
||||
src: 'update.sh',
|
||||
dest: 'ql',
|
||||
},
|
||||
{
|
||||
src: 'task.sh',
|
||||
dest: 'task',
|
||||
},
|
||||
];
|
||||
|
||||
for (const link of linkShell) {
|
||||
const source = path.join(config.rootPath, 'shell', link.src);
|
||||
const target = path.join(commandDir, link.dest);
|
||||
if (fs.existsSync(target)) {
|
||||
fs.unlinkSync(target);
|
||||
}
|
||||
fs.symlink(source, target, (err) => {});
|
||||
}
|
||||
}
|
||||
|
||||
export default async (src: string = 'deps') => {
|
||||
await linkCommand();
|
||||
linkToNodeModule(src);
|
||||
|
||||
const source = path.join(config.rootPath, src);
|
||||
|
||||
+20
-52
@@ -1,31 +1,28 @@
|
||||
import express, { Request, Response, NextFunction, Application } from 'express';
|
||||
import { Request, Response, NextFunction, Application } from 'express';
|
||||
import bodyParser from 'body-parser';
|
||||
import cors from 'cors';
|
||||
import routes from '../api';
|
||||
import config from '../config';
|
||||
import jwt, { UnauthorizedError } from 'express-jwt';
|
||||
import jwt from 'express-jwt';
|
||||
import fs from 'fs';
|
||||
import { getPlatform, getToken } from '../config/util';
|
||||
import { getFileContentByName, getPlatform, getToken } from '../config/util';
|
||||
import Container from 'typedi';
|
||||
import OpenService from '../services/open';
|
||||
import rewrite from 'express-urlrewrite';
|
||||
import UserService from '../services/user';
|
||||
import handler from 'serve-handler';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { EnvModel } from '../data/env';
|
||||
import { errors } from 'celebrate';
|
||||
|
||||
export default ({ app }: { app: Application }) => {
|
||||
app.enable('trust proxy');
|
||||
app.use(cors());
|
||||
app.use(`${config.api.prefix}/static`, express.static(config.uploadPath));
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (req.path.startsWith('/api') || req.path.startsWith('/open')) {
|
||||
next();
|
||||
} else {
|
||||
return handler(req, res, {
|
||||
public: 'static/dist',
|
||||
public: 'dist',
|
||||
rewrites: [{ source: '**', destination: '/index.html' }],
|
||||
});
|
||||
}
|
||||
@@ -71,28 +68,32 @@ export default ({ app }: { app: Application }) => {
|
||||
}
|
||||
}
|
||||
|
||||
const originPath = `${req.baseUrl}${req.path === '/' ? '' : req.path}`;
|
||||
if (
|
||||
!headerToken &&
|
||||
originPath &&
|
||||
config.apiWhiteList.includes(originPath)
|
||||
req.path &&
|
||||
config.apiWhiteList.includes(req.path) &&
|
||||
req.path !== '/api/crons/status'
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
const remoteAddress = req.socket.remoteAddress;
|
||||
if (
|
||||
remoteAddress === '::ffff:127.0.0.1' &&
|
||||
req.path === '/api/crons/status'
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
||||
if (data && headerToken) {
|
||||
if (data) {
|
||||
const { token = '', tokens = {} } = JSON.parse(data);
|
||||
if (headerToken === token || tokens[req.platform] === headerToken) {
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
const errorCode = headerToken ? 'invalid_token' : 'credentials_required';
|
||||
const errorMessage = headerToken
|
||||
? 'jwt malformed'
|
||||
: 'No authorization token was found';
|
||||
const err = new UnauthorizedError(errorCode, { message: errorMessage });
|
||||
const err: any = new Error('UnauthorizedError');
|
||||
err.status = 401;
|
||||
next(err);
|
||||
});
|
||||
|
||||
@@ -102,14 +103,14 @@ export default ({ app }: { app: Application }) => {
|
||||
}
|
||||
const userService = Container.get(UserService);
|
||||
const authInfo = await userService.getUserInfo();
|
||||
const envCount = await EnvModel.count();
|
||||
const envDbContent = getFileContentByName(config.envDbFile);
|
||||
|
||||
let isInitialized = true;
|
||||
if (
|
||||
Object.keys(authInfo).length === 2 &&
|
||||
authInfo.username === 'admin' &&
|
||||
authInfo.password === 'admin' &&
|
||||
envCount === 0
|
||||
envDbContent.length === 0
|
||||
) {
|
||||
isInitialized = false;
|
||||
}
|
||||
@@ -130,7 +131,7 @@ export default ({ app }: { app: Application }) => {
|
||||
next(err);
|
||||
});
|
||||
|
||||
app.use(errors());
|
||||
app.use(Sentry.Handlers.errorHandler());
|
||||
|
||||
app.use(
|
||||
(
|
||||
@@ -149,39 +150,6 @@ export default ({ app }: { app: Application }) => {
|
||||
},
|
||||
);
|
||||
|
||||
app.use(
|
||||
(
|
||||
err: Error & { errors: any[] },
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
if (err.name.includes('Sequelize')) {
|
||||
return res
|
||||
.status(500)
|
||||
.send({
|
||||
code: 400,
|
||||
message: `${err.name} ${err.message}`,
|
||||
validation: err.errors,
|
||||
})
|
||||
.end();
|
||||
}
|
||||
return next(err);
|
||||
},
|
||||
);
|
||||
|
||||
app.use(
|
||||
Sentry.Handlers.errorHandler({
|
||||
shouldHandleError(error) {
|
||||
// 排除 SequelizeUniqueConstraintError / NotFound
|
||||
return (
|
||||
!['SequelizeUniqueConstraintError'].includes(error.name) ||
|
||||
!['Not Found'].includes(error.message)
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
app.use(
|
||||
(
|
||||
err: Error & { status: number },
|
||||
|
||||
+24
-69
@@ -7,7 +7,6 @@ import EnvService from '../services/env';
|
||||
import _ from 'lodash';
|
||||
import { DependenceModel } from '../data/dependence';
|
||||
import { Op } from 'sequelize';
|
||||
import config from '../config';
|
||||
|
||||
export default async () => {
|
||||
const cronService = Container.get(CronService);
|
||||
@@ -21,17 +20,16 @@ export default async () => {
|
||||
);
|
||||
|
||||
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
||||
DependenceModel.findAll({
|
||||
where: {},
|
||||
order: [['type', 'DESC']],
|
||||
raw: true,
|
||||
}).then(async (docs) => {
|
||||
DependenceModel.findAll({ where: {} }).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) {
|
||||
for (const key in groups) {
|
||||
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
||||
const group = groups[key];
|
||||
const depIds = group.map((x) => x.id);
|
||||
await dependenceService.reInstall(depIds as number[]);
|
||||
for (const dep of depIds) {
|
||||
await dependenceService.reInstall([dep]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -40,7 +38,7 @@ export default async () => {
|
||||
where: {
|
||||
isDisabled: { [Op.ne]: 1 },
|
||||
command: {
|
||||
[Op.or]: [{ [Op.like]: `%ql repo%` }, { [Op.like]: `%ql raw%` }],
|
||||
[Op.or]: [{ [Op.like]: `%ql repo%` }, { [Op.like]: `%$ql raw%` }],
|
||||
},
|
||||
},
|
||||
}).then((docs) => {
|
||||
@@ -52,66 +50,23 @@ export default async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 更新2.11.3以前的脚本路径
|
||||
CrontabModel.findAll({
|
||||
where: {
|
||||
command: {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%\/${config.rootPath}\/scripts\/%` },
|
||||
{ [Op.like]: `%\/${config.rootPath}\/config\/%` },
|
||||
{ [Op.like]: `%\/${config.rootPath}\/log\/%` },
|
||||
{ [Op.like]: `%\/${config.rootPath}\/db\/%` },
|
||||
],
|
||||
},
|
||||
},
|
||||
}).then(async (docs) => {
|
||||
for (let i = 0; i < docs.length; i++) {
|
||||
const doc = docs[i];
|
||||
if (doc) {
|
||||
if (doc.command.includes(`${config.rootPath}/scripts/`)) {
|
||||
await CrontabModel.update(
|
||||
{ command: doc.command.replace(`${config.rootPath}/scripts/`, '') },
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
if (doc.command.includes(`${config.rootPath}/log/`)) {
|
||||
await CrontabModel.update(
|
||||
{
|
||||
command: `${config.rootPath}/data/log/${doc.command.replace(
|
||||
`${config.rootPath}/log/`,
|
||||
'',
|
||||
)}`,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
if (doc.command.includes(`${config.rootPath}/config/`)) {
|
||||
await CrontabModel.update(
|
||||
{
|
||||
command: `${config.rootPath}/data/config/${doc.command.replace(
|
||||
`${config.rootPath}/config/`,
|
||||
'',
|
||||
)}`,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
if (doc.command.includes(`${config.rootPath}/db/`)) {
|
||||
await CrontabModel.update(
|
||||
{
|
||||
command: `${config.rootPath}/data/db/${doc.command.replace(
|
||||
`${config.rootPath}/db/`,
|
||||
'',
|
||||
)}`,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化保存一次ck和定时任务数据
|
||||
await cronService.autosave_crontab();
|
||||
await envService.set_envs();
|
||||
};
|
||||
|
||||
function randomSchedule(from: number, to: number) {
|
||||
const result: any[] = [];
|
||||
const arr = [...Array(from).keys()];
|
||||
let count = arr.length;
|
||||
for (let i = 0; i < to; i++) {
|
||||
const index = ~~(Math.random() * count) + i;
|
||||
if (result.includes(arr[index])) {
|
||||
continue;
|
||||
}
|
||||
result[i] = arr[index];
|
||||
arr[index] = arr[i];
|
||||
count--;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
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');
|
||||
const rootPath = process.cwd();
|
||||
const confFile = path.join(rootPath, 'config/config.sh');
|
||||
const sampleConfigFile = path.join(rootPath, 'sample/config.sample.sh');
|
||||
const sampleAuthFile = path.join(rootPath, 'sample/auth.sample.json');
|
||||
const authConfigFile = path.join(rootPath, 'config/auth.json');
|
||||
const configPath = path.join(rootPath, 'config/');
|
||||
const scriptPath = path.join(rootPath, 'scripts/');
|
||||
const logPath = path.join(rootPath, 'log/');
|
||||
|
||||
export default async () => {
|
||||
const authFileExist = await fileExist(authConfigFile);
|
||||
@@ -26,9 +19,6 @@ export default async () => {
|
||||
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);
|
||||
@@ -50,18 +40,6 @@ export default async () => {
|
||||
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,54 +0,0 @@
|
||||
import { Container } from 'typedi';
|
||||
import _ from 'lodash';
|
||||
import SystemService from '../services/system';
|
||||
import ScheduleService from '../services/schedule';
|
||||
import SubscriptionService from '../services/subscription';
|
||||
import config from '../config';
|
||||
import { fileExist } from '../config/util';
|
||||
|
||||
export default async () => {
|
||||
const systemService = Container.get(SystemService);
|
||||
const scheduleService = Container.get(ScheduleService);
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
|
||||
// 生成内置token
|
||||
let tokenCommand = `ts-node-transpile-only ${config.rootPath}/back/token.ts`;
|
||||
const tokenFile = `${config.rootPath}/static/build/token.js`;
|
||||
if (await fileExist(tokenFile)) {
|
||||
tokenCommand = `node ${tokenFile}`;
|
||||
}
|
||||
const cron = {
|
||||
id: 'token',
|
||||
name: '生成token',
|
||||
command: tokenCommand,
|
||||
};
|
||||
scheduleService.createIntervalTask(cron as any, {
|
||||
days: 28,
|
||||
runImmediately: true,
|
||||
});
|
||||
|
||||
// 运行删除日志任务
|
||||
const data = await systemService.getLogRemoveFrequency();
|
||||
if (data && data.info && data.info.frequency) {
|
||||
const cron = {
|
||||
id: data.id,
|
||||
name: '删除日志',
|
||||
command: `ql rmlog ${data.info.frequency}`,
|
||||
};
|
||||
scheduleService.createIntervalTask(cron, {
|
||||
days: data.info.frequency,
|
||||
runImmediately: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 运行所有订阅
|
||||
const subs = await subscriptionService.list();
|
||||
for (const sub of subs) {
|
||||
await subscriptionService.handleTask(
|
||||
sub,
|
||||
!sub.is_disabled,
|
||||
true,
|
||||
!sub.is_disabled,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
import express from 'express';
|
||||
import { exec } from 'child_process';
|
||||
import Logger from './loaders/logger';
|
||||
import config from './config';
|
||||
|
||||
const app = express();
|
||||
|
||||
app.get('/api/public/panel/log', (req, res) => {
|
||||
exec(
|
||||
'pm2 logs panel --lines 500 --nostream --timestamp',
|
||||
(err, stdout, stderr) => {
|
||||
if (err || stderr) {
|
||||
return res.send({ code: 400, message: (err && err.message) || stderr });
|
||||
}
|
||||
return res.send({ code: 200, data: stdout });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
app
|
||||
.listen(config.publicPort, async () => {
|
||||
await require('./loaders/sentry').default({ expressApp: app });
|
||||
await require('./loaders/db').default();
|
||||
|
||||
Logger.debug(`✌️ Back server launched on port ${config.publicPort}`);
|
||||
})
|
||||
.on('error', (err) => {
|
||||
Logger.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
+50
-247
@@ -5,12 +5,10 @@ import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import { exec, execSync, spawn } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import cron_parser from 'cron-parser';
|
||||
import { getFileContentByName, concurrentRun, fileExist } from '../config/util';
|
||||
import { getFileContentByName, concurrentRun } from '../config/util';
|
||||
import { promises, existsSync } from 'fs';
|
||||
import { promisify } from 'util';
|
||||
import { Op } from 'sequelize';
|
||||
import path from 'path';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
@Service()
|
||||
export default class CronService {
|
||||
@@ -18,7 +16,7 @@ export default class CronService {
|
||||
|
||||
private isSixCron(cron: Crontab) {
|
||||
const { schedule } = cron;
|
||||
if (schedule?.split(/ +/).length === 6) {
|
||||
if (schedule.split(/ +/).length === 6) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -33,6 +31,12 @@ export default class CronService {
|
||||
}
|
||||
|
||||
public async insert(payload: Crontab): Promise<Crontab> {
|
||||
const cron = await CrontabModel.findOne({
|
||||
where: { command: payload.command },
|
||||
});
|
||||
if (cron) {
|
||||
return cron;
|
||||
}
|
||||
return await CrontabModel.create(payload, { returning: true });
|
||||
}
|
||||
|
||||
@@ -113,69 +117,9 @@ export default class CronService {
|
||||
}
|
||||
}
|
||||
|
||||
private formatViewQuery(query: any, viewQuery: any) {
|
||||
if (viewQuery.filters && viewQuery.filters.length > 0) {
|
||||
if (!query[Op.and]) {
|
||||
query[Op.and] = [];
|
||||
}
|
||||
for (const col of viewQuery.filters) {
|
||||
const { property, value, operation } = col;
|
||||
let q: any = {};
|
||||
let operate2 = null;
|
||||
let operate = null;
|
||||
switch (operation) {
|
||||
case 'Reg':
|
||||
operate = Op.like;
|
||||
operate2 = Op.or;
|
||||
break;
|
||||
case 'NotReg':
|
||||
operate = Op.notLike;
|
||||
operate2 = Op.and;
|
||||
break;
|
||||
case 'In':
|
||||
q[Op.or] = [
|
||||
{
|
||||
[property]: value,
|
||||
},
|
||||
property === 'status' && value.includes(2)
|
||||
? { isDisabled: 1 }
|
||||
: {},
|
||||
];
|
||||
break;
|
||||
case 'Nin':
|
||||
q[Op.and] = [
|
||||
{
|
||||
[property]: {
|
||||
[Op.notIn]: value,
|
||||
},
|
||||
},
|
||||
property === 'status' && value.includes(2)
|
||||
? { isDisabled: { [Op.ne]: 1 } }
|
||||
: {},
|
||||
];
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (operate && operate2) {
|
||||
q[property] = {
|
||||
[operate2]: [
|
||||
{ [operate]: `%${value}%` },
|
||||
{ [operate]: `%${encodeURIComponent(value)}%` },
|
||||
],
|
||||
};
|
||||
}
|
||||
query[Op.and].push(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private formatSearchText(query: any, searchText: string | undefined) {
|
||||
public async crontabs(searchText?: string): Promise<Crontab[]> {
|
||||
let query = {};
|
||||
if (searchText) {
|
||||
if (!query[Op.and]) {
|
||||
query[Op.and] = [];
|
||||
}
|
||||
let q: any = {};
|
||||
const textArray = searchText.split(':');
|
||||
switch (textArray[0]) {
|
||||
case 'name':
|
||||
@@ -183,11 +127,13 @@ export default class CronService {
|
||||
case 'schedule':
|
||||
case 'label':
|
||||
const column = textArray[0] === 'label' ? 'labels' : textArray[0];
|
||||
q[column] = {
|
||||
query = {
|
||||
[column]: {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${textArray[1]}%` },
|
||||
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
|
||||
],
|
||||
},
|
||||
};
|
||||
break;
|
||||
default:
|
||||
@@ -197,7 +143,8 @@ export default class CronService {
|
||||
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
||||
],
|
||||
};
|
||||
q[Op.or] = [
|
||||
query = {
|
||||
[Op.or]: [
|
||||
{
|
||||
name: reg,
|
||||
},
|
||||
@@ -210,83 +157,17 @@ export default class CronService {
|
||||
{
|
||||
labels: reg,
|
||||
},
|
||||
];
|
||||
],
|
||||
};
|
||||
break;
|
||||
}
|
||||
query[Op.and].push(q);
|
||||
}
|
||||
}
|
||||
|
||||
private formatFilterQuery(query: any, filterQuery: any) {
|
||||
if (filterQuery) {
|
||||
if (!query[Op.and]) {
|
||||
query[Op.and] = [];
|
||||
}
|
||||
const filterKeys: any = Object.keys(filterQuery);
|
||||
for (const key of filterKeys) {
|
||||
let q: any = {};
|
||||
if (filterKeys[key]) {
|
||||
q[key] = filterKeys[key];
|
||||
}
|
||||
query[Op.and].push(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private formatViewSort(order: string[][], viewQuery: any) {
|
||||
if (viewQuery.sorts && viewQuery.sorts.length > 0) {
|
||||
for (const { property, type } of viewQuery.sorts) {
|
||||
order.unshift([property, type]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async crontabs(params?: {
|
||||
searchValue: string;
|
||||
page: string;
|
||||
size: string;
|
||||
sorter: string;
|
||||
filters: string;
|
||||
queryString: string;
|
||||
}): Promise<{ data: Crontab[]; total: number }> {
|
||||
const searchText = params?.searchValue;
|
||||
const page = Number(params?.page || '0');
|
||||
const size = Number(params?.size || '0');
|
||||
const viewQuery = JSON.parse(params?.queryString || '{}');
|
||||
const filterQuery = JSON.parse(params?.filters || '{}');
|
||||
const sorterQuery = JSON.parse(params?.sorter || '{}');
|
||||
|
||||
let query: any = {};
|
||||
let order = [
|
||||
['isPinned', 'DESC'],
|
||||
['isDisabled', 'ASC'],
|
||||
['status', 'ASC'],
|
||||
['createdAt', 'DESC'],
|
||||
];
|
||||
|
||||
this.formatViewQuery(query, viewQuery);
|
||||
this.formatSearchText(query, searchText);
|
||||
this.formatFilterQuery(query, filterQuery);
|
||||
this.formatViewSort(order, viewQuery);
|
||||
|
||||
if (sorterQuery) {
|
||||
const { field, type } = sorterQuery;
|
||||
if (field && type) {
|
||||
order.unshift([field, type]);
|
||||
}
|
||||
}
|
||||
let condition: any = {
|
||||
where: query,
|
||||
order: order,
|
||||
};
|
||||
if (page && size) {
|
||||
condition.offset = (page - 1) * size;
|
||||
condition.limit = size;
|
||||
}
|
||||
try {
|
||||
const result = await CrontabModel.findAll(condition);
|
||||
const count = await CrontabModel.count({ where: query });
|
||||
return { data: result, total: count };
|
||||
const result = await CrontabModel.findAll({
|
||||
where: query,
|
||||
order: [['updatedAt', 'DESC']],
|
||||
});
|
||||
return result as any;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
@@ -319,23 +200,13 @@ export default class CronService {
|
||||
}
|
||||
}
|
||||
const err = await this.killTask(doc.command);
|
||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||
|
||||
const endTime = dayjs();
|
||||
const diffTimeStr = doc.last_execution_time
|
||||
? `,耗时 ${endTime.diff(
|
||||
dayjs(doc.last_execution_time * 1000),
|
||||
'second',
|
||||
)}`
|
||||
: '';
|
||||
if (logFileExist) {
|
||||
if (doc.log_path) {
|
||||
const str = err ? `\n${err}` : '';
|
||||
fs.appendFileSync(
|
||||
`${absolutePath}`,
|
||||
`${str}\n## 执行结束... ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)}${diffTimeStr}`,
|
||||
`${doc.log_path}`,
|
||||
`${str}\n## 执行结束... ${new Date()
|
||||
.toLocaleString('zh', { hour12: false })
|
||||
.replace(' 24:', ' 00:')} `,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -363,7 +234,6 @@ export default class CronService {
|
||||
pids = pids.slice(0, 3);
|
||||
for (const id of pids) {
|
||||
const c = `kill -9 ${id.slice(1)}`;
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync(c);
|
||||
if (stderr) {
|
||||
killLogs.push(stderr);
|
||||
@@ -371,9 +241,6 @@ export default class CronService {
|
||||
if (stdout) {
|
||||
killLogs.push(stdout);
|
||||
}
|
||||
} catch (error: any) {
|
||||
killLogs.push(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return killLogs.length > 0 ? JSON.stringify(killLogs) : '';
|
||||
@@ -391,8 +258,6 @@ export default class CronService {
|
||||
}
|
||||
|
||||
let { id, command, log_path } = cron;
|
||||
const absolutePath = path.resolve(config.logPath, `${log_path}`);
|
||||
const logFileExist = log_path && (await fileExist(absolutePath));
|
||||
|
||||
this.logger.silly('Running job');
|
||||
this.logger.silly('ID: ' + id);
|
||||
@@ -402,13 +267,7 @@ export default class CronService {
|
||||
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')
|
||||
) {
|
||||
if (cmdStr.endsWith('.js')) {
|
||||
cmdStr = `${cmdStr} now`;
|
||||
}
|
||||
|
||||
@@ -419,22 +278,28 @@ export default class CronService {
|
||||
{ where: { id } },
|
||||
);
|
||||
cp.stderr.on('data', (data) => {
|
||||
if (logFileExist) {
|
||||
fs.appendFileSync(`${absolutePath}`, `${data}`);
|
||||
if (log_path) {
|
||||
fs.appendFileSync(`${log_path}`, `${data}`);
|
||||
}
|
||||
});
|
||||
cp.on('error', (err) => {
|
||||
if (logFileExist) {
|
||||
fs.appendFileSync(`${absolutePath}`, `${JSON.stringify(err)}`);
|
||||
if (log_path) {
|
||||
fs.appendFileSync(`${log_path}`, `${JSON.stringify(err)}`);
|
||||
}
|
||||
});
|
||||
|
||||
cp.on('exit', async (code, signal) => {
|
||||
this.logger.info(
|
||||
`任务 ${command} 进程id: ${cp.pid} 退出,退出码 ${code}`,
|
||||
`${command} pid: ${cp.pid} exit ${code} signal ${signal}`,
|
||||
);
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id } },
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
cp.on('close', async (code) => {
|
||||
this.logger.info(`${command} pid: ${cp.pid} closed ${code}`);
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id } },
|
||||
@@ -460,10 +325,8 @@ export default class CronService {
|
||||
return '';
|
||||
}
|
||||
|
||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||
if (logFileExist) {
|
||||
return getFileContentByName(`${absolutePath}`);
|
||||
if (doc.log_path) {
|
||||
return getFileContentByName(`${doc.log_path}`);
|
||||
}
|
||||
const [, commandStr, url] = doc.command.split(/ +/);
|
||||
let logPath = this.getKey(commandStr);
|
||||
@@ -486,75 +349,15 @@ export default class CronService {
|
||||
}
|
||||
}
|
||||
|
||||
public async logs(id: number) {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (doc.log_path) {
|
||||
const relativeDir = path.dirname(`${doc.log_path}`);
|
||||
const dir = path.resolve(config.logPath, relativeDir);
|
||||
if (existsSync(dir)) {
|
||||
let files = await promises.readdir(dir);
|
||||
return files
|
||||
.map((x) => ({
|
||||
filename: x,
|
||||
directory: relativeDir.replace(config.logPath, ''),
|
||||
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
||||
}))
|
||||
.sort((a, b) => b.time - a.time);
|
||||
}
|
||||
}
|
||||
|
||||
const [, commandStr, url] = doc.command.split(/ +/);
|
||||
let logPath = this.getKey(commandStr);
|
||||
const isQlCommand = doc.command.startsWith('ql ');
|
||||
const key =
|
||||
(url && ['repo', 'raw'].includes(commandStr) && this.getKey(url)) ||
|
||||
logPath;
|
||||
if (isQlCommand) {
|
||||
logPath = 'update';
|
||||
}
|
||||
let logDir = `${config.logPath}${logPath}`;
|
||||
if (existsSync(logDir)) {
|
||||
let files = await promises.readdir(logDir);
|
||||
if (isQlCommand) {
|
||||
files = files.filter((x) => x.includes(key));
|
||||
}
|
||||
return files
|
||||
.map((x) => ({
|
||||
filename: x,
|
||||
directory: logPath,
|
||||
time: fs.statSync(`${logDir}/${x}`).mtime.getTime(),
|
||||
}))
|
||||
.sort((a, b) => b.time - a.time);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private getKey(command: string): string {
|
||||
private getKey(command: string) {
|
||||
const start =
|
||||
command.lastIndexOf('/') !== -1 ? command.lastIndexOf('/') + 1 : 0;
|
||||
const end =
|
||||
command.lastIndexOf('.') !== -1
|
||||
? command.lastIndexOf('.')
|
||||
: command.length;
|
||||
|
||||
const tmpStr = command.substring(0, start - 1);
|
||||
let index = 0;
|
||||
if (tmpStr.lastIndexOf('/') !== -1 && tmpStr.startsWith('http')) {
|
||||
index = tmpStr.lastIndexOf('/');
|
||||
} else if (tmpStr.lastIndexOf(':') !== -1 && tmpStr.startsWith('git@')) {
|
||||
index = tmpStr.lastIndexOf(':');
|
||||
}
|
||||
if (index) {
|
||||
return `${tmpStr.substring(index + 1)}_${command.substring(start, end)}`;
|
||||
} else {
|
||||
return command.substring(start, end);
|
||||
}
|
||||
}
|
||||
|
||||
private make_command(tab: Crontab) {
|
||||
const crontab_job_string = `ID=${tab.id} ${tab.command}`;
|
||||
@@ -564,9 +367,9 @@ export default class CronService {
|
||||
private async set_crontab(needReloadSchedule: boolean = false) {
|
||||
const tabs = await this.crontabs();
|
||||
var crontab_string = '';
|
||||
tabs.data.forEach((tab) => {
|
||||
tabs.forEach((tab) => {
|
||||
const _schedule = tab.schedule && tab.schedule.split(/ +/);
|
||||
if (tab.isDisabled === 1 || _schedule!.length !== 5) {
|
||||
if (tab.isDisabled === 1 || _schedule.length !== 5) {
|
||||
crontab_string += '# ';
|
||||
crontab_string += tab.schedule;
|
||||
crontab_string += ' ';
|
||||
@@ -592,22 +395,22 @@ export default class CronService {
|
||||
|
||||
public import_crontab() {
|
||||
exec('crontab -l', (error, stdout, stderr) => {
|
||||
const lines = stdout.split('\n');
|
||||
const namePrefix = new Date().getTime();
|
||||
var lines = stdout.split('\n');
|
||||
var namePrefix = new Date().getTime();
|
||||
|
||||
lines.reverse().forEach(async (line, index) => {
|
||||
line = line.replace(/\t+/g, ' ');
|
||||
const regex =
|
||||
var regex =
|
||||
/^((\@[a-zA-Z]+\s+)|(([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+))/;
|
||||
const command = line.replace(regex, '').trim();
|
||||
const schedule = line.replace(command, '').trim();
|
||||
var command = line.replace(regex, '').trim();
|
||||
var schedule = line.replace(command, '').trim();
|
||||
|
||||
if (
|
||||
command &&
|
||||
schedule &&
|
||||
cron_parser.parseExpression(schedule).hasNext()
|
||||
) {
|
||||
const name = namePrefix + '_' + index;
|
||||
var name = namePrefix + '_' + index;
|
||||
|
||||
const _crontab = await CrontabModel.findOne({
|
||||
where: { command, schedule },
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { CrontabView, CrontabViewModel } from '../data/cronView';
|
||||
import { initEnvPosition } from '../data/env';
|
||||
|
||||
@Service()
|
||||
export default class CronViewService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public async create(payload: CrontabView): Promise<CrontabView> {
|
||||
let position = initEnvPosition;
|
||||
const views = await this.list();
|
||||
if (views && views.length > 0 && views[views.length - 1].position) {
|
||||
position = views[views.length - 1].position as number;
|
||||
}
|
||||
position = position / 2;
|
||||
const tab = new CrontabView({ ...payload, position });
|
||||
const doc = await this.insert(tab);
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async insert(payload: CrontabView): Promise<CrontabView> {
|
||||
return await CrontabViewModel.create(payload, { returning: true });
|
||||
}
|
||||
|
||||
public async update(payload: CrontabView): Promise<CrontabView> {
|
||||
const newDoc = await this.updateDb(payload);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
public async updateDb(payload: CrontabView): Promise<CrontabView> {
|
||||
await CrontabViewModel.update(payload, { where: { id: payload.id } });
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
await CrontabViewModel.destroy({ where: { id: ids } });
|
||||
}
|
||||
|
||||
public async list(): Promise<CrontabView[]> {
|
||||
try {
|
||||
const result = await CrontabViewModel.findAll({
|
||||
where: {},
|
||||
order: [['position', 'DESC']],
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async getDb(query: any): Promise<CrontabView> {
|
||||
const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
|
||||
return doc && (doc.get({ plain: true }) as CrontabView);
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await CrontabViewModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await CrontabViewModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async move({
|
||||
id,
|
||||
fromIndex,
|
||||
toIndex,
|
||||
}: {
|
||||
fromIndex: number;
|
||||
toIndex: number;
|
||||
id: number;
|
||||
}): Promise<CrontabView> {
|
||||
let targetPosition: number;
|
||||
const isUpward = fromIndex > toIndex;
|
||||
const views = await this.list();
|
||||
if (toIndex === 0 || toIndex === views.length - 1) {
|
||||
targetPosition = isUpward
|
||||
? views[0].position * 2
|
||||
: views[toIndex].position / 2;
|
||||
} else {
|
||||
targetPosition = isUpward
|
||||
? (views[toIndex].position + views[toIndex - 1].position) / 2
|
||||
: (views[toIndex].position + views[toIndex + 1].position) / 2;
|
||||
}
|
||||
const newDoc = await this.update({
|
||||
id,
|
||||
position: targetPosition,
|
||||
});
|
||||
return newDoc;
|
||||
}
|
||||
}
|
||||
+36
-49
@@ -13,8 +13,6 @@ import _ from 'lodash';
|
||||
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 {
|
||||
@@ -29,7 +27,7 @@ export default class DependenceService {
|
||||
return tab;
|
||||
});
|
||||
const docs = await this.insert(tabs);
|
||||
this.installDependenceOneByOne(docs);
|
||||
this.installOrUninstallDependencies(docs);
|
||||
return docs;
|
||||
}
|
||||
|
||||
@@ -49,7 +47,7 @@ export default class DependenceService {
|
||||
status: DependenceStatus.installing,
|
||||
});
|
||||
const newDoc = await this.updateDb(tab);
|
||||
this.installDependenceOneByOne([newDoc]);
|
||||
this.installOrUninstallDependencies([newDoc]);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
@@ -58,13 +56,13 @@ export default class DependenceService {
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
||||
public async remove(ids: number[]) {
|
||||
await DependenceModel.update(
|
||||
{ status: DependenceStatus.removing, log: [] },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
this.installDependenceOneByOne(docs, false, force);
|
||||
this.installOrUninstallDependencies(docs, false);
|
||||
return docs;
|
||||
}
|
||||
|
||||
@@ -82,7 +80,7 @@ export default class DependenceService {
|
||||
const encodeText = encodeURIComponent(searchValue);
|
||||
const reg = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchValue}%` },
|
||||
{ [Op.like]: `%${searchValue}&` },
|
||||
{ [Op.like]: `%${encodeText}%` },
|
||||
],
|
||||
};
|
||||
@@ -100,20 +98,6 @@ export default class DependenceService {
|
||||
}
|
||||
}
|
||||
|
||||
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: [] },
|
||||
@@ -121,7 +105,7 @@ export default class DependenceService {
|
||||
);
|
||||
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
this.installDependenceOneByOne(docs);
|
||||
await this.installOrUninstallDependencies(docs);
|
||||
return docs;
|
||||
}
|
||||
|
||||
@@ -144,16 +128,12 @@ export default class DependenceService {
|
||||
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
|
||||
@@ -162,23 +142,24 @@ export default class DependenceService {
|
||||
)[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`;
|
||||
const cp = spawn(`${depRunCommand} ${depNames}`, { shell: '/bin/bash' });
|
||||
const startTime = Date.now();
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
message,
|
||||
type: 'installDependence',
|
||||
message: `开始${actionText}依赖 ${depNames},开始时间 ${new Date(
|
||||
startTime,
|
||||
).toLocaleString()}`,
|
||||
references: depIds,
|
||||
});
|
||||
await this.updateLog(depIds, message);
|
||||
|
||||
const cp = spawn(`${depRunCommand} ${depNames}`, { shell: '/bin/bash' });
|
||||
|
||||
await this.updateLog(
|
||||
depIds,
|
||||
`开始${actionText}依赖 ${depNames},开始时间 ${new Date(
|
||||
startTime,
|
||||
).toLocaleString()}\n`,
|
||||
);
|
||||
cp.stdout.on('data', async (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
type: 'installDependence',
|
||||
message: data.toString(),
|
||||
references: depIds,
|
||||
});
|
||||
@@ -187,7 +168,7 @@ export default class DependenceService {
|
||||
|
||||
cp.stderr.on('data', async (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
type: 'installDependence',
|
||||
message: data.toString(),
|
||||
references: depIds,
|
||||
});
|
||||
@@ -196,7 +177,7 @@ export default class DependenceService {
|
||||
|
||||
cp.on('error', async (err) => {
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
type: 'installDependence',
|
||||
message: JSON.stringify(err),
|
||||
references: depIds,
|
||||
});
|
||||
@@ -205,19 +186,23 @@ export default class DependenceService {
|
||||
});
|
||||
|
||||
cp.on('close', async (code) => {
|
||||
const endTime = dayjs();
|
||||
const endTime = Date.now();
|
||||
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,
|
||||
type: 'installDependence',
|
||||
message: `依赖${actionText}${resultText},结束时间 ${new Date(
|
||||
endTime,
|
||||
).toLocaleString()},耗时 ${(endTime - startTime) / 1000} 秒`,
|
||||
references: depIds,
|
||||
});
|
||||
await this.updateLog(depIds, message);
|
||||
await this.updateLog(
|
||||
depIds,
|
||||
`依赖${actionText}${resultText},结束时间 ${new Date(
|
||||
endTime,
|
||||
).toLocaleString()},耗时 ${(endTime - startTime) / 1000} 秒`,
|
||||
);
|
||||
|
||||
let status = null;
|
||||
if (isSucceed) {
|
||||
@@ -231,9 +216,11 @@ export default class DependenceService {
|
||||
}
|
||||
await DependenceModel.update({ status }, { where: { id: depIds } });
|
||||
|
||||
// 如果删除依赖成功或者强制删除
|
||||
if ((isSucceed || force) && !isInstall) {
|
||||
// 如果删除依赖成功,3秒后删除数据库记录
|
||||
if (isSucceed && !isInstall) {
|
||||
setTimeout(() => {
|
||||
this.removeDb(depIds);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
resolve(null);
|
||||
|
||||
+9
-12
@@ -28,12 +28,8 @@ export default class EnvService {
|
||||
}
|
||||
|
||||
public async insert(payloads: Env[]): Promise<Env[]> {
|
||||
const result = [];
|
||||
for (const env of payloads) {
|
||||
const doc = await EnvModel.create(env, { returning: true });
|
||||
result.push(doc);
|
||||
}
|
||||
return result;
|
||||
const docs = await EnvModel.bulkCreate(payloads);
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async update(payload: Env): Promise<Env> {
|
||||
@@ -49,7 +45,6 @@ export default class EnvService {
|
||||
|
||||
public async remove(ids: string[]) {
|
||||
await EnvModel.destroy({ where: { id: ids } });
|
||||
await this.set_envs();
|
||||
}
|
||||
|
||||
public async move(
|
||||
@@ -168,11 +163,13 @@ export default class EnvService {
|
||||
.filter((x) => x.status !== EnvStatus.disabled)
|
||||
.map('value')
|
||||
.join('&')
|
||||
.replace(/(\\)[^n]/g, '\\\\')
|
||||
.replace(/(\\$)/, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.trim();
|
||||
env_string += `export ${key}="${value}"\n`;
|
||||
.replace(/ /g, '');
|
||||
if (/"/.test(value)) {
|
||||
value = `'${value}'`;
|
||||
} else {
|
||||
value = `"${value}"`;
|
||||
}
|
||||
env_string += `export ${key}=${value}\n`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-41
@@ -16,8 +16,6 @@ export default class NotificationService {
|
||||
['gotify', this.gotify],
|
||||
['goCqHttpBot', this.goCqHttpBot],
|
||||
['serverChan', this.serverChan],
|
||||
['pushDeer', this.pushDeer],
|
||||
['chat', this.chat],
|
||||
['bark', this.bark],
|
||||
['telegramBot', this.telegramBot],
|
||||
['dingtalkBot', this.dingtalkBot],
|
||||
@@ -92,12 +90,14 @@ export default class NotificationService {
|
||||
private async goCqHttpBot() {
|
||||
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
|
||||
const res: any = await got
|
||||
.post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, {
|
||||
.post(
|
||||
`${goCqHttpBotUrl}?access_token=${goCqHttpBotToken}&${goCqHttpBotQq}`,
|
||||
{
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
json: { message: `${this.title}\n${this.content}` },
|
||||
headers: { Authorization: 'Bearer ' + goCqHttpBotToken },
|
||||
})
|
||||
},
|
||||
)
|
||||
.json();
|
||||
return res.retcode === 0;
|
||||
}
|
||||
@@ -118,40 +118,8 @@ export default class NotificationService {
|
||||
return res.errno === 0 || res.data.errno === 0;
|
||||
}
|
||||
|
||||
private async pushDeer() {
|
||||
const { pushDeerKey } = this.params;
|
||||
const url = `https://api2.pushdeer.com/message/push`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
body: `pushkey=${pushDeerKey}&text=${encodeURIComponent(
|
||||
this.title,
|
||||
)}&desp=${encodeURIComponent(this.content)}&type=markdown`,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
.json();
|
||||
return (
|
||||
res.content.result.length !== undefined && res.content.result.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private async chat() {
|
||||
const { chatUrl, chatToken } = this.params;
|
||||
const url = `${chatUrl}${chatToken}`;
|
||||
const res: any = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
body: `payload={"text":"${this.title}\n${this.content}"}`,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
.json();
|
||||
return res.success;
|
||||
}
|
||||
|
||||
private async bark() {
|
||||
let { barkPush, barkIcon, barkSound, barkGroup } = this.params;
|
||||
let { barkPush, barkSound, barkGroup } = this.params;
|
||||
if (!barkPush.startsWith('http') && !barkPush.startsWith('https')) {
|
||||
barkPush = `https://api.day.app/${barkPush}`;
|
||||
}
|
||||
@@ -159,7 +127,7 @@ export default class NotificationService {
|
||||
this.title,
|
||||
)}/${encodeURIComponent(
|
||||
this.content,
|
||||
)}?icon=${barkIcon}?sound=${barkSound}&group=${barkGroup}`;
|
||||
)}?sound=${barkSound}&group=${barkGroup}`;
|
||||
const res: any = await got
|
||||
.get(url, {
|
||||
timeout: this.timeout,
|
||||
@@ -260,7 +228,7 @@ export default class NotificationService {
|
||||
const [corpid, corpsecret, touser, agentid, thumb_media_id = '1'] =
|
||||
weWorkAppKey.split(',');
|
||||
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken`;
|
||||
const tokenRes: any = await got
|
||||
const { access_token } = await got
|
||||
.post(url, {
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
@@ -311,7 +279,7 @@ export default class NotificationService {
|
||||
|
||||
const res: any = await got
|
||||
.post(
|
||||
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${tokenRes.access_token}`,
|
||||
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`,
|
||||
{
|
||||
timeout: this.timeout,
|
||||
retry: 0,
|
||||
|
||||
+5
-44
@@ -24,8 +24,8 @@ export default class OpenService {
|
||||
return { ...doc, tokens: [] };
|
||||
}
|
||||
|
||||
public async insert(payload: App): Promise<App> {
|
||||
const doc = await AppModel.create(payload, { returning: true });
|
||||
public async insert(payloads: App): Promise<App> {
|
||||
const doc = await AppModel.create(payloads, { returning: true });
|
||||
return doc.get({ plain: true }) as App;
|
||||
}
|
||||
|
||||
@@ -90,9 +90,7 @@ export default class OpenService {
|
||||
}
|
||||
try {
|
||||
const result = await this.find(condition);
|
||||
return result
|
||||
.filter((x) => x.name !== 'system')
|
||||
.map((x) => ({ ...x, tokens: [] }));
|
||||
return result.map((x) => ({ ...x, tokens: [] }));
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
@@ -110,26 +108,12 @@ export default class OpenService {
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
}): Promise<any> {
|
||||
let token = uuidV4();
|
||||
const token = uuidV4();
|
||||
const expiration = Math.round(Date.now() / 1000) + 2592000; // 2592000 30天
|
||||
const doc = await AppModel.findOne({ where: { client_id, client_secret } });
|
||||
if (doc) {
|
||||
const timestamp = Math.round(Date.now() / 1000);
|
||||
const invalidTokens = (doc.tokens || []).filter(
|
||||
(x) => x.expiration >= timestamp,
|
||||
);
|
||||
let tokens = invalidTokens;
|
||||
if (invalidTokens.length > 5) {
|
||||
tokens = [
|
||||
...invalidTokens.slice(0, 4),
|
||||
{ ...invalidTokens[4], expiration },
|
||||
];
|
||||
token = invalidTokens[4].value;
|
||||
} else {
|
||||
tokens = [...invalidTokens, { value: token, expiration }];
|
||||
}
|
||||
await AppModel.update(
|
||||
{ tokens },
|
||||
{ tokens: [...(doc.tokens || []), { value: token, expiration }] },
|
||||
{ where: { client_id, client_secret } },
|
||||
);
|
||||
return {
|
||||
@@ -144,27 +128,4 @@ export default class OpenService {
|
||||
return { code: 400, message: 'client_id或client_seret有误' };
|
||||
}
|
||||
}
|
||||
|
||||
public async generateSystemToken(): Promise<{
|
||||
value: string;
|
||||
expiration: number;
|
||||
}> {
|
||||
let systemApp = (await AppModel.findOne({
|
||||
where: { name: 'system' },
|
||||
})) as App;
|
||||
if (!systemApp) {
|
||||
systemApp = await this.create({
|
||||
name: 'system',
|
||||
scopes: ['crons', 'system'],
|
||||
} as App);
|
||||
}
|
||||
const { data } = await this.authToken({
|
||||
client_id: systemApp.client_id,
|
||||
client_secret: systemApp.client_secret,
|
||||
});
|
||||
return {
|
||||
...data,
|
||||
value: data.token,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+36
-166
@@ -1,192 +1,62 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import nodeSchedule from 'node-schedule';
|
||||
import { ChildProcessWithoutNullStreams, exec, spawn } from 'child_process';
|
||||
import {
|
||||
ToadScheduler,
|
||||
LongIntervalJob,
|
||||
AsyncTask,
|
||||
SimpleIntervalSchedule,
|
||||
} from 'toad-scheduler';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
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>;
|
||||
}
|
||||
import { Crontab } from '../data/cron';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
@Service()
|
||||
export default class ScheduleService {
|
||||
private scheduleStacks = new Map<string, nodeSchedule.Job>();
|
||||
|
||||
private intervalSchedule = new ToadScheduler();
|
||||
|
||||
private maxBuffer = 200 * 1024 * 1024;
|
||||
private scheduleStacks = new Map<number, nodeSchedule.Job>();
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
async runTask(command: string, callbacks: TaskCallbacks = {}) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const startTime = dayjs();
|
||||
await callbacks.onBefore?.(startTime);
|
||||
|
||||
const cp = spawn(command, { shell: '/bin/bash' });
|
||||
|
||||
// TODO:
|
||||
callbacks.onStart?.(cp, startTime);
|
||||
|
||||
cp.stdout.on('data', async (data) => {
|
||||
await callbacks.onLog?.(data.toString());
|
||||
});
|
||||
|
||||
cp.stderr.on('data', async (data) => {
|
||||
this.logger.error(
|
||||
'执行任务 %s 失败,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
data.toString(),
|
||||
);
|
||||
await callbacks.onError?.(data.toString());
|
||||
});
|
||||
|
||||
cp.on('error', async (err) => {
|
||||
this.logger.error(
|
||||
'创建任务 %s 失败,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
err,
|
||||
);
|
||||
await callbacks.onError?.(JSON.stringify(err));
|
||||
});
|
||||
|
||||
cp.on('exit', async (code, signal) => {
|
||||
async generateSchedule({ id = 0, command, name, schedule }: Crontab) {
|
||||
this.logger.info(
|
||||
`任务 ${command} 进程id: ${cp.pid} 退出,退出码 ${code}`,
|
||||
);
|
||||
});
|
||||
|
||||
cp.on('close', async (code) => {
|
||||
const endTime = dayjs();
|
||||
await callbacks.onEnd?.(
|
||||
cp,
|
||||
endTime,
|
||||
endTime.diff(startTime, 'seconds'),
|
||||
);
|
||||
resolve(null);
|
||||
});
|
||||
} catch (error) {
|
||||
await this.logger.error(
|
||||
'执行任务%s失败,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
error,
|
||||
);
|
||||
await callbacks.onError?.(JSON.stringify(error));
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async createCronTask(
|
||||
{ id = 0, command, name, schedule = '' }: ScheduleTaskType,
|
||||
callbacks?: TaskCallbacks,
|
||||
runImmediately = false,
|
||||
) {
|
||||
const _id = this.formatId(id);
|
||||
this.logger.info(
|
||||
'[创建cron任务],任务ID: %s,cron: %s,任务名: %s,执行命令: %s',
|
||||
_id,
|
||||
'[创建定时任务],任务ID: %s,cron: %s,任务名: %s,执行命令: %s',
|
||||
id,
|
||||
schedule,
|
||||
name,
|
||||
command,
|
||||
);
|
||||
|
||||
this.scheduleStacks.set(
|
||||
_id,
|
||||
nodeSchedule.scheduleJob(_id, schedule, async () => {
|
||||
await this.runTask(command, callbacks);
|
||||
}),
|
||||
);
|
||||
|
||||
if (runImmediately) {
|
||||
await this.runTask(command, callbacks);
|
||||
}
|
||||
}
|
||||
|
||||
async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
|
||||
const _id = this.formatId(id);
|
||||
this.logger.info('[取消定时任务],任务名:%s', name);
|
||||
this.scheduleStacks.has(_id) && this.scheduleStacks.get(_id)?.cancel();
|
||||
}
|
||||
|
||||
async createIntervalTask(
|
||||
{ id = 0, command, name = '' }: ScheduleTaskType,
|
||||
schedule: SimpleIntervalSchedule,
|
||||
runImmediately = true,
|
||||
callbacks?: TaskCallbacks,
|
||||
) {
|
||||
const _id = this.formatId(id);
|
||||
this.logger.info(
|
||||
'[创建interval任务],任务ID: %s,任务名: %s,执行命令: %s',
|
||||
_id,
|
||||
name,
|
||||
command,
|
||||
);
|
||||
const task = new AsyncTask(
|
||||
name,
|
||||
async () => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
await this.runTask(command, callbacks);
|
||||
});
|
||||
},
|
||||
(err) => {
|
||||
this.logger.error(
|
||||
id,
|
||||
nodeSchedule.scheduleJob(id + '', schedule, async () => {
|
||||
try {
|
||||
exec(command, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
await this.logger.info(
|
||||
'执行任务%s失败,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
err,
|
||||
error,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const job = new LongIntervalJob(
|
||||
{ runImmediately: false, ...schedule },
|
||||
task,
|
||||
_id,
|
||||
);
|
||||
|
||||
this.intervalSchedule.addIntervalJob(job);
|
||||
|
||||
if (runImmediately) {
|
||||
await this.runTask(command, callbacks);
|
||||
}
|
||||
}
|
||||
|
||||
async cancelIntervalTask({ id = 0, name }: ScheduleTaskType) {
|
||||
const _id = this.formatId(id);
|
||||
this.logger.info('[取消interval任务],任务ID: %s,任务名:%s', _id, name);
|
||||
this.intervalSchedule.removeById(_id);
|
||||
if (stderr) {
|
||||
await this.logger.info(
|
||||
'执行任务%s失败,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
stderr,
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
await this.logger.info(
|
||||
'执行任务%s失败,时间:%s, 错误信息:%j',
|
||||
command,
|
||||
new Date().toLocaleString(),
|
||||
error,
|
||||
);
|
||||
} finally {
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private formatId(id: number): string {
|
||||
return String(id);
|
||||
async cancelSchedule({ id = 0, name }: Crontab) {
|
||||
this.logger.info('[取消定时任务],任务名:%s', name);
|
||||
this.scheduleStacks.has(id) && this.scheduleStacks.get(id)?.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
+32
-34
@@ -1,11 +1,8 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { spawn } from 'child_process';
|
||||
import SockService from './sock';
|
||||
import CronService from './cron';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import config from '../config';
|
||||
|
||||
@Service()
|
||||
export default class ScriptService {
|
||||
@@ -13,43 +10,44 @@ export default class ScriptService {
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
private sockService: SockService,
|
||||
private cronService: CronService,
|
||||
private scheduleService: ScheduleService,
|
||||
) {}
|
||||
|
||||
private taskCallbacks(filePath: string): TaskCallbacks {
|
||||
return {
|
||||
onEnd: async (cp, endTime, diff) => {
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
} catch (error) {}
|
||||
},
|
||||
onError: async (message: string) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message,
|
||||
});
|
||||
},
|
||||
onLog: async (message: string) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
public async runScript(path: string) {
|
||||
const cp = spawn(`task -l ${path} now`, { shell: '/bin/bash' });
|
||||
|
||||
public async runScript(filePath: string) {
|
||||
const relativePath = path.relative(config.scriptPath, filePath);
|
||||
const command = `task -l ${relativePath} now`;
|
||||
this.scheduleService.runTask(command, this.taskCallbacks(filePath));
|
||||
cp.stdout.on('data', (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message: data.toString(),
|
||||
});
|
||||
});
|
||||
|
||||
cp.stderr.on('data', (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message: data.toString(),
|
||||
});
|
||||
});
|
||||
|
||||
cp.on('error', (err) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message: JSON.stringify(err),
|
||||
});
|
||||
});
|
||||
|
||||
cp.on('close', (err) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
message: `执行结束`,
|
||||
});
|
||||
});
|
||||
|
||||
return { code: 200 };
|
||||
}
|
||||
|
||||
public async stopScript(filePath: string) {
|
||||
const relativePath = path.relative(config.scriptPath, filePath);
|
||||
const err = await this.cronService.killTask(`task -l ${relativePath} now`);
|
||||
|
||||
public async stopScript(path: string) {
|
||||
const err = await this.cronService.killTask(`task -l ${path} now`);
|
||||
const str = err ? `\n${err}` : '';
|
||||
this.sockService.sendMessage({
|
||||
type: 'manuallyRunScript',
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
@Service()
|
||||
export default class SshKeyService {
|
||||
private homedir = os.homedir();
|
||||
private sshPath = path.resolve(this.homedir, '.ssh');
|
||||
private sshConfigFilePath = path.resolve(this.sshPath, 'config');
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
private generatePrivateKeyFile(alias: string, key: string): void {
|
||||
try {
|
||||
fs.writeFileSync(`${this.sshPath}/${alias}`, key, {
|
||||
encoding: 'utf8',
|
||||
mode: '400',
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error('生成私钥文件失败', error);
|
||||
}
|
||||
}
|
||||
|
||||
private getConfigRegx(alias: string) {
|
||||
return new RegExp(
|
||||
`Host ${alias}\n.*[^StrictHostKeyChecking]*.*[\n]*.*StrictHostKeyChecking no`,
|
||||
'g',
|
||||
);
|
||||
}
|
||||
|
||||
private removePrivateKeyFile(alias: string): void {
|
||||
try {
|
||||
fs.unlinkSync(`${this.sshPath}/${alias}`);
|
||||
} catch (error) {
|
||||
this.logger.error('删除私钥文件失败', error);
|
||||
}
|
||||
}
|
||||
|
||||
private generateSingleSshConfig(alias: string, host: string): string {
|
||||
return `\nHost ${alias}\n Hostname ${host}\n IdentityFile ${this.sshPath}/${alias}\n StrictHostKeyChecking no`;
|
||||
}
|
||||
|
||||
private generateSshConfig(configs: string[]) {
|
||||
try {
|
||||
for (const config of configs) {
|
||||
fs.appendFileSync(this.sshConfigFilePath, config, {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('写入ssh配置文件失败', error);
|
||||
}
|
||||
}
|
||||
|
||||
private removeSshConfig(alias: string) {
|
||||
try {
|
||||
const configRegx = this.getConfigRegx(alias);
|
||||
const data = fs
|
||||
.readFileSync(this.sshConfigFilePath, { encoding: 'utf8' })
|
||||
.replace(configRegx, '')
|
||||
.replace(/\n[\n]+/g, '\n');
|
||||
fs.writeFileSync(this.sshConfigFilePath, data, {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(`删除ssh配置文件${alias}失败`, error);
|
||||
}
|
||||
}
|
||||
|
||||
public addSSHKey(key: string, alias: string, host: string): void {
|
||||
this.generatePrivateKeyFile(alias, key);
|
||||
const config = this.generateSingleSshConfig(alias, host);
|
||||
this.removeSshConfig(alias);
|
||||
this.generateSshConfig([config]);
|
||||
}
|
||||
|
||||
public removeSSHKey(alias: string, host: string): void {
|
||||
this.removePrivateKeyFile(alias);
|
||||
const config = this.generateSingleSshConfig(alias, host);
|
||||
this.removeSshConfig(config);
|
||||
}
|
||||
}
|
||||
@@ -1,459 +0,0 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import config from '../config';
|
||||
import {
|
||||
Subscription,
|
||||
SubscriptionModel,
|
||||
SubscriptionStatus,
|
||||
} from '../data/subscription';
|
||||
import {
|
||||
ChildProcessWithoutNullStreams,
|
||||
exec,
|
||||
execSync,
|
||||
spawn,
|
||||
} from 'child_process';
|
||||
import fs from 'fs';
|
||||
import cron_parser from 'cron-parser';
|
||||
import {
|
||||
getFileContentByName,
|
||||
concurrentRun,
|
||||
fileExist,
|
||||
createFile,
|
||||
} from '../config/util';
|
||||
import { promises, existsSync } from 'fs';
|
||||
import { promisify } from 'util';
|
||||
import { Op } from 'sequelize';
|
||||
import path from 'path';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||
import SockService from './sock';
|
||||
import SshKeyService from './sshKey';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
@Service()
|
||||
export default class SubscriptionService {
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
private scheduleService: ScheduleService,
|
||||
private sockService: SockService,
|
||||
private sshKeyService: SshKeyService,
|
||||
) {}
|
||||
|
||||
public async list(searchText?: string): Promise<Subscription[]> {
|
||||
let query = {};
|
||||
if (searchText) {
|
||||
const reg = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchText}%` },
|
||||
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
|
||||
],
|
||||
};
|
||||
query = {
|
||||
[Op.or]: [
|
||||
{
|
||||
name: reg,
|
||||
},
|
||||
{
|
||||
url: reg,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
try {
|
||||
const result = await SubscriptionModel.findAll({
|
||||
where: query,
|
||||
order: [['createdAt', 'DESC']],
|
||||
});
|
||||
return result as any;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private formatCommand(doc: Subscription, url?: string) {
|
||||
let command = 'ql ';
|
||||
let _url = url || this.formatUrl(doc).url;
|
||||
const { type, whitelist, blacklist, dependences, branch, extensions } = doc;
|
||||
if (type === 'file') {
|
||||
command += `raw "${_url}"`;
|
||||
} else {
|
||||
command += `repo "${_url}" "${whitelist || ''}" "${blacklist || ''}" "${
|
||||
dependences || ''
|
||||
}" "${branch || ''}" "${extensions || ''}"`;
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
private formatUrl(doc: Subscription) {
|
||||
let url = doc.url;
|
||||
let host = '';
|
||||
if (doc.type === 'private-repo') {
|
||||
if (doc.pull_type === 'ssh-key') {
|
||||
host = doc.url!.replace(/.*\@([^\:]+)\:.*/, '$1');
|
||||
url = doc.url!.replace(host, doc.alias);
|
||||
} else {
|
||||
host = doc.url!.replace(/.*\:\/\/([^\/]+)\/.*/, '$1');
|
||||
const { username, password } = doc.pull_option as any;
|
||||
url = doc.url!.replace(host, `${username}:${password}@${host}`);
|
||||
}
|
||||
}
|
||||
return { url, host };
|
||||
}
|
||||
|
||||
public async handleTask(
|
||||
doc: Subscription,
|
||||
needCreate = true,
|
||||
needAddKey = true,
|
||||
runImmediately = false,
|
||||
) {
|
||||
const { url, host } = this.formatUrl(doc);
|
||||
if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
|
||||
if (needAddKey) {
|
||||
this.sshKeyService.addSSHKey(
|
||||
(doc.pull_option as any).private_key,
|
||||
doc.alias,
|
||||
host,
|
||||
);
|
||||
} else {
|
||||
this.sshKeyService.removeSSHKey(doc.alias, host);
|
||||
}
|
||||
}
|
||||
|
||||
doc.command = this.formatCommand(doc, url as string);
|
||||
|
||||
if (doc.schedule_type === 'crontab') {
|
||||
this.scheduleService.cancelCronTask(doc as any);
|
||||
needCreate &&
|
||||
(await this.scheduleService.createCronTask(
|
||||
doc as any,
|
||||
this.taskCallbacks(doc),
|
||||
runImmediately,
|
||||
));
|
||||
} else {
|
||||
this.scheduleService.cancelIntervalTask(doc as any);
|
||||
const { type, value } = doc.interval_schedule as any;
|
||||
needCreate &&
|
||||
(await this.scheduleService.createIntervalTask(
|
||||
doc as any,
|
||||
{ [type]: value } as SimpleIntervalSchedule,
|
||||
runImmediately,
|
||||
this.taskCallbacks(doc),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private async promiseExec(command: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(
|
||||
command,
|
||||
{ maxBuffer: 200 * 1024 * 1024, encoding: 'utf8' },
|
||||
(err, stdout, stderr) => {
|
||||
resolve(stdout || stderr || JSON.stringify(err));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
return {
|
||||
onBefore: async (startTime) => {
|
||||
const logTime = startTime.format('YYYY-MM-DD-HH-mm-ss');
|
||||
const logPath = `${doc.alias}/${logTime}.log`;
|
||||
await SubscriptionModel.update(
|
||||
{
|
||||
status: SubscriptionStatus.running,
|
||||
log_path: logPath,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
const absolutePath = await this.handleLogPath(
|
||||
logPath as string,
|
||||
`## 开始执行... ${startTime.format('YYYY-MM-DD HH:mm:ss')}\n`,
|
||||
);
|
||||
|
||||
// 执行sub_before
|
||||
let beforeStr = '';
|
||||
try {
|
||||
if (doc.sub_before) {
|
||||
fs.appendFileSync(absolutePath, `\n## 执行before命令...\n\n`);
|
||||
beforeStr = await this.promiseExec(doc.sub_before);
|
||||
}
|
||||
} catch (error: any) {
|
||||
beforeStr =
|
||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||
}
|
||||
if (beforeStr) {
|
||||
fs.appendFileSync(absolutePath, `${beforeStr}\n`);
|
||||
}
|
||||
},
|
||||
onStart: async (cp: ChildProcessWithoutNullStreams, startTime) => {
|
||||
await SubscriptionModel.update(
|
||||
{
|
||||
pid: cp.pid,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
},
|
||||
onEnd: async (cp, endTime, diff) => {
|
||||
const sub = await this.getDb({ id: doc.id });
|
||||
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||
|
||||
// 执行 sub_after
|
||||
let afterStr = '';
|
||||
try {
|
||||
if (sub.sub_after) {
|
||||
fs.appendFileSync(absolutePath, `\n\n## 执行after命令...\n\n`);
|
||||
afterStr = await this.promiseExec(sub.sub_after);
|
||||
}
|
||||
} catch (error: any) {
|
||||
afterStr =
|
||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||
}
|
||||
if (afterStr) {
|
||||
fs.appendFileSync(absolutePath, `${afterStr}\n`);
|
||||
}
|
||||
|
||||
fs.appendFileSync(
|
||||
absolutePath,
|
||||
`\n## 执行结束... ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)} 耗时 ${diff} 秒`,
|
||||
);
|
||||
|
||||
await SubscriptionModel.update(
|
||||
{ status: SubscriptionStatus.idle, pid: undefined },
|
||||
{ where: { id: sub.id } },
|
||||
);
|
||||
|
||||
this.sockService.sendMessage({
|
||||
type: 'runSubscriptionEnd',
|
||||
message: '订阅执行完成',
|
||||
references: [doc.id as number],
|
||||
});
|
||||
},
|
||||
onError: async (message: string) => {
|
||||
const sub = await this.getDb({ id: doc.id });
|
||||
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
||||
},
|
||||
onLog: async (message: string) => {
|
||||
const sub = await this.getDb({ id: doc.id });
|
||||
const absolutePath = await this.handleLogPath(sub.log_path as string);
|
||||
fs.appendFileSync(absolutePath, `\n${message}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public async create(payload: Subscription): Promise<Subscription> {
|
||||
const tab = new Subscription(payload);
|
||||
const doc = await this.insert(tab);
|
||||
await this.handleTask(doc);
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async insert(payload: Subscription): Promise<Subscription> {
|
||||
return await SubscriptionModel.create(payload, { returning: true });
|
||||
}
|
||||
|
||||
public async update(payload: Subscription): Promise<Subscription> {
|
||||
const newDoc = await this.updateDb(payload);
|
||||
await this.handleTask(newDoc, !newDoc.is_disabled);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
public async updateDb(payload: Subscription): Promise<Subscription> {
|
||||
await SubscriptionModel.update(payload, { where: { id: payload.id } });
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async status({
|
||||
ids,
|
||||
status,
|
||||
pid,
|
||||
log_path,
|
||||
last_running_time = 0,
|
||||
last_execution_time = 0,
|
||||
}: {
|
||||
ids: number[];
|
||||
status: SubscriptionStatus;
|
||||
pid: number;
|
||||
log_path: string;
|
||||
last_running_time: number;
|
||||
last_execution_time: number;
|
||||
}) {
|
||||
const options: any = {
|
||||
status,
|
||||
pid,
|
||||
log_path,
|
||||
last_execution_time,
|
||||
};
|
||||
if (last_running_time > 0) {
|
||||
options.last_running_time = last_running_time;
|
||||
}
|
||||
|
||||
return await SubscriptionModel.update(
|
||||
{ ...options },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
}
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc, false, false);
|
||||
}
|
||||
await SubscriptionModel.destroy({ where: { id: ids } });
|
||||
}
|
||||
|
||||
public async getDb(query: any): Promise<Subscription> {
|
||||
const doc: any = await SubscriptionModel.findOne({ where: { ...query } });
|
||||
return doc && (doc.get({ plain: true }) as Subscription);
|
||||
}
|
||||
|
||||
public async run(ids: number[]) {
|
||||
await SubscriptionModel.update(
|
||||
{ status: SubscriptionStatus.queued },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
concurrentRun(
|
||||
ids.map((id) => async () => await this.runSingle(id)),
|
||||
10,
|
||||
);
|
||||
}
|
||||
|
||||
public async stop(ids: number[]) {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
for (const doc of docs) {
|
||||
if (doc.pid) {
|
||||
try {
|
||||
process.kill(-doc.pid);
|
||||
} catch (error) {
|
||||
this.logger.silly(error);
|
||||
}
|
||||
}
|
||||
const command = this.formatCommand(doc);
|
||||
const err = await this.killTask(command);
|
||||
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
||||
const str = err ? `\n${err}` : '';
|
||||
|
||||
fs.appendFileSync(
|
||||
`${absolutePath}`,
|
||||
`${str}\n## 执行结束... ${dayjs().format('YYYY-MM-DD HH:mm:ss')} `,
|
||||
);
|
||||
}
|
||||
|
||||
await SubscriptionModel.update(
|
||||
{ status: SubscriptionStatus.idle, pid: undefined },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
}
|
||||
|
||||
public async killTask(name: string) {
|
||||
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`;
|
||||
const execAsync = promisify(exec);
|
||||
try {
|
||||
let pid = (await execAsync(taskCommand)).stdout;
|
||||
if (pid) {
|
||||
pid = (await execAsync(`pstree -p ${pid}`)).stdout;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
let pids = pid.match(/\(\d+/g);
|
||||
const killLogs = [];
|
||||
if (pids && pids.length > 0) {
|
||||
// node 执行脚本时还会有10个子进程,但是ps -ef中不存在,所以截取前三个
|
||||
for (const id of pids) {
|
||||
const c = `kill -9 ${id.slice(1)}`;
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync(c);
|
||||
if (stderr) {
|
||||
killLogs.push(stderr);
|
||||
}
|
||||
if (stdout) {
|
||||
killLogs.push(stdout);
|
||||
}
|
||||
} catch (error: any) {
|
||||
killLogs.push(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return killLogs.length > 0 ? JSON.stringify(killLogs) : '';
|
||||
} catch (e) {
|
||||
return JSON.stringify(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async runSingle(subscriptionId: number) {
|
||||
const subscription = await this.getDb({ id: subscriptionId });
|
||||
if (subscription.status !== SubscriptionStatus.queued) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = this.formatCommand(subscription);
|
||||
|
||||
await this.scheduleService.runTask(
|
||||
command,
|
||||
this.taskCallbacks(subscription),
|
||||
);
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc, false);
|
||||
}
|
||||
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc);
|
||||
}
|
||||
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async log(id: number) {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc || !doc.log_path) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const absolutePath = await this.handleLogPath(doc.log_path as string);
|
||||
return getFileContentByName(absolutePath);
|
||||
}
|
||||
|
||||
public async logs(id: number) {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (doc.log_path) {
|
||||
const relativeDir = path.dirname(`${doc.log_path}`);
|
||||
const dir = path.resolve(config.logPath, relativeDir);
|
||||
if (existsSync(dir)) {
|
||||
let files = await promises.readdir(dir);
|
||||
return files
|
||||
.map((x) => ({
|
||||
filename: x,
|
||||
directory: relativeDir.replace(config.logPath, ''),
|
||||
time: fs.statSync(`${dir}/${x}`).mtime.getTime(),
|
||||
}))
|
||||
.sort((a, b) => b.time - a.time);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-22
@@ -24,7 +24,7 @@ export default class SystemService {
|
||||
|
||||
public async getLogRemoveFrequency() {
|
||||
const doc = await this.getDb({ type: AuthDataType.removeLogFrequency });
|
||||
return doc || {};
|
||||
return (doc && doc.info) || {};
|
||||
}
|
||||
|
||||
private async updateAuthDb(payload: AuthInfo): Promise<any> {
|
||||
@@ -52,14 +52,12 @@ export default class SystemService {
|
||||
});
|
||||
return { code: 200, data: { ...result, code } };
|
||||
} else {
|
||||
return { code: 400, message: '通知发送失败,请检查参数' };
|
||||
return { code: 400, data: '通知发送失败,请检查参数' };
|
||||
}
|
||||
}
|
||||
|
||||
public async updateLogRemoveFrequency(frequency: number) {
|
||||
const oDoc = await this.getLogRemoveFrequency();
|
||||
const result = await this.updateAuthDb({
|
||||
...oDoc,
|
||||
type: AuthDataType.removeLogFrequency,
|
||||
info: { frequency },
|
||||
});
|
||||
@@ -67,13 +65,11 @@ export default class SystemService {
|
||||
id: result.id,
|
||||
name: '删除日志',
|
||||
command: `ql rmlog ${frequency}`,
|
||||
schedule: `5 23 */${frequency} * *`,
|
||||
};
|
||||
await this.scheduleService.cancelIntervalTask(cron);
|
||||
await this.scheduleService.cancelSchedule(cron);
|
||||
if (frequency > 0) {
|
||||
await this.scheduleService.createIntervalTask(cron, {
|
||||
days: frequency,
|
||||
runImmediately: true,
|
||||
});
|
||||
await this.scheduleService.generateSchedule(cron);
|
||||
}
|
||||
return { code: 200, data: { ...cron } };
|
||||
}
|
||||
@@ -89,10 +85,13 @@ export default class SystemService {
|
||||
let lastVersion = '';
|
||||
let lastLog = '';
|
||||
try {
|
||||
const result = await got.get(config.lastVersionFile, {
|
||||
timeout: 6000,
|
||||
const result = await Promise.race([
|
||||
got.get(config.lastVersionFile, { timeout: 1000, retry: 0 }),
|
||||
got.get(`https://ghproxy.com/${config.lastVersionFile}`, {
|
||||
timeout: 5000,
|
||||
retry: 0,
|
||||
});
|
||||
}),
|
||||
]);
|
||||
const lastVersionFileContent = result.body;
|
||||
lastVersion = lastVersionFileContent.match(versionRegx)![1];
|
||||
lastLog = lastVersionFileContent.match(logRegx)
|
||||
@@ -111,7 +110,7 @@ export default class SystemService {
|
||||
} catch (error: any) {
|
||||
return {
|
||||
code: 400,
|
||||
message: error.message,
|
||||
data: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -165,13 +164,4 @@ export default class SystemService {
|
||||
|
||||
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: '通知发送失败,请检查系统设置/通知配置' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+120
-20
@@ -13,7 +13,7 @@ import { Request } from 'express';
|
||||
import ScheduleService from './schedule';
|
||||
import { spawn } from 'child_process';
|
||||
import SockService from './sock';
|
||||
import dayjs from 'dayjs';
|
||||
import got from 'got';
|
||||
|
||||
@Service()
|
||||
export default class UserService {
|
||||
@@ -111,7 +111,7 @@ export default class UserService {
|
||||
});
|
||||
await this.notificationService.notify(
|
||||
'登录通知',
|
||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||
`你于${new Date(timestamp).toLocaleString()}在 ${address} ${
|
||||
req.platform
|
||||
}端 登录成功,ip地址 ${ip}`,
|
||||
);
|
||||
@@ -140,7 +140,7 @@ export default class UserService {
|
||||
});
|
||||
await this.notificationService.notify(
|
||||
'登录通知',
|
||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||
`你于${new Date(timestamp).toLocaleString()}在 ${address} ${
|
||||
req.platform
|
||||
}端 登录失败,ip地址 ${ip}`,
|
||||
);
|
||||
@@ -221,12 +221,6 @@ export default class UserService {
|
||||
return { code: 200, message: '更新成功' };
|
||||
}
|
||||
|
||||
public async updateAvatar(avatar: string) {
|
||||
const authInfo = this.getAuthInfo();
|
||||
this.updateAuthInfo(authInfo, { avatar });
|
||||
return { code: 200, data: avatar, message: '更新成功' };
|
||||
}
|
||||
|
||||
public getUserInfo(): Promise<any> {
|
||||
return new Promise((resolve) => {
|
||||
fs.readFile(config.authConfigFile, 'utf8', (err, data) => {
|
||||
@@ -313,17 +307,14 @@ export default class UserService {
|
||||
return (doc && doc.info) || {};
|
||||
}
|
||||
|
||||
private async updateAuthDb(payload: AuthInfo): Promise<any> {
|
||||
let doc = await AuthModel.findOne({ type: payload.type });
|
||||
if (doc) {
|
||||
const updateResult = await AuthModel.update(payload, {
|
||||
where: { id: doc.id },
|
||||
returning: true,
|
||||
});
|
||||
doc = updateResult[1][0];
|
||||
} else {
|
||||
doc = await AuthModel.create(payload, { returning: true });
|
||||
public async getLogRemoveFrequency() {
|
||||
const doc = await this.getDb({ type: AuthDataType.removeLogFrequency });
|
||||
return (doc && doc.info) || {};
|
||||
}
|
||||
|
||||
private async updateAuthDb(payload: AuthInfo): Promise<any> {
|
||||
await AuthModel.upsert({ ...payload });
|
||||
const doc = await this.getDb({ type: payload.type });
|
||||
return doc;
|
||||
}
|
||||
|
||||
@@ -346,7 +337,116 @@ export default class UserService {
|
||||
});
|
||||
return { code: 200, data: { ...result, code } };
|
||||
} else {
|
||||
return { code: 400, message: '通知发送失败,请检查参数' };
|
||||
return { code: 400, data: '通知发送失败,请检查参数' };
|
||||
}
|
||||
}
|
||||
|
||||
public async updateLogRemoveFrequency(frequency: number) {
|
||||
const result = await this.updateAuthDb({
|
||||
type: AuthDataType.removeLogFrequency,
|
||||
info: { frequency },
|
||||
});
|
||||
const cron = {
|
||||
id: result.id,
|
||||
name: '删除日志',
|
||||
command: `ql rmlog ${frequency}`,
|
||||
schedule: `5 23 */${frequency} * *`,
|
||||
};
|
||||
await this.scheduleService.cancelSchedule(cron);
|
||||
if (frequency > 0) {
|
||||
await this.scheduleService.generateSchedule(cron);
|
||||
}
|
||||
return { code: 200, data: { ...cron } };
|
||||
}
|
||||
|
||||
public async checkUpdate() {
|
||||
try {
|
||||
const versionRegx = /.*export const version = \'(.*)\'\;/;
|
||||
const logRegx = /.*export const changeLog = \`((.*\n.*)+)\`;/;
|
||||
|
||||
const currentVersionFile = fs.readFileSync(config.versionFile, 'utf8');
|
||||
const currentVersion = currentVersionFile.match(versionRegx)![1];
|
||||
|
||||
let lastVersion = '';
|
||||
let lastLog = '';
|
||||
try {
|
||||
const result = await Promise.race([
|
||||
got.get(config.lastVersionFile, { timeout: 1000, retry: 0 }),
|
||||
got.get(`https://ghproxy.com/${config.lastVersionFile}`, {
|
||||
timeout: 5000,
|
||||
retry: 0,
|
||||
}),
|
||||
]);
|
||||
const lastVersionFileContent = result.body;
|
||||
lastVersion = lastVersionFileContent.match(versionRegx)![1];
|
||||
lastLog = lastVersionFileContent.match(logRegx)
|
||||
? lastVersionFileContent.match(logRegx)![1]
|
||||
: '';
|
||||
} catch (error) {}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
hasNewVersion: this.checkHasNewVersion(currentVersion, lastVersion),
|
||||
lastVersion,
|
||||
lastLog,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
code: 400,
|
||||
data: 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('ql -l update', { shell: '/bin/bash' });
|
||||
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateSystemVersion',
|
||||
message: `开始更新系统`,
|
||||
});
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import OpenService from './services/open';
|
||||
import { Container } from 'typedi';
|
||||
import LoggerInstance from './loaders/logger';
|
||||
import fs from 'fs';
|
||||
import config from './config';
|
||||
import path from 'path';
|
||||
|
||||
const tokenFile = path.join(config.configPath, 'token.json');
|
||||
|
||||
async function getToken() {
|
||||
try {
|
||||
Container.set('logger', LoggerInstance);
|
||||
const openService = Container.get(OpenService);
|
||||
const appToken = await openService.generateSystemToken();
|
||||
console.log(appToken.value);
|
||||
await writeFile({
|
||||
value: appToken.value,
|
||||
expiration: appToken.expiration,
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function writeFile(data: any) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
fs.writeFile(tokenFile, JSON.stringify(data), { encoding: 'utf8' }, () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getToken();
|
||||
@@ -0,0 +1,14 @@
|
||||
version: '2'
|
||||
services:
|
||||
web:
|
||||
image: whyour/qinglong:latest
|
||||
volumes:
|
||||
- ./data/config:/ql/config
|
||||
- ./data/log:/ql/log
|
||||
- ./data/db:/ql/db
|
||||
- ./data/scripts:/ql/scripts
|
||||
- ./data/repo:/ql/repo
|
||||
- ./data/raw:/ql/raw
|
||||
ports:
|
||||
- "0.0.0.0:5700:5700"
|
||||
restart: unless-stopped
|
||||
+16
-22
@@ -1,22 +1,17 @@
|
||||
FROM python:alpine
|
||||
|
||||
FROM node:lts-alpine3.12
|
||||
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 \
|
||||
ARG QL_BRANCH=master
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
|
||||
LANG=zh_CN.UTF-8 \
|
||||
SHELL=/bin/bash \
|
||||
PS1="\u@\h:\w \$ " \
|
||||
QL_DIR=/ql \
|
||||
QL_BRANCH=${QL_BRANCH}
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
RUN set -x \
|
||||
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
||||
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \
|
||||
&& apk update -f \
|
||||
&& apk upgrade \
|
||||
&& apk --no-cache add -f bash \
|
||||
@@ -29,32 +24,31 @@ RUN set -x \
|
||||
perl \
|
||||
openssl \
|
||||
nginx \
|
||||
nodejs \
|
||||
python3 \
|
||||
jq \
|
||||
openssh \
|
||||
npm \
|
||||
py3-pip \
|
||||
python2 \
|
||||
g++ \
|
||||
make \
|
||||
&& rm -rf /var/cache/apk/* \
|
||||
&& apk update \
|
||||
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||
&& echo "Asia/Shanghai" > /etc/timezone \
|
||||
&& touch ~/.bashrc \
|
||||
&& git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||
&& 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 \
|
||||
&& npm install -g pnpm \
|
||||
&& pnpm install -g pm2 \
|
||||
&& pnpm install -g ts-node typescript tslib \
|
||||
&& rm -rf /root/.npm \
|
||||
&& 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 \
|
||||
&& cp -rf /static/* ${QL_DIR} \
|
||||
&& rm -rf /static
|
||||
|
||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
version: '2'
|
||||
services:
|
||||
web:
|
||||
image: whyour/qinglong:latest
|
||||
volumes:
|
||||
- ./data:/ql/data
|
||||
ports:
|
||||
- "0.0.0.0:5700:5700"
|
||||
restart: unless-stopped
|
||||
@@ -9,15 +9,7 @@ make_dir /etc/nginx/conf.d
|
||||
make_dir /run/nginx
|
||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
||||
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
|
||||
pm2 l &>/dev/null
|
||||
|
||||
if [[ $PipMirror ]]; then
|
||||
pip3 config set global.index-url $PipMirror
|
||||
fi
|
||||
if [[ $NpmMirror ]]; then
|
||||
npm config set registry $NpmMirror
|
||||
fi
|
||||
echo
|
||||
|
||||
echo -e "======================2. 安装依赖========================\n"
|
||||
@@ -28,29 +20,24 @@ echo -e "======================3. 启动nginx========================\n"
|
||||
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
|
||||
echo -e "nginx启动成功...\n"
|
||||
|
||||
echo -e "======================4. 启动面板监控========================\n"
|
||||
pm2 delete public &>/dev/null
|
||||
pm2 start $dir_static/build/public.js -n public --source-map-support --time
|
||||
echo -e "监控服务启动成功...\n"
|
||||
|
||||
echo -e "======================5. 启动控制面板========================\n"
|
||||
echo -e "======================4. 启动控制面板========================\n"
|
||||
pm2 delete panel &>/dev/null
|
||||
pm2 start $dir_static/build/app.js -n panel --source-map-support --time
|
||||
pm2 start $dir_root/build/app.js -n panel --source-map-support --time
|
||||
echo -e "控制面板启动成功...\n"
|
||||
|
||||
echo -e "======================6. 启动定时任务========================\n"
|
||||
echo -e "======================5. 启动定时任务========================\n"
|
||||
pm2 delete schedule &>/dev/null
|
||||
pm2 start $dir_static/build/schedule.js -n schedule --source-map-support --time
|
||||
pm2 start $dir_root/build/schedule.js -n schedule --source-map-support --time
|
||||
echo -e "定时任务启动成功...\n"
|
||||
|
||||
if [[ $AutoStartBot == true ]]; then
|
||||
echo -e "======================7. 启动bot========================\n"
|
||||
echo -e "======================6. 启动bot========================\n"
|
||||
nohup ql bot >>$dir_log/start.log 2>&1 &
|
||||
echo -e "bot后台启动中...\n"
|
||||
fi
|
||||
|
||||
if [[ $EnableExtraShell == true ]]; then
|
||||
echo -e "======================8. 执行自定义脚本========================\n"
|
||||
echo -e "======================7. 执行自定义脚本========================\n"
|
||||
nohup ql extra >>$dir_log/start.log 2>&1 &
|
||||
echo -e "自定义脚本后台执行中...\n"
|
||||
fi
|
||||
|
||||
+8
-19
@@ -1,11 +1,7 @@
|
||||
upstream baseApi {
|
||||
upstream api {
|
||||
server 0.0.0.0:5600;
|
||||
}
|
||||
|
||||
upstream publicApi {
|
||||
server 0.0.0.0:5400;
|
||||
}
|
||||
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default keep-alive;
|
||||
'websocket' upgrade;
|
||||
@@ -13,31 +9,24 @@ map $http_upgrade $connection_upgrade {
|
||||
|
||||
server {
|
||||
listen 5700;
|
||||
root /ql/static/dist;
|
||||
root /ql/dist;
|
||||
ssl_session_timeout 5m;
|
||||
|
||||
location QL_BASE_URL/api/public/ {
|
||||
location /api {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://publicApi/api/public/;
|
||||
}
|
||||
|
||||
location QL_BASE_URL/api/ {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://baseApi/api/;
|
||||
proxy_pass http://api;
|
||||
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
location QL_BASE_URL/open/ {
|
||||
location /open {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://baseApi/open/;
|
||||
proxy_pass http://api;
|
||||
}
|
||||
|
||||
gzip on;
|
||||
@@ -49,9 +38,9 @@ server {
|
||||
gzip_buffers 16 8k;
|
||||
gzip_http_version 1.0;
|
||||
|
||||
location QL_BASE_URL/ {
|
||||
location / {
|
||||
index index.html index.htm;
|
||||
try_files $uri $uri/ QL_BASE_URL/index.html;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~ .*\.(html)$ {
|
||||
|
||||
+58
-77
@@ -1,17 +1,14 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "concurrently -n w: npm:start:*",
|
||||
"start:front": "umi dev",
|
||||
"start:back": "nodemon",
|
||||
"start:public": "ts-node back/public.ts",
|
||||
"build:front": "umi build",
|
||||
"build:back": "tsc -p tsconfig.back.json",
|
||||
"panel": "npm run build:back && node static/build/app.js",
|
||||
"schedule": "npm run build:back && node static/build/schedule.js",
|
||||
"public": "npm run build:back && node static/build/public.js",
|
||||
"start": "umi dev",
|
||||
"build": "umi build",
|
||||
"build-back": "tsc -p tsconfig.back.json",
|
||||
"start-back": "nodemon",
|
||||
"panel": "npm run build-back && node build/app.js",
|
||||
"schedule": "npm run build-back && node build/schedule.js",
|
||||
"prepare": "umi generate tmp",
|
||||
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
||||
"postinstall": "umi generate tmp 2>/dev/null || true",
|
||||
"test": "umi-test",
|
||||
"test:coverage": "umi-test --coverage"
|
||||
},
|
||||
@@ -26,88 +23,73 @@
|
||||
"prettier --parser=typescript --write"
|
||||
]
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
"allowedVersions": {
|
||||
"react": "17",
|
||||
"react-dom": "17"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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",
|
||||
"@sentry/node": "^6.16.1",
|
||||
"@sentry/tracing": "^6.16.1",
|
||||
"body-parser": "^1.19.0",
|
||||
"celebrate": "^13.0.3",
|
||||
"chokidar": "^3.5.2",
|
||||
"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",
|
||||
"cron-parser": "^3.5.0",
|
||||
"dotenv": "^8.2.0",
|
||||
"express": "^4.17.1",
|
||||
"express-jwt": "^6.0.0",
|
||||
"express-urlrewrite": "^1.4.0",
|
||||
"got": "^11.8.2",
|
||||
"hpagent": "^0.1.2",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"lodash": "^4.17.21",
|
||||
"multer": "^1.4.4",
|
||||
"nedb": "^1.8.0",
|
||||
"node-schedule": "^2.1.0",
|
||||
"nodemailer": "^6.7.2",
|
||||
"p-queue": "7.2.0",
|
||||
"node-fetch": "^2.6.1",
|
||||
"node-schedule": "^2.0.0",
|
||||
"nodemailer": "^6.7.0",
|
||||
"p-queue": "6.6.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"sequelize": "^6.20.1",
|
||||
"sequelize": "^7.0.0-alpha.3",
|
||||
"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",
|
||||
"sockjs": "^0.3.21",
|
||||
"sqlite3": "^5.0.2",
|
||||
"typedi": "^0.8.0",
|
||||
"uuid": "^8.3.2",
|
||||
"winston": "^3.6.0",
|
||||
"yargs": "^17.3.1"
|
||||
"winston": "^3.3.3",
|
||||
"yargs": "^17.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ant-design/icons": "^4.7.0",
|
||||
"@ant-design/pro-layout": "^6.33.1",
|
||||
"@ant-design/icons": "^4.6.2",
|
||||
"@ant-design/pro-layout": "^6.26.0",
|
||||
"@monaco-editor/react": "^4.3.1",
|
||||
"@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/jsonwebtoken": "^8.5.8",
|
||||
"@types/lodash": "^4.14.179",
|
||||
"@types/multer": "^1.4.7",
|
||||
"@types/nedb": "^1.8.12",
|
||||
"@types/node": "^17.0.21",
|
||||
"@sentry/react": "^6.16.1",
|
||||
"@sentry/webpack-plugin": "^1.18.3",
|
||||
"@types/cors": "^2.8.10",
|
||||
"@types/express": "^4.17.8",
|
||||
"@types/express-jwt": "^6.0.1",
|
||||
"@types/jsonwebtoken": "^8.5.0",
|
||||
"@types/lodash": "^4.14.170",
|
||||
"@types/nedb": "^1.8.11",
|
||||
"@types/node": "^14.11.2",
|
||||
"@types/node-fetch": "^2.5.8",
|
||||
"@types/node-schedule": "^1.3.2",
|
||||
"@types/nodemailer": "^6.4.4",
|
||||
"@types/qrcode.react": "^1.0.2",
|
||||
"@types/react": "^17.0.39",
|
||||
"@types/react-dom": "^17.0.13",
|
||||
"@types/qrcode.react": "^1.0.1",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@types/serve-handler": "^6.1.1",
|
||||
"@types/sockjs": "^0.3.33",
|
||||
"@types/sockjs-client": "^1.5.1",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@umijs/plugin-antd": "^0.15.0",
|
||||
"@umijs/plugin-esbuild": "^1.4.1",
|
||||
"@umijs/ssr-darkreader": "^4.9.45",
|
||||
"@umijs/test": "^3.5.21",
|
||||
"ansi-to-react": "^6.1.6",
|
||||
"antd": "^4.20.5",
|
||||
"antd-img-crop": "^4.2.3",
|
||||
"codemirror": "^5.65.2",
|
||||
"compression-webpack-plugin": "9.2.0",
|
||||
"concurrently": "^7.0.0",
|
||||
"lint-staged": "^12.3.4",
|
||||
"nodemon": "^2.0.15",
|
||||
"prettier": "^2.5.1",
|
||||
"qiniu": "^7.4.0",
|
||||
"@types/uuid": "^8.3.3",
|
||||
"@umijs/plugin-antd": "^0.11.0",
|
||||
"@umijs/test": "^3.3.9",
|
||||
"antd": "^4.17.0-alpha.6",
|
||||
"codemirror": "^5.62.2",
|
||||
"compression-webpack-plugin": "6.1.1",
|
||||
"darkreader": "^4.9.27",
|
||||
"lint-staged": "^10.0.7",
|
||||
"@mapbox/node-pre-gyp": "1.0.8",
|
||||
"nodemon": "^2.0.4",
|
||||
"prettier": "^2.2.0",
|
||||
"qrcode.react": "^1.0.1",
|
||||
"rc-tween-one": "^3.0.6",
|
||||
"react": "17.x",
|
||||
"react-codemirror2": "^7.2.1",
|
||||
"react-diff-viewer": "^3.1.1",
|
||||
@@ -115,14 +97,13 @@
|
||||
"react-dnd-html5-backend": "^14.0.0",
|
||||
"react-dom": "17.x",
|
||||
"react-split-pane": "^0.1.92",
|
||||
"sockjs-client": "^1.6.0",
|
||||
"ts-node": "^10.6.0",
|
||||
"tslib": "^2.4.0",
|
||||
"typescript": "^4.6.2",
|
||||
"umi": "^3.5.21",
|
||||
"umi-request": "^1.4.0",
|
||||
"sockjs-client": "^1.5.2",
|
||||
"ts-node": "^9.0.0",
|
||||
"typescript": "^4.1.2",
|
||||
"umi": "^3.5.0",
|
||||
"umi-request": "^1.3.5",
|
||||
"vh-check": "^2.0.5",
|
||||
"webpack": "^5.70.0",
|
||||
"webpack": "^5.28.0",
|
||||
"yorkie": "^2.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
+2
-25
@@ -29,14 +29,6 @@ MaxConcurrentNum="5"
|
||||
## 默认给javascript任务加随机延迟,如 RandomDelay="300" ,表示任务将在 1-300 秒内随机延迟一个秒数,然后再运行,取消延迟赋值为空
|
||||
RandomDelay="300"
|
||||
|
||||
## 需要随机延迟运行任务的文件后缀,直接写后缀名即可,多个后缀用空格分开,例如: js py ts
|
||||
## 默认仅给javascript任务加随机延迟,其它任务按定时规则准点运行。全部任务随机延迟赋值为空
|
||||
RandomDelayFileExtensions="js"
|
||||
|
||||
## 每小时的第几分钟准点运行任务,当在这些时间运行任务时将忽略 RandomDelay 配置,不会被随机延迟
|
||||
## 默认是第0分钟和第30分钟,例如21:00或21:30分的任务将会准点运行。不需要准点运行赋值为空
|
||||
RandomDelayIgnoredMinutes="0 30"
|
||||
|
||||
## 如果你自己会写shell脚本,并且希望在每次运行 ql update 命令时,额外运行你的 shell 脚本,请赋值为 "true",默认为true
|
||||
EnableExtraShell="true"
|
||||
|
||||
@@ -46,11 +38,8 @@ AutoStartBot=""
|
||||
## 是否使用第三方bot,默认不使用,使用时填入仓库地址,存到ql/repo目录下,文件夹命名为diybot
|
||||
BotRepoUrl=""
|
||||
|
||||
## 安装python依赖时指定pip源,默认使用清华源
|
||||
PipMirror="https://pypi.doubanio.com/simple/"
|
||||
|
||||
## 安装node依赖时指定pip源,默认使用清华源
|
||||
NpmMirror="https://registry.npmmirror.com"
|
||||
## 安装bot依赖时指定pip源,默认使用清华源,如不需要源,设置此参数为空
|
||||
PipMirror="https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
|
||||
## 通知环境变量
|
||||
## 1. Server酱
|
||||
@@ -61,8 +50,6 @@ export PUSH_KEY=""
|
||||
## 2. BARK
|
||||
## 下方填写app提供的设备码,例如:https://api.day.app/123 那么此处的设备码就是123
|
||||
export BARK_PUSH=""
|
||||
## 下方填写推送图标设置,自定义推送图标(需iOS15或以上)
|
||||
export BARK_ICON="http://qn.whyour.cn/logo.png"
|
||||
## 下方填写推送声音设置,例如choo,具体值请在bark-推送铃声-查看所有铃声
|
||||
export BARK_SOUND=""
|
||||
## 下方填写推送消息分组,默认为"QingLong"
|
||||
@@ -136,14 +123,4 @@ export GOTIFY_URL=""
|
||||
export GOTIFY_TOKEN=""
|
||||
export GOTIFY_PRIORITY=0
|
||||
|
||||
## 11. PushDeer
|
||||
## deer_key 填写PushDeer的key
|
||||
export DEER_KEY=""
|
||||
|
||||
## 12. Chat
|
||||
## chat_url 填写synology chat地址,http://IP:PORT/webapi/***token=
|
||||
## chat_token 填写后面的token
|
||||
export CHAT_URL=""
|
||||
export CHAT_TOKEN=""
|
||||
|
||||
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
## 添加你需要重启自动执行的任意命令,比如 ql repo
|
||||
## 安装node依赖使用 pnpm add -g xxx xxx
|
||||
## 安装node依赖使用 pnpm install -g xxx xxx
|
||||
## 安装python依赖使用 pip3 install xxx
|
||||
|
||||
+11
-141
@@ -34,22 +34,9 @@ let GOBOT_QQ = ''; // 如果GOBOT_URL设置 /send_private_msg 则需要填入 us
|
||||
//(环境变量名 PUSH_KEY)
|
||||
let SCKEY = '';
|
||||
|
||||
// =======================================PushDeer通知设置区域===========================================
|
||||
//此处填你申请的PushDeer KEY.
|
||||
//(环境变量名 DEER_KEY)
|
||||
let PUSHDEER_KEY = '';
|
||||
|
||||
// =======================================Synology Chat通知设置区域===========================================
|
||||
//此处填你申请的CHAT_URL与CHAT_TOKEN
|
||||
//(环境变量名 CHAT_URL CHAT_TOKEN)
|
||||
let CHAT_URL = '';
|
||||
let CHAT_TOKEN = '';
|
||||
|
||||
// =======================================Bark App通知设置区域===========================================
|
||||
//此处填你BarkAPP的信息(IP/设备码,例如:https://api.day.app/XXXXXXXX)
|
||||
let BARK_PUSH = '';
|
||||
//BARK app推送图标,自定义推送图标(需iOS15或以上)
|
||||
let BARK_ICON = 'http://qn.whyour.cn/logo.png';
|
||||
//BARK app推送铃声,铃声列表去APP查看复制填写
|
||||
let BARK_SOUND = '';
|
||||
//BARK app推送消息的分组, 默认为"QingLong"
|
||||
@@ -103,13 +90,6 @@ let IGOT_PUSH_KEY = '';
|
||||
let PUSH_PLUS_TOKEN = '';
|
||||
let PUSH_PLUS_USER = '';
|
||||
|
||||
// =======================================Cool Push设置区域=======================================
|
||||
//官方文档:https://cp.xuthus.cc/docs
|
||||
//QQ_SKEY: Cool Push登录授权后推送消息的调用代码Skey
|
||||
//QQ_MODE: 推送模式详情请登录获取QQ_SKEY后见https://cp.xuthus.cc/feat
|
||||
let QQ_SKEY = '';
|
||||
let QQ_MODE = '';
|
||||
|
||||
//==========================云端环境变量的判断与接收=========================
|
||||
if (process.env.GOTIFY_URL) {
|
||||
GOTIFY_URL = process.env.GOTIFY_URL;
|
||||
@@ -135,18 +115,6 @@ if (process.env.PUSH_KEY) {
|
||||
SCKEY = process.env.PUSH_KEY;
|
||||
}
|
||||
|
||||
if (process.env.DEER_KEY) {
|
||||
PUSHDEER_KEY = process.env.DEER_KEY;
|
||||
}
|
||||
|
||||
if (process.env.CHAT_URL) {
|
||||
CHAT_URL = process.env.CHAT_URL;
|
||||
}
|
||||
|
||||
if (process.env.CHAT_TOKEN) {
|
||||
CHAT_TOKEN = process.env.CHAT_TOKEN;
|
||||
}
|
||||
|
||||
if (process.env.QQ_SKEY) {
|
||||
QQ_SKEY = process.env.QQ_SKEY;
|
||||
}
|
||||
@@ -165,9 +133,6 @@ if (process.env.BARK_PUSH) {
|
||||
} else {
|
||||
BARK_PUSH = `https://api.day.app/${process.env.BARK_PUSH}`;
|
||||
}
|
||||
if (process.env.BARK_ICON) {
|
||||
BARK_ICON = process.env.BARK_ICON;
|
||||
}
|
||||
if (process.env.BARK_SOUND) {
|
||||
BARK_SOUND = process.env.BARK_SOUND;
|
||||
}
|
||||
@@ -251,10 +216,8 @@ async function sendNotify(
|
||||
qywxBotNotify(text, desp), //企业微信机器人
|
||||
qywxamNotify(text, desp), //企业微信应用消息推送
|
||||
iGotNotify(text, desp, params), //iGot
|
||||
gobotNotify(text, desp), //go-cqhttp
|
||||
gotifyNotify(text, desp), //gotify
|
||||
ChatNotify(text, desp), //synolog chat
|
||||
PushDeerNotify(text, desp), //PushDeer
|
||||
gobotNotify(text, desp),//go-cqhttp
|
||||
gotifyNotify(text, desp),//gotify
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -263,12 +226,10 @@ function gotifyNotify(text, desp) {
|
||||
if (GOTIFY_URL && GOTIFY_TOKEN) {
|
||||
const options = {
|
||||
url: `${GOTIFY_URL}/message?token=${GOTIFY_TOKEN}`,
|
||||
body: `title=${encodeURIComponent(text)}&message=${encodeURIComponent(
|
||||
desp,
|
||||
)}&priority=${GOTIFY_PRIORITY}`,
|
||||
body: `title=${encodeURIComponent(text)}&message=${encodeURIComponent(desp)}&priority=${GOTIFY_PRIORITY}`,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
}
|
||||
};
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
@@ -300,7 +261,7 @@ function gobotNotify(text, desp, time = 2100) {
|
||||
if (GOBOT_URL) {
|
||||
const options = {
|
||||
url: `${GOBOT_URL}?access_token=${GOBOT_TOKEN}&${GOBOT_QQ}`,
|
||||
json: { message: `${text}\n${desp}` },
|
||||
json: {message:`${text}\n${desp}`},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
@@ -385,91 +346,6 @@ function serverNotify(text, desp, time = 2100) {
|
||||
});
|
||||
}
|
||||
|
||||
function PushDeerNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (PUSHDEER_KEY) {
|
||||
// PushDeer 建议对消息内容进行 urlencode
|
||||
desp = encodeURI(desp);
|
||||
const options = {
|
||||
url: `https://api2.pushdeer.com/message/push`,
|
||||
body: `pushkey=${PUSHDEER_KEY}&text=${text}&desp=${desp}&type=markdown`,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
$.post(
|
||||
options,
|
||||
(err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log('发送通知调用API失败!!\n');
|
||||
console.log(err);
|
||||
} else {
|
||||
data = JSON.parse(data);
|
||||
// 通过返回的result的长度来判断是否成功
|
||||
if (
|
||||
data.content.result.length !== undefined &&
|
||||
data.content.result.length > 0
|
||||
) {
|
||||
console.log('PushDeer发送通知消息成功🎉\n');
|
||||
} else {
|
||||
console.log(
|
||||
`PushDeer发送通知消息异常\n${JSON.stringify(data)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e, resp);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
},
|
||||
time,
|
||||
);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function ChatNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (CHAT_URL && CHAT_TOKEN) {
|
||||
// 对消息内容进行 urlencode
|
||||
desp = encodeURI(desp);
|
||||
const options = {
|
||||
url: `${CHAT_URL}${CHAT_TOKEN}`,
|
||||
body: `payload={"text":"${text}\n${desp}"}`,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
};
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log('发送通知调用API失败!!\n');
|
||||
console.log(err);
|
||||
} else {
|
||||
data = JSON.parse(data);
|
||||
if (data.success) {
|
||||
console.log('Chat发送通知消息成功🎉\n');
|
||||
} else {
|
||||
console.log(`Chat发送通知消息异常\n${JSON.stringify(data)}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function CoolPush(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
if (QQ_SKEY) {
|
||||
@@ -553,9 +429,7 @@ function BarkNotify(text, desp, params = {}) {
|
||||
const options = {
|
||||
url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent(
|
||||
desp,
|
||||
)}?icon=${BARK_ICON}?sound=${BARK_SOUND}&group=${BARK_GROUP}&${querystring.stringify(
|
||||
params,
|
||||
)}`,
|
||||
)}?sound=${BARK_SOUND}&group=${BARK_GROUP}&${querystring.stringify(params)}`,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
@@ -591,13 +465,9 @@ function tgBotNotify(text, desp) {
|
||||
if (TG_BOT_TOKEN && TG_USER_ID) {
|
||||
const options = {
|
||||
url: `https://${TG_API_HOST}/bot${TG_BOT_TOKEN}/sendMessage`,
|
||||
json: {
|
||||
chat_id: `${TG_USER_ID}`,
|
||||
text: `${text}\n\n${desp}`,
|
||||
disable_web_page_preview: true,
|
||||
},
|
||||
body: `chat_id=${TG_USER_ID}&text=${text}\n\n${desp}&disable_web_page_preview=true`,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
@@ -785,9 +655,9 @@ function qywxamNotify(text, desp) {
|
||||
timeout,
|
||||
};
|
||||
$.post(options_accesstoken, (err, resp, data) => {
|
||||
let html = desp.replace(/\n/g, '<br/>');
|
||||
let json = JSON.parse(data);
|
||||
let accesstoken = json.access_token;
|
||||
html = desp.replace(/\n/g, '<br/>');
|
||||
var json = JSON.parse(data);
|
||||
accesstoken = json.access_token;
|
||||
let options;
|
||||
|
||||
switch (QYWX_AM_AY[4]) {
|
||||
|
||||
@@ -35,7 +35,6 @@ push_config = {
|
||||
'BARK_ARCHIVE': '', # bark 推送是否存档
|
||||
'BARK_GROUP': '', # bark 推送分组
|
||||
'BARK_SOUND': '', # bark 推送声音
|
||||
'BARK_ICON': '', # bark 推送图标
|
||||
|
||||
'CONSOLE': True, # 控制台输出
|
||||
|
||||
@@ -60,11 +59,6 @@ push_config = {
|
||||
|
||||
'PUSH_KEY': '', # server 酱的 PUSH_KEY,兼容旧版与 Turbo 版
|
||||
|
||||
'DEER_KEY': '', # PushDeer 的 PUSHDEER_KEY
|
||||
|
||||
'CHAT_URL': '', # synology chat url
|
||||
'CHAT_TOKEN': '', # synology chat token
|
||||
|
||||
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
||||
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
||||
|
||||
@@ -110,7 +104,6 @@ def bark(title: str, content: str) -> None:
|
||||
"BARK_ARCHIVE": "isArchive",
|
||||
"BARK_GROUP": "group",
|
||||
"BARK_SOUND": "sound",
|
||||
"BARK_ICON": "icon",
|
||||
}
|
||||
params = ""
|
||||
for pair in filter(
|
||||
@@ -266,43 +259,6 @@ def serverJ(title: str, content: str) -> None:
|
||||
print(f'serverJ 推送失败!错误码:{response["message"]}')
|
||||
|
||||
|
||||
def pushdeer(title: str, content: str) -> None:
|
||||
"""
|
||||
通过PushDeer 推送消息
|
||||
"""
|
||||
if not push_config.get("DEER_KEY"):
|
||||
print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送")
|
||||
return
|
||||
print("PushDeer 服务启动")
|
||||
data = {"text": title, "desp": content, "type": "markdown", "pushkey": push_config.get("DEER_KEY")}
|
||||
url = 'https://api2.pushdeer.com/message/push'
|
||||
response = requests.post(url, data=data).json()
|
||||
|
||||
if len(response.get("content").get("result")) > 0:
|
||||
print("PushDeer 推送成功!")
|
||||
else:
|
||||
print("PushDeer 推送失败!错误信息:", response)
|
||||
|
||||
|
||||
def chat(title: str, content: str) -> None:
|
||||
"""
|
||||
通过Chat 推送消息
|
||||
"""
|
||||
if not push_config.get("CHAT_URL") or not push_config.get("CHAT_TOKEN"):
|
||||
print("chat 服务的 CHAT_URL或CHAT_TOKEN 未设置!!\n取消推送")
|
||||
return
|
||||
print("chat 服务启动")
|
||||
data = 'payload=' + json.dumps({'text': title + '\n' + content})
|
||||
url = push_config.get("CHAT_URL") + push_config.get("CHAT_TOKEN")
|
||||
response = requests.post(url, data=data)
|
||||
|
||||
if response.status_code == 200:
|
||||
print("Chat 推送成功!")
|
||||
else:
|
||||
print("Chat 推送失败!错误信息:", response)
|
||||
|
||||
|
||||
|
||||
def pushplus_bot(title: str, content: str) -> None:
|
||||
"""
|
||||
通过 push+ 推送消息。
|
||||
@@ -547,10 +503,6 @@ if push_config.get("IGOT_PUSH_KEY"):
|
||||
notify_function.append(iGot)
|
||||
if push_config.get("PUSH_KEY"):
|
||||
notify_function.append(serverJ)
|
||||
if push_config.get("DEER_KEY"):
|
||||
notify_function.append(pushdeer)
|
||||
if push_config.get("CHAT_URL") and push_config.get("CHAT_TOKEN"):
|
||||
notify_function.append(chat)
|
||||
if push_config.get("PUSH_PLUS_TOKEN"):
|
||||
notify_function.append(pushplus_bot)
|
||||
if push_config.get("QMSG_KEY") and push_config.get("QMSG_TYPE"):
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import * as qiniu from 'qiniu';
|
||||
import dotenv from 'dotenv';
|
||||
const envFound = dotenv.config();
|
||||
|
||||
const accessKey = process.env.QINIU_AK;
|
||||
const secretKey = process.env.QINIU_SK;
|
||||
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
|
||||
const key = 'version.ts';
|
||||
const options = {
|
||||
scope: `${process.env.QINIU_SCOPE}:${key}`,
|
||||
};
|
||||
const putPolicy = new qiniu.rs.PutPolicy(options);
|
||||
const uploadToken = putPolicy.uploadToken(mac);
|
||||
|
||||
const localFile = 'src/version.ts';
|
||||
const config = new qiniu.conf.Config({ zone: qiniu.zone.Zone_z1 });
|
||||
const formUploader = new qiniu.form_up.FormUploader(config);
|
||||
const putExtra = new qiniu.form_up.PutExtra(
|
||||
'',
|
||||
{},
|
||||
'text/plain; charset=utf-8',
|
||||
);
|
||||
// 文件上传
|
||||
formUploader.putFile(
|
||||
uploadToken,
|
||||
key,
|
||||
localFile,
|
||||
putExtra,
|
||||
function (respErr, respBody, respInfo) {
|
||||
if (respErr) {
|
||||
throw respErr;
|
||||
}
|
||||
if (respInfo.statusCode == 200) {
|
||||
console.log(respBody);
|
||||
} else {
|
||||
console.log(respInfo.statusCode);
|
||||
console.log(respBody);
|
||||
}
|
||||
},
|
||||
);
|
||||
+25
-33
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
get_token() {
|
||||
token=$(cat $file_auth_token | jq -r .value)
|
||||
token=$(cat $file_auth_user | jq -r .token)
|
||||
}
|
||||
|
||||
add_cron_api() {
|
||||
@@ -17,7 +17,7 @@ add_cron_api() {
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
||||
@@ -52,7 +52,7 @@ update_cron_api() {
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
@@ -84,7 +84,7 @@ update_cron_command_api() {
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
@@ -109,7 +109,7 @@ del_cron_api() {
|
||||
local ids=$1
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons?t=$currentTimeStamp" \
|
||||
-X 'DELETE' \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
@@ -130,6 +130,24 @@ del_cron_api() {
|
||||
fi
|
||||
}
|
||||
|
||||
get_user_info() {
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/user?t=$currentTimeStamp" \
|
||||
-H 'Accept: */*' \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \
|
||||
-H 'Referer: http://0.0.0.0:5700/crontab' \
|
||||
-H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
if [[ $code != 200 ]]; then
|
||||
echo -e "请先登录!"
|
||||
exit 0
|
||||
fi
|
||||
}
|
||||
|
||||
update_cron() {
|
||||
local ids="$1"
|
||||
local status="$2"
|
||||
@@ -139,7 +157,7 @@ update_cron() {
|
||||
local runningTime="${6:-0}"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/status?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/crons/status?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
@@ -154,33 +172,7 @@ update_cron() {
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
if [[ $code != 200 ]]; then
|
||||
echo -e "\n## 更新任务状态失败(${message})\n" >> $dir_log/$log_path
|
||||
fi
|
||||
}
|
||||
|
||||
notify_api() {
|
||||
local title=$1
|
||||
local content=$2
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/system/notify?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Accept: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
-H "Origin: http://0.0.0.0:5700" \
|
||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
||||
--data-raw "{\"title\":\"$title\",\"content\":\"$content\"}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo $api | jq -r .code)
|
||||
message=$(echo $api | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "通知发送成功"
|
||||
else
|
||||
echo -e "通知失败(${message})"
|
||||
echo -e "\n## 更新任务状态失败(${message})\n" >> $log_path
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
+7
-7
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
## 导入通用变量与函数
|
||||
dir_shell=$QL_DIR/shell
|
||||
dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
|
||||
if [[ -z ${BotRepoUrl} ]]; then
|
||||
@@ -22,9 +22,9 @@ if [[ ! -d ${repo_path}/.git ]]; then
|
||||
git_clone_scripts ${url} ${repo_path} "main"
|
||||
fi
|
||||
|
||||
cp -rf "$repo_path/jbot" $dir_data
|
||||
if [[ ! -f "$dir_config/bot.json" ]]; then
|
||||
cp -f "$repo_path/config/bot.json" "$dir_config"
|
||||
cp -rf "$repo_path/jbot" $dir_root
|
||||
if [[ ! -f "$dir_root/config/bot.json" ]]; then
|
||||
cp -f "$repo_path/config/bot.json" "$dir_root/config"
|
||||
fi
|
||||
echo -e "\nbot文件下载成功...\n"
|
||||
|
||||
@@ -32,9 +32,9 @@ echo -e "3、安装python3依赖...\n"
|
||||
if [[ $PipMirror ]]; then
|
||||
pip3 config set global.index-url $PipMirror
|
||||
fi
|
||||
cp -f "$repo_path/jbot/requirements.txt" "$dir_data"
|
||||
cp -f "$repo_path/jbot/requirements.txt" "$dir_root"
|
||||
|
||||
cd $dir_data
|
||||
cd $dir_root
|
||||
cat requirements.txt | while read LREAD
|
||||
do
|
||||
if [[ ! $(pip3 show "${LREAD%%=*}" 2>/dev/null) ]]; then
|
||||
@@ -46,7 +46,7 @@ echo -e "\npython3依赖安装成功...\n"
|
||||
|
||||
echo -e "4、启动bot程序...\n"
|
||||
make_dir $dir_log/bot
|
||||
cd $dir_data
|
||||
cd $dir_root
|
||||
ps -ef | grep "python3 -m jbot" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
|
||||
nohup python3 -m jbot >$dir_log/bot/nohup.log 2>&1 &
|
||||
echo -e "bot启动成功...\n"
|
||||
|
||||
+15
-9
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
dir_shell=$QL_DIR/shell
|
||||
dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
. $dir_shell/api.sh
|
||||
|
||||
@@ -10,11 +10,13 @@ reset_env() {
|
||||
echo -e "---> 配置文件检测完成\n"
|
||||
|
||||
echo -e "---> 2. 开始安装青龙依赖\n"
|
||||
rm -rf $dir_root/node_modules
|
||||
npm_install_2 $dir_root
|
||||
echo -e "---> 青龙依赖安装完成\n"
|
||||
|
||||
echo -e "---> 3. 开始安装脚本依赖\n"
|
||||
cp -f $dir_sample/package.json $dir_scripts/package.json
|
||||
rm -rf $dir_scripts/node_modules
|
||||
npm_install_2 $dir_scripts
|
||||
echo -e "---> 脚本依赖安装完成\n"
|
||||
}
|
||||
@@ -31,16 +33,25 @@ copy_dep() {
|
||||
echo -e "---> 2. 复制nginx配置文件\n"
|
||||
cp -fv $nginx_conf /etc/nginx/nginx.conf
|
||||
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
|
||||
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
|
||||
echo -e "---> 配置文件复制完成\n"
|
||||
}
|
||||
|
||||
reload_pm2() {
|
||||
pm2 l &>/dev/null
|
||||
|
||||
pm2 delete panel --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_root/build/app.js -n panel --source-map-support --time &>/dev/null
|
||||
|
||||
pm2 delete schedule --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_root/build/schedule.js -n schedule --source-map-support --time &>/dev/null
|
||||
}
|
||||
|
||||
pm2_log() {
|
||||
echo -e "---> pm2日志"
|
||||
local panelOut="/root/.pm2/logs/panel-out.log"
|
||||
local panelError="/root/.pm2/logs/panel-error.log"
|
||||
tail -n 100 "$panelOut"
|
||||
tail -n 100 "$panelError"
|
||||
tail -n 20 "$panelOut"
|
||||
tail -n 20 "$panelError"
|
||||
}
|
||||
|
||||
check_nginx() {
|
||||
@@ -89,11 +100,6 @@ check_pm2() {
|
||||
|
||||
main() {
|
||||
echo -e "=====> 开始检测"
|
||||
npm i -g pnpm
|
||||
pnpm setup &>/dev/null
|
||||
source ~/.bashrc
|
||||
pnpm install -g &>/dev/null
|
||||
pnpm add -g pm2
|
||||
copy_dep
|
||||
check_ql
|
||||
check_nginx
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
const notify = require('/ql/scripts/sendNotify.js');
|
||||
const title = process.argv[2];
|
||||
const content = process.argv[3];
|
||||
|
||||
notify.sendNotify(`${title}`, `${content}`);
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
#author:spark thanks to: https://github.com/sparkssssssss/scripts
|
||||
|
||||
. /ql/config/config.sh
|
||||
title=$(echo $1|sed 's/-/_/g')
|
||||
msg=$(echo -e $2)
|
||||
|
||||
node /ql/shell/notify.js "$title" "$msg"
|
||||
@@ -1,32 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
echo -e "开始发布"
|
||||
|
||||
echo -e "切换master分支"
|
||||
git checkout master
|
||||
|
||||
echo -e "合并develop代码"
|
||||
git merge origin/develop
|
||||
|
||||
echo -e "提交master代码"
|
||||
git push
|
||||
|
||||
echo -e "更新cdn文件"
|
||||
ts-node sample/tool.ts
|
||||
|
||||
string=$(cat src/version.ts | grep "version" | egrep "[^\']*" -o | egrep "\d\.*")
|
||||
version="v$string"
|
||||
echo -e "当前版本$version"
|
||||
|
||||
echo -e "删除已经存在的本地tag"
|
||||
git tag -d "$version" &>/dev/null
|
||||
|
||||
echo -e "删除已经存在的远程tag"
|
||||
git push origin :refs/tags/$version &>/dev/null
|
||||
|
||||
echo -e "创建新tag"
|
||||
git tag -a "$version" -m "release $version"
|
||||
|
||||
echo -e "提交tag"
|
||||
git push --tags
|
||||
|
||||
echo -e "完成发布"
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
## 导入通用变量与函数
|
||||
dir_shell=$QL_DIR/shell
|
||||
dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
|
||||
days=$1
|
||||
|
||||
+27
-102
@@ -1,19 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
## 目录
|
||||
dir_root=$QL_DIR
|
||||
dir_data=$dir_root/data
|
||||
dir_root=/ql
|
||||
dir_shell=$dir_root/shell
|
||||
dir_sample=$dir_root/sample
|
||||
dir_static=$dir_root/static
|
||||
dir_config=$dir_data/config
|
||||
dir_scripts=$dir_data/scripts
|
||||
dir_repo=$dir_data/repo
|
||||
dir_raw=$dir_data/raw
|
||||
dir_log=$dir_data/log
|
||||
dir_db=$dir_data/db
|
||||
dir_dep=$dir_data/deps
|
||||
dir_config=$dir_root/config
|
||||
dir_scripts=$dir_root/scripts
|
||||
dir_repo=$dir_root/repo
|
||||
dir_raw=$dir_root/raw
|
||||
dir_log=$dir_root/log
|
||||
dir_db=$dir_root/db
|
||||
dir_dep=$dir_root/deps
|
||||
dir_list_tmp=$dir_log/.tmp
|
||||
dir_code=$dir_log/code
|
||||
dir_update_log=$dir_log/update
|
||||
ql_static_repo=$dir_repo/static
|
||||
|
||||
@@ -24,7 +23,6 @@ file_sharecode=$dir_config/sharecode.sh
|
||||
file_config_user=$dir_config/config.sh
|
||||
file_auth_sample=$dir_sample/auth.sample.json
|
||||
file_auth_user=$dir_config/auth.json
|
||||
file_auth_token=$dir_config/token.json
|
||||
file_extra_shell=$dir_config/extra.sh
|
||||
file_task_before=$dir_config/task_before.sh
|
||||
file_task_after=$dir_config/task_after.sh
|
||||
@@ -52,26 +50,25 @@ list_own_drop=$dir_list_tmp/own_drop.list
|
||||
link_name=(
|
||||
task
|
||||
ql
|
||||
notify
|
||||
)
|
||||
original_name=(
|
||||
task.sh
|
||||
update.sh
|
||||
notify.sh
|
||||
)
|
||||
|
||||
init_env() {
|
||||
export 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
|
||||
export PYTHONUNBUFFERED=1
|
||||
export NODE_PATH=/usr/local/bin:/usr/local/pnpm-global/5/node_modules:/usr/local/lib/node_modules
|
||||
}
|
||||
|
||||
import_config() {
|
||||
[[ -f $file_config_user ]] && . $file_config_user
|
||||
[[ -f $file_env ]] && . $file_env
|
||||
|
||||
ql_base_url=${QlBaseUrl:-""}
|
||||
command_timeout_time=${CommandTimeoutTime:-"1h"}
|
||||
proxy_url=${ProxyUrl:-""}
|
||||
file_extensions=${RepoFileExtensions:-"js py"}
|
||||
current_branch=${QL_BRANCH}
|
||||
|
||||
if [[ -n "${DefaultCronRule}" ]]; then
|
||||
default_cron="${DefaultCronRule}"
|
||||
@@ -100,7 +97,7 @@ make_dir() {
|
||||
}
|
||||
|
||||
detect_termux() {
|
||||
if [[ $PATH == *com.termux* ]]; then
|
||||
if [[ ${ANDROID_RUNTIME_ROOT}${ANDROID_ROOT} ]] || [[ $PATH == *com.termux* ]]; then
|
||||
is_termux=1
|
||||
else
|
||||
is_termux=0
|
||||
@@ -164,8 +161,6 @@ define_cmd() {
|
||||
}
|
||||
|
||||
fix_config() {
|
||||
make_dir $dir_static
|
||||
make_dir $dir_data
|
||||
make_dir $dir_config
|
||||
make_dir $dir_log
|
||||
make_dir $dir_db
|
||||
@@ -226,7 +221,7 @@ fix_config() {
|
||||
|
||||
if [[ -s /etc/nginx/conf.d/default.conf ]]; then
|
||||
echo -e "检测到默认nginx配置文件,清空...\n"
|
||||
cat /dev/null >/etc/nginx/conf.d/default.conf
|
||||
cat /dev/null > /etc/nginx/conf.d/default.conf
|
||||
echo
|
||||
fi
|
||||
|
||||
@@ -246,11 +241,11 @@ fix_config() {
|
||||
|
||||
npm_install_sub() {
|
||||
if [ $is_termux -eq 1 ]; then
|
||||
npm install --production --no-bin-links
|
||||
npm install --production --no-bin-links --registry=https://registry.npm.taobao.org || npm install --production --no-bin-links
|
||||
elif ! type pnpm &>/dev/null; then
|
||||
npm install --production
|
||||
npm install --production --registry=https://registry.npm.taobao.org || npm install --production
|
||||
else
|
||||
pnpm install --loglevel error --production
|
||||
pnpm install --production --registry=https://registry.npm.taobao.org || pnpm install --production
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -307,23 +302,25 @@ git_clone_scripts() {
|
||||
|
||||
set_proxy
|
||||
git clone $part_cmd $url $dir
|
||||
exit_status=$?
|
||||
unset_proxy
|
||||
|
||||
exit_status=$?
|
||||
}
|
||||
|
||||
git_pull_scripts() {
|
||||
local dir_current=$(pwd)
|
||||
local dir_work="$1"
|
||||
local branch="$2"
|
||||
[[ $branch ]] && local part_cmd="origin/${branch}"
|
||||
cd $dir_work
|
||||
echo -e "开始更新仓库:$dir_work\n"
|
||||
|
||||
set_proxy
|
||||
git fetch --all
|
||||
exit_status=$?
|
||||
git pull &>/dev/null
|
||||
git reset --hard $part_cmd
|
||||
git pull
|
||||
unset_proxy
|
||||
reset_branch "$branch"
|
||||
|
||||
cd $dir_current
|
||||
}
|
||||
@@ -334,99 +331,27 @@ reset_romote_url() {
|
||||
local url=$2
|
||||
local branch="$3"
|
||||
|
||||
[[ $branch ]] && local part_cmd="origin/${branch}"
|
||||
|
||||
if [[ -d "$dir_work/.git" ]]; then
|
||||
cd $dir_work
|
||||
[[ -f ".git/index.lock" ]] && rm -f .git/index.lock >/dev/null
|
||||
git remote set-url origin $url &>/dev/null
|
||||
|
||||
local part_cmd=""
|
||||
reset_branch "$branch"
|
||||
git remote set-url origin $url >/dev/null
|
||||
git reset --hard $part_cmd >/dev/null
|
||||
cd $dir_current
|
||||
fi
|
||||
}
|
||||
|
||||
reset_branch() {
|
||||
local branch="$1"
|
||||
if [[ $branch ]]; then
|
||||
part_cmd="origin/${branch}"
|
||||
git checkout -B "$branch"
|
||||
git branch --set-upstream-to=$part_cmd $branch
|
||||
fi
|
||||
git reset --hard $part_cmd &>/dev/null
|
||||
}
|
||||
|
||||
random_range() {
|
||||
local beg=$1
|
||||
local end=$2
|
||||
echo $((RANDOM % ($end - $beg) + $beg))
|
||||
}
|
||||
|
||||
reload_pm2() {
|
||||
pm2 l &>/dev/null
|
||||
|
||||
echo -e "启动面板服务\n"
|
||||
pm2 delete panel --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_static/build/app.js -n panel --source-map-support --time &>/dev/null
|
||||
|
||||
echo -e "启动定时任务服务\n"
|
||||
pm2 delete schedule --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_static/build/schedule.js -n schedule --source-map-support --time &>/dev/null
|
||||
|
||||
echo -e "启动公开服务\n"
|
||||
pm2 delete public --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
|
||||
}
|
||||
|
||||
diff_time() {
|
||||
local format="$1"
|
||||
local begin_time="$2"
|
||||
local end_time="$3"
|
||||
|
||||
if [[ $is_macos -eq 1 ]]; then
|
||||
diff_time=$(($(date -j -f "$format" "$end_time" +%s) - $(date -j -f "$format" "$begin_time" +%s)))
|
||||
else
|
||||
diff_time=$(($(date +%s -d "$end_time") - $(date +%s -d "$begin_time")))
|
||||
fi
|
||||
echo "$diff_time"
|
||||
}
|
||||
|
||||
format_time() {
|
||||
local format="$1"
|
||||
local time="$2"
|
||||
|
||||
if [[ $is_macos -eq 1 ]]; then
|
||||
echo $(date -j -f "$format" "$time" "+%Y-%m-%d %H:%M:%S")
|
||||
else
|
||||
echo $(date -d "$time" "+%Y-%m-%d %H:%M:%S")
|
||||
fi
|
||||
}
|
||||
|
||||
format_log_time() {
|
||||
local format="$1"
|
||||
local time="$2"
|
||||
|
||||
if [[ $is_macos -eq 1 ]]; then
|
||||
echo $(date -j -f "$format" "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||
else
|
||||
echo $(date -d "$time" "+%Y-%m-%d-%H-%M-%S")
|
||||
fi
|
||||
}
|
||||
|
||||
format_timestamp() {
|
||||
local format="$1"
|
||||
local time="$2"
|
||||
|
||||
if [[ $is_macos -eq 1 ]]; then
|
||||
echo $(date -j -f "$format" "$time" "+%s")
|
||||
else
|
||||
echo $(date -d "$time" "+%s")
|
||||
fi
|
||||
}
|
||||
|
||||
init_env
|
||||
detect_termux
|
||||
detect_macos
|
||||
define_cmd
|
||||
fix_config
|
||||
|
||||
import_config $1 >$task_error_log_path 2>&1
|
||||
import_config $1 > $task_error_log_path 2>&1
|
||||
|
||||
+68
-121
@@ -1,20 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
## 导入通用变量与函数
|
||||
dir_shell=$QL_DIR/shell
|
||||
dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
. $dir_shell/api.sh
|
||||
|
||||
## 选择python3还是node
|
||||
define_program() {
|
||||
local file_param=$1
|
||||
if [[ $file_param == *.js ]]; then
|
||||
local first_param=$1
|
||||
if [[ $first_param == *.js ]]; then
|
||||
which_program="node"
|
||||
elif [[ $file_param == *.py ]] || [[ $file_param == *.pyc ]]; then
|
||||
elif [[ $first_param == *.py ]] || [[ $first_param == *.pyc ]]; then
|
||||
which_program="python3"
|
||||
elif [[ $file_param == *.sh ]]; then
|
||||
elif [[ $first_param == *.sh ]]; then
|
||||
which_program="bash"
|
||||
elif [[ $file_param == *.ts ]]; then
|
||||
elif [[ $first_param == *.ts ]]; then
|
||||
which_program="ts-node-transpile-only"
|
||||
else
|
||||
which_program=""
|
||||
@@ -24,30 +24,13 @@ define_program() {
|
||||
random_delay() {
|
||||
local random_delay_max=$RandomDelay
|
||||
if [[ $random_delay_max ]] && [[ $random_delay_max -gt 0 ]]; then
|
||||
local file_param=$1
|
||||
local file_extensions=${RandomDelayFileExtensions-"js"}
|
||||
local ignored_minutes=${RandomDelayIgnoredMinutes-"0 30"}
|
||||
|
||||
if [[ -n $file_extensions ]]; then
|
||||
if ! echo "$file_param" | grep -qE "\.${file_extensions// /$|\\.}$"; then
|
||||
# echo -e "\n当前文件需要准点运行, 放弃随机延迟\n"
|
||||
return
|
||||
fi
|
||||
fi
|
||||
|
||||
local current_min
|
||||
current_min=$(date "+%-M")
|
||||
for minute in $ignored_minutes; do
|
||||
if [[ $current_min -eq $minute ]]; then
|
||||
# echo -e "\n当前时间需要准点运行, 放弃随机延迟\n"
|
||||
return
|
||||
fi
|
||||
done
|
||||
|
||||
local delay_second=$(($(gen_random_num "$random_delay_max") + 1))
|
||||
local current_min=$(date "+%-M")
|
||||
if [[ $current_min -ne 0 ]] && [[ $current_min -ne 30 ]]; then
|
||||
delay_second=$(($(gen_random_num $random_delay_max) + 1))
|
||||
echo -e "\n命令未添加 \"now\",随机延迟 $delay_second 秒后再执行任务,如需立即终止,请按 CTRL+C...\n"
|
||||
sleep $delay_second
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
## scripts目录下所有可运行脚本数组
|
||||
@@ -93,61 +76,53 @@ run_nohup() {
|
||||
|
||||
## 正常运行单个脚本,$1:传入参数
|
||||
run_normal() {
|
||||
local file_param=$1
|
||||
define_program "$file_param"
|
||||
local first_param=$1
|
||||
define_program "$first_param"
|
||||
if [[ $first_param == *.js ]]; then
|
||||
if [[ $# -eq 1 ]]; then
|
||||
random_delay "$file_param"
|
||||
random_delay
|
||||
fi
|
||||
fi
|
||||
|
||||
local time=$(date "+$time_format")
|
||||
log_time=$(format_log_time "$time_format" "$time")
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_dir_tmp="${first_param##*/}"
|
||||
log_dir_tmp_path="${first_param%%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_dir="$dir_log/${log_dir_tmp%%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
cmd="&>> $log_path"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
|
||||
local begin_time=$(format_time "$time_format" "$time")
|
||||
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||
make_dir "$log_dir"
|
||||
|
||||
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local begin_timestamp=$(date "+%s")
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $first_param" | perl -pe "s|.*ID=(.*) $cmd_task $first_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
local relative_path="${first_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${first_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
first_param=${first_param/$relative_path\//}
|
||||
fi
|
||||
|
||||
eval $timeoutCmd $which_program $file_param $cmd
|
||||
eval timeout -k 10s $command_timeout_time $which_program $first_param $cmd
|
||||
|
||||
eval . $file_task_after "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local end_timestamp=$(date "+%s")
|
||||
local diff_time=$(expr $end_timestamp - $begin_timestamp)
|
||||
local diff_time=$(( $end_timestamp - $begin_timestamp ))
|
||||
[[ $id ]] && update_cron "\"$id\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
eval echo -e "\\\n\#\# 执行结束... $end_time 耗时 $diff_time 秒" $cmd
|
||||
}
|
||||
|
||||
## 并发执行时,设定的 RandomDelay 不会生效,即所有任务立即执行
|
||||
run_concurrent() {
|
||||
local file_param="$1"
|
||||
local first_param="$1"
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|")
|
||||
if [[ ! $env_param ]]; then
|
||||
@@ -168,57 +143,50 @@ run_concurrent() {
|
||||
done
|
||||
|
||||
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
define_program "$file_param"
|
||||
local time=$(date "+$time_format")
|
||||
log_time=$(format_log_time "$time_format" "$time")
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
define_program "$first_param"
|
||||
log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_dir_tmp="${first_param##*/}"
|
||||
log_dir_tmp_path="${first_param%%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_dir="$dir_log/${log_dir_tmp%%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
cmd="&>> $log_path"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
make_dir $log_dir
|
||||
|
||||
local begin_time=$(format_time "$time_format" "$time")
|
||||
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local begin_timestamp=$(date "+%s")
|
||||
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $file_param" | perl -pe "s|.*ID=(.*) $cmd_task $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task $first_param" | perl -pe "s|.*ID=(.*) $cmd_task $first_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
single_log_time=$(date "+%Y-%m-%d-%H-%M-%S.%N")
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
local relative_path="${first_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${first_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
first_param=${first_param/$relative_path\//}
|
||||
fi
|
||||
for i in "${!array[@]}"; do
|
||||
export ${env_param}=${array[i]}
|
||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
eval $timeoutCmd $which_program $file_param &>$single_log_path &
|
||||
single_log_path="$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
timeout -k 10s $command_timeout_time $which_program $first_param &>$single_log_path &
|
||||
done
|
||||
|
||||
wait
|
||||
for i in "${!array[@]}"; do
|
||||
single_log_path="$dir_log/$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
single_log_path="$log_dir/${single_log_time}_$((i + 1)).log"
|
||||
eval cat $single_log_path $cmd
|
||||
[[ -f $single_log_path ]] && rm -f $single_log_path
|
||||
done
|
||||
@@ -241,27 +209,19 @@ run_designated() {
|
||||
fi
|
||||
|
||||
define_program "$file_param"
|
||||
local time=$(date "+$time_format")
|
||||
log_time=$(format_log_time "$time_format" "$time")
|
||||
log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_dir_tmp_path="${file_param%%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_dir="$dir_log/${log_dir_tmp%%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
cmd="&>> $log_path"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
make_dir $log_dir
|
||||
|
||||
local begin_time=$(format_time "$time_format" "$time")
|
||||
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local begin_timestamp=$(date "+%s")
|
||||
|
||||
local envs=$(eval echo "\$${env_param}")
|
||||
local array=($(echo $envs | sed 's/&/ /g'))
|
||||
@@ -276,7 +236,6 @@ run_designated() {
|
||||
done
|
||||
|
||||
local cookieStr=$(echo ${array_run[*]} | sed 's/\ /\&/g')
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
@@ -285,13 +244,15 @@ run_designated() {
|
||||
[[ $id ]] && update_cron "\"$id\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
eval . $file_task_before "$@" $cmd
|
||||
|
||||
[[ ! -z $cookieStr ]] && export ${env_param}=${cookieStr}
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
eval $timeoutCmd $which_program $file_param $cmd
|
||||
eval timeout -k 10s $command_timeout_time $which_program $file_param $cmd
|
||||
|
||||
eval . $file_task_after "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
@@ -305,27 +266,19 @@ run_designated() {
|
||||
run_else() {
|
||||
local file_param="$1"
|
||||
define_program "$file_param"
|
||||
local time=$(date "+$time_format")
|
||||
log_time=$(format_log_time "$time_format" "$time")
|
||||
log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
log_dir_tmp="${file_param##*/}"
|
||||
if [[ $file_param =~ "/" ]]; then
|
||||
if [[ $file_param == /* ]]; then
|
||||
log_dir_tmp_path="${file_param:1}"
|
||||
else
|
||||
log_dir_tmp_path="${file_param}"
|
||||
fi
|
||||
fi
|
||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||
log_dir_tmp_path="${file_param%%/*}"
|
||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||
log_dir="${log_dir_tmp%.*}"
|
||||
log_dir="$dir_log/${log_dir_tmp%%.*}"
|
||||
log_path="$log_dir/$log_time.log"
|
||||
cmd=">> $dir_log/$log_path 2>&1"
|
||||
cmd="&>> $log_path"
|
||||
[[ "$show_log" == "true" ]] && cmd=""
|
||||
make_dir "$dir_log/$log_dir"
|
||||
make_dir $log_dir
|
||||
|
||||
local begin_time=$(format_time "$time_format" "$time")
|
||||
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local begin_timestamp=$(date "+%s")
|
||||
|
||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||
[[ -f $task_error_log_path ]] && eval cat $task_error_log_path $cmd
|
||||
@@ -342,7 +295,7 @@ run_else() {
|
||||
fi
|
||||
|
||||
shift
|
||||
eval $timeoutCmd $which_program "$file_param" "$@" $cmd
|
||||
eval timeout -k 10s $command_timeout_time $which_program "$file_param" "$@" $cmd
|
||||
|
||||
eval . $file_task_after "$file_param" "$@" $cmd
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
@@ -365,13 +318,7 @@ main() {
|
||||
done
|
||||
[[ "$show_log" == "true" ]] && shift $(($OPTIND - 1))
|
||||
|
||||
timeoutCmd=""
|
||||
if type timeout &>/dev/null; then
|
||||
timeoutCmd="timeout -k 10s $command_timeout_time "
|
||||
fi
|
||||
|
||||
time_format="%Y-%m-%d %H:%M:%S"
|
||||
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.pyc ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||
case $# in
|
||||
1)
|
||||
run_normal "$1"
|
||||
@@ -393,7 +340,7 @@ main() {
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
[[ -f "$dir_log/$log_path" ]] && cat "$dir_log/$log_path"
|
||||
[[ -f $log_path ]] && cat $log_path
|
||||
elif [[ $# -eq 0 ]]; then
|
||||
echo
|
||||
usage
|
||||
|
||||
+56
-87
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
dir_shell=$QL_DIR/shell
|
||||
dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
. $dir_shell/api.sh
|
||||
|
||||
@@ -12,16 +12,14 @@ diff_cron() {
|
||||
local list_task="$2"
|
||||
local list_add="$3"
|
||||
local list_drop="$4"
|
||||
if [[ -s $list_task ]] && [[ -s $list_scripts ]]; then
|
||||
if [[ -s $list_task ]]; then
|
||||
grep -vwf $list_task $list_scripts >$list_add
|
||||
grep -vwf $list_scripts $list_task >$list_drop
|
||||
fi
|
||||
|
||||
if [[ ! -s $list_task ]] && [[ -s $list_scripts ]]; then
|
||||
elif [[ ! -s $list_task ]] && [[ -s $list_scripts ]]; then
|
||||
cp -f $list_scripts $list_add
|
||||
fi
|
||||
|
||||
if [[ ! -s $list_scripts ]] && [[ -s $list_task ]]; then
|
||||
if [[ -s $list_scripts ]]; then
|
||||
grep -vwf $list_scripts $list_task >$list_drop
|
||||
else
|
||||
cp -f $list_task $list_drop
|
||||
fi
|
||||
}
|
||||
@@ -45,7 +43,7 @@ detect_config_version() {
|
||||
local notify_title="配置文件更新通知"
|
||||
local notify_content="更新日期: $update_date\n用户版本: $ver_config_user\n新的版本: $ver_config_sample\n更新内容: $update_content\n更新说明: 如需使用新功能请对照config.sample.sh,将相关新参数手动增加到你自己的config.sh中,否则请无视本消息。本消息只在该新版本配置文件更新当天发送一次。\n"
|
||||
echo -e $notify_content
|
||||
notify_api "$notify_title" "$notify_content"
|
||||
notify "$notify_title" "$notify_content"
|
||||
[[ $? -eq 0 ]] && echo $ver_config_sample >$send_mark
|
||||
fi
|
||||
else
|
||||
@@ -93,7 +91,7 @@ del_cron() {
|
||||
done
|
||||
if [[ $ids ]]; then
|
||||
result=$(del_cron_api "$ids")
|
||||
notify_api "$path 删除任务${result}" "$detail"
|
||||
notify "$path 删除任务${result}" "$detail"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -133,7 +131,7 @@ add_cron() {
|
||||
fi
|
||||
fi
|
||||
done
|
||||
notify_api "$path 新增任务" "$detail"
|
||||
notify "$path 新增任务" "$detail"
|
||||
}
|
||||
|
||||
## 更新仓库
|
||||
@@ -143,7 +141,6 @@ update_repo() {
|
||||
local blackword="$3"
|
||||
local dependence="$4"
|
||||
local branch="$5"
|
||||
local extensions="$6"
|
||||
local tmp="${url%/*}"
|
||||
local authorTmp1="${tmp##*/}"
|
||||
local authorTmp2="${authorTmp1##*:}"
|
||||
@@ -162,10 +159,18 @@ update_repo() {
|
||||
fi
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新${repo_path}成功...\n"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence"
|
||||
else
|
||||
echo -e "\n更新${repo_path}失败,重新下载全新仓库...\n"
|
||||
rm -rf ${repo_path}
|
||||
git_clone_scripts "${formatUrl}" ${repo_path} "${branch}"
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新${repo_path}成功...\n"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence"
|
||||
else
|
||||
echo -e "\n更新${repo_path}失败,请检查网络...\n"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
## 更新所有 raw 文件
|
||||
@@ -206,7 +211,7 @@ update_raw() {
|
||||
if [[ -z $cron_id ]]; then
|
||||
result=$(add_cron_api "$cron_line:$cmd_task $filename:$cron_name")
|
||||
echo -e "$result\n"
|
||||
notify_api "新增任务通知" "\n$result"
|
||||
notify "新增任务通知" "\n$result"
|
||||
# update_cron_api "$cron_line:$cmd_task $filename:$cron_name:$cron_id"
|
||||
fi
|
||||
else
|
||||
@@ -234,7 +239,7 @@ usage() {
|
||||
echo -e "1. $cmd_update update # 更新并重启青龙"
|
||||
echo -e "2. $cmd_update extra # 运行自定义脚本"
|
||||
echo -e "3. $cmd_update raw <fileurl> # 更新单个脚本文件"
|
||||
echo -e "4. $cmd_update repo <repourl> <path> <blacklist> <dependence> <branch> <extensions> # 更新单个仓库的脚本"
|
||||
echo -e "4. $cmd_update repo <repourl> <path> <blacklist> <dependence> <branch> # 更新单个仓库的脚本"
|
||||
echo -e "5. $cmd_update rmlog <days> # 删除旧日志"
|
||||
echo -e "6. $cmd_update bot # 启动tg-bot"
|
||||
echo -e "7. $cmd_update check # 检测青龙环境并修复"
|
||||
@@ -247,17 +252,12 @@ update_qinglong() {
|
||||
patch_version
|
||||
|
||||
local no_restart="$1"
|
||||
local all_branch=$(git branch -a)
|
||||
local primary_branch="master"
|
||||
if [[ "${all_branch}" =~ "${current_branch}" ]]; then
|
||||
primary_branch="${current_branch}"
|
||||
fi
|
||||
[[ -f $dir_root/package.json ]] && ql_depend_old=$(cat $dir_root/package.json)
|
||||
reset_romote_url ${dir_root} "https://github.com/whyour/qinglong.git" ${primary_branch}
|
||||
git_pull_scripts $dir_root ${primary_branch}
|
||||
reset_romote_url ${dir_root} "https://github.com/whyour/qinglong.git" "master"
|
||||
git_pull_scripts $dir_root "master"
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新青龙源文件成功...\n"
|
||||
echo -e "\n更新$dir_root成功...\n"
|
||||
cp -f $file_config_sample $dir_config/config.sample.sh
|
||||
detect_config_version
|
||||
update_depend
|
||||
@@ -265,23 +265,23 @@ update_qinglong() {
|
||||
[[ -f $dir_root/package.json ]] && ql_depend_new=$(cat $dir_root/package.json)
|
||||
[[ "$ql_depend_old" != "$ql_depend_new" ]] && npm_install_2 $dir_root
|
||||
else
|
||||
echo -e "\n更新青龙源文件失败,请检查原因...\n"
|
||||
echo -e "\n更新$dir_root失败,请检查原因...\n"
|
||||
fi
|
||||
|
||||
local url="https://github.com/whyour/qinglong-static.git"
|
||||
if [[ -d ${ql_static_repo}/.git ]]; then
|
||||
reset_romote_url ${ql_static_repo} ${url} ${primary_branch}
|
||||
git_pull_scripts ${ql_static_repo} ${primary_branch}
|
||||
reset_romote_url ${ql_static_repo} ${url} "master"
|
||||
git_pull_scripts ${ql_static_repo} "master"
|
||||
else
|
||||
git_clone_scripts ${url} ${ql_static_repo} ${primary_branch}
|
||||
git_clone_scripts ${url} ${ql_static_repo}
|
||||
fi
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n更新青龙静态资源成功...\n"
|
||||
local static_version=$(cat $dir_root/src/version.ts | perl -pe "s|.*\'(.*)\';\.*|\1|" | head -1)
|
||||
echo -e "\n更新$ql_static_repo成功...\n"
|
||||
local static_version=$(cat /ql/src/version.ts | perl -pe "s|.*\'(.*)\';\.*|\1|" | head -1)
|
||||
echo -e "\n当前版本 $static_version...\n"
|
||||
|
||||
rm -rf $dir_static/*
|
||||
cp -rf $ql_static_repo/* $dir_static
|
||||
cd $dir_root
|
||||
rm -rf $dir_root/build && rm -rf $dir_root/dist
|
||||
cp -rf $ql_static_repo/* $dir_root
|
||||
if [[ $no_restart != "no-restart" ]]; then
|
||||
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
|
||||
echo -e "重启面板中..."
|
||||
@@ -289,63 +289,34 @@ update_qinglong() {
|
||||
reload_pm2
|
||||
fi
|
||||
else
|
||||
echo -e "\n更新青龙静态资源失败,请检查原因...\n"
|
||||
echo -e "\n更新$dir_root失败,请检查原因...\n"
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
patch_version() {
|
||||
# 兼容pnpm@7
|
||||
pnpm setup &>/dev/null
|
||||
source ~/.bashrc
|
||||
pnpm install -g &>/dev/null
|
||||
|
||||
if [[ -f "$dir_root/db/cookie.db" ]]; then
|
||||
if [[ -f "/ql/db/cookie.db" ]]; then
|
||||
echo -e "检测到旧的db文件,拷贝为新db...\n"
|
||||
mv $dir_root/db/cookie.db $dir_root/db/env.db
|
||||
rm -rf $dir_root/db/cookie.db
|
||||
mv /ql/db/cookie.db /ql/db/env.db
|
||||
rm -rf /ql/db/cookie.db
|
||||
echo
|
||||
fi
|
||||
|
||||
if ! type ts-node &>/dev/null; then
|
||||
pnpm add -g ts-node typescript tslib
|
||||
pnpm i -g ts-node typescript tslib
|
||||
fi
|
||||
|
||||
git config --global pull.rebase false
|
||||
}
|
||||
|
||||
cp -f $dir_root/.env.example $dir_root/.env
|
||||
reload_pm2() {
|
||||
pm2 l &>/dev/null
|
||||
|
||||
if [[ -d "$dir_root/db" ]]; then
|
||||
echo -e "检测到旧的db目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/config $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/scripts" ]]; then
|
||||
echo -e "检测到旧的scripts目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/scripts $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/log" ]]; then
|
||||
echo -e "检测到旧的log目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/log $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ -d "$dir_root/config" ]]; then
|
||||
echo -e "检测到旧的config目录,拷贝到data目录...\n"
|
||||
cp -rf $dir_root/config $dir_root/data
|
||||
echo
|
||||
fi
|
||||
|
||||
if [[ $PipMirror ]]; then
|
||||
pip3 config set global.index-url $PipMirror
|
||||
fi
|
||||
if [[ $NpmMirror ]]; then
|
||||
npm config set registry $NpmMirror
|
||||
fi
|
||||
pm2 delete panel --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_root/build/app.js -n panel --source-map-support --time &>/dev/null
|
||||
|
||||
pm2 delete schedule --source-map-support --time &>/dev/null
|
||||
pm2 start $dir_root/build/schedule.js -n schedule --source-map-support --time &>/dev/null
|
||||
}
|
||||
|
||||
## 对比脚本
|
||||
@@ -356,9 +327,8 @@ diff_scripts() {
|
||||
local path="$3"
|
||||
local blackword="$4"
|
||||
local dependence="$5"
|
||||
local extensions="$6"
|
||||
|
||||
gen_list_repo "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions"
|
||||
gen_list_repo "$repo_path" "$author" "$path" "$blackword" "$dependence"
|
||||
|
||||
local list_add="$dir_list_tmp/${uniq_path}_add.list"
|
||||
local list_drop="$dir_list_tmp/${uniq_path}_drop.list"
|
||||
@@ -394,12 +364,6 @@ gen_list_repo() {
|
||||
|
||||
local cmd="find ."
|
||||
local index=0
|
||||
if [[ $6 ]]; then
|
||||
file_extensions="$6"
|
||||
if [[ $file_extensions =~ "|" ]]; then
|
||||
file_extensions=$(echo $file_extensions | sed 's/|/ /g')
|
||||
fi
|
||||
fi
|
||||
for extension in $file_extensions; do
|
||||
if [[ $index -eq 0 ]]; then
|
||||
cmd="${cmd} -name \"*.${extension}\""
|
||||
@@ -480,7 +444,6 @@ main() {
|
||||
local p4=$4
|
||||
local p5=$5
|
||||
local p6=$6
|
||||
local p7=$7
|
||||
local log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
local log_path="$dir_log/update/${log_time}_$p1.log"
|
||||
local begin_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
@@ -499,18 +462,26 @@ main() {
|
||||
run_extra_shell >>$log_path
|
||||
;;
|
||||
repo)
|
||||
get_user_info
|
||||
get_uniq_path "$p2" "$p6"
|
||||
log_path="$dir_log/update/${log_time}_${uniq_path}.log"
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||
if [[ -n $p2 ]]; then
|
||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7"
|
||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" >>$log_path
|
||||
else
|
||||
echo -e "命令输入错误...\n"
|
||||
usage
|
||||
fi
|
||||
;;
|
||||
raw)
|
||||
get_user_info
|
||||
get_uniq_path "$p2"
|
||||
log_path="$dir_log/update/${log_time}_${uniq_path}.log"
|
||||
echo -e "## 开始执行... $begin_time\n" >>$log_path
|
||||
[[ -f $task_error_log_path ]] && cat $task_error_log_path >>$log_path
|
||||
if [[ -n $p2 ]]; then
|
||||
update_raw "$p2"
|
||||
update_raw "$p2" >>$log_path
|
||||
else
|
||||
echo -e "命令输入错误...\n"
|
||||
usage
|
||||
@@ -549,11 +520,9 @@ main() {
|
||||
;;
|
||||
esac
|
||||
local end_time=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
local diff_time=$(diff_time "%Y-%m-%d %H:%M:%S" "$begin_time" "$end_time")
|
||||
if [[ $p1 != "repo" ]] && [[ $p1 != "raw" ]]; then
|
||||
local diff_time=$(($(date +%s -d "$end_time") - $(date +%s -d "$begin_time")))
|
||||
echo -e "\n## 执行结束... $end_time 耗时 $diff_time 秒" >>$log_path
|
||||
cat $log_path
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { createFromIconfontCN } from '@ant-design/icons';
|
||||
|
||||
const IconFont = createFromIconfontCN({
|
||||
scriptUrl: ['//at.alicdn.com/t/font_3354854_ds8pa06q1qa.js'],
|
||||
});
|
||||
|
||||
export default IconFont;
|
||||
@@ -1,77 +0,0 @@
|
||||
.react-terminal-wrapper {
|
||||
width: 100%;
|
||||
background: #252a33;
|
||||
color: #eee;
|
||||
font-size: 18px;
|
||||
font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier,
|
||||
monospace;
|
||||
border-radius: 4px;
|
||||
padding: 75px 45px 35px;
|
||||
position: relative;
|
||||
-webkit-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.react-terminal {
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.react-terminal-wrapper.react-terminal-light {
|
||||
background: #ddd;
|
||||
color: #1a1e24;
|
||||
}
|
||||
|
||||
.react-terminal-wrapper:before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
left: 15px;
|
||||
display: inline-block;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border-radius: 50%;
|
||||
background: #d9515d;
|
||||
-webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930;
|
||||
box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930;
|
||||
}
|
||||
|
||||
.react-terminal-wrapper:after {
|
||||
content: attr(data-terminal-name);
|
||||
position: absolute;
|
||||
color: #a2a2a2;
|
||||
top: 5px;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.react-terminal-wrapper.react-terminal-light:after {
|
||||
color: #d76d77;
|
||||
}
|
||||
|
||||
.react-terminal-line {
|
||||
display: block;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.react-terminal-line:before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
color: #a2a2a2;
|
||||
}
|
||||
|
||||
.react-terminal-light .react-terminal-line:before {
|
||||
color: #d76d77;
|
||||
}
|
||||
|
||||
.react-terminal-input:before {
|
||||
margin-right: 0.75em;
|
||||
content: '$';
|
||||
}
|
||||
|
||||
.react-terminal-input[data-terminal-prompt]:before {
|
||||
content: attr(data-terminal-prompt);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { Tag, Input } from 'antd';
|
||||
import { TweenOneGroup } from 'rc-tween-one';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
const EditableTagGroup = ({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value?: string[];
|
||||
onChange?: (tags: string[]) => void;
|
||||
}) => {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const [inputVisible, setInputVisible] = useState(false);
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const saveInputRef = useRef<any>();
|
||||
|
||||
const handleClose = (removedTag: string) => {
|
||||
const _tags = tags.filter((tag) => tag !== removedTag);
|
||||
setTags(_tags);
|
||||
onChange?.(_tags);
|
||||
};
|
||||
|
||||
const showInput = () => {
|
||||
setInputVisible(true);
|
||||
};
|
||||
|
||||
const handleInputChange = (e) => {
|
||||
setInputValue(e.target.value);
|
||||
};
|
||||
|
||||
const handleInputConfirm = () => {
|
||||
if (inputValue && !tags.includes(inputValue)) {
|
||||
setTags([...tags, inputValue]);
|
||||
onChange?.([...tags, inputValue]);
|
||||
}
|
||||
setInputVisible(false);
|
||||
setInputValue('');
|
||||
};
|
||||
|
||||
const tagChild = tags.map((tag) => {
|
||||
const tagElem = (
|
||||
<Tag
|
||||
closable
|
||||
onClose={(e) => {
|
||||
e.preventDefault();
|
||||
handleClose(tag);
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</Tag>
|
||||
);
|
||||
return (
|
||||
<span key={tag} style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||
{tagElem}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (inputVisible && saveInputRef) {
|
||||
saveInputRef.current.focus();
|
||||
}
|
||||
}, [inputVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (value) {
|
||||
setTags(value);
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<TweenOneGroup
|
||||
enter={{
|
||||
scale: 0.8,
|
||||
opacity: 0,
|
||||
type: 'from',
|
||||
duration: 100,
|
||||
}}
|
||||
leave={{ opacity: 0, width: 0, scale: 0, duration: 200 }}
|
||||
appear={false}
|
||||
>
|
||||
{tagChild}
|
||||
</TweenOneGroup>
|
||||
{inputVisible && (
|
||||
<Input
|
||||
ref={saveInputRef}
|
||||
type="text"
|
||||
size="small"
|
||||
style={{ width: 78 }}
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
onBlur={handleInputConfirm}
|
||||
onPressEnter={handleInputConfirm}
|
||||
/>
|
||||
)}
|
||||
{!inputVisible && (
|
||||
<Tag
|
||||
onClick={showInput}
|
||||
style={{ borderStyle: 'dashed', cursor: 'pointer' }}
|
||||
>
|
||||
<PlusOutlined /> 新建
|
||||
</Tag>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditableTagGroup;
|
||||
@@ -1,80 +0,0 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import './index.less';
|
||||
|
||||
export enum LineType {
|
||||
Input,
|
||||
Output,
|
||||
}
|
||||
|
||||
export enum ColorMode {
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
export interface Props {
|
||||
name?: string;
|
||||
prompt?: string;
|
||||
colorMode?: ColorMode;
|
||||
lineData: Array<{ type: LineType; value: string | React.ReactNode }>;
|
||||
startingInputValue?: string;
|
||||
}
|
||||
|
||||
const Terminal = ({
|
||||
name,
|
||||
prompt,
|
||||
colorMode,
|
||||
lineData,
|
||||
startingInputValue = '',
|
||||
}: Props) => {
|
||||
const lastLineRef = useRef<null | HTMLElement>(null);
|
||||
|
||||
// An effect that handles scrolling into view the last line of terminal input or output
|
||||
const performScrolldown = useRef(false);
|
||||
useEffect(() => {
|
||||
if (performScrolldown.current) {
|
||||
// skip scrolldown when the component first loads
|
||||
setTimeout(
|
||||
() =>
|
||||
lastLineRef?.current?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'nearest',
|
||||
}),
|
||||
500,
|
||||
);
|
||||
}
|
||||
performScrolldown.current = true;
|
||||
}, [lineData.length]);
|
||||
|
||||
const renderedLineData = lineData.map((ld, i) => {
|
||||
const classes = ['react-terminal-line'];
|
||||
if (ld.type === LineType.Input) {
|
||||
classes.push('react-terminal-input');
|
||||
}
|
||||
// `lastLineRef` is used to ensure the terminal scrolls into view to the last line; make sure to add the ref to the last
|
||||
if (lineData.length === i + 1) {
|
||||
return (
|
||||
<span className={classes.join(' ')} key={i} ref={lastLineRef}>
|
||||
{ld.value}
|
||||
</span>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<span className={classes.join(' ')} key={i}>
|
||||
{ld.value}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const classes = ['react-terminal-wrapper'];
|
||||
if (colorMode === ColorMode.Light) {
|
||||
classes.push('react-terminal-light');
|
||||
}
|
||||
return (
|
||||
<div className={classes.join(' ')} data-terminal-name={name}>
|
||||
<div className="react-terminal">{renderedLineData}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Terminal;
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
ControlOutlined,
|
||||
ContainerOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import IconFont from '@/components/iconfont';
|
||||
|
||||
export default {
|
||||
route: {
|
||||
@@ -26,58 +25,46 @@ export default {
|
||||
hideInMenu: true,
|
||||
component: '@/pages/initialization/index',
|
||||
},
|
||||
{
|
||||
name: '错误',
|
||||
path: '/error',
|
||||
hideInMenu: true,
|
||||
component: '@/pages/error/index',
|
||||
},
|
||||
{
|
||||
path: '/crontab',
|
||||
name: '定时任务',
|
||||
icon: <IconFont type="ql-icon-crontab" />,
|
||||
icon: <FieldTimeOutlined />,
|
||||
component: '@/pages/crontab/index',
|
||||
},
|
||||
{
|
||||
path: '/subscription',
|
||||
name: '订阅管理',
|
||||
icon: <IconFont type="ql-icon-subs" />,
|
||||
component: '@/pages/subscription/index',
|
||||
},
|
||||
{
|
||||
path: '/env',
|
||||
name: '环境变量',
|
||||
icon: <IconFont type="ql-icon-env" />,
|
||||
icon: <RadiusSettingOutlined />,
|
||||
component: '@/pages/env/index',
|
||||
},
|
||||
{
|
||||
path: '/config',
|
||||
name: '配置文件',
|
||||
icon: <IconFont type="ql-icon-config" />,
|
||||
icon: <ControlOutlined />,
|
||||
component: '@/pages/config/index',
|
||||
},
|
||||
{
|
||||
path: '/script',
|
||||
name: '脚本管理',
|
||||
icon: <IconFont type="ql-icon-script" />,
|
||||
icon: <FormOutlined />,
|
||||
component: '@/pages/script/index',
|
||||
},
|
||||
{
|
||||
path: '/dependence',
|
||||
name: '依赖管理',
|
||||
icon: <IconFont type="ql-icon-dependence" />,
|
||||
icon: <ContainerOutlined />,
|
||||
component: '@/pages/dependence/index',
|
||||
},
|
||||
{
|
||||
path: '/diff',
|
||||
name: '对比工具',
|
||||
icon: <IconFont type="ql-icon-diff" />,
|
||||
icon: <DiffOutlined />,
|
||||
component: '@/pages/diff/index',
|
||||
},
|
||||
{
|
||||
path: '/log',
|
||||
name: '任务日志',
|
||||
icon: <IconFont type="ql-icon-log" />,
|
||||
icon: <FolderOutlined />,
|
||||
component: '@/pages/log/index',
|
||||
},
|
||||
{
|
||||
|
||||
+23
-61
@@ -1,4 +1,4 @@
|
||||
@import '~antd/es/style/themes/default.less';
|
||||
@import '~antd/lib/style/themes/default.less';
|
||||
@import '~@/styles/variable.less';
|
||||
@import '~codemirror/lib/codemirror.css';
|
||||
|
||||
@@ -9,12 +9,6 @@
|
||||
url('../assets/fonts/SourceCodePro-Regular.ttf') format('truetype');
|
||||
}
|
||||
|
||||
.ant-modal-body {
|
||||
max-height: calc(85vh - 110px);
|
||||
max-height: calc(85vh - var(--vh-offset, 110px));
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.log-modal {
|
||||
.ant-modal {
|
||||
padding-bottom: 0 !important;
|
||||
@@ -32,7 +26,6 @@
|
||||
.monaco-editor:not(.rename-box) {
|
||||
height: calc(100vh - 128px) !important;
|
||||
height: calc(100vh - var(--vh-offset, 0px) - 128px) !important;
|
||||
|
||||
.view-overlays .current-line {
|
||||
border-width: 0;
|
||||
}
|
||||
@@ -40,7 +33,6 @@
|
||||
|
||||
.rename-box {
|
||||
height: 0;
|
||||
|
||||
.rename-input {
|
||||
height: 0;
|
||||
padding: 0 !important;
|
||||
@@ -51,18 +43,11 @@
|
||||
.ant-pro-grid-content.wide {
|
||||
max-width: unset !important;
|
||||
overflow: auto;
|
||||
|
||||
.ant-pro-page-container-children-content {
|
||||
overflow: auto;
|
||||
height: 100%;
|
||||
background-color: @component-background;
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.ql-container-wrapper-has-tab {
|
||||
.ant-pro-grid-content.wide .ant-pro-page-container-children-content {
|
||||
padding-top: 0;
|
||||
background-color: #fff;
|
||||
padding: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +57,6 @@
|
||||
|
||||
.ant-tooltip {
|
||||
max-width: 500px !important;
|
||||
|
||||
.ant-tooltip-inner {
|
||||
word-break: break-all !important;
|
||||
}
|
||||
@@ -88,7 +72,6 @@
|
||||
.log-select {
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
.ant-page-header-heading-left {
|
||||
min-width: 100px;
|
||||
}
|
||||
@@ -98,7 +81,6 @@
|
||||
.config-select {
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
.ant-page-header-heading-left {
|
||||
min-width: 100px;
|
||||
}
|
||||
@@ -137,13 +119,10 @@
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 48px);
|
||||
height: calc(100vh - var(--vh-offset, 0px) - 48px);
|
||||
|
||||
.ant-pro-grid-content.wide {
|
||||
flex: 1;
|
||||
|
||||
.ant-pro-grid-content-children {
|
||||
height: 100%;
|
||||
|
||||
height: calc(100% - 36px);
|
||||
> div,
|
||||
.log-container,
|
||||
.react-codemirror2,
|
||||
@@ -178,7 +157,7 @@
|
||||
}
|
||||
|
||||
.Resizer {
|
||||
background: @component-background;
|
||||
background: #fff;
|
||||
opacity: 0.2;
|
||||
z-index: 1;
|
||||
-moz-box-sizing: border-box;
|
||||
@@ -218,7 +197,6 @@
|
||||
.Resizer.disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.Resizer.disabled:hover {
|
||||
border-color: transparent;
|
||||
}
|
||||
@@ -231,7 +209,6 @@
|
||||
|
||||
.inline-countdown.ant-statistic {
|
||||
display: inline-block;
|
||||
|
||||
.ant-statistic-content {
|
||||
font-size: 14px;
|
||||
padding: 0 3px;
|
||||
@@ -270,24 +247,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ant-pro-basicLayout-content {
|
||||
margin: 12px;
|
||||
|
||||
.ant-pro-page-container {
|
||||
margin: -12px;
|
||||
}
|
||||
|
||||
.ant-pro-page-container-warp .ant-page-header {
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.ant-pro-page-container-children-content {
|
||||
margin: 0;
|
||||
}
|
||||
.ant-pro-page-container-children-content {
|
||||
margin: 18px 18px 18px;
|
||||
}
|
||||
|
||||
.ant-pro-global-header {
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.03);
|
||||
.ant-pro-basicLayout-content {
|
||||
margin: 18px;
|
||||
.ant-pro-page-container {
|
||||
margin: -18px -18px -18px;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-menu-item.ant-pro-sider-collapsed-button {
|
||||
@@ -298,7 +266,7 @@
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
color: @text-color;
|
||||
color: rgba(0, 0, 0, 0.85);
|
||||
|
||||
.side-menu-collapse-button:hover {
|
||||
color: #1890ff;
|
||||
@@ -312,31 +280,25 @@
|
||||
|
||||
.side-menu-user-drop-menu {
|
||||
position: relative;
|
||||
text-align: left;
|
||||
outline: none;
|
||||
margin: 0;
|
||||
padding: 4px 0;
|
||||
border: 1px solid fade(@component-background, 0.12);
|
||||
text-align: left;
|
||||
background-clip: padding-box;
|
||||
outline: none;
|
||||
background-color: #fff;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
|
||||
overflow: auto;
|
||||
background-color: @component-background;
|
||||
}
|
||||
|
||||
[data-dark='true'] .side-menu-user-drop-menu {
|
||||
background-color: #373739;
|
||||
}
|
||||
|
||||
.ant-layout-sider {
|
||||
border-right: 1px solid rgba(0, 0, 0, 0.06) !important;
|
||||
box-shadow: 0 6px 16px -8px rgb(0 0 0 / 8%), 0 9px 28px 0 rgb(0 0 0 / 5%),
|
||||
0 12px 48px 16px rgb(0 0 0 / 3%);
|
||||
.ant-dropdown-menu-item:hover {
|
||||
color: #1890ff;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-pro-sider-logo {
|
||||
padding: 16px 8px !important;
|
||||
|
||||
h1 {
|
||||
margin-left: 5px !important;
|
||||
}
|
||||
|
||||
img {
|
||||
width: 32px !important;
|
||||
border-radius: 52% !important;
|
||||
|
||||
+62
-64
@@ -1,6 +1,11 @@
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
|
||||
import * as DarkReader from '@umijs/ssr-darkreader';
|
||||
import {
|
||||
enable as enableDarkMode,
|
||||
disable as disableDarkMode,
|
||||
auto as followSystemColorScheme,
|
||||
setFetchMethod,
|
||||
} from 'darkreader';
|
||||
import defaultProps from './defaultProps';
|
||||
import { Link, history } from 'umi';
|
||||
import {
|
||||
@@ -19,24 +24,24 @@ import { message, Badge, Modal, Avatar, Dropdown, Menu, Image } from 'antd';
|
||||
// @ts-ignore
|
||||
import SockJS from 'sockjs-client';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { init } from '../utils/init';
|
||||
import { Integrations } from '@sentry/tracing';
|
||||
|
||||
Sentry.init({
|
||||
dsn: 'https://3406424fb1dc4813a62d39e844a9d0ac@o1098464.ingest.sentry.io/6122818',
|
||||
integrations: [new Integrations.BrowserTracing()],
|
||||
release: version,
|
||||
tracesSampleRate: 1.0,
|
||||
});
|
||||
|
||||
export default function (props: any) {
|
||||
const ctx = useCtx();
|
||||
const { theme, reloadTheme } = useTheme();
|
||||
const [user, setUser] = useState<any>({});
|
||||
const theme = useTheme();
|
||||
const [user, setUser] = useState<any>();
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [systemInfo, setSystemInfo] = useState<{ isInitialized: boolean }>();
|
||||
const ws = useRef<any>(null);
|
||||
const [socketMessage, setSocketMessage] = useState<any>();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const {
|
||||
enable: enableDarkMode,
|
||||
disable: disableDarkMode,
|
||||
exportGeneratedCSS: collectCSS,
|
||||
setFetchMethod,
|
||||
auto: followSystemColorScheme,
|
||||
} = DarkReader || {};
|
||||
|
||||
const logout = () => {
|
||||
request.post(`${config.apiPrefix}user/logout`).then(() => {
|
||||
@@ -86,10 +91,26 @@ export default function (props: any) {
|
||||
});
|
||||
};
|
||||
|
||||
const reloadUser = (needLoading = false) => {
|
||||
getUser(needLoading);
|
||||
const reloadUser = () => {
|
||||
getUser(false);
|
||||
};
|
||||
|
||||
const setTheme = () => {
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const storageTheme = localStorage.getItem('qinglong_dark_theme');
|
||||
const isDark =
|
||||
(media.matches && storageTheme !== 'light') || storageTheme === 'dark';
|
||||
if (isDark) {
|
||||
document.body.setAttribute('data-dark', 'true');
|
||||
} else {
|
||||
document.body.setAttribute('data-dark', 'false');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
vhCheck();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (systemInfo && systemInfo.isInitialized && !user) {
|
||||
getUser();
|
||||
@@ -103,25 +124,12 @@ export default function (props: any) {
|
||||
}, [systemInfo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (theme === 'vs-dark') {
|
||||
document.body.setAttribute('data-dark', 'true');
|
||||
} else {
|
||||
document.body.setAttribute('data-dark', 'false');
|
||||
}
|
||||
}, [theme]);
|
||||
setTheme();
|
||||
}, [theme.theme]);
|
||||
|
||||
useEffect(() => {
|
||||
vhCheck();
|
||||
init();
|
||||
|
||||
const _theme = localStorage.getItem('qinglong_dark_theme') || 'auto';
|
||||
if (typeof window === 'undefined') return;
|
||||
if (typeof window.matchMedia === 'undefined') return;
|
||||
if (!DarkReader) {
|
||||
return () => null;
|
||||
}
|
||||
setFetchMethod(fetch);
|
||||
|
||||
setFetchMethod(window.fetch);
|
||||
if (_theme === 'dark') {
|
||||
enableDarkMode({});
|
||||
} else if (_theme === 'light') {
|
||||
@@ -129,10 +137,6 @@ export default function (props: any) {
|
||||
} else {
|
||||
followSystemColorScheme({});
|
||||
}
|
||||
|
||||
return () => {
|
||||
disableDarkMode();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -183,10 +187,9 @@ export default function (props: any) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (
|
||||
['/login', '/initialization', '/error'].includes(props.location.pathname)
|
||||
) {
|
||||
document.title = `${(config.documentTitleMap as any)[props.location.pathname]
|
||||
if (['/login', '/initialization'].includes(props.location.pathname)) {
|
||||
document.title = `${
|
||||
(config.documentTitleMap as any)[props.location.pathname]
|
||||
} - 控制面板`;
|
||||
if (
|
||||
systemInfo?.isInitialized &&
|
||||
@@ -195,14 +198,14 @@ export default function (props: any) {
|
||||
history.push('/crontab');
|
||||
}
|
||||
|
||||
if (systemInfo || props.location.pathname === '/error') {
|
||||
if (systemInfo) {
|
||||
return React.Children.map(props.children, (child) => {
|
||||
return React.cloneElement(child, {
|
||||
...ctx,
|
||||
theme,
|
||||
...theme,
|
||||
user,
|
||||
reloadUser,
|
||||
reloadTheme,
|
||||
reloadTheme: setTheme,
|
||||
ws: ws.current,
|
||||
});
|
||||
});
|
||||
@@ -216,11 +219,11 @@ export default function (props: any) {
|
||||
const isQQBrowser = navigator.userAgent.includes('QQBrowser');
|
||||
|
||||
const menu = (
|
||||
<Menu
|
||||
className="side-menu-user-drop-menu"
|
||||
items={[{ label: '退出登录', key: 'logout', icon: <LogoutOutlined /> }]}
|
||||
onClick={logout}
|
||||
/>
|
||||
<Menu className="side-menu-user-drop-menu">
|
||||
<Menu.Item key="1" icon={<LogoutOutlined />} onClick={logout}>
|
||||
退出登录
|
||||
</Menu.Item>
|
||||
</Menu>
|
||||
);
|
||||
return loading ? (
|
||||
<PageLoading />
|
||||
@@ -229,7 +232,12 @@ export default function (props: any) {
|
||||
selectedKeys={[props.location.pathname]}
|
||||
loading={loading}
|
||||
ErrorBoundary={Sentry.ErrorBoundary}
|
||||
logo={<Image preview={false} src="http://qn.whyour.cn/logo.png" />}
|
||||
logo={
|
||||
<Image
|
||||
preview={false}
|
||||
src="https://pic.imgdb.cn/item/61acd0dd2ab3f51d912b1986.png"
|
||||
/>
|
||||
}
|
||||
title={
|
||||
<>
|
||||
<span style={{ fontSize: 16 }}>控制面板</span>
|
||||
@@ -275,15 +283,10 @@ export default function (props: any) {
|
||||
collapsed={collapsed}
|
||||
rightContentRender={() =>
|
||||
ctx.isPhone && (
|
||||
<Dropdown overlay={menu} placement="bottomRight" trigger={['click']}>
|
||||
<Dropdown overlay={menu} trigger={['click']}>
|
||||
<span className="side-menu-user-wrapper">
|
||||
<Avatar
|
||||
shape="square"
|
||||
size="small"
|
||||
icon={<UserOutlined />}
|
||||
src={user.avatar ? `/api/static/${user.avatar}` : ''}
|
||||
/>
|
||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||
<Avatar shape="square" size="small" icon={<UserOutlined />} />
|
||||
<span style={{ marginLeft: 5 }}>admin</span>
|
||||
</span>
|
||||
</Dropdown>
|
||||
)
|
||||
@@ -297,15 +300,10 @@ export default function (props: any) {
|
||||
}}
|
||||
>
|
||||
{!collapsed && !ctx.isPhone && (
|
||||
<Dropdown overlay={menu} placement="topLeft" trigger={['hover']}>
|
||||
<Dropdown overlay={menu} trigger={['hover']}>
|
||||
<span className="side-menu-user-wrapper">
|
||||
<Avatar
|
||||
shape="square"
|
||||
size="small"
|
||||
icon={<UserOutlined />}
|
||||
src={user.avatar ? `/api/static/${user.avatar}` : ''}
|
||||
/>
|
||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||
<Avatar shape="square" size="small" icon={<UserOutlined />} />
|
||||
<span style={{ marginLeft: 5 }}>admin</span>
|
||||
</span>
|
||||
</Dropdown>
|
||||
)}
|
||||
@@ -322,10 +320,10 @@ export default function (props: any) {
|
||||
{React.Children.map(props.children, (child) => {
|
||||
return React.cloneElement(child, {
|
||||
...ctx,
|
||||
theme,
|
||||
...theme,
|
||||
user,
|
||||
reloadUser,
|
||||
reloadTheme,
|
||||
reloadTheme: setTheme,
|
||||
socketMessage,
|
||||
});
|
||||
})}
|
||||
|
||||
@@ -1,575 +0,0 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
message,
|
||||
Input,
|
||||
Form,
|
||||
Button,
|
||||
Card,
|
||||
Tag,
|
||||
List,
|
||||
Divider,
|
||||
Typography,
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import {
|
||||
ClockCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
FieldTimeOutlined,
|
||||
Loading3QuartersOutlined,
|
||||
FileOutlined,
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
FullscreenOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { CrontabStatus } from './index';
|
||||
import { diffTime } from '@/utils/date';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
import CronLogModal from './logModal';
|
||||
import Editor from '@monaco-editor/react';
|
||||
import IconFont from '@/components/iconfont';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const tabList = [
|
||||
{
|
||||
key: 'log',
|
||||
tab: '日志',
|
||||
},
|
||||
{
|
||||
key: 'script',
|
||||
tab: '脚本',
|
||||
},
|
||||
];
|
||||
const LangMap: any = {
|
||||
'.py': 'python',
|
||||
'.js': 'javascript',
|
||||
'.sh': 'shell',
|
||||
'.ts': 'typescript',
|
||||
};
|
||||
|
||||
interface LogItem {
|
||||
directory: string;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
const language = navigator.language || navigator.languages[0];
|
||||
|
||||
const CronDetailModal = ({
|
||||
cron = {},
|
||||
handleCancel,
|
||||
visible,
|
||||
theme,
|
||||
isPhone,
|
||||
}: {
|
||||
cron?: any;
|
||||
visible: boolean;
|
||||
handleCancel: (needUpdate?: boolean) => void;
|
||||
theme: string;
|
||||
isPhone: boolean;
|
||||
}) => {
|
||||
const [activeTabKey, setActiveTabKey] = useState('log');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [logs, setLogs] = useState<LogItem[]>([]);
|
||||
const [log, setLog] = useState('');
|
||||
const [value, setValue] = useState('');
|
||||
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
||||
const editorRef = useRef<any>(null);
|
||||
const [scriptInfo, setScriptInfo] = useState<any>({});
|
||||
const [logUrl, setLogUrl] = useState('');
|
||||
const [validTabs, setValidTabs] = useState(tabList);
|
||||
const [currentCron, setCurrentCron] = useState<any>({});
|
||||
|
||||
const contentList: any = {
|
||||
log: (
|
||||
<List
|
||||
dataSource={logs}
|
||||
loading={loading}
|
||||
renderItem={(item) => (
|
||||
<List.Item className="log-item" onClick={() => onClickItem(item)}>
|
||||
<FileOutlined style={{ marginRight: 10 }} />
|
||||
{item.directory}/{item.filename}
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
),
|
||||
script: scriptInfo.filename && (
|
||||
<Editor
|
||||
language={LangMap[scriptInfo.filename.slice(-3)] || ''}
|
||||
theme={theme}
|
||||
value={value}
|
||||
options={{
|
||||
fontSize: 12,
|
||||
lineNumbersMinChars: 3,
|
||||
fontFamily: 'Source Code Pro',
|
||||
folding: false,
|
||||
glyphMargin: false,
|
||||
wordWrap: 'on',
|
||||
}}
|
||||
onMount={(editor, monaco) => {
|
||||
editorRef.current = editor;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
};
|
||||
|
||||
const onClickItem = (item: LogItem) => {
|
||||
localStorage.setItem('logCron', currentCron.id);
|
||||
setLogUrl(
|
||||
`${config.apiPrefix}logs/${item.filename}?path=${item.directory || ''}`,
|
||||
);
|
||||
request
|
||||
.get(
|
||||
`${config.apiPrefix}logs/${item.filename}?path=${item.directory || ''}`,
|
||||
)
|
||||
.then((data) => {
|
||||
setLog(data.data);
|
||||
setIsLogModalVisible(true);
|
||||
});
|
||||
};
|
||||
|
||||
const onTabChange = (key: string) => {
|
||||
setActiveTabKey(key);
|
||||
};
|
||||
|
||||
const getLogs = () => {
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}crons/${cron.id}/logs`)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setLogs(data.data);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const getScript = () => {
|
||||
const cmd = cron.command.split(' ') as string[];
|
||||
if (cmd[0] === 'task') {
|
||||
setValidTabs(validTabs);
|
||||
if (cmd[1].startsWith('/ql/data/scripts')) {
|
||||
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
||||
}
|
||||
|
||||
let p: string, s: string;
|
||||
let index = cmd[1].lastIndexOf('/');
|
||||
if (index >= 0) {
|
||||
s = cmd[1].slice(index + 1);
|
||||
p = cmd[1].slice(0, index);
|
||||
} else {
|
||||
s = cmd[1];
|
||||
p = '';
|
||||
}
|
||||
setScriptInfo({ parent: p, filename: s });
|
||||
request
|
||||
.get(`${config.apiPrefix}scripts/${s}?path=${p || ''}`)
|
||||
.then((data) => {
|
||||
setValue(data.data);
|
||||
});
|
||||
} else {
|
||||
setValidTabs([validTabs[0]]);
|
||||
}
|
||||
};
|
||||
|
||||
const saveFile = () => {
|
||||
Modal.confirm({
|
||||
title: `确认保存`,
|
||||
content: (
|
||||
<>
|
||||
确认保存文件
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{scriptInfo.filename}
|
||||
</Text>{' '}
|
||||
,保存后不可恢复
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
const content = editorRef.current
|
||||
? editorRef.current.getValue().replace(/\r\n/g, '\n')
|
||||
: value;
|
||||
return new Promise((resolve, reject) => {
|
||||
request
|
||||
.put(`${config.apiPrefix}scripts`, {
|
||||
data: {
|
||||
filename: scriptInfo.filename,
|
||||
path: scriptInfo.parent || '',
|
||||
content,
|
||||
},
|
||||
})
|
||||
.then((_data: any) => {
|
||||
if (_data.code === 200) {
|
||||
setValue(content);
|
||||
message.success(`保存成功`);
|
||||
} else {
|
||||
message.error(_data);
|
||||
}
|
||||
resolve(null);
|
||||
})
|
||||
.catch((e) => reject(e));
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const runCron = () => {
|
||||
Modal.confirm({
|
||||
title: '确认运行',
|
||||
content: (
|
||||
<>
|
||||
确认运行定时任务{' '}
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{currentCron.name}
|
||||
</Text>{' '}
|
||||
吗
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/run`, { data: [currentCron.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setCurrentCron({ ...currentCron, status: CrontabStatus.running });
|
||||
setTimeout(() => {
|
||||
getLogs();
|
||||
}, 1000);
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const stopCron = () => {
|
||||
Modal.confirm({
|
||||
title: '确认停止',
|
||||
content: (
|
||||
<>
|
||||
确认停止定时任务{' '}
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{currentCron.name}
|
||||
</Text>{' '}
|
||||
吗
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/stop`, { data: [currentCron.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setCurrentCron({ ...currentCron, status: CrontabStatus.idle });
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const enabledOrDisabledCron = () => {
|
||||
Modal.confirm({
|
||||
title: `确认${currentCron.isDisabled === 1 ? '启用' : '禁用'}`,
|
||||
content: (
|
||||
<>
|
||||
确认{currentCron.isDisabled === 1 ? '启用' : '禁用'}
|
||||
定时任务{' '}
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{currentCron.name}
|
||||
</Text>{' '}
|
||||
吗
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.put(
|
||||
`${config.apiPrefix}crons/${
|
||||
currentCron.isDisabled === 1 ? 'enable' : 'disable'
|
||||
}`,
|
||||
{
|
||||
data: [currentCron.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setCurrentCron({
|
||||
...currentCron,
|
||||
isDisabled: currentCron.isDisabled === 1 ? 0 : 1,
|
||||
});
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const pinOrUnPinCron = () => {
|
||||
Modal.confirm({
|
||||
title: `确认${currentCron.isPinned === 1 ? '取消置顶' : '置顶'}`,
|
||||
content: (
|
||||
<>
|
||||
确认{currentCron.isPinned === 1 ? '取消置顶' : '置顶'}
|
||||
定时任务{' '}
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{currentCron.name}
|
||||
</Text>{' '}
|
||||
吗
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.put(
|
||||
`${config.apiPrefix}crons/${
|
||||
currentCron.isPinned === 1 ? 'unpin' : 'pin'
|
||||
}`,
|
||||
{
|
||||
data: [currentCron.id],
|
||||
},
|
||||
)
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setCurrentCron({
|
||||
...currentCron,
|
||||
isPinned: currentCron.isPinned === 1 ? 0 : 1,
|
||||
});
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const fullscreen = () => {
|
||||
const editorElement = editorRef.current._domElement as HTMLElement;
|
||||
editorElement.parentElement?.requestFullscreen();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (cron && cron.id) {
|
||||
setCurrentCron(cron);
|
||||
getLogs();
|
||||
getScript();
|
||||
}
|
||||
}, [cron]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={
|
||||
<div className="crontab-title-wrapper">
|
||||
<div>
|
||||
<span>{currentCron.name}</span>
|
||||
{currentCron.labels?.length > 0 && currentCron.labels[0] !== '' && (
|
||||
<Divider type="vertical"></Divider>
|
||||
)}
|
||||
{currentCron.labels?.length > 0 &&
|
||||
currentCron.labels[0] !== '' &&
|
||||
currentCron.labels?.map((label: string, i: number) => (
|
||||
<Tag color="blue" style={{ marginRight: 5 }}>
|
||||
{label}
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="operations">
|
||||
<Tooltip
|
||||
title={
|
||||
currentCron.status === CrontabStatus.idle ? '运行' : '停止'
|
||||
}
|
||||
>
|
||||
<Button
|
||||
type="link"
|
||||
icon={
|
||||
currentCron.status === CrontabStatus.idle ? (
|
||||
<PlayCircleOutlined />
|
||||
) : (
|
||||
<PauseCircleOutlined />
|
||||
)
|
||||
}
|
||||
size="small"
|
||||
onClick={
|
||||
currentCron.status === CrontabStatus.idle ? runCron : stopCron
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={currentCron.isDisabled === 1 ? '启用' : '禁用'}>
|
||||
<Button
|
||||
type="link"
|
||||
icon={
|
||||
<IconFont
|
||||
type={
|
||||
currentCron.isDisabled === 1
|
||||
? 'ql-icon-enable'
|
||||
: 'ql-icon-disable'
|
||||
}
|
||||
/>
|
||||
}
|
||||
size="small"
|
||||
onClick={enabledOrDisabledCron}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={currentCron.isPinned === 1 ? '取消置顶' : '置顶'}>
|
||||
<Button
|
||||
type="link"
|
||||
icon={
|
||||
<IconFont
|
||||
type={
|
||||
currentCron.isPinned === 1
|
||||
? 'ql-icon-untop'
|
||||
: 'ql-icon-top'
|
||||
}
|
||||
/>
|
||||
}
|
||||
size="small"
|
||||
onClick={pinOrUnPinCron}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
centered
|
||||
visible={visible}
|
||||
forceRender
|
||||
footer={false}
|
||||
onCancel={() => handleCancel()}
|
||||
wrapClassName="crontab-detail"
|
||||
width={!isPhone ? '80vw' : ''}
|
||||
>
|
||||
<div className="card-wrapper">
|
||||
<Card>
|
||||
<div className="cron-detail-info-item">
|
||||
<div className="cron-detail-info-title">任务</div>
|
||||
<div className="cron-detail-info-value">{currentCron.command}</div>
|
||||
</div>
|
||||
</Card>
|
||||
<Card style={{ marginTop: 10 }}>
|
||||
<div className="cron-detail-info-item">
|
||||
<div className="cron-detail-info-title">状态</div>
|
||||
<div className="cron-detail-info-value">
|
||||
{(!currentCron.isDisabled ||
|
||||
currentCron.status !== CrontabStatus.idle) && (
|
||||
<>
|
||||
{currentCron.status === CrontabStatus.idle && (
|
||||
<Tag icon={<ClockCircleOutlined />} color="default">
|
||||
空闲中
|
||||
</Tag>
|
||||
)}
|
||||
{currentCron.status === CrontabStatus.running && (
|
||||
<Tag
|
||||
icon={<Loading3QuartersOutlined spin />}
|
||||
color="processing"
|
||||
>
|
||||
运行中
|
||||
</Tag>
|
||||
)}
|
||||
{currentCron.status === CrontabStatus.queued && (
|
||||
<Tag icon={<FieldTimeOutlined />} color="default">
|
||||
队列中
|
||||
</Tag>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{currentCron.isDisabled === 1 &&
|
||||
currentCron.status === CrontabStatus.idle && (
|
||||
<Tag icon={<CloseCircleOutlined />} color="error">
|
||||
已禁用
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="cron-detail-info-item">
|
||||
<div className="cron-detail-info-title">定时</div>
|
||||
<div className="cron-detail-info-value">{currentCron.schedule}</div>
|
||||
</div>
|
||||
<div className="cron-detail-info-item">
|
||||
<div className="cron-detail-info-title">最后运行时间</div>
|
||||
<div className="cron-detail-info-value">
|
||||
{currentCron.last_execution_time
|
||||
? new Date(currentCron.last_execution_time * 1000)
|
||||
.toLocaleString(language, {
|
||||
hour12: false,
|
||||
})
|
||||
.replace(' 24:', ' 00:')
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="cron-detail-info-item">
|
||||
<div className="cron-detail-info-title">最后运行时长</div>
|
||||
<div className="cron-detail-info-value">
|
||||
{currentCron.last_running_time
|
||||
? diffTime(currentCron.last_running_time)
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="cron-detail-info-item">
|
||||
<div className="cron-detail-info-title">下次运行时间</div>
|
||||
<div className="cron-detail-info-value">
|
||||
{currentCron.nextRunTime &&
|
||||
currentCron.nextRunTime
|
||||
.toLocaleString(language, {
|
||||
hour12: false,
|
||||
})
|
||||
.replace(' 24:', ' 00:')}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
<Card
|
||||
style={{ marginTop: 10 }}
|
||||
tabList={validTabs}
|
||||
activeTabKey={activeTabKey}
|
||||
onTabChange={(key) => {
|
||||
onTabChange(key);
|
||||
}}
|
||||
tabBarExtraContent={
|
||||
activeTabKey === 'script' && (
|
||||
<>
|
||||
<Button
|
||||
type="primary"
|
||||
style={{ marginRight: 8 }}
|
||||
onClick={saveFile}
|
||||
>
|
||||
保存
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<FullscreenOutlined />}
|
||||
onClick={fullscreen}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{contentList[activeTabKey]}
|
||||
</Card>
|
||||
</div>
|
||||
<CronLogModal
|
||||
visible={isLogModalVisible}
|
||||
handleCancel={() => {
|
||||
setIsLogModalVisible(false);
|
||||
}}
|
||||
cron={cron}
|
||||
data={log}
|
||||
logUrl={logUrl}
|
||||
/>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default CronDetailModal;
|
||||
@@ -1,178 +1,3 @@
|
||||
.ant-table-pagination.ant-pagination {
|
||||
margin-bottom: 0 !important;
|
||||
}
|
||||
|
||||
.crontab-detail {
|
||||
.card-wrapper {
|
||||
height: 80vh;
|
||||
height: calc(80vh - var(--vh-offset, 0px));
|
||||
|
||||
.ant-card:last-child {
|
||||
.ant-card-body {
|
||||
height: calc(80vh - 238px);
|
||||
height: calc(80vh - var(--vh-offset, 0px) - 238px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-modal-body {
|
||||
background: #eee;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.ant-card-body {
|
||||
padding: 18px;
|
||||
}
|
||||
.ant-card-head {
|
||||
padding: 0 18px;
|
||||
}
|
||||
|
||||
.ant-card:first-child {
|
||||
max-height: 66px;
|
||||
overflow: auto;
|
||||
|
||||
.ant-card-body {
|
||||
min-width: 600px;
|
||||
}
|
||||
|
||||
.cron-detail-info-item {
|
||||
display: flex;
|
||||
|
||||
.cron-detail-info-title {
|
||||
width: 50px;
|
||||
}
|
||||
|
||||
.cron-detail-info-value {
|
||||
flex: 1;
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-card:nth-child(2) {
|
||||
overflow-x: auto;
|
||||
|
||||
.ant-card-body {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
min-width: 600px;
|
||||
}
|
||||
}
|
||||
|
||||
.cron-detail-info-item {
|
||||
flex: auto;
|
||||
|
||||
.cron-detail-info-title {
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.cron-detail-info-value {
|
||||
margin-top: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.crontab-title-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-right: 32px;
|
||||
|
||||
.operations {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
.ant-btn:not(:first-child) {
|
||||
margin-left: 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.log-item {
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
background: #fafafa;
|
||||
}
|
||||
}
|
||||
|
||||
.crontab-view {
|
||||
.ant-tabs-nav-wrap {
|
||||
flex: unset !important;
|
||||
}
|
||||
|
||||
.ant-tabs-nav-operations {
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.view-more {
|
||||
margin-left: 32px;
|
||||
padding: 8px 0;
|
||||
cursor: pointer;
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 0;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: #1890ff;
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 50px;
|
||||
}
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: #1890ff;
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 50px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.more-active {
|
||||
.ant-tabs-nav-list {
|
||||
.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
|
||||
color: unset;
|
||||
}
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
width: 0 !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.view-create-modal-filters {
|
||||
display: flex;
|
||||
|
||||
.ant-space-item:nth-child(3) {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.view-create-modal-sorts {
|
||||
display: flex;
|
||||
|
||||
.ant-space-item:nth-child(2) {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
tr.drop-over-downward td {
|
||||
border-bottom: 2px dashed #1890ff;
|
||||
}
|
||||
|
||||
tr.drop-over-upward td {
|
||||
border-top: 2px dashed #1890ff;
|
||||
}
|
||||
|
||||
.view-manage-modal {
|
||||
.ant-modal-body {
|
||||
padding-top: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
+157
-362
@@ -12,8 +12,6 @@ import {
|
||||
Typography,
|
||||
Input,
|
||||
Popover,
|
||||
Tabs,
|
||||
TablePaginationConfig,
|
||||
} from 'antd';
|
||||
import {
|
||||
ClockCircleOutlined,
|
||||
@@ -29,39 +27,29 @@ import {
|
||||
PauseCircleOutlined,
|
||||
FieldTimeOutlined,
|
||||
PushpinOutlined,
|
||||
DownOutlined,
|
||||
SettingOutlined,
|
||||
PlusOutlined,
|
||||
UnorderedListOutlined,
|
||||
CheckOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import config from '@/utils/config';
|
||||
import { PageContainer } from '@ant-design/pro-layout';
|
||||
import { request } from '@/utils/http';
|
||||
import CronModal, { CronLabelModal } from './modal';
|
||||
import CronModal,{ CronLabelModal } from './modal';
|
||||
import CronLogModal from './logModal';
|
||||
import CronDetailModal from './detail';
|
||||
import cron_parser from 'cron-parser';
|
||||
import { diffTime } from '@/utils/date';
|
||||
import { getTableScroll } from '@/utils/index';
|
||||
import { history } from 'umi';
|
||||
import './index.less';
|
||||
import ViewCreateModal from './viewCreateModal';
|
||||
import ViewManageModal from './viewManageModal';
|
||||
import pagination from 'antd/lib/pagination';
|
||||
import { FilterValue, SorterResult } from 'antd/lib/table/interface';
|
||||
|
||||
const { Text, Paragraph } = Typography;
|
||||
const { Text } = Typography;
|
||||
const { Search } = Input;
|
||||
|
||||
export enum CrontabStatus {
|
||||
enum CrontabStatus {
|
||||
'running',
|
||||
'idle',
|
||||
'disabled',
|
||||
'queued',
|
||||
}
|
||||
|
||||
const CrontabSort: any = { 0: 0, 5: 1, 3: 2, 1: 3, 4: 4 };
|
||||
const CrontabSort: any = { 0: 0, 3: 1, 1: 2, 4: 3 };
|
||||
|
||||
enum OperationName {
|
||||
'启用',
|
||||
@@ -81,10 +69,10 @@ enum OperationPath {
|
||||
'unpin',
|
||||
}
|
||||
|
||||
const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const Crontab = ({ headerStyle, isPhone }: any) => {
|
||||
const columns: any = [
|
||||
{
|
||||
title: '名称',
|
||||
title: '任务名',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 150,
|
||||
@@ -93,37 +81,10 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<>
|
||||
<a
|
||||
onClick={() => {
|
||||
setDetailCron(record);
|
||||
setIsDetailModalVisible(true);
|
||||
goToScriptManager(record);
|
||||
}}
|
||||
>
|
||||
{record.labels?.length > 0 && record.labels[0] !== '' && false ? (
|
||||
<Popover
|
||||
placement="right"
|
||||
trigger={isPhone ? 'click' : 'hover'}
|
||||
content={
|
||||
<div>
|
||||
{record.labels?.map((label: string) => (
|
||||
<Tag
|
||||
color="blue"
|
||||
style={{ cursor: 'point' }}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setSearchValue(`label:${label}`);
|
||||
setSearchText(`label:${label}`);
|
||||
}}
|
||||
>
|
||||
<a>{label}</a>
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{record.name || '-'}
|
||||
</Popover>
|
||||
) : (
|
||||
record.name || '-'
|
||||
)}
|
||||
{record.name || record._id}{' '}
|
||||
{record.isPinned ? (
|
||||
<span>
|
||||
<PushpinOutlined />
|
||||
@@ -132,57 +93,69 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
''
|
||||
)}
|
||||
</a>
|
||||
<span>
|
||||
{record.labels?.length > 0 && record.labels[0] !== '' ?
|
||||
<Popover placement='right' trigger={isPhone ? 'click' : 'hover'}
|
||||
content={
|
||||
<div>
|
||||
{record.labels?.map((label: string, i: number) => (
|
||||
<Tag color="blue"
|
||||
onClick={() => { onSearch(`label:${label}`) }}>
|
||||
{label}
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
}>
|
||||
<Tag color="blue">{record.labels[0]}</Tag>
|
||||
</Popover>
|
||||
: ''}
|
||||
</span>
|
||||
</>
|
||||
),
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => a?.name?.localeCompare(b?.name),
|
||||
compare: (a: any, b: any) => a.name.localeCompare(b.name),
|
||||
multiple: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '命令',
|
||||
title: '任务',
|
||||
dataIndex: 'command',
|
||||
key: 'command',
|
||||
width: 300,
|
||||
width: 250,
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any) => {
|
||||
return (
|
||||
<Paragraph
|
||||
<span
|
||||
style={{
|
||||
wordBreak: 'break-all',
|
||||
marginBottom: 0,
|
||||
textAlign: 'left',
|
||||
}}
|
||||
ellipsis={{ tooltip: text, rows: 2 }}
|
||||
>
|
||||
<a
|
||||
onClick={() => {
|
||||
goToScriptManager(record);
|
||||
width: '100%',
|
||||
display: 'inline-block',
|
||||
wordBreak: 'break-all',
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</a>
|
||||
</Paragraph>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => a.command.localeCompare(b.command),
|
||||
multiple: 3,
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '定时规则',
|
||||
title: '任务定时',
|
||||
dataIndex: 'schedule',
|
||||
key: 'schedule',
|
||||
width: 110,
|
||||
align: 'center' as const,
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => a.schedule.localeCompare(b.schedule),
|
||||
multiple: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '最后运行时间',
|
||||
align: 'center' as const,
|
||||
dataIndex: 'last_execution_time',
|
||||
key: 'last_execution_time',
|
||||
width: 150,
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => {
|
||||
@@ -212,17 +185,24 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
title: '最后运行时长',
|
||||
align: 'center' as const,
|
||||
width: 120,
|
||||
dataIndex: 'last_running_time',
|
||||
key: 'last_running_time',
|
||||
sorter: {
|
||||
compare: (a: any, b: any) => {
|
||||
return a.last_running_time - b.last_running_time;
|
||||
},
|
||||
},
|
||||
render: (text: string, record: any) => {
|
||||
return record.last_running_time
|
||||
const language = navigator.language || navigator.languages[0];
|
||||
return (
|
||||
<span
|
||||
style={{
|
||||
display: 'block',
|
||||
}}
|
||||
>
|
||||
{record.last_running_time
|
||||
? diffTime(record.last_running_time)
|
||||
: '-';
|
||||
: '-'}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -236,11 +216,19 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
},
|
||||
render: (text: string, record: any) => {
|
||||
const language = navigator.language || navigator.languages[0];
|
||||
return record.nextRunTime
|
||||
return (
|
||||
<span
|
||||
style={{
|
||||
display: 'block',
|
||||
}}
|
||||
>
|
||||
{record.nextRunTime
|
||||
.toLocaleString(language, {
|
||||
hour12: false,
|
||||
})
|
||||
.replace(' 24:', ' 00:');
|
||||
.replace(' 24:', ' 00:')}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -319,8 +307,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
{record.status === CrontabStatus.idle && (
|
||||
<Tooltip title={isPc ? '运行' : ''}>
|
||||
<a
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick={() => {
|
||||
runCron(record, index);
|
||||
}}
|
||||
>
|
||||
@@ -331,8 +318,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
{record.status !== CrontabStatus.idle && (
|
||||
<Tooltip title={isPc ? '停止' : ''}>
|
||||
<a
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick={() => {
|
||||
stopCron(record, index);
|
||||
}}
|
||||
>
|
||||
@@ -342,8 +328,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
)}
|
||||
<Tooltip title={isPc ? '日志' : ''}>
|
||||
<a
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick={() => {
|
||||
setLogCron({ ...record, timestamp: Date.now() });
|
||||
}}
|
||||
>
|
||||
@@ -360,46 +345,26 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const [value, setValue] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isModalVisible, setIsModalVisible] = useState(false);
|
||||
const [isLabelModalVisible, setIsLabelModalVisible] = useState(false);
|
||||
const [isLabelModalVisible, setisLabelModalVisible] = useState(false);
|
||||
const [editedCron, setEditedCron] = useState();
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
|
||||
const [logCron, setLogCron] = useState<any>();
|
||||
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
|
||||
const [pageConf, setPageConf] = useState<{
|
||||
page: number;
|
||||
size: number;
|
||||
sorter: any;
|
||||
filters: any;
|
||||
}>({} as any);
|
||||
const [viewConf, setViewConf] = useState<any>();
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [tableScrollHeight, setTableScrollHeight] = useState<number>();
|
||||
const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
|
||||
const [detailCron, setDetailCron] = useState<any>();
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const [total, setTotal] = useState<number>();
|
||||
const [isCreateViewModalVisible, setIsCreateViewModalVisible] =
|
||||
useState(false);
|
||||
const [isViewManageModalVisible, setIsViewManageModalVisible] =
|
||||
useState(false);
|
||||
const [cronViews, setCronViews] = useState<any[]>([]);
|
||||
const [enabledCronViews, setEnabledCronViews] = useState<any[]>([]);
|
||||
const [moreMenuActive, setMoreMenuActive] = useState(false);
|
||||
|
||||
const goToScriptManager = (record: any) => {
|
||||
const cmd = record.command.split(' ') as string[];
|
||||
if (cmd[0] === 'task') {
|
||||
if (cmd[1].startsWith('/ql/data/scripts')) {
|
||||
cmd[1] = cmd[1].replace('/ql/data/scripts/', '');
|
||||
if (cmd[1].startsWith('/ql/scripts')) {
|
||||
cmd[1] = cmd[1].replace('/ql/scripts/', '');
|
||||
}
|
||||
|
||||
let p: string, s: string;
|
||||
let index = cmd[1].lastIndexOf('/');
|
||||
if (index >= 0) {
|
||||
s = cmd[1].slice(index + 1);
|
||||
p = cmd[1].slice(0, index);
|
||||
} else {
|
||||
s = cmd[1];
|
||||
let [p, s] = cmd[1].split('/');
|
||||
if (!s) {
|
||||
s = p;
|
||||
p = '';
|
||||
}
|
||||
history.push(`/script?p=${p}&s=${s}`);
|
||||
@@ -410,23 +375,22 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
|
||||
const getCrons = () => {
|
||||
setLoading(true);
|
||||
const { page, size, sorter, filters } = pageConf;
|
||||
let url = `${config.apiPrefix}crons?searchValue=${searchText}&page=${page}&size=${size}&filters=${JSON.stringify(filters)}`;
|
||||
if (sorter && sorter.field) {
|
||||
url += `&sorter=${JSON.stringify({ field: sorter.field, type: sorter.order === 'ascend' ? 'ASC' : 'DESC' })}`;
|
||||
}
|
||||
if (viewConf) {
|
||||
url += `&queryString=${JSON.stringify({
|
||||
filters: viewConf.filters,
|
||||
sorts: viewConf.sorts,
|
||||
})}`;
|
||||
}
|
||||
request
|
||||
.get(url)
|
||||
.then((_data: any) => {
|
||||
const { data, total } = _data.data;
|
||||
.get(`${config.apiPrefix}crons?searchValue=${searchText}`)
|
||||
.then((data: any) => {
|
||||
setValue(
|
||||
data.map((x) => {
|
||||
data.data
|
||||
.sort((a: any, b: any) => {
|
||||
const sortA = a.isDisabled ? 4 : a.status;
|
||||
const sortB = b.isDisabled ? 4 : b.status;
|
||||
a.isPinned = a.isPinned ? a.isPinned : 0;
|
||||
b.isPinned = b.isPinned ? b.isPinned : 0;
|
||||
if (a.isPinned === b.isPinned) {
|
||||
return CrontabSort[sortA] - CrontabSort[sortB];
|
||||
}
|
||||
return b.isPinned - a.isPinned;
|
||||
})
|
||||
.map((x) => {
|
||||
return {
|
||||
...x,
|
||||
nextRunTime: cron_parser
|
||||
@@ -436,7 +400,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
};
|
||||
}),
|
||||
);
|
||||
setTotal(total);
|
||||
setCurrentPage(1);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -471,10 +435,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
message.success('删除成功');
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
result.splice(i, 1);
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
@@ -505,13 +467,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
if (data.code === 200) {
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
result.splice(i, 1, {
|
||||
...record,
|
||||
status: CrontabStatus.running,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
@@ -542,14 +502,12 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
if (data.code === 200) {
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
result.splice(i, 1, {
|
||||
...record,
|
||||
pid: null,
|
||||
status: CrontabStatus.idle,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
@@ -577,7 +535,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.put(
|
||||
`${config.apiPrefix}crons/${record.isDisabled === 1 ? 'enable' : 'disable'
|
||||
`${config.apiPrefix}crons/${
|
||||
record.isDisabled === 1 ? 'enable' : 'disable'
|
||||
}`,
|
||||
{
|
||||
data: [record.id],
|
||||
@@ -588,13 +547,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const newStatus = record.isDisabled === 1 ? 0 : 1;
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
result.splice(i, 1, {
|
||||
...record,
|
||||
isDisabled: newStatus,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
@@ -622,7 +579,8 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
onOk() {
|
||||
request
|
||||
.put(
|
||||
`${config.apiPrefix}crons/${record.isPinned === 1 ? 'unpin' : 'pin'
|
||||
`${config.apiPrefix}crons/${
|
||||
record.isPinned === 1 ? 'unpin' : 'pin'
|
||||
}`,
|
||||
{
|
||||
data: [record.id],
|
||||
@@ -633,13 +591,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const newStatus = record.isPinned === 1 ? 0 : 1;
|
||||
const result = [...value];
|
||||
const i = result.findIndex((x) => x.id === record.id);
|
||||
if (i !== -1) {
|
||||
result.splice(i, 1, {
|
||||
...record,
|
||||
isPinned: newStatus,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
@@ -651,43 +607,45 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
};
|
||||
|
||||
const getMenuItems = (record: any) => {
|
||||
return [
|
||||
{ label: '编辑', key: 'edit', icon: <EditOutlined /> },
|
||||
{
|
||||
label: record.isDisabled === 1 ? '启用' : '禁用',
|
||||
key: 'enableOrDisable',
|
||||
icon:
|
||||
record.isDisabled === 1 ? <CheckCircleOutlined /> : <StopOutlined />,
|
||||
},
|
||||
{ label: '删除', key: 'delete', icon: <DeleteOutlined /> },
|
||||
{
|
||||
label: record.isPinned === 1 ? '取消置顶' : '置顶',
|
||||
key: 'pinOrUnPin',
|
||||
icon: record.isPinned === 1 ? <StopOutlined /> : <PushpinOutlined />,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const MoreBtn: React.FC<{
|
||||
record: any;
|
||||
index: number;
|
||||
}> = ({ record, index }) => (
|
||||
<Dropdown
|
||||
arrow={{ pointAtCenter: true }}
|
||||
placement="bottomRight"
|
||||
arrow
|
||||
trigger={['click']}
|
||||
overlay={
|
||||
<Menu
|
||||
items={getMenuItems(record)}
|
||||
onClick={({ key, domEvent }) => {
|
||||
domEvent.stopPropagation();
|
||||
action(key, record, index);
|
||||
}}
|
||||
/>
|
||||
<Menu onClick={({ key }) => action(key, record, index)}>
|
||||
<Menu.Item key="edit" icon={<EditOutlined />}>
|
||||
编辑
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
key="enableOrDisable"
|
||||
icon={
|
||||
record.isDisabled === 1 ? (
|
||||
<CheckCircleOutlined />
|
||||
) : (
|
||||
<StopOutlined />
|
||||
)
|
||||
}
|
||||
>
|
||||
<a onClick={(e) => e.stopPropagation()}>
|
||||
{record.isDisabled === 1 ? '启用' : '禁用'}
|
||||
</Menu.Item>
|
||||
<Menu.Item key="delete" icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
key="pinOrUnPin"
|
||||
icon={
|
||||
record.isPinned === 1 ? <StopOutlined /> : <PushpinOutlined />
|
||||
}
|
||||
>
|
||||
{record.isPinned === 1 ? '取消置顶' : '置顶'}
|
||||
</Menu.Item>
|
||||
</Menu>
|
||||
}
|
||||
>
|
||||
<a>
|
||||
<EllipsisOutlined />
|
||||
</a>
|
||||
</Dropdown>
|
||||
@@ -750,13 +708,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
.parseExpression(data.data.schedule)
|
||||
.next()
|
||||
.toDate();
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1, {
|
||||
...cron,
|
||||
...data.data,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -774,6 +730,11 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
const rowSelection = {
|
||||
selectedRowIds,
|
||||
onChange: onSelectChange,
|
||||
selections: [
|
||||
Table.SELECTION_ALL,
|
||||
Table.SELECTION_INVERT,
|
||||
Table.SELECTION_NONE,
|
||||
],
|
||||
};
|
||||
|
||||
const delCrons = () => {
|
||||
@@ -822,18 +783,14 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
});
|
||||
};
|
||||
|
||||
const onPageChange = (
|
||||
pagination: TablePaginationConfig,
|
||||
filters: Record<string, FilterValue | null>,
|
||||
sorter: SorterResult<any> | SorterResult<any>[],
|
||||
) => {
|
||||
const { current, pageSize } = pagination;
|
||||
setPageConf({ page: current as number, size: pageSize as number, sorter, filters });
|
||||
localStorage.setItem('pageSize', String(pageSize));
|
||||
const onPageChange = (page: number, pageSize: number | undefined) => {
|
||||
setCurrentPage(page);
|
||||
setPageSize(pageSize as number);
|
||||
localStorage.setItem('pageSize', pageSize + '');
|
||||
};
|
||||
|
||||
const getRowClassName = (record: any, index: number) => {
|
||||
return record.isPinned ? 'pinned-cron cron' : 'cron';
|
||||
return record.isPinned ? 'pinned-cron' : '';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -844,37 +801,36 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
}, [logCron]);
|
||||
|
||||
useEffect(() => {
|
||||
setPageConf({ ...pageConf, page: 1 });
|
||||
getCrons();
|
||||
}, [searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageConf.page && pageConf.size) {
|
||||
getCrons();
|
||||
}
|
||||
}, [pageConf, viewConf]);
|
||||
|
||||
useEffect(() => {
|
||||
if (viewConf && enabledCronViews && enabledCronViews.length > 0) {
|
||||
const view = enabledCronViews.slice(2).find((x) => x.id === viewConf.id);
|
||||
setMoreMenuActive(!!view);
|
||||
}
|
||||
}, [viewConf, enabledCronViews]);
|
||||
|
||||
useEffect(() => {
|
||||
setPageConf({
|
||||
page: 1,
|
||||
size: parseInt(localStorage.getItem('pageSize') || '20'),
|
||||
sorter: {},
|
||||
filters: {}
|
||||
});
|
||||
setPageSize(parseInt(localStorage.getItem('pageSize') || '20'));
|
||||
setTimeout(() => {
|
||||
setTableScrollHeight(getTableScroll());
|
||||
});
|
||||
getCronViews();
|
||||
}, []);
|
||||
|
||||
const panelContent = (
|
||||
<>
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper crontab-wrapper"
|
||||
title="定时任务"
|
||||
extra={[
|
||||
<Search
|
||||
placeholder="请输入名称或者关键词"
|
||||
style={{ width: 'auto' }}
|
||||
enterButton
|
||||
loading={loading}
|
||||
onSearch={onSearch}
|
||||
/>,
|
||||
<Button key="2" type="primary" onClick={() => addCron()}>
|
||||
新建任务
|
||||
</Button>,
|
||||
]}
|
||||
header={{
|
||||
style: headerStyle,
|
||||
}}
|
||||
>
|
||||
{selectedRowIds.length > 0 && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<Button type="primary" style={{ marginBottom: 5 }} onClick={delCrons}>
|
||||
@@ -920,7 +876,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
onClick={() => setIsLabelModalVisible(true)}
|
||||
onClick={() => setisLabelModalVisible(true)}
|
||||
style={{ marginLeft: 8, marginRight: 8 }}
|
||||
>
|
||||
批量修改标签
|
||||
@@ -934,16 +890,15 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<Table
|
||||
columns={columns}
|
||||
pagination={{
|
||||
current: pageConf.page,
|
||||
pageSize: pageConf.size,
|
||||
current: currentPage,
|
||||
onChange: onPageChange,
|
||||
pageSize: pageSize,
|
||||
showSizeChanger: true,
|
||||
simple: isPhone,
|
||||
total,
|
||||
defaultPageSize: 20,
|
||||
showTotal: (total: number, range: number[]) =>
|
||||
`第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
|
||||
pageSizeOptions: [10, 20, 50, 100, 200, 500, total || 10000].sort(
|
||||
(a, b) => a - b,
|
||||
),
|
||||
pageSizeOptions: [10, 20, 50, 100, 200, 500, 1000],
|
||||
}}
|
||||
dataSource={value}
|
||||
rowKey="id"
|
||||
@@ -952,135 +907,7 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
loading={loading}
|
||||
rowSelection={rowSelection}
|
||||
rowClassName={getRowClassName}
|
||||
onChange={onPageChange}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
const viewAction = (key: string) => {
|
||||
switch (key) {
|
||||
case 'new':
|
||||
setIsCreateViewModalVisible(true);
|
||||
break;
|
||||
case 'manage':
|
||||
setIsViewManageModalVisible(true);
|
||||
break;
|
||||
|
||||
default:
|
||||
tabClick(key);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const menu = (
|
||||
<Menu
|
||||
onClick={({ key, domEvent }) => {
|
||||
domEvent.stopPropagation();
|
||||
viewAction(key);
|
||||
}}
|
||||
items={[
|
||||
...[...enabledCronViews].slice(2).map((x) => ({
|
||||
label: (
|
||||
<Space style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>{x.name}</span>
|
||||
{viewConf?.id === x.id && (
|
||||
<CheckOutlined style={{ color: '#1890ff' }} />
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
key: x.id,
|
||||
icon: <UnorderedListOutlined />,
|
||||
})),
|
||||
{
|
||||
type: 'divider',
|
||||
},
|
||||
{
|
||||
label: '新建视图',
|
||||
key: 'new',
|
||||
icon: <PlusOutlined />,
|
||||
},
|
||||
{
|
||||
label: '视图管理',
|
||||
key: 'manage',
|
||||
icon: <SettingOutlined />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
const getCronViews = () => {
|
||||
setLoading(true);
|
||||
request
|
||||
.get(`${config.apiPrefix}crons/views`)
|
||||
.then((data: any) => {
|
||||
setCronViews(data.data);
|
||||
setEnabledCronViews(data.data.filter((x) => !x.isDisabled));
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
};
|
||||
|
||||
const tabClick = (key: string) => {
|
||||
const view = enabledCronViews.find((x) => x.id == key);
|
||||
setPageConf({ ...pageConf, page: 1 });
|
||||
setViewConf(view ? view : null);
|
||||
};
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper crontab-wrapper ql-container-wrapper-has-tab"
|
||||
title="定时任务"
|
||||
extra={[
|
||||
<Search
|
||||
placeholder="请输入名称或者关键词"
|
||||
style={{ width: 'auto' }}
|
||||
enterButton
|
||||
allowClear
|
||||
loading={loading}
|
||||
value={searchValue}
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
onSearch={onSearch}
|
||||
/>,
|
||||
<Button key="2" type="primary" onClick={() => addCron()}>
|
||||
新建任务
|
||||
</Button>,
|
||||
]}
|
||||
header={{
|
||||
style: headerStyle,
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
defaultActiveKey="all"
|
||||
size="small"
|
||||
tabPosition="top"
|
||||
className={`crontab-view ${moreMenuActive ? 'more-active' : ''}`}
|
||||
tabBarExtraContent={
|
||||
<Dropdown
|
||||
overlay={menu}
|
||||
trigger={['click']}
|
||||
overlayStyle={{ minWidth: 200 }}
|
||||
>
|
||||
<div className={`view-more ${moreMenuActive ? 'active' : ''}`}>
|
||||
<Space>
|
||||
更多
|
||||
<DownOutlined />
|
||||
</Space>
|
||||
<div className="ant-tabs-ink-bar ant-tabs-ink-bar-animated"></div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
}
|
||||
onTabClick={tabClick}
|
||||
>
|
||||
<Tabs.TabPane tab="全部任务" key="all">
|
||||
{panelContent}
|
||||
</Tabs.TabPane>
|
||||
{[...enabledCronViews].slice(0, 2).map((x) => (
|
||||
<Tabs.TabPane tab={x.name} key={x.id}>
|
||||
{panelContent}
|
||||
</Tabs.TabPane>
|
||||
))}
|
||||
</Tabs>
|
||||
<CronLogModal
|
||||
visible={isLogModalVisible}
|
||||
handleCancel={() => {
|
||||
@@ -1097,45 +924,13 @@ const Crontab = ({ headerStyle, isPhone, theme }: any) => {
|
||||
<CronLabelModal
|
||||
visible={isLabelModalVisible}
|
||||
handleCancel={(needUpdate?: boolean) => {
|
||||
setIsLabelModalVisible(false);
|
||||
setisLabelModalVisible(false);
|
||||
if (needUpdate) {
|
||||
getCrons();
|
||||
}
|
||||
}}
|
||||
ids={selectedRowIds}
|
||||
/>
|
||||
<CronDetailModal
|
||||
visible={isDetailModalVisible}
|
||||
handleCancel={() => {
|
||||
setIsDetailModalVisible(false);
|
||||
}}
|
||||
cron={detailCron}
|
||||
theme={theme}
|
||||
isPhone={isPhone}
|
||||
/>
|
||||
<ViewCreateModal
|
||||
visible={isCreateViewModalVisible}
|
||||
handleCancel={(data) => {
|
||||
setIsCreateViewModalVisible(false);
|
||||
getCronViews();
|
||||
if (data && data.id === viewConf.id) {
|
||||
setViewConf({ ...viewConf, ...data });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<ViewManageModal
|
||||
cronViews={cronViews}
|
||||
visible={isViewManageModalVisible}
|
||||
handleCancel={() => {
|
||||
setIsViewManageModalVisible(false);
|
||||
}}
|
||||
cronViewChange={(data) => {
|
||||
getCronViews();
|
||||
if (data && data.id === viewConf.id) {
|
||||
setViewConf({ ...viewConf, ...data });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -20,14 +20,10 @@ const CronLogModal = ({
|
||||
cron,
|
||||
handleCancel,
|
||||
visible,
|
||||
data,
|
||||
logUrl,
|
||||
}: {
|
||||
cron?: any;
|
||||
visible: boolean;
|
||||
handleCancel: () => void;
|
||||
data?: string;
|
||||
logUrl?: string;
|
||||
}) => {
|
||||
const [value, setValue] = useState<string>('启动中...');
|
||||
const [loading, setLoading] = useState<any>(true);
|
||||
@@ -40,7 +36,7 @@ const CronLogModal = ({
|
||||
setLoading(true);
|
||||
}
|
||||
request
|
||||
.get(logUrl ? logUrl : `${config.apiPrefix}crons/${cron.id}/log`)
|
||||
.get(`${config.apiPrefix}crons/${cron.id}/log`)
|
||||
.then((data: any) => {
|
||||
if (localStorage.getItem('logCron') === String(cron.id)) {
|
||||
const log = data.data as string;
|
||||
@@ -94,23 +90,17 @@ const CronLogModal = ({
|
||||
return (
|
||||
<>
|
||||
{(executing || loading) && <Loading3QuartersOutlined spin />}
|
||||
{!executing && !loading && <CheckCircleOutlined />}
|
||||
<span style={{ marginLeft: 5 }}>{cron && cron.name}</span>
|
||||
{!executing && <CheckCircleOutlined />}
|
||||
<span style={{ marginLeft: 5 }}>日志-{cron && cron.name}</span>{' '}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (cron && cron.id && visible) {
|
||||
if (cron) {
|
||||
getCronLog(true);
|
||||
}
|
||||
}, [cron, visible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
setValue(data);
|
||||
}
|
||||
}, [data]);
|
||||
}, [cron]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsPhone(document.body.clientWidth < 768);
|
||||
@@ -123,6 +113,8 @@ const CronLogModal = ({
|
||||
centered
|
||||
className="log-modal"
|
||||
bodyStyle={{
|
||||
overflowY: 'auto',
|
||||
maxHeight: 'calc(80vh - var(--vh-offset, 0px))',
|
||||
minHeight: '300px',
|
||||
}}
|
||||
forceRender
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Modal, message, Input, Form, Button } from 'antd';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
import cronParse from 'cron-parser';
|
||||
import EditableTagGroup from '@/components/tag';
|
||||
|
||||
const CronModal = ({
|
||||
cron,
|
||||
@@ -21,6 +20,11 @@ const CronModal = ({
|
||||
setLoading(true);
|
||||
const method = cron ? 'put' : 'post';
|
||||
const payload = { ...values };
|
||||
if (typeof payload.labels === 'string') {
|
||||
payload.labels = values.labels.split(/,|,/);
|
||||
} else if (!payload.labels) {
|
||||
payload.labels = [];
|
||||
}
|
||||
if (cron) {
|
||||
payload.id = cron.id;
|
||||
}
|
||||
@@ -49,8 +53,6 @@ const CronModal = ({
|
||||
title={cron ? '编辑任务' : '新建任务'}
|
||||
visible={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
onOk={() => {
|
||||
form
|
||||
.validateFields()
|
||||
@@ -91,7 +93,7 @@ const CronModal = ({
|
||||
{ required: true },
|
||||
{
|
||||
validator: (rule, value) => {
|
||||
if (!value || cronParse.parseExpression(value).hasNext()) {
|
||||
if (cronParse.parseExpression(value).hasNext()) {
|
||||
return Promise.resolve();
|
||||
} else {
|
||||
return Promise.reject('Cron表达式格式有误');
|
||||
@@ -103,7 +105,7 @@ const CronModal = ({
|
||||
<Input placeholder="秒(可选) 分 时 天 月 周" />
|
||||
</Form.Item>
|
||||
<Form.Item name="labels" label="标签">
|
||||
<EditableTagGroup />
|
||||
<Input placeholder="请输入任务标签" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
@@ -126,6 +128,9 @@ const CronLabelModal = ({
|
||||
form
|
||||
.validateFields()
|
||||
.then(async (values) => {
|
||||
if (typeof values.labels === 'string') {
|
||||
values.labels = values.labels.split(/,|,/);
|
||||
}
|
||||
setLoading(true);
|
||||
const payload = { ids, labels: values.labels };
|
||||
const { code, data } = await request[action](
|
||||
@@ -168,15 +173,13 @@ const CronLabelModal = ({
|
||||
title="批量修改标签"
|
||||
visible={visible}
|
||||
footer={buttons}
|
||||
centered
|
||||
maskClosable={false}
|
||||
forceRender
|
||||
onCancel={() => handleCancel(false)}
|
||||
confirmLoading={loading}
|
||||
>
|
||||
<Form form={form} layout="vertical" name="form_in_label_modal">
|
||||
<Form.Item name="labels" label="标签">
|
||||
<EditableTagGroup />
|
||||
<Input placeholder="请输入任务标签" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
message,
|
||||
Input,
|
||||
Form,
|
||||
Statistic,
|
||||
Button,
|
||||
Space,
|
||||
Select,
|
||||
} from 'antd';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
|
||||
const PROPERTIES = [
|
||||
{ name: '命令', value: 'command' },
|
||||
{ name: '名称', value: 'name' },
|
||||
{ name: '定时规则', value: 'schedule' },
|
||||
{ name: '状态', value: 'status' },
|
||||
];
|
||||
|
||||
const OPERATIONS = [
|
||||
{ name: '包含', value: 'Reg' },
|
||||
{ name: '不包含', value: 'NotReg' },
|
||||
{ name: '属于', value: 'In' },
|
||||
{ name: '不属于', value: 'Nin' },
|
||||
// { name: '等于', value: 'Eq' },
|
||||
// { name: '不等于', value: 'Ne' },
|
||||
// { name: '为空', value: 'IsNull' },
|
||||
// { name: '不为空', value: 'NotNull' },
|
||||
];
|
||||
|
||||
const SORTTYPES = [
|
||||
{ name: '顺序', value: 'ASC' },
|
||||
{ name: '倒序', value: 'DESC' },
|
||||
];
|
||||
|
||||
const STATUS = [
|
||||
{ name: '运行中', value: 0 },
|
||||
{ name: '空闲中', value: 1 },
|
||||
{ name: '已禁用', value: 2 },
|
||||
];
|
||||
|
||||
const ViewCreateModal = ({
|
||||
view,
|
||||
handleCancel,
|
||||
visible,
|
||||
}: {
|
||||
view?: any;
|
||||
visible: boolean;
|
||||
handleCancel: (param?: any) => void;
|
||||
}) => {
|
||||
const [form] = Form.useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [operationMap, setOperationMap] = useState<any>();
|
||||
|
||||
const handleOk = async (values: any) => {
|
||||
setLoading(true);
|
||||
const method = view ? 'put' : 'post';
|
||||
try {
|
||||
const { code, data } = await request[method](
|
||||
`${config.apiPrefix}crons/views`,
|
||||
{
|
||||
data: view ? { ...values, id: view.id } : values,
|
||||
},
|
||||
);
|
||||
if (code !== 200) {
|
||||
message.error(data);
|
||||
}
|
||||
setLoading(false);
|
||||
handleCancel(data);
|
||||
} catch (error: any) {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!view) {
|
||||
form.resetFields();
|
||||
}
|
||||
form.setFieldsValue(
|
||||
view || {
|
||||
filters: [{ property: 'command', operation: 'Reg' }],
|
||||
},
|
||||
);
|
||||
}, [view, visible]);
|
||||
|
||||
const operationElement = (
|
||||
<Select
|
||||
style={{ width: 100 }}
|
||||
onChange={() => {
|
||||
setOperationMap({});
|
||||
}}
|
||||
>
|
||||
{OPERATIONS.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
|
||||
const propertyElement = (props: any, style: React.CSSProperties = {}) => {
|
||||
return (
|
||||
<Select style={style}>
|
||||
{props.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
};
|
||||
|
||||
const typeElement = (
|
||||
<Select>
|
||||
{SORTTYPES.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
|
||||
const statusElement = (
|
||||
<Select mode="multiple" allowClear placeholder="请选择状态">
|
||||
{STATUS.map((x) => (
|
||||
<Select.Option key={x.name} value={x.value}>
|
||||
{x.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={view ? '编辑视图' : '新建视图'}
|
||||
visible={visible}
|
||||
forceRender
|
||||
width={580}
|
||||
centered
|
||||
maskClosable={false}
|
||||
onOk={() => {
|
||||
form
|
||||
.validateFields()
|
||||
.then((values) => {
|
||||
handleOk(values);
|
||||
})
|
||||
.catch((info) => {
|
||||
console.log('Validate Failed:', info);
|
||||
});
|
||||
}}
|
||||
onCancel={() => handleCancel()}
|
||||
confirmLoading={loading}
|
||||
>
|
||||
<Form form={form} layout="vertical" name="env_modal">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="视图名称"
|
||||
rules={[{ required: true, message: '请输入视图名称' }]}
|
||||
>
|
||||
<Input placeholder="请输入视图名称" />
|
||||
</Form.Item>
|
||||
<Form.List name="filters">
|
||||
{(fields, { add, remove }) => (
|
||||
<>
|
||||
{fields.map(({ key, name, ...restField }, index) => (
|
||||
<Form.Item
|
||||
label={index === 0 ? '筛选条件' : ''}
|
||||
key={key}
|
||||
style={{ marginBottom: 0 }}
|
||||
required
|
||||
>
|
||||
<Space className="view-create-modal-filters" align="baseline">
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'property']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{propertyElement(PROPERTIES, { width: 120 })}
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'operation']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{operationElement}
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'value']}
|
||||
rules={[{ required: true, message: '请输入内容' }]}
|
||||
>
|
||||
{['In', 'Nin'].includes(
|
||||
form.getFieldValue(['filters', index, 'operation']),
|
||||
) ? (
|
||||
statusElement
|
||||
) : (
|
||||
<Input placeholder="请输入内容" />
|
||||
)}
|
||||
</Form.Item>
|
||||
{index !== 0 && (
|
||||
<MinusCircleOutlined onClick={() => remove(name)} />
|
||||
)}
|
||||
</Space>
|
||||
</Form.Item>
|
||||
))}
|
||||
<Form.Item>
|
||||
<a
|
||||
onClick={() => add({ property: 'command', operation: 'Reg' })}
|
||||
>
|
||||
<PlusOutlined />
|
||||
新增筛选条件
|
||||
</a>
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
<Form.List name="sorts">
|
||||
{(fields, { add, remove }) => (
|
||||
<>
|
||||
{fields.map(({ key, name, ...restField }, index) => (
|
||||
<Form.Item
|
||||
label={index === 0 ? '排序方式' : ''}
|
||||
key={key}
|
||||
style={{ marginBottom: 0 }}
|
||||
>
|
||||
<Space className="view-create-modal-sorts" align="baseline">
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'property']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{propertyElement(PROPERTIES, { width: 240 })}
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, 'type']}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
{typeElement}
|
||||
</Form.Item>
|
||||
<MinusCircleOutlined onClick={() => remove(name)} />
|
||||
</Space>
|
||||
</Form.Item>
|
||||
))}
|
||||
<Form.Item>
|
||||
<a onClick={() => add({ property: 'command', type: 'ASC' })}>
|
||||
<PlusOutlined />
|
||||
新增排序方式
|
||||
</a>
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ViewCreateModal;
|
||||
@@ -1,272 +0,0 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
message,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
Button,
|
||||
Switch,
|
||||
} from 'antd';
|
||||
import { request } from '@/utils/http';
|
||||
import config from '@/utils/config';
|
||||
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
|
||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||
import ViewCreateModal from './viewCreateModal';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const type = 'DragableBodyRow';
|
||||
|
||||
const DragableBodyRow = ({
|
||||
index,
|
||||
moveRow,
|
||||
className,
|
||||
style,
|
||||
...restProps
|
||||
}: any) => {
|
||||
const ref = useRef();
|
||||
const [{ isOver, dropClassName }, drop] = useDrop({
|
||||
accept: type,
|
||||
collect: (monitor) => {
|
||||
const { index: dragIndex } = (monitor.getItem() as any) || {};
|
||||
if (dragIndex === index) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
isOver: monitor.isOver(),
|
||||
dropClassName:
|
||||
dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
|
||||
};
|
||||
},
|
||||
drop: (item: any) => {
|
||||
moveRow(item.index, index);
|
||||
},
|
||||
});
|
||||
const [, drag] = useDrag({
|
||||
type,
|
||||
item: { index },
|
||||
collect: (monitor) => ({
|
||||
isDragging: monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
drop(drag(ref));
|
||||
|
||||
return (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={`${className}${isOver ? dropClassName : ''}`}
|
||||
style={{ cursor: 'move', ...style }}
|
||||
{...restProps}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const ViewManageModal = ({
|
||||
cronViews,
|
||||
handleCancel,
|
||||
visible,
|
||||
cronViewChange,
|
||||
}: {
|
||||
cronViews: any[];
|
||||
visible: boolean;
|
||||
handleCancel: () => void;
|
||||
cronViewChange: (data?: any) => void;
|
||||
}) => {
|
||||
const columns: any = [
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
align: 'center' as const,
|
||||
},
|
||||
{
|
||||
title: '显示',
|
||||
key: 'isDisabled',
|
||||
dataIndex: 'isDisabled',
|
||||
align: 'center' as const,
|
||||
width: 100,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return (
|
||||
<Switch
|
||||
checked={!record.isDisabled}
|
||||
onChange={(checked) => onShowChange(checked, record, index)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 140,
|
||||
align: 'center' as const,
|
||||
render: (text: string, record: any, index: number) => {
|
||||
return (
|
||||
<Space size="middle">
|
||||
<a onClick={() => editView(record, index)}>
|
||||
<EditOutlined />
|
||||
</a>
|
||||
<a onClick={() => deleteView(record, index)}>
|
||||
<DeleteOutlined />
|
||||
</a>
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
const [list, setList] = useState<any[]>([]);
|
||||
const [isCreateViewModalVisible, setIsCreateViewModalVisible] =
|
||||
useState<boolean>(false);
|
||||
const [editedView, setEditedView] = useState<any>(null);
|
||||
|
||||
const editView = (record: any, index: number) => {
|
||||
setEditedView(record);
|
||||
setIsCreateViewModalVisible(true);
|
||||
};
|
||||
|
||||
const deleteView = (record: any, index: number) => {
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: (
|
||||
<>
|
||||
确认删除视图{' '}
|
||||
<Text style={{ wordBreak: 'break-all' }} type="warning">
|
||||
{record.name}
|
||||
</Text>{' '}
|
||||
吗
|
||||
</>
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}crons/views`, { data: [record.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
message.success('删除成功');
|
||||
cronViewChange();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
console.log('Cancel');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const onShowChange = (checked: boolean, record: any, index: number) => {
|
||||
console.log(checked);
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/views/${checked ? 'enable' : 'disable'}`, {
|
||||
data: [record.id],
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
const _list = [...list];
|
||||
_list.splice(index, 1, { ...list[index], isDisabled: !checked });
|
||||
setList(_list);
|
||||
cronViewChange();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const components = {
|
||||
body: {
|
||||
row: DragableBodyRow,
|
||||
},
|
||||
};
|
||||
|
||||
const moveRow = useCallback(
|
||||
(dragIndex, hoverIndex) => {
|
||||
if (dragIndex === hoverIndex) {
|
||||
return;
|
||||
}
|
||||
const dragRow = list[dragIndex];
|
||||
request
|
||||
.put(`${config.apiPrefix}crons/views/move`, {
|
||||
data: { fromIndex: dragIndex, toIndex: hoverIndex, id: dragRow.id },
|
||||
})
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
const newData = [...list];
|
||||
newData.splice(dragIndex, 1);
|
||||
newData.splice(hoverIndex, 0, { ...dragRow, ...data.data });
|
||||
setList(newData);
|
||||
cronViewChange();
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
});
|
||||
},
|
||||
[list],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setList(cronViews);
|
||||
}, [cronViews]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="视图管理"
|
||||
visible={visible}
|
||||
centered
|
||||
width={620}
|
||||
onCancel={() => handleCancel()}
|
||||
className="view-manage-modal"
|
||||
forceRender
|
||||
footer={false}
|
||||
maskClosable={false}
|
||||
>
|
||||
<Space
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
marginBottom: 10,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
key="2"
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
setEditedView(null);
|
||||
setIsCreateViewModalVisible(true);
|
||||
}}
|
||||
>
|
||||
新建视图
|
||||
</Button>
|
||||
</Space>
|
||||
<DndProvider backend={HTML5Backend}>
|
||||
<Table
|
||||
bordered
|
||||
columns={columns}
|
||||
pagination={false}
|
||||
dataSource={list}
|
||||
rowKey="id"
|
||||
size="middle"
|
||||
style={{ marginBottom: 20 }}
|
||||
components={components}
|
||||
onRow={(record: any, index: number) => {
|
||||
return {
|
||||
index,
|
||||
moveRow,
|
||||
} as any;
|
||||
}}
|
||||
/>
|
||||
</DndProvider>
|
||||
<ViewCreateModal
|
||||
view={editedView}
|
||||
visible={isCreateViewModalVisible}
|
||||
handleCancel={(data) => {
|
||||
setIsCreateViewModalVisible(false);
|
||||
cronViewChange(data);
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ViewManageModal;
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
DeleteOutlined,
|
||||
SyncOutlined,
|
||||
CheckCircleOutlined,
|
||||
DeleteFilled,
|
||||
StopOutlined,
|
||||
BugOutlined,
|
||||
FileTextOutlined,
|
||||
} from '@ant-design/icons';
|
||||
@@ -120,15 +120,6 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
const isPc = !isPhone;
|
||||
return (
|
||||
<Space size="middle">
|
||||
<Tooltip title={isPc ? '日志' : ''}>
|
||||
<a
|
||||
onClick={() => {
|
||||
setLogDependence({ ...record, timestamp: Date.now() });
|
||||
}}
|
||||
>
|
||||
<FileTextOutlined />
|
||||
</a>
|
||||
</Tooltip>
|
||||
{record.status !== Status.安装中 &&
|
||||
record.status !== Status.删除中 && (
|
||||
<>
|
||||
@@ -142,13 +133,17 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
<DeleteOutlined />
|
||||
</a>
|
||||
</Tooltip>
|
||||
<Tooltip title={isPc ? '强制删除' : ''}>
|
||||
<a onClick={() => deleteDependence(record, index, true)}>
|
||||
<DeleteFilled />
|
||||
</a>
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
<Tooltip title={isPc ? '日志' : ''}>
|
||||
<a
|
||||
onClick={() => {
|
||||
setLogDependence({ ...record, timestamp: Date.now() });
|
||||
}}
|
||||
>
|
||||
<FileTextOutlined />
|
||||
</a>
|
||||
</Tooltip>
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
@@ -187,11 +182,7 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
setIsModalVisible(true);
|
||||
};
|
||||
|
||||
const deleteDependence = (
|
||||
record: any,
|
||||
index: number,
|
||||
force: boolean = false,
|
||||
) => {
|
||||
const deleteDependence = (record: any, index: number) => {
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: (
|
||||
@@ -205,19 +196,10 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
),
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}dependencies${force ? '/force' : ''}`, {
|
||||
data: [record.id],
|
||||
})
|
||||
.delete(`${config.apiPrefix}dependencies`, { data: [record.id] })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
if (force) {
|
||||
const i = value.findIndex((x) => x.id === data.data[0].id);
|
||||
if (i !== -1) {
|
||||
const result = [...value];
|
||||
result.splice(i, 1);
|
||||
setValue(result);
|
||||
}
|
||||
}
|
||||
handleDependence(data.data[0]);
|
||||
} else {
|
||||
message.error(data);
|
||||
}
|
||||
@@ -271,12 +253,10 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
result.push(...dependence);
|
||||
} else {
|
||||
const index = value.findIndex((x) => x.id === dependence.id);
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1, {
|
||||
...dependence,
|
||||
});
|
||||
}
|
||||
}
|
||||
setValue(result);
|
||||
};
|
||||
|
||||
@@ -295,16 +275,13 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
onChange: onSelectChange,
|
||||
};
|
||||
|
||||
const delDependencies = (force: boolean) => {
|
||||
const forceUrl = force ? '/force' : '';
|
||||
const delDependencies = () => {
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: <>确认删除选中的依赖吗</>,
|
||||
onOk() {
|
||||
request
|
||||
.delete(`${config.apiPrefix}dependencies${forceUrl}`, {
|
||||
data: selectedRowIds,
|
||||
})
|
||||
.delete(`${config.apiPrefix}dependencies`, { data: selectedRowIds })
|
||||
.then((data: any) => {
|
||||
if (data.code === 200) {
|
||||
setSelectedRowIds([]);
|
||||
@@ -326,13 +303,11 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
.then((data: any) => {
|
||||
const index = value.findIndex((x) => x.id === dependence.id);
|
||||
const result = [...value];
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1, {
|
||||
...dependence,
|
||||
...data.data,
|
||||
});
|
||||
setValue(result);
|
||||
}
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -375,13 +350,11 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
const result = [...value];
|
||||
for (let i = 0; i < references.length; i++) {
|
||||
const index = value.findIndex((x) => x.id === references[i]);
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1, {
|
||||
...value[index],
|
||||
...result[index],
|
||||
status,
|
||||
});
|
||||
}
|
||||
}
|
||||
setValue(result);
|
||||
|
||||
if (status === Status.已删除) {
|
||||
@@ -389,10 +362,8 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
const _result = [...value];
|
||||
for (let i = 0; i < references.length; i++) {
|
||||
const index = value.findIndex((x) => x.id === references[i]);
|
||||
if (index !== -1) {
|
||||
_result.splice(index, 1);
|
||||
}
|
||||
}
|
||||
setValue(_result);
|
||||
}, 5000);
|
||||
}
|
||||
@@ -406,17 +377,10 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
<Button
|
||||
type="primary"
|
||||
style={{ marginBottom: 5, marginLeft: 8 }}
|
||||
onClick={() => delDependencies(false)}
|
||||
onClick={delDependencies}
|
||||
>
|
||||
批量删除
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
style={{ marginBottom: 5, marginLeft: 8 }}
|
||||
onClick={() => delDependencies(true)}
|
||||
>
|
||||
批量强制删除
|
||||
</Button>
|
||||
<span style={{ marginLeft: 8 }}>
|
||||
已选择
|
||||
<a>{selectedRowIds?.length}</a>项
|
||||
@@ -444,7 +408,7 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
className="ql-container-wrapper dependence-wrapper ql-container-wrapper-has-tab"
|
||||
className="ql-container-wrapper dependence-wrapper"
|
||||
title="依赖管理"
|
||||
extra={[
|
||||
<Search
|
||||
@@ -491,10 +455,8 @@ const Dependence = ({ headerStyle, isPhone, socketMessage }: any) => {
|
||||
if (needRemove) {
|
||||
const index = value.findIndex((x) => x.id === logDependence.id);
|
||||
const result = [...value];
|
||||
if (index !== -1) {
|
||||
result.splice(index, 1);
|
||||
setValue(result);
|
||||
}
|
||||
} else if ([...value].map((x) => x.id).includes(logDependence.id)) {
|
||||
getDependenceDetail(logDependence);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
CheckCircleOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { PageLoading } from '@ant-design/pro-layout';
|
||||
import Ansi from 'ansi-to-react';
|
||||
|
||||
const DependenceLogModal = ({
|
||||
dependence,
|
||||
@@ -90,19 +89,17 @@ const DependenceLogModal = ({
|
||||
}, [dependence]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!socketMessage || !dependence) return;
|
||||
if (!socketMessage) return;
|
||||
const { type, message, references } = socketMessage;
|
||||
if (
|
||||
type === 'installDependence' &&
|
||||
references.length > 0 &&
|
||||
references.includes(dependence.id)
|
||||
message.includes('结束时间') &&
|
||||
references.length > 0
|
||||
) {
|
||||
if (message.includes('结束时间')) {
|
||||
setExecuting(false);
|
||||
setIsRemoveFailed(message.includes('删除失败'));
|
||||
}
|
||||
setValue(`${value}${message}`);
|
||||
}
|
||||
}, [socketMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -143,7 +140,7 @@ const DependenceLogModal = ({
|
||||
: {}
|
||||
}
|
||||
>
|
||||
<Ansi>{value}</Ansi>
|
||||
{value}
|
||||
</pre>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
@@ -71,8 +71,6 @@ const DependenceModal = ({
|
||||
title={dependence ? '编辑依赖' : '新建依赖'}
|
||||
visible={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
onOk={() => {
|
||||
form
|
||||
.validateFields()
|
||||
|
||||
Vendored
-2
@@ -41,8 +41,6 @@ const EditNameModal = ({
|
||||
title="修改环境变量名称"
|
||||
visible={visible}
|
||||
forceRender
|
||||
centered
|
||||
maskClosable={false}
|
||||
onOk={() => {
|
||||
form
|
||||
.validateFields()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user