Compare commits

...
110 Commits
Author SHA1 Message Date
whyour 86e3d8736b 更新版本 v2.15.15 2023-05-28 20:06:15 +08:00
whyour 85d32d00e1 修改打包 latest 镜像分支 2023-05-28 20:06:05 +08:00
whyour 6a52e2f804 修复 env.js 路径 2023-05-27 23:05:46 +08:00
whyour b4cb72c5d0 修改错误页面提示 2023-05-27 11:35:30 +08:00
whyour 79fd4ec58f 修复 nginx 变量替换 2023-05-26 17:08:40 +08:00
jzksnsjswkwandGitHub 49ed5c6632 修复 可执行文件 提示找不到文件的问题 (#1943) 2023-05-26 15:17:47 +08:00
whyour ffba7ee4a1 增加定时任务服务启动失败日志 2023-05-25 21:45:28 +08:00
whyour 91d080472f 修复环境变量接口前缀 2023-05-24 23:46:07 +08:00
whyour 826f214f0f 修复设置通知错误时提示不清晰 2023-05-24 23:37:44 +08:00
whyour ca150dc6a6 修复 docker-compose 配置 2023-05-22 20:20:46 +08:00
whyour ae5db60211 修复筛选可能报错 2023-05-21 12:29:29 +08:00
whyour 490bdc15f6 支持非根目录部署 2023-05-19 01:10:33 +08:00
whyour 1377fe31aa 更新版本 v2.15.14 2023-05-15 23:44:42 +08:00
whyour 3d1cf6bf2e 修改群晖名称 2023-05-15 23:44:32 +08:00
whyour 6ac755b478 修复后端 html 缓存 2023-05-15 22:34:06 +08:00
whyour e70fa83074 修复获取配置文件参数 2023-05-14 20:53:45 +08:00
whyour 41521f1d08 修复 token 任务脚本路径,容器启动 bot 2023-05-13 01:10:49 +08:00
whyour 8b7bef097c 修复拉取仓库逻辑 2023-05-12 18:28:01 +08:00
whyour 618756d4a9 修复设置代理时,服务启动失败 2023-05-10 23:17:05 +08:00
whyour 70d0c71414 修复错误日志样式 2023-05-10 23:01:51 +08:00
whyour 65eb9c806d 更新 sqlite 2023-05-10 21:58:11 +08:00
whyour 50718ba714 修复 public 服务转发 2023-05-10 01:07:46 +08:00
whyour 7c3bb90d12 修复删除依赖和移动环境变量接口数据结构 2023-05-08 21:29:25 +08:00
whyour f66390eabd 修改初始系统状态逻辑已经错误页面 2023-05-07 23:40:37 +08:00
whyour 481646501c 修复订阅更新仓库失败 2023-05-06 22:58:05 +08:00
whyour 5baa8e4391 增加 pm2 平滑重启 2023-05-06 00:09:03 +08:00
whyour 3d11210aeb pnpm 版本降至 8.3.1 2023-05-05 00:26:23 +08:00
whyour e1863407f2 修复 npm 源判断 2023-05-04 22:23:55 +08:00
whyour 0c28b63ab7 修改容器启动流程 2023-05-04 22:07:39 +08:00
whyour 8b8bd279c6 修复 nginx 转发stream接口失效,停止运行命令支持 pid 参数 2023-05-04 21:28:14 +08:00
whyour 01b404765e 更新版本 v2.15.13 2023-05-04 17:13:18 +08:00
whyour c231a871d7 修复 check 异常 2023-05-04 17:13:04 +08:00
whyour 598c6b4e57 修复 task 打印日志逻辑 2023-05-04 15:17:38 +08:00
whyour 2295fabcc5 修复 task 命令日志目录判断 2023-05-04 13:11:18 +08:00
whyour be94d796ac 增加 procps 依赖 2023-05-04 13:05:48 +08:00
whyour c84908d7fa 修复运行命令api任务日志路径 2023-05-04 10:25:04 +08:00
whyour d8ae039b92 修复内容区头部样式 2023-05-03 21:23:13 +08:00
whyour bce1431d03 修复错误界面重试次数判断 2023-05-03 19:59:06 +08:00
whyour 9db0095e29 修复系统通知错误提示,gotifyPriority 配置参数 2023-05-03 18:18:28 +08:00
whyour 77dc7817fb 修复 pnpm 8.4.0 重新安装依赖会默认进行询问 2023-05-03 01:58:41 +08:00
whyour d0dd97631e 修复 task 命令任务 ID 查询参数 2023-05-03 01:27:14 +08:00
whyour d11d6d0c18 增加容器健康检查 2023-05-02 22:11:50 +08:00
whyour 0af687f781 增加停止指定命令接口 2023-05-01 22:56:47 +08:00
whyour 8db997abe8 修改 check 逻辑 2023-05-01 16:16:47 +08:00
whyour aab6bbeb15 增加运行指定命令接口 2023-05-01 14:28:58 +08:00
whyour df1addc1ff 修改 task 命令超时时间判断 2023-05-01 11:05:36 +08:00
whyour 1f8f35476a 移除任务默认超时时间 2023-04-30 20:02:14 +08:00
whyour 5354fc76db 修复 task 命令任务ID查询,系统依赖安装逻辑 2023-04-30 19:35:14 +08:00
whyour b29a9e012c 修复停止任务无效 2023-04-29 22:49:50 +08:00
whyour 6e5d89c197 修改 task 命令生成日志逻辑和关联任务查询 2023-04-28 23:15:07 +08:00
whyour d6cfb18f06 修改仓库拉取状态判断逻辑 2023-04-24 15:37:58 +08:00
whyour 9a3e38051d 克隆仓库增加 depth 2023-04-24 14:47:17 +08:00
whyour b705ad6ee8 修复更新任务、环境变量、依赖、订阅状态丢失 2023-04-21 21:15:28 +08:00
whyour db564d1add 更新版本 v2.15.12 2023-04-18 15:38:06 +08:00
whyour 4f422c0658 修改 dockerfile LANG 环境变量 2023-04-18 15:37:43 +08:00
whyour f267720af4 修复初始化定时服务运行非禁用任务 2023-04-17 13:36:37 +08:00
whyour 4a0c66bcc0 修复初始化 ssh 配置文件不存在 2023-04-15 12:14:56 +08:00
whyour ef7283a9fd 修改依赖安装初始状态 2023-04-12 00:45:06 +08:00
whyour 4498449eea 修复容器启动逻辑 2023-04-11 14:15:34 +08:00
whyour ebb9676a51 修复定时服务启动路径 2023-04-08 21:58:34 +08:00
whyour 6fb39ce835 重构六位定时任务服务 2023-04-08 17:07:06 +08:00
whyour 59c26d90d3 修改手机端网页样式 2023-04-06 21:49:42 +08:00
whyour 1d2df860e8 修复 ssh 配置文件目录 2023-04-06 14:23:02 +08:00
whyour ce22cad5b2 修改列表页更多菜单弹窗 2023-04-06 14:08:08 +08:00
whyour dc44ce6b1a 修复 workflow pnpm 版本 2023-04-06 13:41:18 +08:00
whyour b27ee23cc3 重构私有仓库ssh配置逻辑 2023-04-06 13:38:55 +08:00
whyour 083c8869aa 修复更新环境变量、定时任务、订阅等操作 2023-04-06 13:00:28 +08:00
whyour 6a971a0d6e 更新 readme 2023-04-02 14:49:30 +08:00
whyour a25bfb6912 修复定时任务状态筛选 2023-04-02 14:42:18 +08:00
whyour f19dd21155 更新 readme 2023-04-01 21:05:21 +08:00
whyour 79b342d1d2 更新版本 v2.15.11 2023-03-31 22:38:32 +08:00
whyour 20b0d75b0d 修改 pnpm 版本 2023-03-30 23:20:38 +08:00
whyour c89724906e 修复定时任务表头样式 2023-03-23 22:19:48 +08:00
whyour c3a548ece3 修改定时任务列表滚动 2023-03-22 22:30:47 +08:00
whyour b431e39f8f 修复系统设置中登录日志样式 2023-03-20 23:23:03 +08:00
whyour 710746809b 修复删除视图筛选条件 2023-03-20 23:00:13 +08:00
whyour 8a225e9beb 修复视图筛选条件样式 2023-03-20 18:03:09 +08:00
whyour a5ecb204b2 修复 python Server酱推送 2023-03-19 22:54:50 +08:00
whyour f1f009da3b 禁止手机浏览器下拉刷新 2023-03-19 15:15:01 +08:00
whyour 7291098f98 修复手机页面滚动 2023-03-19 15:11:28 +08:00
whyour 666545ff03 修改初始化依赖安装逻辑 2023-03-18 22:26:29 +08:00
whyour 81e2bbb14c 更新版本 v2.15.10 2023-03-17 21:30:13 +08:00
whyour 970dff144c 修复订阅下载 http 协议文件 2023-03-15 21:44:11 +08:00
whyour 819b15b15e 容器增加 ipv6 检测,自动配置 nginx 2023-03-14 22:39:10 +08:00
whyour 3fa57c69ac 修改检查 pm2 状态 api 2023-03-13 23:57:56 +08:00
whyour 18689c8119 修复 shell 引入通用变量 2023-03-13 22:30:53 +08:00
adams549659584andGitHub 61e7049baa 修复系统 bark 推送铃声 (#1850) 2023-03-13 22:13:20 +08:00
whyour 39c40a328d 修复检查更新弹框逻辑 2023-03-12 21:48:31 +08:00
whyour 955d815d14 修改 task 获取 token 逻辑 2023-03-12 21:33:46 +08:00
adams549659584andGitHub 3a3b945de8 修复 js 下 bark 推送声音 bug (#1847) 2023-03-12 20:58:26 +08:00
whyour 73c53dbc8d 修改 typescript execute 2023-03-12 20:53:15 +08:00
whyour f76828d4ec 修改 shell 文件权限 2023-03-11 01:10:03 +08:00
whyour 7b2956eb0a 修复日志删除逻辑 2023-03-10 14:21:52 +08:00
whyour b2167ae5e4 修复自定义通知 2023-03-07 22:20:08 +08:00
whyour 98dfa4c425 更新版本 v2.15.9 2023-03-04 15:48:29 +08:00
whyour 5bf08b76de 修复系统更新源判断,回退 @monaco-editor/react 2023-03-03 23:45:38 +08:00
whyour 5c5b4f804e 更新 antd 2023-03-03 22:52:44 +08:00
whyour 6455245d11 更新 @umijs/max 2023-03-03 22:14:03 +08:00
pharaoh2012andGitHub 2ff3d9c601 根据标题跳过消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔 (#1833) 2023-03-03 21:59:44 +08:00
whyour d342fbf29f 修改登录日志表格样式 2023-03-03 11:58:06 +08:00
whyour f865018cd6 修改表格样式 2023-03-02 23:31:46 +08:00
whyour 3b9a4f0834 修复定时任务状态筛选 2023-03-02 23:16:18 +08:00
whyour 67bc305950 修复拉取仓库重置操作 2023-03-01 22:12:49 +08:00
whyour 97f128d59f 修改 ql extra 执行逻辑 2023-02-28 22:56:06 +08:00
whyour e25885c4d9 修改 nginx ipv6 配置 2023-02-27 23:30:00 +08:00
whyour c285026339 修改删除日志逻辑 2023-02-27 23:25:08 +08:00
whyour 6c34045a48 修改订阅名称必填 2023-02-26 23:36:32 +08:00
whyour e1e6261b4f 修复定时任务/视图/环境变量更新逻辑 2023-02-24 23:21:08 +08:00
whyour 697bcb5922 暂时去掉 vlist 2023-02-24 23:04:18 +08:00
whyour e05b0a2491 修复文件类型订阅重复添加任务 2023-02-18 14:38:13 +08:00
94 changed files with 8580 additions and 6275 deletions
+6 -5
View File
@@ -45,7 +45,7 @@ jobs:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: pnpm/action-setup@v2 - uses: pnpm/action-setup@v2
with: with:
version: latest version: '8.3.1'
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
@@ -85,8 +85,6 @@ jobs:
git push --force --quiet gitlab ${GITHUB_BRANCH}:${GITHUB_BRANCH} git push --force --quiet gitlab ${GITHUB_BRANCH}:${GITHUB_BRANCH}
build: build:
if: github.ref != 'refs/heads/master'
needs: build-static needs: build-static
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -99,7 +97,7 @@ jobs:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: pnpm/action-setup@v2 - uses: pnpm/action-setup@v2
with: with:
version: latest version: '8.3.1'
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
cache: 'pnpm' cache: 'pnpm'
@@ -131,11 +129,14 @@ jobs:
ghcr.io/${{ github.repository }} ghcr.io/${{ github.repository }}
# generate Docker tags based on the following events/attributes # generate Docker tags based on the following events/attributes
# nightly, master, pr-2, 1.2.3, 1.2, 1 # nightly, master, pr-2, 1.2.3, 1.2, 1
flavor: |
latest=false
tags: | tags: |
type=schedule,pattern=nightly type=schedule,pattern=nightly
type=edge type=edge
type=ref,event=branch
type=ref,event=pr type=ref,event=pr
type=ref,event=branch,enable=${{ github.ref != format('refs/heads/{0}', 'master') }}
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'master') }}
type=semver,pattern={{version}} type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}} type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}} type=semver,pattern={{major}}
+7 -3
View File
@@ -1,25 +1,28 @@
import { defineConfig } from '@umijs/max'; import { defineConfig } from '@umijs/max';
const CompressionPlugin = require('compression-webpack-plugin'); const CompressionPlugin = require('compression-webpack-plugin');
const baseUrl = process.env.QlBaseUrl || '/';
export default defineConfig({ export default defineConfig({
hash: true, hash: true,
antd: {}, antd: {},
outputPath: 'static/dist', outputPath: 'static/dist',
fastRefresh: true, fastRefresh: true,
favicons: ['./images/favicon.svg'], favicons: [`https://qn.whyour.cn/favicon.svg`],
mfsu: { mfsu: {
strategy: 'eager', strategy: 'eager',
}, },
publicPath: process.env.NODE_ENV === 'production' ? './' : '/', publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
proxy: { proxy: {
'/api/public': { [`${baseUrl}api/public`]: {
target: 'http://127.0.0.1:5400/', target: 'http://127.0.0.1:5400/',
changeOrigin: true, changeOrigin: true,
pathRewrite: { [`^${baseUrl}api/public`]: '/api' },
}, },
'/api': { [`${baseUrl}api`]: {
target: 'http://127.0.0.1:5600/', target: 'http://127.0.0.1:5600/',
changeOrigin: true, changeOrigin: true,
ws: true, ws: true,
pathRewrite: { [`^${baseUrl}api`]: '/api' },
}, },
}, },
chainWebpack: ((config: any) => { chainWebpack: ((config: any) => {
@@ -37,6 +40,7 @@ export default defineConfig({
'react-dom': 'window.ReactDOM', 'react-dom': 'window.ReactDOM',
}, },
headScripts: [ headScripts: [
`./api/env.js`,
'https://gw.alipayobjects.com/os/lib/react/18.2.0/umd/react.production.min.js', 'https://gw.alipayobjects.com/os/lib/react/18.2.0/umd/react.production.min.js',
'https://gw.alipayobjects.com/os/lib/react-dom/18.2.0/umd/react-dom.production.min.js', 'https://gw.alipayobjects.com/os/lib/react-dom/18.2.0/umd/react-dom.production.min.js',
], ],
+3 -3
View File
@@ -8,7 +8,7 @@
<div align="center"> <div align="center">
Timed task management panel with python3, javaScript, shell, typescript support Timed task management platform supporting Python3, JavaScript, Shell, Typescript
[![docker version][docker-version-image]][docker-version-url] [![docker pulls][docker-pulls-image]][docker-pulls-url] [![docker stars][docker-stars-image]][docker-stars-url] [![docker image size][docker-image-size-image]][docker-image-size-url] [![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 @@ Timed task management panel with python3, javaScript, shell, typescript support
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong [docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
</div> </div>
[![](https://user-images.githubusercontent.com/22700758/203243067-1a8a570d-b1b4-4837-9f12-d78d83e31f35.jpg)](https://whyour.cn) [![](https://user-images.githubusercontent.com/22700758/229290661-03aabe84-8780-4ef0-8e75-2146f4636130.jpeg)](https://whyour.cn)
[简体中文](./README.md) | English [简体中文](./README.md) | English
@@ -198,7 +198,7 @@ $ git clone git@github.com:whyour/qinglong.git
$ cd qinglong $ cd qinglong
$ cp .env.example .env $ cp .env.example .env
# Recommended use pnpm https://pnpm.io/zh/installation # Recommended use pnpm https://pnpm.io/zh/installation
$ npm install -g pnpm $ npm install -g pnpm@8.3.1
$ pnpm install $ pnpm install
$ pnpm start $ pnpm start
``` ```
+7 -4
View File
@@ -8,7 +8,7 @@
<div align="center"> <div align="center">
支持python3、javaScript、shell、typescript 的定时任务管理面板 支持 Python3、JavaScript、Shell、Typescript 的定时任务管理平台
[![docker version][docker-version-image]][docker-version-url] [![docker pulls][docker-pulls-image]][docker-pulls-url] [![docker stars][docker-stars-image]][docker-stars-url] [![docker image size][docker-image-size-image]][docker-image-size-url] [![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 [docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
</div> </div>
[![](https://user-images.githubusercontent.com/22700758/203243067-1a8a570d-b1b4-4837-9f12-d78d83e31f35.jpg)](https://whyour.cn) [![](https://user-images.githubusercontent.com/22700758/229290661-03aabe84-8780-4ef0-8e75-2146f4636130.jpeg)](https://whyour.cn)
简体中文 | [English](./README-en.md) 简体中文 | [English](./README-en.md)
@@ -59,6 +59,8 @@ podman run -dit \
--network bridge \ --network bridge \
-v $PWD/ql/data:/ql/data \ -v $PWD/ql/data:/ql/data \
-p 5700:5700 \ -p 5700:5700 \
# 部署路径非必须,以斜杠开头和结尾,比如 /test/
-e QlBaseUrl="/" \
--name qinglong \ --name qinglong \
--hostname qinglong \ --hostname qinglong \
docker.io/whyour/qinglong:latest docker.io/whyour/qinglong:latest
@@ -73,7 +75,6 @@ sudo curl -sSL get.docker.com | sh
``` ```
2. 配置国内镜像源 2. 配置国内镜像源
Configure domestic mirror sources
```bash ```bash
mkdir -p /etc/docker mkdir -p /etc/docker
@@ -98,6 +99,8 @@ systemctl restart docker
docker run -dit \ docker run -dit \
-v $PWD/ql/data:/ql/data \ -v $PWD/ql/data:/ql/data \
-p 5700:5700 \ -p 5700:5700 \
# 部署路径非必须,以斜杠开头和结尾,比如 /test/
-e QlBaseUrl="/" \
--name qinglong \ --name qinglong \
--hostname qinglong \ --hostname qinglong \
--restart unless-stopped \ --restart unless-stopped \
@@ -198,7 +201,7 @@ $ git clone git@github.com:whyour/qinglong.git
$ cd qinglong $ cd qinglong
$ cp .env.example .env $ cp .env.example .env
# 推荐使用 pnpm https://pnpm.io/zh/installation # 推荐使用 pnpm https://pnpm.io/zh/installation
$ npm install -g pnpm $ npm install -g pnpm@8.3.1
$ pnpm install $ pnpm install
$ pnpm start $ pnpm start
``` ```
+4 -3
View File
@@ -5,6 +5,7 @@ import { Logger } from 'winston';
import config from '../config'; import config from '../config';
import * as fs from 'fs'; import * as fs from 'fs';
import { celebrate, Joi } from 'celebrate'; import { celebrate, Joi } from 'celebrate';
import { join } from 'path';
const route = Router(); const route = Router();
export default (app: Router) => { export default (app: Router) => {
@@ -41,11 +42,11 @@ export default (app: Router) => {
} }
if (req.params.file.includes('sample')) { if (req.params.file.includes('sample')) {
content = getFileContentByName( content = getFileContentByName(
`${config.samplePath}${req.params.file}`, join(config.samplePath, req.params.file),
); );
} else { } else {
content = getFileContentByName( content = getFileContentByName(
`${config.configPath}${req.params.file}`, join(config.configPath, req.params.file),
); );
} }
res.send({ code: 200, data: content }); res.send({ code: 200, data: content });
@@ -70,7 +71,7 @@ export default (app: Router) => {
if (config.blackFileList.includes(name)) { if (config.blackFileList.includes(name)) {
res.send({ code: 403, message: '文件无法访问' }); res.send({ code: 403, message: '文件无法访问' });
} }
const path = `${config.configPath}${name}`; const path = join(config.configPath, name);
fs.writeFileSync(path, content); fs.writeFileSync(path, content);
res.send({ code: 200, message: '保存成功' }); res.send({ code: 200, message: '保存成功' });
} catch (e) { } catch (e) {
+15
View File
@@ -152,6 +152,21 @@ export default (app: Router) => {
} }
}); });
route.get(
'/detail',
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
const cronService = Container.get(CronService);
const data = await cronService.find(req.query as any);
return res.send({ code: 200, data });
} catch (e) {
logger.error('🔥 error: %o', e);
return next(e);
}
},
);
route.post( route.post(
'/', '/',
celebrate({ celebrate({
+3 -3
View File
@@ -94,7 +94,7 @@ export default (app: Router) => {
path += '/'; path += '/';
} }
if (!path.startsWith('/')) { if (!path.startsWith('/')) {
path = `${config.scriptPath}${path}`; path = join(config.scriptPath, path);
} }
if (config.writePathList.every((x) => !path.startsWith(x))) { if (config.writePathList.every((x) => !path.startsWith(x))) {
return res.send({ return res.send({
@@ -124,7 +124,7 @@ export default (app: Router) => {
if (fs.existsSync(originFilePath)) { if (fs.existsSync(originFilePath)) {
fs.copyFileSync( fs.copyFileSync(
originFilePath, originFilePath,
`${config.bakPath}${originFilename.replace(/\//g, '')}`, join(config.bakPath, originFilename.replace(/\//g, '')),
); );
if (filename !== originFilename) { if (filename !== originFilename) {
fs.unlinkSync(originFilePath); fs.unlinkSync(originFilePath);
@@ -207,7 +207,7 @@ export default (app: Router) => {
let { filename } = req.body as { let { filename } = req.body as {
filename: string; filename: string;
}; };
const filePath = `${config.scriptPath}${filename}`; const filePath = join(config.scriptPath, filename);
// const stats = fs.statSync(filePath); // const stats = fs.statSync(filePath);
// res.set({ // res.set({
// 'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件 // 'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
+66 -1
View File
@@ -7,7 +7,12 @@ import SystemService from '../services/system';
import { celebrate, Joi } from 'celebrate'; import { celebrate, Joi } from 'celebrate';
import UserService from '../services/user'; import UserService from '../services/user';
import { EnvModel } from '../data/env'; import { EnvModel } from '../data/env';
import { parseVersion, promiseExec } from '../config/util'; import {
getUniqPath,
handleLogPath,
parseVersion,
promiseExec,
} from '../config/util';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
const route = Router(); const route = Router();
@@ -147,4 +152,64 @@ export default (app: Router) => {
} }
}, },
); );
route.put(
'/command-run',
celebrate({
body: Joi.object({
command: Joi.string().required(),
}),
}),
async (req: Request, res: Response, next: NextFunction) => {
try {
const systemService = Container.get(SystemService);
const uniqPath = await getUniqPath(req.body.command);
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
const logPath = `${uniqPath}/${logTime}.log`;
res.setHeader('Content-type', 'application/octet-stream');
await systemService.run(
{ ...req.body, logPath },
{
onStart: async (cp, startTime) => {
res.setHeader('QL-Task-Pid', `${cp.pid}`);
},
onEnd: async (cp, endTime, diff) => {
res.end();
},
onError: async (message: string) => {
res.write(`\n${message}`);
const absolutePath = await handleLogPath(logPath);
fs.appendFileSync(absolutePath, `\n${message}`);
},
onLog: async (message: string) => {
res.write(`\n${message}`);
const absolutePath = await handleLogPath(logPath);
fs.appendFileSync(absolutePath, `\n${message}`);
},
},
);
} catch (e) {
return next(e);
}
},
);
route.put(
'/command-stop',
celebrate({
body: Joi.object({
command: Joi.string().optional(),
pid: Joi.number().optional(),
}),
}),
async (req: Request, res: Response, next: NextFunction) => {
try {
const systemService = Container.get(SystemService);
const result = await systemService.stop(req.body);
res.send(result);
} catch (e) {
return next(e);
}
},
);
}; };
+1
View File
@@ -18,6 +18,7 @@ async function startServer() {
const server = app const server = app
.listen(config.port, () => { .listen(config.port, () => {
Logger.debug(`✌️ 后端服务启动成功!`); Logger.debug(`✌️ 后端服务启动成功!`);
process.send?.('ready');
}) })
.on('error', (err) => { .on('error', (err) => {
Logger.error(err); Logger.error(err);
+7
View File
@@ -27,6 +27,7 @@ const bakPath = path.join(dataPath, 'bak/');
const logPath = path.join(dataPath, 'log/'); const logPath = path.join(dataPath, 'log/');
const dbPath = path.join(dataPath, 'db/'); const dbPath = path.join(dataPath, 'db/');
const uploadPath = path.join(dataPath, 'upload/'); const uploadPath = path.join(dataPath, 'upload/');
const sshdPath = path.join(dataPath, 'ssh.d/');
const envFile = path.join(configPath, 'env.sh'); const envFile = path.join(configPath, 'env.sh');
const confFile = path.join(configPath, 'config.sh'); const confFile = path.join(configPath, 'config.sh');
@@ -91,8 +92,14 @@ export default {
'/api/system', '/api/system',
'/api/user/init', '/api/user/init',
'/api/user/notification/init', '/api/user/notification/init',
'/open/user/login',
'/open/user/two-factor/login',
'/open/system',
'/open/user/init',
'/open/user/notification/init',
], ],
versionFile, versionFile,
lastVersionFile, lastVersionFile,
sqliteFile, sqliteFile,
sshdPath,
}; };
+20
View File
@@ -0,0 +1,20 @@
import { Request, Response } from 'express';
import { pick } from 'lodash';
let pickedEnv: Record<string, string>;
function getPickedEnv() {
if (pickedEnv) return pickedEnv;
const picked = pick(process.env, ['QlBaseUrl']);
pickedEnv = picked as Record<string, string>;
return picked;
}
export function serveEnv(_req: Request, res: Response) {
res.type('.js');
res.send(
Object.entries(getPickedEnv())
.map(([k, v]) => `window.__ENV__${k}=${JSON.stringify(v)};`)
.join('\n'),
);
}
+61 -7
View File
@@ -7,6 +7,8 @@ import FormData from 'form-data';
import psTreeFun from 'pstree.remy'; import psTreeFun from 'pstree.remy';
import { promisify } from 'util'; import { promisify } from 'util';
import { load } from 'js-yaml'; import { load } from 'js-yaml';
import config from './index';
import { TASK_COMMAND } from './const';
export function getFileContentByName(fileName: string) { export function getFileContentByName(fileName: string) {
if (fs.existsSync(fileName)) { if (fs.existsSync(fileName)) {
@@ -245,6 +247,18 @@ export async function createFile(file: string, data: string = '') {
}); });
} }
export async function handleLogPath(
logPath: string,
data: string = '',
): Promise<string> {
const absolutePath = path.resolve(config.logPath, logPath);
const logFileExist = await fileExist(absolutePath);
if (!logFileExist) {
await createFile(absolutePath, data);
}
return absolutePath;
}
export async function concurrentRun( export async function concurrentRun(
fnList: Array<() => Promise<any>> = [], fnList: Array<() => Promise<any>> = [],
max = 5, max = 5,
@@ -469,19 +483,22 @@ export function psTree(pid: number): Promise<number[]> {
export async function killTask(pid: number) { export async function killTask(pid: number) {
const pids = await psTree(pid); const pids = await psTree(pid);
// SIGALRM 14 时钟信号 // SIGINT 2 程序终止(interrupt)信号,不会打印额外信息
if (pids.length) { if (pids.length) {
process.kill(pids[0], 14); try {
[pid, ...pids].forEach((x) => {
process.kill(x, 2);
});
} catch (error) {}
} else { } else {
process.kill(pid, 14); process.kill(pid, 2);
} }
} }
export async function getPid(name: string) { export async function getPid(name: string) {
let taskCommand = `ps -ef | grep "${name}" | grep -v grep | awk '{print $1}'`; const taskCommand = `ps -eo pid,command | grep "${name}" | grep -v grep | awk '{print $1}' | head -1 | xargs echo -n`;
const execAsync = promisify(exec); const pid = await promiseExec(taskCommand);
let pid = (await execAsync(taskCommand)).stdout; return pid ? Number(pid) : undefined;
return Number(pid);
} }
interface IVersion { interface IVersion {
@@ -497,3 +514,40 @@ export async function parseVersion(path: string): Promise<IVersion> {
export async function parseContentVersion(content: string): Promise<IVersion> { export async function parseContentVersion(content: string): Promise<IVersion> {
return load(content) as IVersion; return load(content) as IVersion;
} }
export async function getUniqPath(command: string): Promise<string> {
const idStr = `cat ${config.crontabFile} | grep -E "${command}" | perl -pe "s|.*ID=(.*) ${command}.*|\\1|" | head -1 | awk -F " " '{print $1}' | xargs echo -n`;
let id = await promiseExec(idStr);
if (/^\d\d*\d$/.test(id)) {
id = `_${id}`;
} else {
id = '';
}
const items = command.split(/ +/);
let str = items[0];
if (items[0] === TASK_COMMAND) {
str = items[1];
}
const dotIndex = str.lastIndexOf('.');
if (dotIndex !== -1) {
str = str.slice(0, dotIndex);
}
const slashIndex = str.lastIndexOf('/');
let tempStr = '';
if (slashIndex !== -1) {
tempStr = str.slice(0, slashIndex);
const _slashIndex = tempStr.lastIndexOf('/');
if (_slashIndex !== -1) {
tempStr = tempStr.slice(_slashIndex + 1);
}
str = `${tempStr}_${str.slice(slashIndex + 1)}`;
}
return `${str}${id}`;
}
+1 -1
View File
@@ -26,7 +26,7 @@ export class Crontab {
this.saved = options.saved; this.saved = options.saved;
this.id = options.id; this.id = options.id;
this.status = this.status =
options.status && CrontabStatus[options.status] typeof options.status === 'number' && CrontabStatus[options.status]
? options.status ? options.status
: CrontabStatus.idle; : CrontabStatus.idle;
this.timestamp = new Date().toString(); this.timestamp = new Date().toString();
+5 -1
View File
@@ -12,7 +12,10 @@ export class Dependence {
constructor(options: Dependence) { constructor(options: Dependence) {
this.id = options.id; this.id = options.id;
this.status = options.status || DependenceStatus.installing; this.status =
typeof options.status === 'number' && DependenceStatus[options.status]
? options.status
: DependenceStatus.installing;
this.type = options.type || DependenceTypes.nodejs; this.type = options.type || DependenceTypes.nodejs;
this.timestamp = new Date().toString(); this.timestamp = new Date().toString();
this.name = options.name; this.name = options.name;
@@ -28,6 +31,7 @@ export enum DependenceStatus {
'removing', 'removing',
'removed', 'removed',
'removeFailed', 'removeFailed',
'queued',
} }
export enum DependenceTypes { export enum DependenceTypes {
+4 -1
View File
@@ -13,7 +13,10 @@ export class Env {
constructor(options: Env) { constructor(options: Env) {
this.value = options.value; this.value = options.value;
this.id = options.id; this.id = options.id;
this.status = options.status || EnvStatus.normal; this.status =
typeof options.status === 'number' && EnvStatus[options.status]
? options.status
: EnvStatus.normal;
this.timestamp = new Date().toString(); this.timestamp = new Date().toString();
this.position = options.position; this.position = options.position;
this.name = options.name; this.name = options.name;
+2 -1
View File
@@ -1,9 +1,10 @@
import { Sequelize, Transaction } from 'sequelize'; import { Sequelize, Transaction } from 'sequelize';
import config from '../config/index'; import config from '../config/index';
import { join } from 'path';
export const sequelize = new Sequelize({ export const sequelize = new Sequelize({
dialect: 'sqlite', dialect: 'sqlite',
storage: `${config.dbPath}database.sqlite`, storage: join(config.dbPath, 'database.sqlite'),
logging: false, logging: false,
retry: { retry: {
max: 10, max: 10,
+2 -2
View File
@@ -37,8 +37,8 @@ export class Subscription {
this.name = options.name || options.alias; this.name = options.name || options.alias;
this.type = options.type; this.type = options.type;
this.schedule = options.schedule; this.schedule = options.schedule;
this.status = this.status = this.status =
options.status && SubscriptionStatus[options.status] typeof options.status === 'number' && SubscriptionStatus[options.status]
? options.status ? options.status
: SubscriptionStatus.idle; : SubscriptionStatus.idle;
this.url = options.url; this.url = options.url;
+13 -10
View File
@@ -14,22 +14,25 @@ import handler from 'serve-handler';
import * as Sentry from '@sentry/node'; import * as Sentry from '@sentry/node';
import { EnvModel } from '../data/env'; import { EnvModel } from '../data/env';
import { errors } from 'celebrate'; import { errors } from 'celebrate';
import path from 'path';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { serveEnv } from '../config/serverEnv';
export default ({ app }: { app: Application }) => { export default ({ app }: { app: Application }) => {
app.enable('trust proxy'); app.enable('trust proxy');
app.use(cors()); app.use(cors());
app.get(`${config.api.prefix}/env.js`, serveEnv);
app.use(`${config.api.prefix}/static`, express.static(config.uploadPath)); app.use(`${config.api.prefix}/static`, express.static(config.uploadPath));
app.use((req, res, next) => { app.use(
if (req.path.startsWith('/api') || req.path.startsWith('/open')) { '/api/public',
next(); createProxyMiddleware({
} else { target: `http://localhost:${config.publicPort}/api`,
return handler(req, res, { changeOrigin: true,
public: 'static/dist', pathRewrite: { '/api/public': '' },
rewrites: [{ source: '**', destination: '/index.html' }], }),
}); );
}
});
app.use(bodyParser.json({ limit: '50mb' })); app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
+7 -10
View File
@@ -4,8 +4,7 @@ import { Container } from 'typedi';
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron'; import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
import CronService from '../services/cron'; import CronService from '../services/cron';
import EnvService from '../services/env'; import EnvService from '../services/env';
import groupBy from 'lodash/groupBy'; import { DependenceModel, DependenceStatus } from '../data/dependence';
import { DependenceModel } from '../data/dependence';
import { Op } from 'sequelize'; import { Op } from 'sequelize';
import config from '../config'; import config from '../config';
import { CrontabViewModel, CronViewType } from '../data/cronView'; import { CrontabViewModel, CronViewType } from '../data/cronView';
@@ -42,16 +41,14 @@ export default async () => {
order: [['type', 'DESC']], order: [['type', 'DESC']],
raw: true, raw: true,
}).then(async (docs) => { }).then(async (docs) => {
const groups = groupBy(docs, 'type'); await DependenceModel.update(
const keys = Object.keys(groups).sort((a, b) => parseInt(b) - parseInt(a)); { status: DependenceStatus.queued, log: [] },
for (const key of keys) { { where: { id: docs.map((x) => x.id!) } },
const group = groups[key]; );
const depIds = group.map((x) => x.id); dependenceService.installDependenceOneByOne(docs);
await dependenceService.reInstall(depIds as number[]);
}
}); });
// 初始化时执行一次所有的ql repo 任务 // 初始化时执行一次所有的 ql repo 任务
CrontabModel.findAll({ CrontabModel.findAll({
where: { where: {
isDisabled: { [Op.ne]: 1 }, isDisabled: { [Op.ne]: 1 },
+6
View File
@@ -19,6 +19,7 @@ const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
const sampleAuthFile = path.join(samplePath, 'auth.sample.json'); const sampleAuthFile = path.join(samplePath, 'auth.sample.json');
const homedir = os.homedir(); const homedir = os.homedir();
const sshPath = path.resolve(homedir, '.ssh'); const sshPath = path.resolve(homedir, '.ssh');
const sshdPath = path.join(dataPath, 'ssh.d');
export default async () => { export default async () => {
const authFileExist = await fileExist(authConfigFile); const authFileExist = await fileExist(authConfigFile);
@@ -29,6 +30,7 @@ export default async () => {
const uploadDirExist = await fileExist(uploadPath); const uploadDirExist = await fileExist(uploadPath);
const sshDirExist = await fileExist(sshPath); const sshDirExist = await fileExist(sshPath);
const bakDirExist = await fileExist(bakPath); const bakDirExist = await fileExist(bakPath);
const sshdDirExist = await fileExist(sshdPath);
if (!configDirExist) { if (!configDirExist) {
fs.mkdirSync(configPath); fs.mkdirSync(configPath);
@@ -62,6 +64,10 @@ export default async () => {
fs.mkdirSync(bakPath); fs.mkdirSync(bakPath);
} }
if (!sshdDirExist) {
fs.mkdirSync(sshdPath);
}
dotenv.config({ path: confFile }); dotenv.config({ path: confFile });
Logger.info('✌️ Init file down'); Logger.info('✌️ Init file down');
+5 -2
View File
@@ -4,6 +4,7 @@ import ScheduleService from '../services/schedule';
import SubscriptionService from '../services/subscription'; import SubscriptionService from '../services/subscription';
import config from '../config'; import config from '../config';
import { fileExist } from '../config/util'; import { fileExist } from '../config/util';
import { join } from 'path';
export default async () => { export default async () => {
const systemService = Container.get(SystemService); const systemService = Container.get(SystemService);
@@ -11,8 +12,9 @@ export default async () => {
const subscriptionService = Container.get(SubscriptionService); const subscriptionService = Container.get(SubscriptionService);
// 生成内置token // 生成内置token
let tokenCommand = `ts-node-transpile-only ${config.rootPath}/back/token.ts`; let tokenCommand = `tsx ${join(config.rootPath, 'back/token.ts')}`;
const tokenFile = `${config.rootPath}static/build/token.js`; const tokenFile = join(config.rootPath, 'static/build/token.js');
if (await fileExist(tokenFile)) { if (await fileExist(tokenFile)) {
tokenCommand = `node ${tokenFile}`; tokenCommand = `node ${tokenFile}`;
} }
@@ -41,6 +43,7 @@ export default async () => {
} }
// 运行所有订阅 // 运行所有订阅
await subscriptionService.setSshConfig();
const subs = await subscriptionService.list(); const subs = await subscriptionService.list();
for (const sub of subs) { for (const sub of subs) {
subscriptionService.handleTask(sub, !sub.is_disabled, !sub.is_disabled); subscriptionService.handleTask(sub, !sub.is_disabled, !sub.is_disabled);
+8 -2
View File
@@ -9,8 +9,14 @@ export default async ({ server }: { server: Server }) => {
process.on('SIGINT', () => { process.on('SIGINT', () => {
Logger.info('✌️ Server need close'); Logger.info('✌️ Server need close');
server.close(() => { server.close(() => {
Logger.info('✌️ Server closed'); setTimeout(() => {
process.exit(0); process.exit();
}, 10000);
}); });
setTimeout(() => {
console.log('Forcing server close !!!');
process.exit(1);
}, 15000);
}); });
}; };
+22
View File
@@ -0,0 +1,22 @@
syntax = "proto3";
package com.ql.cron;
service Cron {
rpc addCron(AddCronRequest) returns (AddCronResponse);
rpc delCron(DeleteCronRequest) returns (DeleteCronResponse);
}
message ICron {
string id = 1;
string schedule = 2;
string command = 3;
}
message AddCronRequest { repeated ICron crons = 1; }
message AddCronResponse {}
message DeleteCronRequest { repeated string ids = 1; }
message DeleteCronResponse {}
+482
View File
@@ -0,0 +1,482 @@
/* eslint-disable */
import {
CallOptions,
ChannelCredentials,
Client,
ClientOptions,
ClientUnaryCall,
handleUnaryCall,
makeGenericClientConstructor,
Metadata,
ServiceError,
UntypedServiceImplementation,
} from '@grpc/grpc-js';
import _m0 from 'protobufjs/minimal';
export const protobufPackage = 'com.ql.cron';
export interface ICron {
id: string;
schedule: string;
command: string;
}
export interface AddCronRequest {
crons: ICron[];
}
export interface AddCronResponse {}
export interface DeleteCronRequest {
ids: string[];
}
export interface DeleteCronResponse {}
function createBaseICron(): ICron {
return { id: '', schedule: '', command: '' };
}
export const ICron = {
encode(message: ICron, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.id !== '') {
writer.uint32(10).string(message.id);
}
if (message.schedule !== '') {
writer.uint32(18).string(message.schedule);
}
if (message.command !== '') {
writer.uint32(26).string(message.command);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ICron {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseICron();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
if (tag != 10) {
break;
}
message.id = reader.string();
continue;
case 2:
if (tag != 18) {
break;
}
message.schedule = reader.string();
continue;
case 3:
if (tag != 26) {
break;
}
message.command = reader.string();
continue;
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(object: any): ICron {
return {
id: isSet(object.id) ? String(object.id) : '',
schedule: isSet(object.schedule) ? String(object.schedule) : '',
command: isSet(object.command) ? String(object.command) : '',
};
},
toJSON(message: ICron): unknown {
const obj: any = {};
message.id !== undefined && (obj.id = message.id);
message.schedule !== undefined && (obj.schedule = message.schedule);
message.command !== undefined && (obj.command = message.command);
return obj;
},
create<I extends Exact<DeepPartial<ICron>, I>>(base?: I): ICron {
return ICron.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<ICron>, I>>(object: I): ICron {
const message = createBaseICron();
message.id = object.id ?? '';
message.schedule = object.schedule ?? '';
message.command = object.command ?? '';
return message;
},
};
function createBaseAddCronRequest(): AddCronRequest {
return { crons: [] };
}
export const AddCronRequest = {
encode(
message: AddCronRequest,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
for (const v of message.crons) {
ICron.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): AddCronRequest {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseAddCronRequest();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
if (tag != 10) {
break;
}
message.crons.push(ICron.decode(reader, reader.uint32()));
continue;
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(object: any): AddCronRequest {
return {
crons: Array.isArray(object?.crons)
? object.crons.map((e: any) => ICron.fromJSON(e))
: [],
};
},
toJSON(message: AddCronRequest): unknown {
const obj: any = {};
if (message.crons) {
obj.crons = message.crons.map((e) => (e ? ICron.toJSON(e) : undefined));
} else {
obj.crons = [];
}
return obj;
},
create<I extends Exact<DeepPartial<AddCronRequest>, I>>(
base?: I,
): AddCronRequest {
return AddCronRequest.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(
object: I,
): AddCronRequest {
const message = createBaseAddCronRequest();
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
return message;
},
};
function createBaseAddCronResponse(): AddCronResponse {
return {};
}
export const AddCronResponse = {
encode(
_: AddCronResponse,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): AddCronResponse {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseAddCronResponse();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(_: any): AddCronResponse {
return {};
},
toJSON(_: AddCronResponse): unknown {
const obj: any = {};
return obj;
},
create<I extends Exact<DeepPartial<AddCronResponse>, I>>(
base?: I,
): AddCronResponse {
return AddCronResponse.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(
_: I,
): AddCronResponse {
const message = createBaseAddCronResponse();
return message;
},
};
function createBaseDeleteCronRequest(): DeleteCronRequest {
return { ids: [] };
}
export const DeleteCronRequest = {
encode(
message: DeleteCronRequest,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
for (const v of message.ids) {
writer.uint32(10).string(v!);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): DeleteCronRequest {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseDeleteCronRequest();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
if (tag != 10) {
break;
}
message.ids.push(reader.string());
continue;
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(object: any): DeleteCronRequest {
return {
ids: Array.isArray(object?.ids)
? object.ids.map((e: any) => String(e))
: [],
};
},
toJSON(message: DeleteCronRequest): unknown {
const obj: any = {};
if (message.ids) {
obj.ids = message.ids.map((e) => e);
} else {
obj.ids = [];
}
return obj;
},
create<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(
base?: I,
): DeleteCronRequest {
return DeleteCronRequest.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(
object: I,
): DeleteCronRequest {
const message = createBaseDeleteCronRequest();
message.ids = object.ids?.map((e) => e) || [];
return message;
},
};
function createBaseDeleteCronResponse(): DeleteCronResponse {
return {};
}
export const DeleteCronResponse = {
encode(
_: DeleteCronResponse,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): DeleteCronResponse {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseDeleteCronResponse();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(_: any): DeleteCronResponse {
return {};
},
toJSON(_: DeleteCronResponse): unknown {
const obj: any = {};
return obj;
},
create<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(
base?: I,
): DeleteCronResponse {
return DeleteCronResponse.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(
_: I,
): DeleteCronResponse {
const message = createBaseDeleteCronResponse();
return message;
},
};
export type CronService = typeof CronService;
export const CronService = {
addCron: {
path: '/com.ql.cron.Cron/addCron',
requestStream: false,
responseStream: false,
requestSerialize: (value: AddCronRequest) =>
Buffer.from(AddCronRequest.encode(value).finish()),
requestDeserialize: (value: Buffer) => AddCronRequest.decode(value),
responseSerialize: (value: AddCronResponse) =>
Buffer.from(AddCronResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
},
delCron: {
path: '/com.ql.cron.Cron/delCron',
requestStream: false,
responseStream: false,
requestSerialize: (value: DeleteCronRequest) =>
Buffer.from(DeleteCronRequest.encode(value).finish()),
requestDeserialize: (value: Buffer) => DeleteCronRequest.decode(value),
responseSerialize: (value: DeleteCronResponse) =>
Buffer.from(DeleteCronResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => DeleteCronResponse.decode(value),
},
} as const;
export interface CronServer extends UntypedServiceImplementation {
addCron: handleUnaryCall<AddCronRequest, AddCronResponse>;
delCron: handleUnaryCall<DeleteCronRequest, DeleteCronResponse>;
}
export interface CronClient extends Client {
addCron(
request: AddCronRequest,
callback: (error: ServiceError | null, response: AddCronResponse) => void,
): ClientUnaryCall;
addCron(
request: AddCronRequest,
metadata: Metadata,
callback: (error: ServiceError | null, response: AddCronResponse) => void,
): ClientUnaryCall;
addCron(
request: AddCronRequest,
metadata: Metadata,
options: Partial<CallOptions>,
callback: (error: ServiceError | null, response: AddCronResponse) => void,
): ClientUnaryCall;
delCron(
request: DeleteCronRequest,
callback: (
error: ServiceError | null,
response: DeleteCronResponse,
) => void,
): ClientUnaryCall;
delCron(
request: DeleteCronRequest,
metadata: Metadata,
callback: (
error: ServiceError | null,
response: DeleteCronResponse,
) => void,
): ClientUnaryCall;
delCron(
request: DeleteCronRequest,
metadata: Metadata,
options: Partial<CallOptions>,
callback: (
error: ServiceError | null,
response: DeleteCronResponse,
) => void,
): ClientUnaryCall;
}
export const CronClient = makeGenericClientConstructor(
CronService,
'com.ql.cron.Cron',
) as unknown as {
new (
address: string,
credentials: ChannelCredentials,
options?: Partial<ClientOptions>,
): CronClient;
service: typeof CronService;
};
type Builtin =
| Date
| Function
| Uint8Array
| string
| number
| boolean
| undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
type KeysOfUnion<T> = T extends T ? keyof T : never;
export type Exact<P, I extends P> = P extends Builtin
? P
: P & { [K in keyof P]: Exact<P[K], I[K]> } & {
[K in Exclude<keyof I, KeysOfUnion<P>>]: never;
};
function isSet(value: any): boolean {
return value !== null && value !== undefined;
}
+22
View File
@@ -0,0 +1,22 @@
syntax = "proto3";
package com.ql.health;
message HealthCheckRequest {
string service = 1;
}
message HealthCheckResponse {
enum ServingStatus {
UNKNOWN = 0;
SERVING = 1;
NOT_SERVING = 2;
SERVICE_UNKNOWN = 3;
}
ServingStatus status = 1;
}
service Health {
rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}
+317
View File
@@ -0,0 +1,317 @@
/* eslint-disable */
import {
CallOptions,
ChannelCredentials,
Client,
ClientOptions,
ClientReadableStream,
ClientUnaryCall,
handleServerStreamingCall,
handleUnaryCall,
makeGenericClientConstructor,
Metadata,
ServiceError,
UntypedServiceImplementation,
} from '@grpc/grpc-js';
import _m0 from 'protobufjs/minimal';
export const protobufPackage = 'com.ql.health';
export interface HealthCheckRequest {
service: string;
}
export interface HealthCheckResponse {
status: HealthCheckResponse_ServingStatus;
}
export enum HealthCheckResponse_ServingStatus {
UNKNOWN = 0,
SERVING = 1,
NOT_SERVING = 2,
SERVICE_UNKNOWN = 3,
UNRECOGNIZED = -1,
}
export function healthCheckResponse_ServingStatusFromJSON(
object: any,
): HealthCheckResponse_ServingStatus {
switch (object) {
case 0:
case 'UNKNOWN':
return HealthCheckResponse_ServingStatus.UNKNOWN;
case 1:
case 'SERVING':
return HealthCheckResponse_ServingStatus.SERVING;
case 2:
case 'NOT_SERVING':
return HealthCheckResponse_ServingStatus.NOT_SERVING;
case 3:
case 'SERVICE_UNKNOWN':
return HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN;
case -1:
case 'UNRECOGNIZED':
default:
return HealthCheckResponse_ServingStatus.UNRECOGNIZED;
}
}
export function healthCheckResponse_ServingStatusToJSON(
object: HealthCheckResponse_ServingStatus,
): string {
switch (object) {
case HealthCheckResponse_ServingStatus.UNKNOWN:
return 'UNKNOWN';
case HealthCheckResponse_ServingStatus.SERVING:
return 'SERVING';
case HealthCheckResponse_ServingStatus.NOT_SERVING:
return 'NOT_SERVING';
case HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN:
return 'SERVICE_UNKNOWN';
case HealthCheckResponse_ServingStatus.UNRECOGNIZED:
default:
return 'UNRECOGNIZED';
}
}
function createBaseHealthCheckRequest(): HealthCheckRequest {
return { service: '' };
}
export const HealthCheckRequest = {
encode(
message: HealthCheckRequest,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
if (message.service !== '') {
writer.uint32(10).string(message.service);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): HealthCheckRequest {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseHealthCheckRequest();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
if (tag != 10) {
break;
}
message.service = reader.string();
continue;
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(object: any): HealthCheckRequest {
return { service: isSet(object.service) ? String(object.service) : '' };
},
toJSON(message: HealthCheckRequest): unknown {
const obj: any = {};
message.service !== undefined && (obj.service = message.service);
return obj;
},
create<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(
base?: I,
): HealthCheckRequest {
return HealthCheckRequest.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(
object: I,
): HealthCheckRequest {
const message = createBaseHealthCheckRequest();
message.service = object.service ?? '';
return message;
},
};
function createBaseHealthCheckResponse(): HealthCheckResponse {
return { status: 0 };
}
export const HealthCheckResponse = {
encode(
message: HealthCheckResponse,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
if (message.status !== 0) {
writer.uint32(8).int32(message.status);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): HealthCheckResponse {
const reader =
input instanceof _m0.Reader ? input : _m0.Reader.create(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseHealthCheckResponse();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
if (tag != 8) {
break;
}
message.status = reader.int32() as any;
continue;
}
if ((tag & 7) == 4 || tag == 0) {
break;
}
reader.skipType(tag & 7);
}
return message;
},
fromJSON(object: any): HealthCheckResponse {
return {
status: isSet(object.status)
? healthCheckResponse_ServingStatusFromJSON(object.status)
: 0,
};
},
toJSON(message: HealthCheckResponse): unknown {
const obj: any = {};
message.status !== undefined &&
(obj.status = healthCheckResponse_ServingStatusToJSON(message.status));
return obj;
},
create<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(
base?: I,
): HealthCheckResponse {
return HealthCheckResponse.fromPartial(base ?? {});
},
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(
object: I,
): HealthCheckResponse {
const message = createBaseHealthCheckResponse();
message.status = object.status ?? 0;
return message;
},
};
export type HealthService = typeof HealthService;
export const HealthService = {
check: {
path: '/com.ql.health.Health/Check',
requestStream: false,
responseStream: false,
requestSerialize: (value: HealthCheckRequest) =>
Buffer.from(HealthCheckRequest.encode(value).finish()),
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
responseSerialize: (value: HealthCheckResponse) =>
Buffer.from(HealthCheckResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
},
watch: {
path: '/com.ql.health.Health/Watch',
requestStream: false,
responseStream: true,
requestSerialize: (value: HealthCheckRequest) =>
Buffer.from(HealthCheckRequest.encode(value).finish()),
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
responseSerialize: (value: HealthCheckResponse) =>
Buffer.from(HealthCheckResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
},
} as const;
export interface HealthServer extends UntypedServiceImplementation {
check: handleUnaryCall<HealthCheckRequest, HealthCheckResponse>;
watch: handleServerStreamingCall<HealthCheckRequest, HealthCheckResponse>;
}
export interface HealthClient extends Client {
check(
request: HealthCheckRequest,
callback: (
error: ServiceError | null,
response: HealthCheckResponse,
) => void,
): ClientUnaryCall;
check(
request: HealthCheckRequest,
metadata: Metadata,
callback: (
error: ServiceError | null,
response: HealthCheckResponse,
) => void,
): ClientUnaryCall;
check(
request: HealthCheckRequest,
metadata: Metadata,
options: Partial<CallOptions>,
callback: (
error: ServiceError | null,
response: HealthCheckResponse,
) => void,
): ClientUnaryCall;
watch(
request: HealthCheckRequest,
options?: Partial<CallOptions>,
): ClientReadableStream<HealthCheckResponse>;
watch(
request: HealthCheckRequest,
metadata?: Metadata,
options?: Partial<CallOptions>,
): ClientReadableStream<HealthCheckResponse>;
}
export const HealthClient = makeGenericClientConstructor(
HealthService,
'com.ql.health.Health',
) as unknown as {
new (
address: string,
credentials: ChannelCredentials,
options?: Partial<ClientOptions>,
): HealthClient;
service: typeof HealthService;
};
type Builtin =
| Date
| Function
| Uint8Array
| string
| number
| boolean
| undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
type KeysOfUnion<T> = T extends T ? keyof T : never;
export type Exact<P, I extends P> = P extends Builtin
? P
: P & { [K in keyof P]: Exact<P[K], I[K]> } & {
[K in Exclude<keyof I, KeysOfUnion<P>>]: never;
};
function isSet(value: any): boolean {
return value !== null && value !== undefined;
}
+12 -6
View File
@@ -1,16 +1,21 @@
import express from 'express'; import express from 'express';
import { exec } from 'child_process';
import Logger from './loaders/logger'; import Logger from './loaders/logger';
import config from './config'; import config from './config';
import { HealthClient } from './protos/health';
import { credentials } from '@grpc/grpc-js';
const app = express(); const app = express();
const client = new HealthClient(
`localhost:${config.cronPort}`,
credentials.createInsecure(),
);
app.get('/api/public/panel/log', (req, res) => { app.get('/api/health', (req, res) => {
exec('tail -n 300 ~/.pm2/logs/panel-error.log', (err, stdout, stderr) => { client.check({ service: 'cron' }, (err, response) => {
if (err || stderr) { if (err) {
return res.send({ code: 400, message: (err && err.message) || stderr }); return res.status(500).send({ code: 500, error: err });
} }
return res.send({ code: 200, data: stdout }); return res.status(200).send({ code: 200, data: response });
}); });
}); });
@@ -20,6 +25,7 @@ app
await require('./loaders/db').default(); await require('./loaders/db').default();
Logger.debug(`✌️ 公共服务启动成功!`); Logger.debug(`✌️ 公共服务启动成功!`);
process.send?.('ready');
}) })
.on('error', (err) => { .on('error', (err) => {
Logger.error(err); Logger.error(err);
-56
View File
@@ -1,56 +0,0 @@
import schedule from 'node-schedule';
import express from 'express';
import { exec } from 'child_process';
import Logger from './loaders/logger';
import { CrontabModel, CrontabStatus } from './data/cron';
import config from './config';
import { QL_PREFIX, TASK_PREFIX } from './config/const';
const app = express();
const run = async () => {
CrontabModel.findAll({ where: {} })
.then((docs) => {
if (docs && docs.length > 0) {
for (let i = 0; i < docs.length; i++) {
const task = docs[i];
const _schedule = task.schedule && task.schedule.split(/ +/);
if (
_schedule &&
_schedule.length > 5 &&
task.status !== CrontabStatus.disabled &&
!task.isDisabled &&
task.schedule
) {
schedule.scheduleJob(task.schedule, function () {
let command = task.command as string;
if (
!command.startsWith(TASK_PREFIX) &&
!command.startsWith(QL_PREFIX)
) {
command = `${TASK_PREFIX}${command}`;
}
exec(`ID=${task.id} ${command}`);
});
}
}
}
})
.catch((err) => {
Logger.error(err);
process.exit(1);
});
};
app
.listen(config.cronPort, async () => {
await require('./loaders/sentry').default({ expressApp: app });
await require('./loaders/db').default();
await run();
Logger.debug('定时任务服务启动成功!');
})
.on('error', (err) => {
Logger.error(err);
process.exit(1);
});
+27
View File
@@ -0,0 +1,27 @@
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
import { AddCronRequest, AddCronResponse } from '../protos/cron';
import nodeSchedule from 'node-schedule';
import { scheduleStacks } from './data';
import { exec } from 'child_process';
const addCron = (
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
callback: sendUnaryData<AddCronResponse>,
) => {
for (const item of call.request.crons) {
const { id, schedule, command } = item;
if (scheduleStacks.has(id)) {
scheduleStacks.get(id)?.cancel();
}
scheduleStacks.set(
id,
nodeSchedule.scheduleJob(id, schedule, async () => {
exec(`ID=${id} ${command}`);
}),
);
}
callback(null, null);
};
export { addCron };
+40
View File
@@ -0,0 +1,40 @@
import { credentials } from '@grpc/grpc-js';
import {
AddCronRequest,
AddCronResponse,
CronClient,
DeleteCronRequest,
DeleteCronResponse,
} from '../protos/cron';
import config from '../config';
class Client {
private client = new CronClient(
`localhost:${config.cronPort}`,
credentials.createInsecure(),
);
addCron(request: AddCronRequest['crons']): Promise<AddCronResponse> {
return new Promise((resolve, reject) => {
this.client.addCron({ crons: request }, (err, res) => {
if (err) {
reject(err);
}
resolve(res);
});
});
}
delCron(request: DeleteCronRequest['ids']): Promise<DeleteCronResponse> {
return new Promise((resolve, reject) => {
this.client.delCron({ ids: request }, (err, res) => {
if (err) {
reject(err);
}
resolve(res);
});
});
}
}
export default new Client();
+6
View File
@@ -0,0 +1,6 @@
import nodeSchedule from 'node-schedule';
import { ToadScheduler } from 'toad-scheduler';
export const scheduleStacks = new Map<string, nodeSchedule.Job>();
export const intervalSchedule = new ToadScheduler();
+19
View File
@@ -0,0 +1,19 @@
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
import { DeleteCronRequest, DeleteCronResponse } from '../protos/cron';
import { scheduleStacks } from './data';
const delCron = (
call: ServerUnaryCall<DeleteCronRequest, DeleteCronResponse>,
callback: sendUnaryData<DeleteCronResponse>,
) => {
for (const id of call.request.ids) {
if (scheduleStacks.has(id)) {
scheduleStacks.get(id)?.cancel();
scheduleStacks.delete(id);
}
}
callback(null, null);
};
export { delCron };
+33
View File
@@ -0,0 +1,33 @@
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
import { HealthCheckRequest, HealthCheckResponse } from '../protos/health';
import { exec } from 'child_process';
import config from '../config';
import { promiseExec } from '../config/util';
const check = async (
call: ServerUnaryCall<HealthCheckRequest, HealthCheckResponse>,
callback: sendUnaryData<HealthCheckResponse>,
) => {
switch (call.request.service) {
case 'cron':
const res = await promiseExec(
`curl -sf http://localhost:${config.port}/api/system`,
);
if (res.includes('200')) {
return callback(null, { status: 1 });
}
const panelErrLog = await promiseExec(
`tail -n 300 ~/.pm2/logs/panel-error.log`,
);
const scheduleErrLog = await promiseExec(
`tail -n 300 ~/.pm2/logs/schedule-error.log`,
);
return callback(new Error(`${scheduleErrLog}\n${panelErrLog}`));
default:
return callback(null, { status: 1 });
}
};
export { check };
+24
View File
@@ -0,0 +1,24 @@
import { Server, ServerCredentials } from '@grpc/grpc-js';
import { CronService } from '../protos/cron';
import { addCron } from './addCron';
import { delCron } from './delCron';
import { HealthService } from '../protos/health';
import { check } from './health';
import config from '../config';
import Logger from '../loaders/logger';
const server = new Server();
server.addService(HealthService, { check });
server.addService(CronService, { addCron, delCron });
server.bindAsync(
`localhost:${config.cronPort}`,
ServerCredentials.createInsecure(),
(err, port) => {
if (err) {
throw err;
}
server.start();
Logger.debug(`✌️ 定时服务启动成功!`);
process.send?.('ready');
},
);
+75 -13
View File
@@ -12,9 +12,10 @@ import {
killTask, killTask,
} from '../config/util'; } from '../config/util';
import { promises, existsSync } from 'fs'; import { promises, existsSync } from 'fs';
import { Op, where, col as colFn } from 'sequelize'; import { Op, where, col as colFn, FindOptions } from 'sequelize';
import path from 'path'; import path from 'path';
import { TASK_PREFIX, QL_PREFIX } from '../config/const'; import { TASK_PREFIX, QL_PREFIX } from '../config/const';
import cronClient from '../schedule/client';
@Service() @Service()
export default class CronService { export default class CronService {
@@ -32,6 +33,11 @@ export default class CronService {
const tab = new Crontab(payload); const tab = new Crontab(payload);
tab.saved = false; tab.saved = false;
const doc = await this.insert(tab); const doc = await this.insert(tab);
if (this.isSixCron(doc)) {
await cronClient.addCron([
{ id: String(doc.id), schedule: doc.schedule!, command: doc.command },
]);
}
await this.set_crontab(); await this.set_crontab();
return doc; return doc;
} }
@@ -41,8 +47,25 @@ export default class CronService {
} }
public async update(payload: Crontab): Promise<Crontab> { public async update(payload: Crontab): Promise<Crontab> {
payload.saved = false; const doc = await this.getDb({ id: payload.id });
const newDoc = await this.updateDb(payload); const tab = new Crontab({ ...doc, ...payload });
tab.saved = false;
const newDoc = await this.updateDb(tab);
if (doc.isDisabled === 1) {
return newDoc;
}
if (this.isSixCron(doc)) {
await cronClient.delCron([String(newDoc.id)]);
}
if (this.isSixCron(newDoc)) {
await cronClient.addCron([
{
id: String(newDoc.id),
schedule: newDoc.schedule!,
command: newDoc.command,
},
]);
}
await this.set_crontab(); await this.set_crontab();
return newDoc; return newDoc;
} }
@@ -82,6 +105,7 @@ export default class CronService {
public async remove(ids: number[]) { public async remove(ids: number[]) {
await CrontabModel.destroy({ where: { id: ids } }); await CrontabModel.destroy({ where: { id: ids } });
await cronClient.delCron(ids.map(String));
await this.set_crontab(); await this.set_crontab();
} }
@@ -244,8 +268,15 @@ export default class CronService {
const filterKeys: any = Object.keys(filterQuery); const filterKeys: any = Object.keys(filterQuery);
for (const key of filterKeys) { for (const key of filterKeys) {
let q: any = {}; let q: any = {};
if (filterKeys[key]) { if (!filterQuery[key]) continue;
q[key] = filterKeys[key]; if (key === 'status') {
if (filterQuery[key].includes(2)) {
q = { [Op.or]: [{ [key]: filterQuery[key] }, { isDisabled: 1 }] };
} else {
q = { [Op.and]: [{ [key]: filterQuery[key] }, { isDisabled: 0 }] };
}
} else {
q[key] = filterQuery[key];
} }
query[Op.and].push(q); query[Op.and].push(q);
} }
@@ -260,6 +291,19 @@ export default class CronService {
} }
} }
public async find({
log_path,
}: {
log_path: string;
}): Promise<Crontab | null> {
try {
const result = await CrontabModel.findOne({ where: { log_path } });
return result;
} catch (error) {
throw error;
}
}
public async crontabs(params?: { public async crontabs(params?: {
searchValue: string; searchValue: string;
page: string; page: string;
@@ -311,7 +355,7 @@ export default class CronService {
} }
} }
public async getDb(query: any): Promise<Crontab> { public async getDb(query: FindOptions<Crontab>['where']): Promise<Crontab> {
const doc: any = await CrontabModel.findOne({ where: { ...query } }); const doc: any = await CrontabModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Crontab); return doc && (doc.get({ plain: true }) as Crontab);
} }
@@ -409,11 +453,21 @@ export default class CronService {
public async disabled(ids: number[]) { public async disabled(ids: number[]) {
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } }); await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
await cronClient.delCron(ids.map(String));
await this.set_crontab(); await this.set_crontab();
} }
public async enabled(ids: number[]) { public async enabled(ids: number[]) {
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } }); await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
const docs = await CrontabModel.findAll({ where: { id: ids } });
const sixCron = docs
.filter((x) => this.isSixCron(x))
.map((doc) => ({
id: String(doc.id),
schedule: doc.schedule!,
command: doc.command,
}));
await cronClient.addCron(sixCron);
await this.set_crontab(); await this.set_crontab();
} }
@@ -428,7 +482,7 @@ export default class CronService {
if (logFileExist) { if (logFileExist) {
return getFileContentByName(`${absolutePath}`); return getFileContentByName(`${absolutePath}`);
} else { } else {
return '任务未运行或运行失败,请尝试手动运行'; return '任务未运行';
} }
} }
@@ -452,7 +506,6 @@ export default class CronService {
} else { } else {
return []; return [];
} }
} }
private make_command(tab: Crontab) { private make_command(tab: Crontab) {
@@ -466,8 +519,8 @@ export default class CronService {
return crontab_job_string; return crontab_job_string;
} }
private async set_crontab() { private async set_crontab(data?: { data: Crontab[]; total: number }) {
const tabs = await this.crontabs(); const tabs = data ?? (await this.crontabs());
var crontab_string = ''; var crontab_string = '';
tabs.data.forEach((tab) => { tabs.data.forEach((tab) => {
const _schedule = tab.schedule && tab.schedule.split(/ +/); const _schedule = tab.schedule && tab.schedule.split(/ +/);
@@ -489,7 +542,6 @@ export default class CronService {
fs.writeFileSync(config.crontabFile, crontab_string); fs.writeFileSync(config.crontabFile, crontab_string);
execSync(`crontab ${config.crontabFile}`); execSync(`crontab ${config.crontabFile}`);
exec(`pm2 reload schedule`);
await CrontabModel.update({ saved: true }, { where: {} }); await CrontabModel.update({ saved: true }, { where: {} });
} }
@@ -527,7 +579,17 @@ export default class CronService {
}); });
} }
public autosave_crontab() { public async autosave_crontab() {
return this.set_crontab(); const tabs = await this.crontabs();
this.set_crontab(tabs);
const sixCron = tabs.data
.filter((x) => this.isSixCron(x) && x.isDisabled !== 1)
.map((doc) => ({
id: String(doc.id),
schedule: doc.schedule!,
command: doc.command,
}));
await cronClient.addCron(sixCron);
} }
} }
+5 -2
View File
@@ -7,6 +7,7 @@ import {
minPosition, minPosition,
stepPosition, stepPosition,
} from '../data/env'; } from '../data/env';
import { FindOptions } from 'sequelize';
@Service() @Service()
export default class CronViewService { export default class CronViewService {
@@ -31,7 +32,9 @@ export default class CronViewService {
} }
public async update(payload: CrontabView): Promise<CrontabView> { public async update(payload: CrontabView): Promise<CrontabView> {
const newDoc = await this.updateDb(payload); const doc = await this.getDb({ id: payload.id })
const tab = new CrontabView({ ...doc, ...payload });
const newDoc = await this.updateDb(tab);
return newDoc; return newDoc;
} }
@@ -56,7 +59,7 @@ export default class CronViewService {
} }
} }
public async getDb(query: any): Promise<CrontabView> { public async getDb(query: FindOptions<CrontabView>['where']): Promise<CrontabView> {
const doc: any = await CrontabViewModel.findOne({ where: { ...query } }); const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as CrontabView); return doc && (doc.get({ plain: true }) as CrontabView);
} }
+20 -11
View File
@@ -11,7 +11,7 @@ import {
} from '../data/dependence'; } from '../data/dependence';
import { spawn } from 'child_process'; import { spawn } from 'child_process';
import SockService from './sock'; import SockService from './sock';
import { Op } from 'sequelize'; import { FindOptions, Op } from 'sequelize';
import { concurrentRun } from '../config/util'; import { concurrentRun } from '../config/util';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
@@ -24,7 +24,7 @@ export default class DependenceService {
public async create(payloads: Dependence[]): Promise<Dependence[]> { public async create(payloads: Dependence[]): Promise<Dependence[]> {
const tabs = payloads.map((x) => { const tabs = payloads.map((x) => {
const tab = new Dependence({ ...x, status: DependenceStatus.installing }); const tab = new Dependence({ ...x, status: DependenceStatus.queued });
return tab; return tab;
}); });
const docs = await this.insert(tabs); const docs = await this.insert(tabs);
@@ -45,7 +45,7 @@ export default class DependenceService {
const tab = new Dependence({ const tab = new Dependence({
...doc, ...doc,
...other, ...other,
status: DependenceStatus.installing, status: DependenceStatus.queued,
}); });
const newDoc = await this.updateDb(tab); const newDoc = await this.updateDb(tab);
this.installDependenceOneByOne([newDoc]); this.installDependenceOneByOne([newDoc]);
@@ -59,7 +59,7 @@ export default class DependenceService {
public async remove(ids: number[], force = false): Promise<Dependence[]> { public async remove(ids: number[], force = false): Promise<Dependence[]> {
await DependenceModel.update( await DependenceModel.update(
{ status: DependenceStatus.removing, log: [] }, { status: DependenceStatus.queued, log: [] },
{ where: { id: ids } }, { where: { id: ids } },
); );
const docs = await DependenceModel.findAll({ where: { id: ids } }); const docs = await DependenceModel.findAll({ where: { id: ids } });
@@ -99,23 +99,30 @@ export default class DependenceService {
} }
} }
private installDependenceOneByOne( public installDependenceOneByOne(
docs: Dependence[], docs: Dependence[],
isInstall: boolean = true, isInstall: boolean = true,
force: boolean = false, force: boolean = false,
) { ) {
concurrentRun( concurrentRun(
docs.map( docs.map((dep) => async () => {
(dep) => async () => const status = isInstall
await this.installOrUninstallDependencies([dep], isInstall, force), ? DependenceStatus.installing
), : DependenceStatus.removing;
await DependenceModel.update({ status }, { where: { id: dep.id } });
return await this.installOrUninstallDependencies(
[dep],
isInstall,
force,
);
}),
1, 1,
); );
} }
public async reInstall(ids: number[]): Promise<Dependence[]> { public async reInstall(ids: number[]): Promise<Dependence[]> {
await DependenceModel.update( await DependenceModel.update(
{ status: DependenceStatus.installing, log: [] }, { status: DependenceStatus.queued, log: [] },
{ where: { id: ids } }, { where: { id: ids } },
); );
@@ -132,7 +139,9 @@ export default class DependenceService {
return docs; return docs;
} }
public async getDb(query: any): Promise<Dependence> { public async getDb(
query: FindOptions<Dependence>['where'],
): Promise<Dependence> {
const doc: any = await DependenceModel.findOne({ where: { ...query } }); const doc: any = await DependenceModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Dependence); return doc && (doc.get({ plain: true }) as Dependence);
} }
+11 -6
View File
@@ -12,11 +12,11 @@ import {
stepPosition, stepPosition,
} from '../data/env'; } from '../data/env';
import groupBy from 'lodash/groupBy'; import groupBy from 'lodash/groupBy';
import { Op } from 'sequelize'; import { FindOptions, Op } from 'sequelize';
@Service() @Service()
export default class EnvService { export default class EnvService {
constructor(@Inject('logger') private logger: winston.Logger) { } constructor(@Inject('logger') private logger: winston.Logger) {}
public async create(payloads: Env[]): Promise<Env[]> { public async create(payloads: Env[]): Promise<Env[]> {
const envs = await this.envs(); const envs = await this.envs();
@@ -49,7 +49,9 @@ export default class EnvService {
} }
public async update(payload: Env): Promise<Env> { public async update(payload: Env): Promise<Env> {
const newDoc = await this.updateDb(payload); const doc = await this.getDb({ id: payload.id });
const tab = new Env({ ...doc, ...payload });
const newDoc = await this.updateDb(tab);
await this.set_envs(); await this.set_envs();
return newDoc; return newDoc;
} }
@@ -98,7 +100,11 @@ export default class EnvService {
private async checkPosition(position: number, edge: number = 0) { private async checkPosition(position: number, edge: number = 0) {
const precisionPosition = parseFloat(position.toPrecision(16)); const precisionPosition = parseFloat(position.toPrecision(16));
if (precisionPosition < minPosition || precisionPosition > maxPosition || Math.abs(precisionPosition - edge) < minPosition) { if (
precisionPosition < minPosition ||
precisionPosition > maxPosition ||
Math.abs(precisionPosition - edge) < minPosition
) {
const envs = await this.envs(); const envs = await this.envs();
let position = initPosition; let position = initPosition;
for (const env of envs) { for (const env of envs) {
@@ -140,7 +146,6 @@ export default class EnvService {
} }
try { try {
const result = await this.find(condition, [ const result = await this.find(condition, [
['status', 'ASC'],
['position', 'DESC'], ['position', 'DESC'],
['createdAt', 'ASC'], ['createdAt', 'ASC'],
]); ]);
@@ -158,7 +163,7 @@ export default class EnvService {
return docs; return docs;
} }
public async getDb(query: any): Promise<Env> { public async getDb(query: FindOptions<Env>['where']): Promise<Env> {
const doc: any = await EnvModel.findOne({ where: { ...query } }); const doc: any = await EnvModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Env); return doc && (doc.get({ plain: true }) as Env);
} }
+304 -169
View File
@@ -36,7 +36,7 @@ export default class NotificationService {
private content = ''; private content = '';
private params!: Omit<NotificationInfo, 'type'>; private params!: Omit<NotificationInfo, 'type'>;
private gotOption = { private gotOption = {
timeout: 30000, timeout: 10000,
retry: 1, retry: 1,
}; };
@@ -78,33 +78,49 @@ export default class NotificationService {
} }
private async gotify() { private async gotify() {
const { gotifyUrl, gotifyToken, gotifyPriority } = this.params; const { gotifyUrl, gotifyToken, gotifyPriority = 1 } = this.params;
const res: any = await got try {
.post(`${gotifyUrl}/message?token=${gotifyToken}`, { const res: any = await got
...this.gotOption, .post(`${gotifyUrl}/message?token=${gotifyToken}`, {
body: `title=${encodeURIComponent( ...this.gotOption,
this.title, body: `title=${encodeURIComponent(
)}&message=${encodeURIComponent( this.title,
this.content, )}&message=${encodeURIComponent(
)}&priority=${gotifyPriority}`, this.content,
headers: { )}&priority=${gotifyPriority}`,
'Content-Type': 'application/x-www-form-urlencoded', headers: {
}, 'Content-Type': 'application/x-www-form-urlencoded',
}) },
.json(); })
return typeof res.id === 'number'; .json();
if (typeof res.id === 'number') {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async goCqHttpBot() { private async goCqHttpBot() {
const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params; const { goCqHttpBotQq, goCqHttpBotToken, goCqHttpBotUrl } = this.params;
const res: any = await got try {
.post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, { const res: any = await got
...this.gotOption, .post(`${goCqHttpBotUrl}?${goCqHttpBotQq}`, {
json: { message: `${this.title}\n${this.content}` }, ...this.gotOption,
headers: { Authorization: 'Bearer ' + goCqHttpBotToken }, json: { message: `${this.title}\n${this.content}` },
}) headers: { Authorization: 'Bearer ' + goCqHttpBotToken },
.json(); })
return res.retcode === 0; .json();
if (res.retcode === 0) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async serverChan() { private async serverChan() {
@@ -112,63 +128,97 @@ export default class NotificationService {
const url = serverChanKey.startsWith('SCT') const url = serverChanKey.startsWith('SCT')
? `https://sctapi.ftqq.com/${serverChanKey}.send` ? `https://sctapi.ftqq.com/${serverChanKey}.send`
: `https://sc.ftqq.com/${serverChanKey}.send`; : `https://sc.ftqq.com/${serverChanKey}.send`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
body: `title=${this.title}&desp=${this.content}`, ...this.gotOption,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `title=${this.title}&desp=${this.content}`,
}) headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
.json(); })
return res.errno === 0 || res.data.errno === 0; .json();
if (res.errno === 0 || res.data.errno === 0) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async pushDeer() { private async pushDeer() {
const { pushDeerKey, pushDeerUrl } = this.params; const { pushDeerKey, pushDeerUrl } = this.params;
const url = pushDeerUrl || `https://api2.pushdeer.com/message/push`; const url = pushDeerUrl || `https://api2.pushdeer.com/message/push`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
body: `pushkey=${pushDeerKey}&text=${encodeURIComponent( ...this.gotOption,
this.title, body: `pushkey=${pushDeerKey}&text=${encodeURIComponent(
)}&desp=${encodeURIComponent(this.content)}&type=markdown`, this.title,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, )}&desp=${encodeURIComponent(this.content)}&type=markdown`,
}) headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
.json(); })
return ( .json();
res.content.result.length !== undefined && res.content.result.length > 0 if (
); res.content.result.length !== undefined &&
res.content.result.length > 0
) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async chat() { private async chat() {
const { chatUrl, chatToken } = this.params; const { chatUrl, chatToken } = this.params;
const url = `${chatUrl}${chatToken}`; const url = `${chatUrl}${chatToken}`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
body: `payload={"text":"${this.title}\n${this.content}"}`, ...this.gotOption,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `payload={"text":"${this.title}\n${this.content}"}`,
}) headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
.json(); })
return res.success; .json();
if (res.success) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async bark() { private async bark() {
let { barkPush, barkIcon, barkSound, barkGroup } = this.params; let { barkPush, barkIcon, barkSound, barkGroup } = this.params;
if (!barkPush.startsWith('http') && !barkPush.startsWith('https')) { if (!barkPush.startsWith('http')) {
barkPush = `https://api.day.app/${barkPush}`; barkPush = `https://api.day.app/${barkPush}`;
} }
const url = `${barkPush}/${encodeURIComponent( const url = `${barkPush}/${encodeURIComponent(
this.title, this.title,
)}/${encodeURIComponent( )}/${encodeURIComponent(
this.content, this.content,
)}?icon=${barkIcon}?sound=${barkSound}&group=${barkGroup}`; )}?icon=${barkIcon}&sound=${barkSound}&group=${barkGroup}`;
const res: any = await got
.get(url, { try {
...this.gotOption, const res: any = await got
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, .get(url, {
}) ...this.gotOption,
.json(); headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
return res.code === 200; })
.json();
if (res.code === 200) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async telegramBot() { private async telegramBot() {
@@ -200,15 +250,23 @@ export default class NotificationService {
https: httpsAgent, https: httpsAgent,
}; };
} }
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
body: `chat_id=${telegramBotUserId}&text=${this.title}\n\n${this.content}&disable_web_page_preview=true`, ...this.gotOption,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `chat_id=${telegramBotUserId}&text=${this.title}\n\n${this.content}&disable_web_page_preview=true`,
agent, headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}) agent,
.json(); })
return !!res.ok; .json();
if (res.ok) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async dingtalkBot() { private async dingtalkBot() {
@@ -222,35 +280,51 @@ export default class NotificationService {
secretParam = `&timestamp=${dateNow}&sign=${result}`; secretParam = `&timestamp=${dateNow}&sign=${result}`;
} }
const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`; const url = `https://oapi.dingtalk.com/robot/send?access_token=${dingtalkBotToken}${secretParam}`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
json: { ...this.gotOption,
msgtype: 'text', json: {
text: { msgtype: 'text',
content: ` ${this.title}\n\n${this.content}`, text: {
content: ` ${this.title}\n\n${this.content}`,
},
}, },
}, })
}) .json();
.json(); if (res.errcode === 0) {
return res.errcode === 0; return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async weWorkBot() { private async weWorkBot() {
const { weWorkBotKey } = this.params; const { weWorkBotKey } = this.params;
const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${weWorkBotKey}`; const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${weWorkBotKey}`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
json: { ...this.gotOption,
msgtype: 'text', json: {
text: { msgtype: 'text',
content: ` ${this.title}\n\n${this.content}`, text: {
content: ` ${this.title}\n\n${this.content}`,
},
}, },
}, })
}) .json();
.json(); if (res.errcode === 0) {
return res.errcode === 0; return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async weWorkApp() { private async weWorkApp() {
@@ -306,22 +380,30 @@ export default class NotificationService {
break; break;
} }
const res: any = await got try {
.post( const res: any = await got
`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${tokenRes.access_token}`, .post(
{ `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${tokenRes.access_token}`,
...this.gotOption, {
json: { ...this.gotOption,
touser, json: {
agentid, touser,
safe: '0', agentid,
...options, safe: '0',
...options,
},
}, },
}, )
) .json();
.json();
return res.errcode === 0; if (res.errcode === 0) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async aibotk() { private async aibotk() {
@@ -353,85 +435,130 @@ export default class NotificationService {
break; break;
} }
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
json: { ...this.gotOption,
...json, json: {
}, ...json,
}) },
.json(); })
.json();
return res.code === 0; if (res.code === 0) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async iGot() { private async iGot() {
const { iGotPushKey } = this.params; const { iGotPushKey } = this.params;
const url = `https://push.hellyw.com/${iGotPushKey.toLowerCase()}`; const url = `https://push.hellyw.com/${iGotPushKey.toLowerCase()}`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
body: `title=${this.title}&content=${this.content}`, ...this.gotOption,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `title=${this.title}&content=${this.content}`,
}) headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
.json(); })
.json();
return res.ret === 0; if (res.ret === 0) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async pushPlus() { private async pushPlus() {
const { pushPlusToken, pushPlusUser } = this.params; const { pushPlusToken, pushPlusUser } = this.params;
const url = `https://www.pushplus.plus/send`; const url = `https://www.pushplus.plus/send`;
const res: any = await got try {
.post(url, { const res: any = await got
...this.gotOption, .post(url, {
json: { ...this.gotOption,
token: `${pushPlusToken}`, json: {
title: `${this.title}`, token: `${pushPlusToken}`,
content: `${this.content.replace(/[\n\r]/g, '<br>')}`, title: `${this.title}`,
topic: `${pushPlusUser || ''}`, content: `${this.content.replace(/[\n\r]/g, '<br>')}`,
}, topic: `${pushPlusUser || ''}`,
}) },
.json(); })
.json();
return res.code === 200; if (res.code === 200) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async lark() { private async lark() {
const { larkKey } = this.params; let { larkKey } = this.params;
const res: any = await got
.post(`https://open.feishu.cn/open-apis/bot/v2/hook/${larkKey}`, { if (!larkKey.startsWith('http')) {
...this.gotOption, larkKey = `https://open.feishu.cn/open-apis/bot/v2/hook/${larkKey}`;
json: { }
msg_type: 'text',
content: { text: `${this.title}\n\n${this.content}` }, try {
}, const res: any = await got
headers: { 'Content-Type': 'application/json' }, .post(larkKey, {
}) ...this.gotOption,
.json(); json: {
return res.StatusCode === 0; msg_type: 'text',
content: { text: `${this.title}\n\n${this.content}` },
},
headers: { 'Content-Type': 'application/json' },
})
.json();
if (res.StatusCode === 0) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async email() { private async email() {
const { emailPass, emailService, emailUser } = this.params; const { emailPass, emailService, emailUser } = this.params;
const transporter = nodemailer.createTransport({
service: emailService,
auth: {
user: emailUser,
pass: emailPass,
},
});
const info = await transporter.sendMail({ try {
from: `"青龙快讯" <${emailUser}>`, const transporter = nodemailer.createTransport({
to: `${emailUser}`, service: emailService,
subject: `${this.title}`, auth: {
html: `${this.content.replace(/\n/g, '<br/>')}`, user: emailUser,
}); pass: emailPass,
},
});
transporter.close(); const info = await transporter.sendMail({
from: `"青龙快讯" <${emailUser}>`,
to: `${emailUser}`,
subject: `${this.title}`,
html: `${this.content.replace(/\n/g, '<br/>')}`,
});
return !!info.messageId; transporter.close();
if (info.messageId) {
return true;
} else {
throw new Error(JSON.stringify(info));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private async webhook() { private async webhook() {
@@ -460,8 +587,16 @@ export default class NotificationService {
allowGetBody: true, allowGetBody: true,
...bodyParam, ...bodyParam,
}; };
const res = await got(formatUrl, options); try {
return String(res.statusCode).startsWith('20'); const res = await got(formatUrl, options);
if (String(res.statusCode).startsWith('20')) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
} }
private formatBody(contentType: string, body: any): object { private formatBody(contentType: string, body: any): object {
@@ -484,11 +619,11 @@ export default class NotificationService {
return { return {
formatUrl: url formatUrl: url
.replaceAll('$title', encodeURIComponent(this.title)) ?.replaceAll('$title', encodeURIComponent(this.title))
.replaceAll('$content', encodeURIComponent(this.content)), ?.replaceAll('$content', encodeURIComponent(this.content)),
formatBody: body formatBody: body
.replaceAll('$title', this.title) ?.replaceAll('$title', this.title)
.replaceAll('$content', this.content), ?.replaceAll('$content', this.content),
}; };
} }
} }
+4 -1
View File
@@ -138,7 +138,10 @@ export default class ScheduleService {
async cancelCronTask({ id = 0, name }: ScheduleTaskType) { async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
const _id = this.formatId(id); const _id = this.formatId(id);
this.logger.info('[取消定时任务],任务名:%s', name); this.logger.info('[取消定时任务],任务名:%s', name);
this.scheduleStacks.has(_id) && this.scheduleStacks.get(_id)?.cancel(); if (this.scheduleStacks.has(_id)) {
this.scheduleStacks.get(_id)?.cancel();
this.scheduleStacks.delete(_id);
}
} }
async createIntervalTask( async createIntervalTask(
+44 -46
View File
@@ -5,18 +5,38 @@ import os from 'os';
import path from 'path'; import path from 'path';
import { Subscription } from '../data/subscription'; import { Subscription } from '../data/subscription';
import { formatUrl } from '../config/subscription'; import { formatUrl } from '../config/subscription';
import config from '../config';
@Service() @Service()
export default class SshKeyService { export default class SshKeyService {
private homedir = os.homedir(); private homedir = os.homedir();
private sshPath = path.resolve(this.homedir, '.ssh'); private sshPath = config.sshdPath;
private sshConfigFilePath = path.resolve(this.sshPath, 'config'); private sshConfigFilePath = path.resolve(this.homedir, '.ssh', 'config');
private sshConfigHeader = `Include ${path.join(this.sshPath, '*.config')}`;
constructor(@Inject('logger') private logger: winston.Logger) {} constructor(@Inject('logger') private logger: winston.Logger) {
this.initSshConfigFile();
}
private initSshConfigFile() {
let config = '';
if (existsSync(this.sshConfigFilePath)) {
config = fs.readFileSync(this.sshConfigFilePath, { encoding: 'utf-8' });
} else {
fs.writeFileSync(this.sshConfigFilePath, '');
}
if (!config.includes(this.sshConfigHeader)) {
fs.writeFileSync(
this.sshConfigFilePath,
`${this.sshConfigHeader}\n\n${config}`,
{ encoding: 'utf-8' },
);
}
}
private generatePrivateKeyFile(alias: string, key: string): void { private generatePrivateKeyFile(alias: string, key: string): void {
try { try {
fs.writeFileSync(`${this.sshPath}/${alias}`, `${key}${os.EOL}`, { fs.writeFileSync(path.join(this.sshPath, alias), `${key}${os.EOL}`, {
encoding: 'utf8', encoding: 'utf8',
mode: '400', mode: '400',
}); });
@@ -25,56 +45,39 @@ export default class SshKeyService {
} }
} }
private getConfigRegx(alias: string) {
return new RegExp(
`Host ${alias}\n.*[^StrictHostKeyChecking]*.*[\n]*.*StrictHostKeyChecking no`,
'g',
);
}
private removePrivateKeyFile(alias: string): void { private removePrivateKeyFile(alias: string): void {
try { try {
const filePath = path.join(this.sshPath, alias); const filePath = path.join(this.sshPath, alias);
if (existsSync(filePath)) { if (existsSync(filePath)) {
fs.unlinkSync(`${this.sshPath}/${alias}`); fs.unlinkSync(filePath);
} }
} catch (error) { } catch (error) {
this.logger.error('删除私钥文件失败', error); this.logger.error('删除私钥文件失败', error);
} }
} }
private generateSingleSshConfig( private generateSingleSshConfig(alias: string, host: string, proxy?: string) {
alias: string,
host: string,
proxy?: string,
): string {
if (host === 'github.com') { if (host === 'github.com') {
host = `ssh.github.com\n Port 443\n HostkeyAlgorithms +ssh-rsa\n PubkeyAcceptedAlgorithms +ssh-rsa`; host = `ssh.github.com\n Port 443\n HostkeyAlgorithms +ssh-rsa\n PubkeyAcceptedAlgorithms +ssh-rsa`;
} }
const proxyStr = proxy ? ` ProxyCommand nc -v -x ${proxy} %h %p\n` : ''; const proxyStr = proxy
return `Host ${alias}\n Hostname ${host}\n IdentityFile ${this.sshPath}/${alias}\n StrictHostKeyChecking no\n${proxyStr}`; ? ` ProxyCommand nc -v -x ${proxy} %h %p 2>/dev/null\n`
} : '';
const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${path.join(
private generateSshConfig(configs: string[]) { this.sshPath,
try { alias,
fs.writeFileSync(this.sshConfigFilePath, configs.join('\n'), { )}\n StrictHostKeyChecking no\n${proxyStr}`;
encoding: 'utf8', fs.writeFileSync(`${path.join(this.sshPath, `${alias}.config`)}`, config, {
}); encoding: 'utf8',
} catch (error) { });
this.logger.error('写入ssh配置文件失败', error);
}
} }
private removeSshConfig(alias: string) { private removeSshConfig(alias: string) {
try { try {
const configRegx = this.getConfigRegx(alias); const filePath = path.join(this.sshPath, `${alias}.config`);
const data = fs if (existsSync(filePath)) {
.readFileSync(this.sshConfigFilePath, { encoding: 'utf8' }) fs.unlinkSync(filePath);
.replace(configRegx, '') }
.replace(/\n[\n]+/g, '\n');
fs.writeFileSync(this.sshConfigFilePath, data, {
encoding: 'utf8',
});
} catch (error) { } catch (error) {
this.logger.error(`删除ssh配置文件${alias}失败`, error); this.logger.error(`删除ssh配置文件${alias}失败`, error);
} }
@@ -87,32 +90,27 @@ export default class SshKeyService {
proxy?: string, proxy?: string,
): void { ): void {
this.generatePrivateKeyFile(alias, key); this.generatePrivateKeyFile(alias, key);
const config = this.generateSingleSshConfig(alias, host, proxy); this.generateSingleSshConfig(alias, host, proxy);
this.removeSshConfig(alias);
this.generateSshConfig([config]);
} }
public removeSSHKey(alias: string, host: string, proxy?: string): void { public removeSSHKey(alias: string, host: string, proxy?: string): void {
this.removePrivateKeyFile(alias); this.removePrivateKeyFile(alias);
const config = this.generateSingleSshConfig(alias, host, proxy); this.removeSshConfig(alias);
this.removeSshConfig(config);
} }
public setSshConfig(docs: Subscription[]) { public setSshConfig(docs: Subscription[]) {
let result = [];
for (const doc of docs) { for (const doc of docs) {
if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') { if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
const { alias, proxy } = doc; const { alias, proxy } = doc;
const { host } = formatUrl(doc); const { host } = formatUrl(doc);
this.removePrivateKeyFile(alias); this.removePrivateKeyFile(alias);
this.removeSshConfig(alias);
this.generatePrivateKeyFile( this.generatePrivateKeyFile(
alias, alias,
(doc.pull_option as any).private_key, (doc.pull_option as any).private_key,
); );
const config = this.generateSingleSshConfig(alias, host, proxy); this.generateSingleSshConfig(alias, host, proxy);
result.push(config);
} }
} }
this.generateSshConfig(result);
} }
} }
+14 -22
View File
@@ -19,9 +19,10 @@ import {
fileExist, fileExist,
createFile, createFile,
killTask, killTask,
handleLogPath,
} from '../config/util'; } from '../config/util';
import { promises, existsSync } from 'fs'; import { promises, existsSync } from 'fs';
import { Op } from 'sequelize'; import { FindOptions, Op } from 'sequelize';
import path from 'path'; import path from 'path';
import ScheduleService, { TaskCallbacks } from './schedule'; import ScheduleService, { TaskCallbacks } from './schedule';
import { SimpleIntervalSchedule } from 'toad-scheduler'; import { SimpleIntervalSchedule } from 'toad-scheduler';
@@ -104,7 +105,7 @@ export default class SubscriptionService {
} }
} }
private async setSshConfig() { public async setSshConfig() {
const docs = await SubscriptionModel.findAll(); const docs = await SubscriptionModel.findAll();
this.sshKeyService.setSshConfig(docs); this.sshKeyService.setSshConfig(docs);
} }
@@ -121,18 +122,6 @@ export default class SubscriptionService {
}); });
} }
private async handleLogPath(
logPath: string,
data: string = '',
): Promise<string> {
const absolutePath = path.resolve(config.logPath, logPath);
const logFileExist = await fileExist(absolutePath);
if (!logFileExist) {
await createFile(absolutePath, data);
}
return absolutePath;
}
private taskCallbacks(doc: Subscription): TaskCallbacks { private taskCallbacks(doc: Subscription): TaskCallbacks {
return { return {
onBefore: async (startTime) => { onBefore: async (startTime) => {
@@ -145,7 +134,7 @@ export default class SubscriptionService {
}, },
{ where: { id: doc.id } }, { where: { id: doc.id } },
); );
const absolutePath = await this.handleLogPath( const absolutePath = await handleLogPath(
logPath as string, logPath as string,
`## 开始执行... ${startTime.format('YYYY-MM-DD HH:mm:ss')}\n`, `## 开始执行... ${startTime.format('YYYY-MM-DD HH:mm:ss')}\n`,
); );
@@ -175,7 +164,7 @@ export default class SubscriptionService {
}, },
onEnd: async (cp, endTime, diff) => { onEnd: async (cp, endTime, diff) => {
const sub = await this.getDb({ id: doc.id }); const sub = await this.getDb({ id: doc.id });
const absolutePath = await this.handleLogPath(sub.log_path as string); const absolutePath = await handleLogPath(sub.log_path as string);
// 执行 sub_after // 执行 sub_after
let afterStr = ''; let afterStr = '';
@@ -212,12 +201,12 @@ export default class SubscriptionService {
}, },
onError: async (message: string) => { onError: async (message: string) => {
const sub = await this.getDb({ id: doc.id }); const sub = await this.getDb({ id: doc.id });
const absolutePath = await this.handleLogPath(sub.log_path as string); const absolutePath = await handleLogPath(sub.log_path as string);
fs.appendFileSync(absolutePath, `\n${message}`); fs.appendFileSync(absolutePath, `\n${message}`);
}, },
onLog: async (message: string) => { onLog: async (message: string) => {
const sub = await this.getDb({ id: doc.id }); const sub = await this.getDb({ id: doc.id });
const absolutePath = await this.handleLogPath(sub.log_path as string); const absolutePath = await handleLogPath(sub.log_path as string);
fs.appendFileSync(absolutePath, `\n${message}`); fs.appendFileSync(absolutePath, `\n${message}`);
}, },
}; };
@@ -236,7 +225,8 @@ export default class SubscriptionService {
} }
public async update(payload: Subscription): Promise<Subscription> { public async update(payload: Subscription): Promise<Subscription> {
const tab = new Subscription(payload); const doc = await this.getDb({ id: payload.id });
const tab = new Subscription({ ...doc, ...payload });
const newDoc = await this.updateDb(tab); const newDoc = await this.updateDb(tab);
await this.handleTask(newDoc, !newDoc.is_disabled); await this.handleTask(newDoc, !newDoc.is_disabled);
await this.setSshConfig(); await this.setSshConfig();
@@ -288,7 +278,9 @@ export default class SubscriptionService {
await this.setSshConfig(); await this.setSshConfig();
} }
public async getDb(query: any): Promise<Subscription> { public async getDb(
query: FindOptions<Subscription>['where'],
): Promise<Subscription> {
const doc: any = await SubscriptionModel.findOne({ where: { ...query } }); const doc: any = await SubscriptionModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Subscription); return doc && (doc.get({ plain: true }) as Subscription);
} }
@@ -314,7 +306,7 @@ export default class SubscriptionService {
this.logger.silly(error); this.logger.silly(error);
} }
} }
const absolutePath = await this.handleLogPath(doc.log_path as string); const absolutePath = await handleLogPath(doc.log_path as string);
fs.appendFileSync( fs.appendFileSync(
`${absolutePath}`, `${absolutePath}`,
@@ -368,7 +360,7 @@ export default class SubscriptionService {
return ''; return '';
} }
const absolutePath = await this.handleLogPath(doc.log_path as string); const absolutePath = await handleLogPath(doc.log_path as string);
return getFileContentByName(absolutePath); return getFileContentByName(absolutePath);
} }
+43 -2
View File
@@ -5,11 +5,17 @@ import * as fs from 'fs';
import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth'; import { AuthDataType, AuthInfo, AuthModel, LoginStatus } from '../data/auth';
import { NotificationInfo } from '../data/notify'; import { NotificationInfo } from '../data/notify';
import NotificationService from './notify'; import NotificationService from './notify';
import ScheduleService from './schedule'; import ScheduleService, { TaskCallbacks } from './schedule';
import { spawn } from 'child_process'; import { spawn } from 'child_process';
import SockService from './sock'; import SockService from './sock';
import got from 'got'; import got from 'got';
import { parseContentVersion, parseVersion } from '../config/util'; import {
getPid,
killTask,
parseContentVersion,
parseVersion,
} from '../config/util';
import { TASK_COMMAND } from '../config/const';
@Service() @Service()
export default class SystemService { export default class SystemService {
@@ -170,4 +176,39 @@ export default class SystemService {
return { code: 400, message: '通知发送失败,请检查系统设置/通知配置' }; return { code: 400, message: '通知发送失败,请检查系统设置/通知配置' };
} }
} }
public async run(
{ command, logPath }: { command: string; logPath: string },
callback: TaskCallbacks,
) {
if (!command.startsWith(TASK_COMMAND)) {
command = `${TASK_COMMAND} ${command}`;
}
this.scheduleService.runTask(
`real_log_path=${logPath} real_time=true ${command}`,
callback,
);
}
public async stop({ command, pid }: { command: string; pid: number }) {
if (!pid && !command) {
return { code: 400, message: '参数错误' };
}
if (pid) {
await killTask(pid);
return { code: 200 };
}
if (!command.startsWith(TASK_COMMAND)) {
command = `${TASK_COMMAND} ${command}`;
}
const _pid = await getPid(command);
if (_pid) {
await killTask(_pid);
return { code: 200 };
} else {
return { code: 400, message: '任务未找到' };
}
}
} }
+20 -11
View File
@@ -1,6 +1,11 @@
import { Service, Inject } from 'typedi'; import { Service, Inject } from 'typedi';
import winston from 'winston'; import winston from 'winston';
import { createRandomString, getNetIp, getPlatform } from '../config/util'; import {
createRandomString,
fileExist,
getNetIp,
getPlatform,
} from '../config/util';
import config from '../config'; import config from '../config';
import * as fs from 'fs'; import * as fs from 'fs';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
@@ -205,17 +210,16 @@ export default class UserService {
} }
private initAuthInfo() { private initAuthInfo() {
const newPassword = createRandomString(16, 22);
fs.writeFileSync( fs.writeFileSync(
config.authConfigFile, config.authConfigFile,
JSON.stringify({ JSON.stringify({
username: 'admin', username: 'admin',
password: newPassword, password: 'admin',
}), }),
); );
return { return {
code: 100, code: 100,
message: '已初始化密码,请前往auth.json查看并重新登录', message: '未找到认证文件,重新初始化',
}; };
} }
@@ -240,13 +244,18 @@ export default class UserService {
return { code: 200, data: avatar, message: '更新成功' }; return { code: 200, data: avatar, message: '更新成功' };
} }
public getUserInfo(): Promise<any> { public async getUserInfo(): Promise<any> {
return new Promise((resolve) => { const authFileExist = await fileExist(config.authConfigFile);
fs.readFile(config.authConfigFile, 'utf8', (err, data) => { if (!authFileExist) {
if (err) console.log(err); fs.writeFileSync(
resolve(JSON.parse(data)); config.authConfigFile,
}); JSON.stringify({
}); username: 'admin',
password: 'admin',
}),
);
}
return this.getAuthInfo();
} }
public initTwoFactor() { public initTwoFactor() {
+57 -52
View File
@@ -1,11 +1,11 @@
FROM python:3.10-alpine as builder FROM python:3.10-alpine as builder
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/ COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
RUN set -x \ RUN set -x \
&& apk update \ && apk update \
&& apk add nodejs npm git \ && apk add nodejs npm git \
&& npm i -g pnpm \ && npm i -g pnpm@8.3.1 \
&& cd /tmp/build \ && cd /tmp/build \
&& pnpm install --prod && pnpm --registry https://registry.npmmirror.com install --prod
FROM python:3.10-alpine FROM python:3.10-alpine
@@ -15,59 +15,64 @@ ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
ARG QL_BRANCH=develop ARG QL_BRANCH=develop
ENV PNPM_HOME=/root/.local/share/pnpm \ ENV PNPM_HOME=/root/.local/share/pnpm \
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/share/pnpm:/root/.local/share/pnpm/global/5/node_modules:$PNPM_HOME \ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/share/pnpm:/root/.local/share/pnpm/global/5/node_modules:$PNPM_HOME \
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 \ NODE_PATH=/usr/local/bin:/usr/local/pnpm-global/5/node_modules:/usr/local/lib/node_modules:/root/.local/share/pnpm/global/5/node_modules \
LANG=zh_CN.UTF-8 \ LANG=C.UTF-8 \
SHELL=/bin/bash \ SHELL=/bin/bash \
PS1="\u@\h:\w \$ " \ PS1="\u@\h:\w \$ " \
QL_DIR=/ql \ QL_DIR=/ql \
QL_BRANCH=${QL_BRANCH} QL_BRANCH=${QL_BRANCH}
RUN set -x \ RUN set -x \
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \ && sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
&& apk update -f \ && apk update -f \
&& apk upgrade \ && apk upgrade \
&& apk --no-cache add -f bash \ && apk --no-cache add -f bash \
coreutils \ coreutils \
moreutils \ git \
git \ curl \
curl \ wget \
wget \ tzdata \
tzdata \ perl \
perl \ openssl \
openssl \ nginx \
nginx \ nodejs \
nodejs \ jq \
jq \ openssh \
openssh \ procps \
npm \ netcat-openbsd \
&& rm -rf /var/cache/apk/* \ npm \
&& apk update \ && rm -rf /var/cache/apk/* \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ && apk update \
&& echo "Asia/Shanghai" > /etc/timezone \ && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& git config --global user.email "qinglong@@users.noreply.github.com" \ && echo "Asia/Shanghai" > /etc/timezone \
&& git config --global user.name "qinglong" \ && git config --global user.email "qinglong@@users.noreply.github.com" \
&& git config --global http.postBuffer 524288000 \ && git config --global user.name "qinglong" \
&& npm install -g pnpm \ && git config --global http.postBuffer 524288000 \
&& pnpm add -g pm2 ts-node typescript tslib \ && npm install -g pnpm@8.3.1 \
&& rm -rf /root/.pnpm-store \ && cd && pnpm config set registry https://registry.npmmirror.com \
&& rm -rf /root/.local/share/pnpm/store \ && pnpm add -g pm2 tsx \
&& rm -rf /root/.cache \ && rm -rf /root/.pnpm-store \
&& rm -rf /root/.npm && rm -rf /root/.local/share/pnpm/store \
&& rm -rf /root/.cache \
&& rm -rf /root/.npm
ARG SOURCE_COMMIT ARG SOURCE_COMMIT
RUN git clone -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
&& cd ${QL_DIR} \ && cd ${QL_DIR} \
&& cp -f .env.example .env \ && cp -f .env.example .env \
&& chmod 777 ${QL_DIR}/shell/*.sh \ && chmod 777 ${QL_DIR}/shell/*.sh \
&& chmod 777 ${QL_DIR}/docker/*.sh \ && chmod 777 ${QL_DIR}/docker/*.sh \
&& git clone -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \ && git clone --depth=1 -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /static \
&& mkdir -p ${QL_DIR}/static \ && mkdir -p ${QL_DIR}/static \
&& cp -rf /static/* ${QL_DIR}/static \ && cp -rf /static/* ${QL_DIR}/static \
&& rm -rf /static && rm -rf /static
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
WORKDIR ${QL_DIR} WORKDIR ${QL_DIR}
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
CMD curl -sf http://127.0.0.1:5400/api/health || exit 1
ENTRYPOINT ["./docker/docker-entrypoint.sh"] ENTRYPOINT ["./docker/docker-entrypoint.sh"]
+6
View File
@@ -1,9 +1,15 @@
version: '2' version: '2'
services: services:
web: web:
# alpine 基础镜像版本
image: whyour/qinglong:latest image: whyour/qinglong:latest
# debian-slim 基础镜像版本
# image: whyour/qinglong:debian
volumes: volumes:
- ./data:/ql/data - ./data:/ql/data
ports: ports:
- "0.0.0.0:5700:5700" - "0.0.0.0:5700:5700"
environment:
# 部署路径非必须,以斜杠开头和结尾,比如 /test/
QlBaseUrl: '/'
restart: unless-stopped restart: unless-stopped
+19 -25
View File
@@ -9,15 +9,22 @@ export isFirstStartServer=true
echo -e "======================1. 检测配置文件========================\n" echo -e "======================1. 检测配置文件========================\n"
make_dir /etc/nginx/conf.d make_dir /etc/nginx/conf.d
make_dir /run/nginx make_dir /run/nginx
cp -fv $nginx_conf /etc/nginx/nginx.conf init_nginx
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf fix_config
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
pm2 l &>/dev/null pm2 l &>/dev/null
patch_version &>/dev/null
echo
echo -e "======================2. 安装依赖========================\n" echo -e "======================2. 安装依赖========================\n"
patch_version
if [[ $PipMirror ]]; then
pip3 config set global.index-url $PipMirror
fi
current_npm_registry=$(cd && pnpm config get registry)
is_equal_registry=$(echo $current_npm_registry | grep "${NpmMirror}")
if [[ "$is_equal_registry" == "" ]]; then
cd && pnpm config set registry $NpmMirror
pnpm install -g
fi
update_depend update_depend
echo echo
@@ -25,36 +32,23 @@ echo -e "======================3. 启动nginx========================\n"
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
echo -e "nginx启动成功...\n" echo -e "nginx启动成功...\n"
echo -e "======================4. 启动面板监控========================\n" echo -e "======================4. 启动pm2服务========================\n"
pm2 delete public &>/dev/null reload_pm2
pm2 start $dir_static/build/public.js -n public --source-map-support --time
echo -e "监控服务启动成功...\n"
echo -e "======================5. 启动控制面板========================\n"
pm2 delete panel &>/dev/null
pm2 start $dir_static/build/app.js -n panel --source-map-support --time
echo -e "控制面板启动成功...\n"
echo -e "======================6. 启动定时任务========================\n"
pm2 delete schedule &>/dev/null
pm2 start $dir_static/build/schedule.js -n schedule --source-map-support --time
echo -e "定时任务启动成功...\n"
if [[ $AutoStartBot == true ]]; then if [[ $AutoStartBot == true ]]; then
echo -e "======================7. 启动bot========================\n" echo -e "======================5. 启动bot========================\n"
nohup ql bot >$dir_log/bot.log 2>&1 & nohup ql -l bot >$dir_log/bot.log 2>&1 &
echo -e "bot后台启动中...\n" echo -e "bot后台启动中...\n"
fi fi
if [[ $EnableExtraShell == true ]]; then if [[ $EnableExtraShell == true ]]; then
echo -e "======================8. 执行自定义脚本========================\n" echo -e "====================6. 执行自定义脚本========================\n"
nohup ql extra >$dir_log/extra.log 2>&1 & nohup ql -l extra >$dir_log/extra.log 2>&1 &
echo -e "自定义脚本后台执行中...\n" echo -e "自定义脚本后台执行中...\n"
fi fi
echo -e "############################################################\n" echo -e "############################################################\n"
echo -e "容器启动成功..." echo -e "容器启动成功..."
echo -e "\n请先访问5700端口,登录成功面板之后再执行添加定时任务..."
echo -e "############################################################\n" echo -e "############################################################\n"
crond -f >/dev/null crond -f >/dev/null
+12 -7
View File
@@ -13,31 +13,34 @@ map $http_upgrade $connection_upgrade {
server { server {
listen 5700; listen 5700;
root /ql/static/dist; IPV6_CONFIG
ssl_session_timeout 5m; ssl_session_timeout 5m;
location QL_BASE_URL/api/public/ { location QL_BASE_URLapi/public/ {
proxy_set_header Host $http_host; proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://publicApi/api/public/; proxy_pass http://publicApi/api/;
proxy_buffering off;
} }
location QL_BASE_URL/api/ { location QL_BASE_URLapi/ {
proxy_set_header Host $http_host; proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://baseApi/api/; proxy_pass http://baseApi/api/;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade; proxy_set_header Connection $connection_upgrade;
} }
location QL_BASE_URL/open/ { location QL_BASE_URLopen/ {
proxy_set_header Host $http_host; proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://baseApi/open/; proxy_pass http://baseApi/open/;
proxy_buffering off;
} }
gzip on; gzip on;
@@ -48,10 +51,12 @@ server {
gzip_comp_level 6; gzip_comp_level 6;
gzip_buffers 16 8k; gzip_buffers 16 8k;
gzip_http_version 1.0; gzip_http_version 1.0;
QL_ROOT_CONFIG
location QL_BASE_URL/ { location QL_BASE_URL_LOCATION {
QL_ALIAS_CONFIG
index index.html index.htm; index index.html index.htm;
try_files $uri $uri/ QL_BASE_URL/index.html; try_files $uri QL_BASE_URLindex.html;
} }
location ~ .*\.(html)$ { location ~ .*\.(html)$ {
+34
View File
@@ -0,0 +1,34 @@
module.exports = {
apps: [
{
name: 'schedule',
max_restarts: 10,
kill_timeout: 15000,
wait_ready: true,
listen_timeout: 10000,
source_map_support: true,
time: true,
script: 'static/build/schedule/index.js',
},
{
name: 'public',
max_restarts: 10,
kill_timeout: 15000,
wait_ready: true,
listen_timeout: 10000,
source_map_support: true,
time: true,
script: 'static/build/public.js',
},
{
name: 'panel',
max_restarts: 10,
kill_timeout: 15000,
wait_ready: true,
listen_timeout: 10000,
source_map_support: true,
time: true,
script: 'static/build/app.js',
},
],
};
+13 -6
View File
@@ -5,11 +5,13 @@
"start:front": "max dev", "start:front": "max dev",
"start:back": "nodemon", "start:back": "nodemon",
"start:public": "ts-node --transpile-only ./back/public.ts", "start:public": "ts-node --transpile-only ./back/public.ts",
"start:rpc": "ts-node --transpile-only ./back/schedule/index.ts",
"build:front": "max build", "build:front": "max build",
"build:back": "tsc -p tsconfig.back.json", "build:back": "tsc -p tsconfig.back.json",
"panel": "npm run build:back && node static/build/app.js", "panel": "npm run build:back && node static/build/app.js",
"schedule": "npm run build:back && node static/build/schedule.js", "schedule": "npm run build:back && node static/build/schedule/index.js",
"public": "npm run build:back && node static/build/public.js", "public": "npm run build:back && node static/build/public.js",
"gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true",
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'", "prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
"postinstall": "max setup 2>/dev/null || true", "postinstall": "max setup 2>/dev/null || true",
"test": "umi-test", "test": "umi-test",
@@ -53,6 +55,7 @@
} }
}, },
"dependencies": { "dependencies": {
"@grpc/grpc-js": "^1.8.13",
"@otplib/preset-default": "^12.0.1", "@otplib/preset-default": "^12.0.1",
"@sentry/node": "^7.12.1", "@sentry/node": "^7.12.1",
"@sentry/tracing": "^7.12.1", "@sentry/tracing": "^7.12.1",
@@ -69,6 +72,7 @@
"form-data": "^4.0.0", "form-data": "^4.0.0",
"got": "^11.8.2", "got": "^11.8.2",
"hpagent": "^0.1.2", "hpagent": "^0.1.2",
"http-proxy-middleware": "^2.0.6",
"iconv-lite": "^0.6.3", "iconv-lite": "^0.6.3",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
@@ -77,12 +81,13 @@
"nedb": "^1.8.0", "nedb": "^1.8.0",
"node-schedule": "^2.1.0", "node-schedule": "^2.1.0",
"nodemailer": "^6.7.2", "nodemailer": "^6.7.2",
"protobufjs": "^7.2.3",
"pstree.remy": "^1.1.8", "pstree.remy": "^1.1.8",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",
"sequelize": "^6.25.5", "sequelize": "^6.25.5",
"serve-handler": "^6.1.3", "serve-handler": "^6.1.3",
"sockjs": "^0.3.24", "sockjs": "^0.3.24",
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.2", "sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
"toad-scheduler": "^1.6.0", "toad-scheduler": "^1.6.0",
"typedi": "^0.10.0", "typedi": "^0.10.0",
"uuid": "^8.3.2", "uuid": "^8.3.2",
@@ -92,7 +97,7 @@
"devDependencies": { "devDependencies": {
"@ant-design/icons": "^4.7.0", "@ant-design/icons": "^4.7.0",
"@ant-design/pro-layout": "6.38.22", "@ant-design/pro-layout": "6.38.22",
"@monaco-editor/react": "4.4.6", "@monaco-editor/react": "4.2.1",
"@react-hook/resize-observer": "^1.2.6", "@react-hook/resize-observer": "^1.2.6",
"@sentry/react": "^7.12.1", "@sentry/react": "^7.12.1",
"@types/body-parser": "^1.19.2", "@types/body-parser": "^1.19.2",
@@ -115,10 +120,10 @@
"@types/sockjs": "^0.3.33", "@types/sockjs": "^0.3.33",
"@types/sockjs-client": "^1.5.1", "@types/sockjs-client": "^1.5.1",
"@types/uuid": "^8.3.4", "@types/uuid": "^8.3.4",
"@umijs/max": "^4.0.42", "@umijs/max": "^4.0.55",
"@umijs/ssr-darkreader": "^4.9.45", "@umijs/ssr-darkreader": "^4.9.45",
"ansi-to-react": "^6.1.6", "ansi-to-react": "^6.1.6",
"antd": "^4.24.7", "antd": "^4.24.8",
"antd-img-crop": "^4.2.3", "antd-img-crop": "^4.2.3",
"codemirror": "^5.65.2", "codemirror": "^5.65.2",
"compression-webpack-plugin": "9.2.0", "compression-webpack-plugin": "9.2.0",
@@ -141,11 +146,13 @@
"react-split-pane": "^0.1.92", "react-split-pane": "^0.1.92",
"sockjs-client": "^1.6.0", "sockjs-client": "^1.6.0",
"ts-node": "^10.6.0", "ts-node": "^10.6.0",
"ts-proto": "^1.146.0",
"tslib": "^2.4.0", "tslib": "^2.4.0",
"tsx": "^3.12.3",
"typescript": "4.8.4", "typescript": "4.8.4",
"umi-request": "^1.4.0", "umi-request": "^1.4.0",
"vh-check": "^2.0.5", "vh-check": "^2.0.5",
"virtuallist-antd": "^0.7.6", "virtualizedtableforantd4": "1.3.0",
"webpack": "^5.70.0", "webpack": "^5.70.0",
"yorkie": "^2.0.0" "yorkie": "^2.0.0"
} }
+5433 -5169
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.8 KiB

+2 -11
View File
@@ -1,9 +1,3 @@
## Version: v2.8.0
## Date: 2021-06-20
## Update Content: 可持续发展纲要\n1. session管理破坏性修改\n2. 配置管理可编辑config下文件\n3. 自定义脚本改为查看脚本\n4. 移除互助相关
## 上面版本号中,如果第2位数字有变化,那么代表增加了新的参数,如果只有第3位数字有变化,仅代表更新了注释,没有增加新的参数,可更新可不更新
## 在运行 ql repo 命令时,是否自动删除失效的脚本与定时任务 ## 在运行 ql repo 命令时,是否自动删除失效的脚本与定时任务
AutoDelCron="true" AutoDelCron="true"
@@ -24,11 +18,8 @@ CpuWarn=80
MemoryWarn=80 MemoryWarn=80
DiskWarn=90 DiskWarn=90
## 设置定时任务执行的超时时间,默认1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天 ## 设置定时任务执行的超时时间,例如1h,后缀"s"代表秒(默认值), "m"代表分, "h"代表小时, "d"代表天
CommandTimeoutTime="1h" CommandTimeoutTime=""
## 设置批量执行任务时的并发数,默认同时执行5个任务
MaxConcurrentNum="5"
## 在运行 task 命令时,随机延迟启动任务的最大延迟时间 ## 在运行 task 命令时,随机延迟启动任务的最大延迟时间
## 默认给javascript任务加随机延迟,如 RandomDelay="300" ,表示任务将在 1-300 秒内随机延迟一个秒数,然后再运行,取消延迟赋值为空 ## 默认给javascript任务加随机延迟,如 RandomDelay="300" ,表示任务将在 1-300 秒内随机延迟一个秒数,然后再运行,取消延迟赋值为空
+11 -1
View File
@@ -296,6 +296,16 @@ async function sendNotify(
) { ) {
//提供6种通知 //提供6种通知
desp += author; //增加作者信息,防止被贩卖等 desp += author; //增加作者信息,防止被贩卖等
// 根据标题跳过一些消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔
let skipTitle = process.env.SKIP_PUSH_TITLE
if(skipTitle) {
if(skipTitle.split('\n').includes(text)) {
console.info(text + "在SKIP_PUSH_TITLE环境变量内,跳过推送!");
return
}
}
await Promise.all([ await Promise.all([
serverNotify(text, desp), //微信server酱 serverNotify(text, desp), //微信server酱
pushPlusNotify(text, desp), //pushplus(推送加) pushPlusNotify(text, desp), //pushplus(推送加)
@@ -523,7 +533,7 @@ function BarkNotify(text, desp, params = {}) {
const options = { const options = {
url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent( url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent(
desp, desp,
)}?icon=${BARK_ICON}?sound=${BARK_SOUND}&group=${BARK_GROUP}&${querystring.stringify( )}?icon=${BARK_ICON}&sound=${BARK_SOUND}&group=${BARK_GROUP}&${querystring.stringify(
params, params,
)}`, )}`,
headers: { headers: {
+35 -18
View File
@@ -164,7 +164,8 @@ def dingding_bot(title: str, content: str) -> None:
timestamp = str(round(time.time() * 1000)) timestamp = str(round(time.time() * 1000))
secret_enc = push_config.get("DD_BOT_SECRET").encode("utf-8") secret_enc = push_config.get("DD_BOT_SECRET").encode("utf-8")
string_to_sign = "{}\n{}".format(timestamp, push_config.get("DD_BOT_SECRET")) string_to_sign = "{}\n{}".format(
timestamp, push_config.get("DD_BOT_SECRET"))
string_to_sign_enc = string_to_sign.encode("utf-8") string_to_sign_enc = string_to_sign.encode("utf-8")
hmac_code = hmac.new( hmac_code = hmac.new(
secret_enc, string_to_sign_enc, digestmod=hashlib.sha256 secret_enc, string_to_sign_enc, digestmod=hashlib.sha256
@@ -220,7 +221,7 @@ def go_cqhttp(title: str, content: str) -> None:
print("go-cqhttp 推送失败!") print("go-cqhttp 推送失败!")
def gotify(title:str,content:str) -> None: def gotify(title: str, content: str) -> None:
""" """
使用 gotify 推送消息。 使用 gotify 推送消息。
""" """
@@ -230,8 +231,9 @@ def gotify(title:str,content:str) -> None:
print("gotify 服务启动") print("gotify 服务启动")
url = f'{push_config.get("GOTIFY_URL")}/message?token={push_config.get("GOTIFY_TOKEN")}' url = f'{push_config.get("GOTIFY_URL")}/message?token={push_config.get("GOTIFY_TOKEN")}'
data = {"title": title,"message": content,"priority": push_config.get("GOTIFY_PRIORITY")} data = {"title": title, "message": content,
response = requests.post(url,data=data).json() "priority": push_config.get("GOTIFY_PRIORITY")}
response = requests.post(url, data=data).json()
if response.get("id"): if response.get("id"):
print("gotify 推送成功!") print("gotify 推送成功!")
@@ -269,10 +271,10 @@ def serverJ(title: str, content: str) -> None:
print("serverJ 服务启动") print("serverJ 服务启动")
data = {"text": title, "desp": content.replace("\n", "\n\n")} data = {"text": title, "desp": content.replace("\n", "\n\n")}
if push_config.get("PUSH_KEY").index("SCT") != -1: if push_config.get("PUSH_KEY").find("SCT") != -1:
url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send' url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send'
else: else:
url = f'https://sc.ftqq.com/${push_config.get("PUSH_KEY")}.send' url = f'https://sc.ftqq.com/{push_config.get("PUSH_KEY")}.send'
response = requests.post(url, data=data).json() response = requests.post(url, data=data).json()
if response.get("errno") == 0 or response.get("code") == 0: if response.get("errno") == 0 or response.get("code") == 0:
@@ -289,7 +291,8 @@ def pushdeer(title: str, content: str) -> None:
print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送") print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送")
return return
print("PushDeer 服务启动") print("PushDeer 服务启动")
data = {"text": title, "desp": content, "type": "markdown", "pushkey": push_config.get("DEER_KEY")} data = {"text": title, "desp": content, "type": "markdown",
"pushkey": push_config.get("DEER_KEY")}
url = 'https://api2.pushdeer.com/message/push' url = 'https://api2.pushdeer.com/message/push'
if push_config.get("DEER_URL"): if push_config.get("DEER_URL"):
url = push_config.get("DEER_URL") url = push_config.get("DEER_URL")
@@ -320,7 +323,6 @@ def chat(title: str, content: str) -> None:
print("Chat 推送失败!错误信息:", response) print("Chat 推送失败!错误信息:", response)
def pushplus_bot(title: str, content: str) -> None: def pushplus_bot(title: str, content: str) -> None:
""" """
通过 push+ 推送消息。 通过 push+ 推送消息。
@@ -348,7 +350,8 @@ def pushplus_bot(title: str, content: str) -> None:
url_old = "http://pushplus.hxtrip.com/send" url_old = "http://pushplus.hxtrip.com/send"
headers["Accept"] = "application/json" headers["Accept"] = "application/json"
response = requests.post(url=url_old, data=body, headers=headers).json() response = requests.post(
url=url_old, data=body, headers=headers).json()
if response["code"] == 200: if response["code"] == 200:
print("PUSHPLUS(hxtrip) 推送成功!") print("PUSHPLUS(hxtrip) 推送成功!")
@@ -367,7 +370,8 @@ def qmsg_bot(title: str, content: str) -> None:
print("qmsg 服务启动") print("qmsg 服务启动")
url = f'https://qmsg.zendee.cn/{push_config.get("QMSG_TYPE")}/{push_config.get("QMSG_KEY")}' url = f'https://qmsg.zendee.cn/{push_config.get("QMSG_TYPE")}/{push_config.get("QMSG_KEY")}'
payload = {"msg": f'{title}\n\n{content.replace("----", "-")}'.encode("utf-8")} payload = {
"msg": f'{title}\n\n{content.replace("----", "-")}'.encode("utf-8")}
response = requests.post(url=url, params=payload).json() response = requests.post(url=url, params=payload).json()
if response["code"] == 0: if response["code"] == 0:
@@ -553,14 +557,14 @@ def aibotk(title: str, content: str) -> None:
data = { data = {
"apiKey": push_config.get("AIBOTK_KEY"), "apiKey": push_config.get("AIBOTK_KEY"),
"roomName": push_config.get("AIBOTK_NAME"), "roomName": push_config.get("AIBOTK_NAME"),
"message": {"type": 1, "content": f'【青龙快讯】\n\n${title}\n${content}' } "message": {"type": 1, "content": f'【青龙快讯】\n\n{title}\n{content}'}
} }
else: else:
url = "https://api-bot.aibotk.com/openapi/v1/chat/contact" url = "https://api-bot.aibotk.com/openapi/v1/chat/contact"
data = { data = {
"apiKey": push_config.get("AIBOTK_KEY"), "apiKey": push_config.get("AIBOTK_KEY"),
"name": push_config.get("AIBOTK_NAME"), "name": push_config.get("AIBOTK_NAME"),
"message": {"type": 1, "content": f'【青龙快讯】\n\n${title}\n${content}' } "message": {"type": 1, "content": f'【青龙快讯】\n\n{title}\n{content}'}
} }
body = json.dumps(data).encode(encoding="utf-8") body = json.dumps(data).encode(encoding="utf-8")
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
@@ -582,14 +586,19 @@ def smtp(title: str, content: str) -> None:
print("SMTP 邮件 服务启动") print("SMTP 邮件 服务启动")
message = MIMEText(content, 'plain', 'utf-8') message = MIMEText(content, 'plain', 'utf-8')
message['From'] = formataddr((Header(push_config.get("SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL"))) message['From'] = formataddr((Header(push_config.get(
message['To'] = formataddr((Header(push_config.get("SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL"))) "SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL")))
message['To'] = formataddr((Header(push_config.get(
"SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL")))
message['Subject'] = Header(title, 'utf-8') message['Subject'] = Header(title, 'utf-8')
try: try:
smtp_server = smtplib.SMTP_SSL(push_config.get("SMTP_SERVER")) if push_config.get("SMTP_SSL") == 'true' else smtplib.SMTP(push_config.get("SMTP_SERVER")) smtp_server = smtplib.SMTP_SSL(push_config.get("SMTP_SERVER")) if push_config.get(
smtp_server.login(push_config.get("SMTP_EMAIL"), push_config.get("SMTP_PASSWORD")) "SMTP_SSL") == 'true' else smtplib.SMTP(push_config.get("SMTP_SERVER"))
smtp_server.sendmail(push_config.get("SMTP_EMAIL"), push_config.get("SMTP_EMAIL"), message.as_bytes()) smtp_server.login(push_config.get("SMTP_EMAIL"),
push_config.get("SMTP_PASSWORD"))
smtp_server.sendmail(push_config.get("SMTP_EMAIL"),
push_config.get("SMTP_EMAIL"), message.as_bytes())
smtp_server.close() smtp_server.close()
print("SMTP 邮件 推送成功!") print("SMTP 邮件 推送成功!")
except Exception as e: except Exception as e:
@@ -647,13 +656,21 @@ def send(title: str, content: str) -> None:
print(f"{title} 推送内容为空!") print(f"{title} 推送内容为空!")
return return
# 根据标题跳过一些消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔
skipTitle = os.getenv("SKIP_PUSH_TITLE")
if skipTitle:
if (title in re.split("\n", skipTitle)):
print(f"{title} 在SKIP_PUSH_TITLE环境变量内,跳过推送!")
return
hitokoto = push_config.get("HITOKOTO") hitokoto = push_config.get("HITOKOTO")
text = one() if hitokoto else "" text = one() if hitokoto else ""
content += "\n\n" + text content += "\n\n" + text
ts = [ ts = [
threading.Thread(target=mode, args=(title, content), name=mode.__name__) threading.Thread(target=mode, args=(
title, content), name=mode.__name__)
for mode in notify_function for mode in notify_function
] ]
[t.start() for t in ts] [t.start() for t in ts]
-5
View File
@@ -3,13 +3,8 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"crypto-js": "^4.0.0",
"download": "^8.0.0",
"got": "^11.5.1", "got": "^11.5.1",
"http-server": "^0.12.3",
"nodemailer": "^6.8.0", "nodemailer": "^6.8.0",
"qrcode-terminal": "^0.12.0",
"request": "^2.88.2",
"tough-cookie": "^4.0.0", "tough-cookie": "^4.0.0",
"tunnel": "0.0.6", "tunnel": "0.0.6",
"ws": "^7.4.3" "ws": "^7.4.3"
+39 -7
View File
@@ -1,15 +1,24 @@
#!/usr/bin/env bash #!/usr/bin/env bash
create_token() {
local token_command="tsx ${dir_root}/back/token.ts"
local token_file="${dir_root}/static/build/token.js"
if [[ -f $token_file ]]; then
token_command="node ${token_file}"
fi
token=$(eval "$token_command")
}
get_token() { get_token() {
if [[ -f $file_auth_token ]]; then if [[ -f $file_auth_token ]]; then
token=$(cat $file_auth_token | jq -r .value) token=$(cat $file_auth_token | jq -r .value)
else local expiration=$(cat $file_auth_token | jq -r .expiration)
local token_command="ts-node-transpile-only ${dir_root}/back/token.ts" local currentTimeStamp=$(date +%s)
local token_file="${dir_root}static/build/token.js" if [[ $currentTimeStamp -ge $expiration ]]; then
if [[ -f $token_file ]]; then create_token
token_command="node ${token_file}"
fi fi
token=$(eval "$token_command") else
create_token
fi fi
} }
@@ -169,7 +178,7 @@ update_cron() {
code=$(echo "$api" | jq -r .code) code=$(echo "$api" | jq -r .code)
message=$(echo "$api" | jq -r .message) message=$(echo "$api" | jq -r .message)
if [[ $code != 200 ]]; then if [[ $code != 200 ]]; then
echo -e "\n## 更新任务状态失败(${message})\n" >>$dir_log/$log_path echo -e "\n## 更新任务状态失败(${message})\n"
fi fi
} }
@@ -199,4 +208,27 @@ notify_api() {
fi fi
} }
find_cron_api() {
local params=$1
local currentTimeStamp=$(date +%s)
local api=$(
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/detail?$params&t=$currentTimeStamp" \
-H "Accept: application/json" \
-H "Authorization: Bearer $token" \
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
-H "Content-Type: application/json;charset=UTF-8" \
-H "Origin: http://0.0.0.0:5700" \
-H "Referer: http://0.0.0.0:5700/crontab" \
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
--compressed
)
data=$(echo "$api" | jq -r .data)
if [[ $data == 'null' ]]; then
echo -e ""
else
name=$(echo "$api" | jq -r .data.name)
echo -e "$name"
fi
}
get_token get_token
Regular → Executable
+1 -5
View File
@@ -1,9 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
## 导入通用变量与函数
dir_shell=$QL_DIR/shell
. $dir_shell/share.sh
if [[ -z ${BotRepoUrl} ]]; then if [[ -z ${BotRepoUrl} ]]; then
url="https://github.com/SuMaiKaDe/bot.git" url="https://github.com/SuMaiKaDe/bot.git"
repo_path="${dir_repo}/dockerbot" repo_path="${dir_repo}/dockerbot"
@@ -46,6 +42,6 @@ echo -e "\npython3依赖安装成功...\n"
echo -e "4、启动bot程序...\n" echo -e "4、启动bot程序...\n"
make_dir $dir_log/bot make_dir $dir_log/bot
cd $dir_data cd $dir_data
ps -ef | grep "python3 -m jbot" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null ps -eo pid,command | grep "python3 -m jbot" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
nohup python3 -m jbot >$dir_log/bot/nohup.log 2>&1 & nohup python3 -m jbot >$dir_log/bot/nohup.log 2>&1 &
echo -e "bot启动成功...\n" echo -e "bot启动成功...\n"
Regular → Executable
+19 -26
View File
@@ -1,9 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
dir_shell=$QL_DIR/shell
. $dir_shell/share.sh
. $dir_shell/api.sh
reset_env() { reset_env() {
echo -e "---> 1. 开始检测配置文件\n" echo -e "---> 1. 开始检测配置文件\n"
fix_config fix_config
@@ -29,9 +25,7 @@ copy_dep() {
echo -e "---> 通知文件复制完成\n" echo -e "---> 通知文件复制完成\n"
echo -e "---> 2. 复制nginx配置文件\n" echo -e "---> 2. 复制nginx配置文件\n"
cp -fv $nginx_conf /etc/nginx/nginx.conf init_nginx
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
sed -i "s,QL_BASE_URL,${qlBaseUrl},g" /etc/nginx/conf.d/front.conf
echo -e "---> 配置文件复制完成\n" echo -e "---> 配置文件复制完成\n"
} }
@@ -39,12 +33,12 @@ pm2_log() {
echo -e "---> pm2日志" echo -e "---> pm2日志"
local panelOut="/root/.pm2/logs/panel-out.log" local panelOut="/root/.pm2/logs/panel-out.log"
local panelError="/root/.pm2/logs/panel-error.log" local panelError="/root/.pm2/logs/panel-error.log"
tail -n 100 "$panelOut" tail -n 300 "$panelOut"
tail -n 100 "$panelError" tail -n 300 "$panelError"
} }
check_nginx() { check_nginx() {
local nginxPid=$(ps -ef | grep nginx | grep -v grep) local nginxPid=$(ps -eo pid,command | grep nginx | grep -v grep)
echo -e "=====> 检测nginx服务\n$nginxPid" echo -e "=====> 检测nginx服务\n$nginxPid"
if [[ $nginxPid ]]; then if [[ $nginxPid ]]; then
echo -e "\n=====> nginx服务正常\n" echo -e "\n=====> nginx服务正常\n"
@@ -60,9 +54,6 @@ check_ql() {
echo -e "\n=====> 检测面板\n\n$api\n" echo -e "\n=====> 检测面板\n\n$api\n"
if [[ $api =~ "<div id=\"root\"></div>" ]]; then if [[ $api =~ "<div id=\"root\"></div>" ]]; then
echo -e "=====> 面板服务启动正常\n" echo -e "=====> 面板服务启动正常\n"
else
echo -e "=====> 面板服务异常,重置基础环境\n"
reset_env
fi fi
} }
@@ -70,9 +61,8 @@ check_pm2() {
pm2_log pm2_log
local currentTimeStamp=$(date +%s) local currentTimeStamp=$(date +%s)
local api=$( local api=$(
curl -s --noproxy "*" "http://0.0.0.0:5600/api/user?t=$currentTimeStamp" \ curl -s --noproxy "*" "http://0.0.0.0:5600/api/system?t=$currentTimeStamp" \
-H 'Accept: */*' \ -H 'Accept: */*' \
-H "Authorization: Bearer $token" \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \
-H 'Referer: http://0.0.0.0:5700/crontab' \ -H 'Referer: http://0.0.0.0:5700/crontab' \
-H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \ -H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \
@@ -81,23 +71,26 @@ check_pm2() {
echo -e "\n=====> 检测后台\n\n$api\n" echo -e "\n=====> 检测后台\n\n$api\n"
if [[ $api =~ "{\"code\"" ]]; then if [[ $api =~ "{\"code\"" ]]; then
echo -e "=====> 后台服务启动正常\n" echo -e "=====> 后台服务启动正常\n"
else
echo -e "=====> 后台服务异常,重置基础环境并重启后台\n"
reset_env
fi fi
} }
start_public() {
echo -e "=====> 启动公开服务\n"
pm2 delete public --source-map-support --time &>/dev/null
pm2 start $dir_static/build/public.js -n public --source-map-support --time &>/dev/null
}
main() { main() {
echo -e "=====> 开始检测" echo -e "=====> 开始检测"
npm i -g pnpm npm i -g pnpm@8.3.1
patch_version patch_version
start_public
apk add procps netcat-openbsd
if [[ $PipMirror ]]; then
pip3 config set global.index-url $PipMirror
fi
if [[ $NpmMirror ]]; then
cd && pnpm config set registry $NpmMirror
pnpm install -g
fi
pnpm add -g pm2 tsx
reset_env
copy_dep copy_dep
check_ql check_ql
check_nginx check_nginx
Regular → Executable
+3 -46
View File
@@ -1,16 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
## 导入通用变量与函数
dir_shell=$QL_DIR/shell
. $dir_shell/share.sh
. $dir_shell/api.sh
trap "single_hanle" 2 20 15 14
single_hanle() {
handle_task_after "$@"
exit 1
}
random_delay() { random_delay() {
local random_delay_max=$RandomDelay local random_delay_max=$RandomDelay
if [[ $random_delay_max ]] && [[ $random_delay_max -gt 0 ]]; then if [[ $random_delay_max ]] && [[ $random_delay_max -gt 0 ]]; then
@@ -35,7 +24,7 @@ random_delay() {
done done
local delay_second=$(($(gen_random_num "$random_delay_max") + 1)) local delay_second=$(($(gen_random_num "$random_delay_max") + 1))
echo -e "\n命令未添加 \"now\"随机延迟 $delay_second后执行\n" echo -e "任务随机延迟 $delay_second,配置文件参数 RandomDelay 置空可取消延迟 \n"
sleep $delay_second sleep $delay_second
fi fi
} }
@@ -97,42 +86,10 @@ check_server() {
fi fi
} }
handle_task_before() {
begin_time=$(format_time "$time_format" "$time")
begin_timestamp=$(format_timestamp "$time_format" "$time")
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
echo -e "## 开始执行... $begin_time\n"
[[ $is_macos -eq 0 ]] && check_server
if [[ -s $task_error_log_path ]]; then
eval cat $task_error_log_path $cmd
eval echo -e "加载 config.sh 出错,请手动检查" $cmd
eval echo $cmd
fi
. $file_task_before "$@"
}
handle_task_after() {
. $file_task_after "$@"
local etime=$(date "+$time_format")
local end_time=$(format_time "$time_format" "$etime")
local end_timestamp=$(format_timestamp "$time_format" "$etime")
local diff_time=$(($end_timestamp - $begin_timestamp))
echo -e "\n\n## 执行结束... $end_time 耗时 $diff_time 秒     "
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
}
## 正常运行单个脚本,$1:传入参数 ## 正常运行单个脚本,$1:传入参数
run_normal() { run_normal() {
local file_param=$1 local file_param=$1
if [[ $# -eq 1 ]]; then if [[ $# -eq 1 ]] && [[ "$real_time" != "true" ]]; then
random_delay "$file_param" random_delay "$file_param"
fi fi
@@ -236,7 +193,7 @@ run_else() {
local relative_path="${file_param%/*}" local relative_path="${file_param%/*}"
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
cd ${relative_path} cd ${relative_path}
file_param=${file_param/$relative_path\//} file_param=${file_param/$relative_path\//.\/}
fi fi
shift shift
Regular → Executable
+1 -1
View File
@@ -11,7 +11,7 @@ echo -e "提交master代码"
git push git push
echo -e "更新cdn文件" echo -e "更新cdn文件"
ts-node sample/tool.ts tsx sample/tool.ts
string=$(cat version.yaml | grep "version" | egrep "[^ ]*" -o | egrep "\d\.*") string=$(cat version.yaml | grep "version" | egrep "[^ ]*" -o | egrep "\d\.*")
version="v$string" version="v$string"
+12 -6
View File
@@ -1,12 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
## 导入通用变量与函数
dir_shell=$QL_DIR/shell
. $dir_shell/share.sh
days=$1 days=$1
## 删除运行js脚本的旧日志 ## 删除运行脚本的旧日志
remove_js_log() { remove_js_log() {
local log_full_path_list=$(find $dir_log/ -name "*.log") local log_full_path_list=$(find $dir_log/ -name "*.log")
local diff_time local diff_time
@@ -18,7 +14,17 @@ remove_js_log() {
else else
diff_time=$(($(date +%s) - $(date +%s -d "$log_date"))) diff_time=$(($(date +%s) - $(date +%s -d "$log_date")))
fi fi
[[ $diff_time -gt $((${days} * 86400)) ]] && rm -vf $log if [[ $diff_time -gt $((${days} * 86400)) ]]; then
local log_path=$(echo "$log" | sed "s,${dir_log}/,,g")
local result=$(find_cron_api "log_path=$log_path")
echo -e "查询文件 $log_path"
if [[ -z $result ]]; then
echo -e "删除中~"
rm -vf $log
else
echo -e "正在被 $result 使用,跳过~"
fi
fi
fi fi
done done
} }
+91 -59
View File
@@ -18,6 +18,7 @@ dir_update_log=$dir_log/update
ql_static_repo=$dir_repo/static ql_static_repo=$dir_repo/static
## 文件 ## 文件
file_ecosystem_js=$dir_root/ecosystem.config.js
file_config_sample=$dir_sample/config.sample.sh file_config_sample=$dir_sample/config.sample.sh
file_env=$dir_config/env.sh file_env=$dir_config/env.sh
file_sharecode=$dir_config/sharecode.sh file_sharecode=$dir_config/sharecode.sh
@@ -34,7 +35,6 @@ file_notify_js_sample=$dir_sample/notify.js
file_notify_py_sample=$dir_sample/notify.py file_notify_py_sample=$dir_sample/notify.py
file_notify_py=$dir_scripts/notify.py file_notify_py=$dir_scripts/notify.py
file_notify_js=$dir_scripts/sendNotify.js file_notify_js=$dir_scripts/sendNotify.js
task_error_log_path=$dir_log/task_error.log
nginx_app_conf=$dir_root/docker/front.conf nginx_app_conf=$dir_root/docker/front.conf
nginx_conf=$dir_root/docker/nginx.conf nginx_conf=$dir_root/docker/nginx.conf
dep_notify_py=$dir_dep/notify.py dep_notify_py=$dir_dep/notify.py
@@ -67,8 +67,8 @@ import_config() {
[[ -f $file_config_user ]] && . $file_config_user [[ -f $file_config_user ]] && . $file_config_user
[[ -f $file_env ]] && . $file_env [[ -f $file_env ]] && . $file_env
ql_base_url=${QlBaseUrl:-""} ql_base_url=${QlBaseUrl:-"/"}
command_timeout_time=${CommandTimeoutTime:-"1h"} command_timeout_time=${CommandTimeoutTime:-""}
proxy_url=${ProxyUrl:-""} proxy_url=${ProxyUrl:-""}
file_extensions=${RepoFileExtensions:-"js py"} file_extensions=${RepoFileExtensions:-"js py"}
current_branch=${QL_BRANCH} current_branch=${QL_BRANCH}
@@ -98,6 +98,9 @@ set_proxy() {
unset_proxy() { unset_proxy() {
unset http_proxy unset http_proxy
unset https_proxy unset https_proxy
unset ftp_proxy
unset all_proxy
unset no_proxy
} }
make_dir() { make_dir() {
@@ -262,28 +265,13 @@ npm_install_sub() {
fi fi
} }
npm_install_1() {
local dir_current=$(pwd)
local dir_work=$1
cd $dir_work
echo -e "运行 npm install...\n"
npm_install_sub
[[ $? -ne 0 ]] && echo -e "\nnpm install 运行不成功,请进入 $dir_work 目录后手动运行 npm install...\n"
cd $dir_current
}
npm_install_2() { npm_install_2() {
local dir_current=$(pwd) local dir_current=$(pwd)
local dir_work=$1 local dir_work=$1
cd $dir_work cd $dir_work
echo -e "检测到 $dir_work 依赖包有变化,运行 npm install...\n" echo -e "安装 $dir_work 依赖包...\n"
npm_install_sub npm_install_sub
if [[ $? -ne 0 ]]; then
echo -e "\n安装 $dir_work 的依赖包运行不成功,再次尝试一遍...\n"
npm_install_1 $dir_work
fi
cd $dir_current cd $dir_current
} }
@@ -315,8 +303,12 @@ git_clone_scripts() {
echo -e "开始克隆仓库 $url$dir\n" echo -e "开始克隆仓库 $url$dir\n"
set_proxy "$proxy" set_proxy "$proxy"
git clone $part_cmd $url $dir
git clone --depth=1 $part_cmd $url $dir
exit_status=$? exit_status=$?
reset_branch "$branch" "$dir"
unset_proxy unset_proxy
} }
@@ -327,13 +319,25 @@ git_pull_scripts() {
local proxy="$3" local proxy="$3"
cd $dir_work cd $dir_work
echo -e "开始更新仓库:$dir_work" echo -e "开始更新仓库:$dir_work"
set_proxy "$proxy" set_proxy "$proxy"
git fetch --all
exit_status=$?
git pull &>/dev/null
unset_proxy
if [[ ! $branch ]]; then
branch=$(cd $dir_work && git remote show origin | grep 'HEAD branch' | cut -d' ' -f5)
fi
local pre_commit_id=$(git rev-parse --short HEAD)
reset_branch "$branch" "$dir_work"
git fetch --depth 1 origin $branch
exit_status=$?
reset_branch "$branch" "$dir_work"
local cur_commit_id=$(git rev-parse --short HEAD)
if [[ $cur_commit_id != $pre_commit_id ]]; then
exit_status=0
fi
unset_proxy
cd $dir_current cd $dir_current
} }
@@ -351,19 +355,16 @@ reset_romote_url() {
git init git init
git remote add origin $url &>/dev/null git remote add origin $url &>/dev/null
fi fi
reset_branch "$branch"
cd $dir_current cd $dir_current
} }
reset_branch() { reset_branch() {
local branch="$1" local branch="$1"
local part_cmd="" local part_cmd="origin/${branch}"
if [[ $branch ]]; then git remote set-branches origin $branch
part_cmd="origin/${branch}"
git checkout -B "$branch" &>/dev/null
git branch --set-upstream-to=$part_cmd $branch &>/dev/null
fi
git reset --hard $part_cmd &>/dev/null git reset --hard $part_cmd &>/dev/null
git checkout -b $branch $part_cmd &>/dev/null
} }
random_range() { random_range() {
@@ -373,15 +374,11 @@ random_range() {
} }
reload_pm2() { reload_pm2() {
pm2 l &>/dev/null cd $dir_root
# 代理会影响 grpc 服务
echo -e "启动面板服务\n" unset_proxy
pm2 delete panel --source-map-support --time &>/dev/null pm2 flush &>/dev/null
pm2 start $dir_static/build/app.js -n panel --source-map-support --time &>/dev/null pm2 startOrGracefulReload $file_ecosystem_js
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
} }
diff_time() { diff_time() {
@@ -431,17 +428,9 @@ format_timestamp() {
} }
patch_version() { patch_version() {
if [[ $PipMirror ]]; then git config --global pull.rebase false
pip3 config set global.index-url $PipMirror
fi
if [[ $NpmMirror ]]; then
npm config set registry $NpmMirror
fi
# 兼容pnpm@7 cp -f $dir_root/.env.example $dir_root/.env
pnpm setup &>/dev/null
source ~/.bashrc
pnpm install -g &>/dev/null
if [[ -f "$dir_root/db/cookie.db" ]]; then if [[ -f "$dir_root/db/cookie.db" ]]; then
echo -e "检测到旧的db文件,拷贝为新db...\n" echo -e "检测到旧的db文件,拷贝为新db...\n"
@@ -450,12 +439,6 @@ patch_version() {
echo echo
fi fi
pnpm add -g pm2 ts-node typescript tslib
git config --global pull.rebase false
cp -f $dir_root/.env.example $dir_root/.env
if [[ -d "$dir_root/db" ]]; then if [[ -d "$dir_root/db" ]]; then
echo -e "检测到旧的db目录,拷贝到data目录...\n" echo -e "检测到旧的db目录,拷贝到data目录...\n"
cp -rf $dir_root/config $dir_root/data cp -rf $dir_root/config $dir_root/data
@@ -481,10 +464,59 @@ patch_version() {
fi fi
} }
init_nginx() {
cp -fv $nginx_conf /etc/nginx/nginx.conf
cp -fv $nginx_app_conf /etc/nginx/conf.d/front.conf
local location_url="/"
local aliasStr=""
local rootStr=""
if [[ $ql_base_url != "/" ]]; then
location_url="^~${ql_base_url%*/}"
aliasStr="alias ${dir_static}/dist;"
else
rootStr="root ${dir_static}/dist;"
fi
sed -i "s,QL_ALIAS_CONFIG,${aliasStr},g" /etc/nginx/conf.d/front.conf
sed -i "s,QL_ROOT_CONFIG,${rootStr},g" /etc/nginx/conf.d/front.conf
sed -i "s,QL_BASE_URL_LOCATION,${location_url},g" /etc/nginx/conf.d/front.conf
sed -i "s,QL_BASE_URL,${ql_base_url},g" /etc/nginx/conf.d/front.conf
ipv6=$(ip a | grep inet6)
ipv6Str=""
if [[ $ipv6 ]]; then
ipv6Str="listen [::]:5700 ipv6only=on;"
fi
sed -i "s,IPV6_CONFIG,${ipv6Str},g" /etc/nginx/conf.d/front.conf
}
handle_task_before() {
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
echo -e "## 开始执行... $begin_time\n"
[[ $is_macos -eq 0 ]] && check_server
. $file_task_before "$@"
}
handle_task_after() {
. $file_task_after "$@"
local etime=$(date "+$time_format")
local end_time=$(format_time "$time_format" "$etime")
local end_timestamp=$(format_timestamp "$time_format" "$etime")
local diff_time=$(($end_timestamp - $begin_timestamp))
[[ "$diff_time" == 0 ]] && diff_time=1
echo -e "\n\n## 执行结束... $end_time 耗时 $diff_time 秒     "
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
}
init_env init_env
detect_termux detect_termux
detect_macos detect_macos
define_cmd define_cmd
fix_config
import_config $1 2>$task_error_log_path import_config $1
+47 -9
View File
@@ -5,6 +5,12 @@ dir_shell=$QL_DIR/shell
. $dir_shell/share.sh . $dir_shell/share.sh
. $dir_shell/api.sh . $dir_shell/api.sh
trap "single_hanle" 2 3 20 15 14
single_hanle() {
eval handle_task_after "$@" "$cmd"
exit 1
}
## 选择python3还是node ## 选择python3还是node
define_program() { define_program() {
local file_param=$1 local file_param=$1
@@ -15,7 +21,11 @@ define_program() {
elif [[ $file_param == *.sh ]]; then elif [[ $file_param == *.sh ]]; then
which_program="bash" which_program="bash"
elif [[ $file_param == *.ts ]]; then elif [[ $file_param == *.ts ]]; then
which_program="ts-node-transpile-only" if ! type tsx &>/dev/null; then
which_program="ts-node-transpile-only"
else
which_program="tsx"
fi
else else
which_program="" which_program=""
fi fi
@@ -24,14 +34,22 @@ define_program() {
handle_log_path() { handle_log_path() {
local file_param=$1 local file_param=$1
if [[ -z $file_param ]];then if [[ -z $file_param ]]; then
file_param="task" file_param="task"
fi fi
if [[ -z $ID ]]; then
ID=$(cat $list_crontab_user | grep -E "$cmd_task.* $file_param" | perl -pe "s|.*ID=(.*) $cmd_task.* $file_param\.*|\1|" | head -1 | awk -F " " '{print $1}')
fi
local suffix="" local suffix=""
if [[ ! -z $ID ]]; then if [[ ! -z $ID ]]; then
suffix="_${ID}" if [[ "$ID" -gt 0 ]] 2>/dev/null; then
suffix="_${ID}"
else
ID=""
fi
fi fi
time=$(date "+$mtime_format") time=$(date "+$mtime_format")
log_time=$(format_log_time "$mtime_format" "$time") log_time=$(format_log_time "$mtime_format" "$time")
log_dir_tmp="${file_param##*/}" log_dir_tmp="${file_param##*/}"
@@ -47,24 +65,43 @@ handle_log_path() {
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}" [[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
log_dir="${log_dir_tmp%.*}${suffix}" log_dir="${log_dir_tmp%.*}${suffix}"
log_path="$log_dir/$log_time.log" log_path="$log_dir/$log_time.log"
if [[ $real_log_path ]]; then
log_path="$real_log_path"
fi
cmd=">> $dir_log/$log_path 2>&1" cmd=">> $dir_log/$log_path 2>&1"
make_dir "$dir_log/$log_dir"
if [[ "$show_log" == "true" ]]; then if [[ "$show_log" == "true" ]]; then
cmd="2>&1 | tee -a $dir_log/$log_path"
fi
if [[ "$real_time" == "true" ]]; then
cmd="" cmd=""
else
make_dir "$dir_log/$log_dir"
fi fi
} }
format_params() { format_params() {
time_format="%Y-%m-%d %H:%M:%S" time_format="%Y-%m-%d %H:%M:%S"
mtime_format="%Y-%m-%d %H:%M:%S.%3N" if [[ $is_macos -eq 1 ]]; then
mtime_format=$time_format
else
mtime_format="%Y-%m-%d %H:%M:%S.%3N"
fi
timeoutCmd="" timeoutCmd=""
if type timeout &>/dev/null; then if [[ $command_timeout_time ]]; then
timeoutCmd="timeout --foreground -s 14 -k 10s $command_timeout_time " if type timeout &>/dev/null; then
timeoutCmd="timeout --foreground -s 2 -k 10s $command_timeout_time "
fi
fi fi
# params=$(echo "$@" | sed -E 's/([^ ])&([^ ])/\1\\\&\2/g') # params=$(echo "$@" | sed -E 's/([^ ])&([^ ])/\1\\\&\2/g')
} }
init_begin_time() {
begin_time=$(format_time "$time_format" "$time")
begin_timestamp=$(format_timestamp "$time_format" "$time")
}
while getopts ":lm:" opt; do while getopts ":lm:" opt; do
case $opt in case $opt in
l) l)
@@ -84,8 +121,9 @@ fi
format_params "$@" format_params "$@"
define_program "$@" define_program "$@"
handle_log_path "$@" handle_log_path "$@"
init_begin_time
eval . $dir_shell/otask.sh "$cmd" eval . $dir_shell/otask.sh "$cmd"
[[ -f "$dir_log/$log_path" ]] && cat "$dir_log/$log_path" [[ -f "$dir_log/$log_path" ]] && [[ ! $show_log ]] && [[ "$real_time" != "true" ]] && cat "$dir_log/$log_path"
exit 0 exit 0
+30 -32
View File
@@ -46,7 +46,7 @@ del_cron() {
local ids="" local ids=""
echo -e "开始尝试自动删除失效的定时任务...\n" echo -e "开始尝试自动删除失效的定时任务...\n"
for cron in $(cat $list_drop); do for cron in $(cat $list_drop); do
local id=$(cat $list_crontab_user | grep -E "$cmd_task $cron" | perl -pe "s|.*ID=(.*) $cmd_task $cron\.*|\1|" | head -1 | head -1 | awk -F " " '{print $1}') local id=$(cat $list_crontab_user | grep -E "$cmd_task.* $cron" | perl -pe "s|.*ID=(.*) $cmd_task.* $cron\.*|\1|" | head -1 | awk -F " " '{print $1}')
if [[ $ids ]]; then if [[ $ids ]]; then
ids="$ids,\"$id\"" ids="$ids,\"$id\""
else else
@@ -152,28 +152,37 @@ update_raw() {
local autoAddCron="$3" local autoAddCron="$3"
local autoDelCron="$4" local autoDelCron="$4"
if [[ ! $autoAddCron ]];then if [[ ! $autoAddCron ]]; then
autoAddCron=${AutoAddCron} autoAddCron=${AutoAddCron}
fi fi
if [[ ! $autoDelCron ]];then if [[ ! $autoDelCron ]]; then
autoDelCron=${AutoDelCron} autoDelCron=${AutoDelCron}
fi fi
local proxyStr=""
if [[ $proxy ]]; then
if [[ $url == http:* ]]; then
proxyStr="-e \"http_proxy=${proxy}\""
elif [[ $url == https:* ]]; then
proxyStr="-e \"http_proxy=${proxy};https_proxy=${proxy}\""
fi
fi
local raw_url="$url" local raw_url="$url"
local suffix="${raw_url##*.}" local suffix="${raw_url##*.}"
local raw_file_name="${uniq_path}.${suffix}" local raw_file_name="${uniq_path}.${suffix}"
echo -e "开始下载:${raw_url} \n\n保存路径:$dir_raw/${raw_file_name}\n" echo -e "开始下载:${raw_url} \n\n保存路径:$dir_raw/${raw_file_name}\n"
wget -q --no-check-certificate -e "http_proxy=${proxy};https_proxy=${proxy}" -O "$dir_raw/${raw_file_name}.new" ${raw_url} wget -q --no-check-certificate $proxyStr -O "$dir_raw/${raw_file_name}.new" ${raw_url}
if [[ $? -eq 0 ]]; then if [[ $? -eq 0 ]]; then
mv "$dir_raw/${raw_file_name}.new" "$dir_raw/${raw_file_name}" mv "$dir_raw/${raw_file_name}.new" "$dir_raw/${raw_file_name}"
echo -e "下载 ${raw_file_name} 成功...\n" echo -e "下载 ${raw_file_name} 成功...\n"
cd $dir_raw
local filename="raw_${raw_file_name}"
local cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* $filename" | perl -pe "s|.*ID=(.*) $cmd_task.* $filename\.*|\1|" | head -1 | awk -F " " '{print $1}')
cp -f $raw_file_name $dir_scripts/${filename}
if [[ -z $cron_id ]] && [[ ${autoAddCron} == true ]]; then if [[ -z $cron_id ]] && [[ ${autoAddCron} == true ]]; then
cd $dir_raw
local filename="raw_${raw_file_name}"
local cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* $filename" | perl -pe "s|.*ID=(.*) $cmd_task.* $filename\.*|\1|" | head -1 | awk -F " " '{print $1}')
cp -f $raw_file_name $dir_scripts/${filename}
cron_line=$( cron_line=$(
perl -ne "{ perl -ne "{
print if /.*([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*]( |,|\").*$raw_file_name/ print if /.*([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*]( |,|\").*$raw_file_name/
@@ -203,13 +212,10 @@ update_raw() {
## 调用用户自定义的extra.sh ## 调用用户自定义的extra.sh
run_extra_shell() { run_extra_shell() {
if [[ ${EnableExtraShell} == true ]]; then if [[ -f $file_extra_shell ]]; then
if [[ -f $file_extra_shell ]]; then . $file_extra_shell
echo -e "--------------------------------------------------------------\n" else
. $file_extra_shell echo -e "$file_extra_shell文件不存在,跳过执行...\n"
else
echo -e "$file_extra_shell文件不存在,跳过执行...\n"
fi
fi fi
} }
@@ -229,18 +235,17 @@ usage() {
## 更新qinglong ## 更新qinglong
update_qinglong() { update_qinglong() {
local mirror="github" local mirror="gitee"
local githubStatus=$(curl -s -m 2 -IL "https://github.com" | grep 200) local githubStatus=$(curl -s -m 2 -IL "https://google.com" | grep 200)
if [[ ! -z $githubStatus ]]; then if [[ ! -z $githubStatus ]]; then
mirror="gitee" mirror="github"
fi fi
echo -e "使用 ${mirror} 源更新...\n" echo -e "使用 ${mirror} 源更新...\n"
export isFirstStartServer=false export isFirstStartServer=false
local all_branch=$(cd ${dir_root} && git branch -a)
local primary_branch="master" local primary_branch="master"
if [[ "${all_branch}" =~ "${current_branch}" ]]; then if [[ "${QL_BRANCH}" == "develop" ]]; then
primary_branch="${current_branch}" primary_branch="develop"
fi fi
[[ -f $dir_root/package.json ]] && ql_depend_old=$(cat $dir_root/package.json) [[ -f $dir_root/package.json ]] && ql_depend_old=$(cat $dir_root/package.json)
reset_romote_url ${dir_root} "https://${mirror}.com/whyour/qinglong.git" ${primary_branch} reset_romote_url ${dir_root} "https://${mirror}.com/whyour/qinglong.git" ${primary_branch}
@@ -248,7 +253,6 @@ update_qinglong() {
if [[ $exit_status -eq 0 ]]; then if [[ $exit_status -eq 0 ]]; then
echo -e "\n更新青龙源文件成功...\n" echo -e "\n更新青龙源文件成功...\n"
reset_romote_url ${dir_root} "https://${mirror}.com/whyour/qinglong.git" ${primary_branch}
cp -f $file_config_sample $dir_config/config.sample.sh cp -f $file_config_sample $dir_config/config.sample.sh
update_depend update_depend
@@ -274,7 +278,6 @@ update_qinglong_static() {
fi fi
if [[ $exit_status -eq 0 ]]; then if [[ $exit_status -eq 0 ]]; then
echo -e "\n更新青龙静态资源成功...\n" echo -e "\n更新青龙静态资源成功...\n"
reset_romote_url ${ql_static_repo} ${url} ${primary_branch}
rm -rf $dir_static/* rm -rf $dir_static/*
cp -rf $ql_static_repo/* $dir_static cp -rf $ql_static_repo/* $dir_static
@@ -300,11 +303,11 @@ diff_scripts() {
local extensions="$6" local extensions="$6"
local autoAddCron="$7" local autoAddCron="$7"
local autoDelCron="$8" local autoDelCron="$8"
if [[ ! $autoAddCron ]];then if [[ ! $autoAddCron ]]; then
autoAddCron=${AutoAddCron} autoAddCron=${AutoAddCron}
fi fi
if [[ ! $autoDelCron ]];then if [[ ! $autoDelCron ]]; then
autoDelCron=${AutoDelCron} autoDelCron=${AutoDelCron}
fi fi
@@ -453,12 +456,6 @@ main() {
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
fi fi
if [[ -s $task_error_log_path ]]; then
eval cat $task_error_log_path $cmd
eval echo -e "加载 config.sh 出错,请手动检查" $cmd
eval echo $cmd
fi
if [[ "$show_log" == "true" ]] && [[ $ID ]]; then if [[ "$show_log" == "true" ]] && [[ $ID ]]; then
eval echo -e "请移除 -l 参数" $cmd eval echo -e "请移除 -l 参数" $cmd
exit 1 exit 1
@@ -466,6 +463,7 @@ main() {
case $p1 in case $p1 in
update) update)
fix_config
eval update_qinglong "$2" $cmd eval update_qinglong "$2" $cmd
;; ;;
extra) extra)
+16
View File
@@ -0,0 +1,16 @@
const baseUrl = window.__ENV__QlBaseUrl || '/';
export function modifyClientRenderOpts(memo: any) {
return {
...memo,
publicPath: baseUrl,
basename: baseUrl,
};
}
export function modifyContextOpts(memo: any) {
return {
...memo,
basename: baseUrl,
};
}
+404
View File
@@ -0,0 +1,404 @@
import React, {
useRef,
useEffect,
useContext,
createContext,
useReducer,
useState,
useMemo,
} from 'react';
import { throttle, isNumber, debounce } from 'lodash';
const initialState = {
// 行高度
rowHeight: 0,
// 当前的scrollTop
curScrollTop: 0,
// 总行数
totalLen: 0,
};
function reducer(state, action) {
const { curScrollTop, totalLen, ifScrollTopClear, scrollTop } = action;
let stateScrollTop = state.curScrollTop;
switch (action.type) {
// 改变trs 即 改变渲染的列表trs
case 'changeTrs':
return {
...state,
curScrollTop,
};
// 更改totalLen
case 'changeTotalLen':
if (totalLen === 0) {
stateScrollTop = 0;
}
return {
...state,
totalLen,
curScrollTop: stateScrollTop,
};
case 'reset':
return {
...state,
curScrollTop: ifScrollTopClear ? 0 : scrollTop ?? state.curScrollTop,
};
default:
throw new Error();
}
}
// ==============全局常量 ================== //
const DEFAULT_VID = 'vtable';
const vidMap = new Map();
let preData = 0;
// ===============context ============== //
const ScrollContext = createContext({
dispatch: undefined,
renderLen: 1,
start: 0,
offsetStart: 0,
// =============
rowHeight: initialState.rowHeight,
totalLen: 0,
vid: DEFAULT_VID,
});
// =============组件 =================== //
function VCell(props: any): JSX.Element {
const { children, ...restProps } = props;
return (
<td {...restProps}>
<div>{children[1]}</div>
</td>
);
}
function VRow(props: any, ref: any): JSX.Element {
const { rowHeight } = useContext(ScrollContext);
const { children, style, ...restProps } = props;
const trRef = useRef<HTMLTableRowElement>(null);
return (
<tr
{...restProps}
ref={Object.prototype.hasOwnProperty.call(ref, 'current') ? ref : trRef}
style={{
...style,
height: rowHeight || 'auto',
boxSizing: 'border-box',
}}
>
{children}
</tr>
);
}
function VWrapper(props: any): JSX.Element {
const { children, ...restProps } = props;
const { renderLen, start, dispatch, vid, totalLen } =
useContext(ScrollContext);
const contents = useMemo(() => {
return children[1];
}, [children]);
const contentsLen = useMemo(() => {
return contents?.length ?? 0;
}, [contents]);
useEffect(() => {
if (totalLen !== contentsLen) {
dispatch({
type: 'changeTotalLen',
totalLen: contentsLen ?? 0,
});
}
}, [contentsLen, dispatch, vid, totalLen]);
let tempNode = null;
if (Array.isArray(contents) && contents.length) {
tempNode = [
children[0],
contents.slice(start, start + (renderLen ?? 1)).map((item) => {
if (Array.isArray(item)) {
// 兼容antd v4.3.5 --- rc-table 7.8.1及以下
return item[0];
}
// 处理antd ^v4.4.0 --- rc-table ^7.8.2
return item;
}),
];
} else {
tempNode = children;
}
return <tbody {...restProps}>{tempNode}</tbody>;
}
function VTable(props: any, otherParams): JSX.Element {
const { style, children, ...rest } = props;
const { width, ...rest_style } = style;
const { vid, scrollY, resetScrollTopWhenDataChange, rowHeight, scrollTop } =
otherParams ?? {};
const [state, dispatch] = useReducer(reducer, {
...initialState,
curScrollTop: scrollTop,
rowHeight,
});
const wrap_tableRef = useRef<HTMLDivElement>(null);
const tableRef = useRef<HTMLTableElement>(null);
const ifChangeRef = useRef(false);
// 数据的总条数
const [totalLen, setTotalLen] = useState<number>(
children[1]?.props?.data?.length ?? 0,
);
useEffect(() => {
setTotalLen(state.totalLen);
}, [state.totalLen]);
// 组件卸载的清除操作
useEffect(() => {
return () => {
vidMap.delete(vid);
};
}, [vid]);
// 数据变更
useEffect(() => {
ifChangeRef.current = true;
// console.log('数据变更')
if (isNumber(children[1]?.props?.data?.length)) {
dispatch({
type: 'changeTotalLen',
totalLen: children[1]?.props?.data?.length ?? 0,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [children[1].props.data]);
// table总高度
const tableHeight = useMemo<string | number>(() => {
let temp: string | number = 'auto';
if (rowHeight && totalLen) {
temp = rowHeight * totalLen;
}
return temp;
}, [totalLen]);
// table的scrollY值
const [tableScrollY, setTableScrollY] = useState(0);
// tableScrollY 随scrollY / tableHeight 进行变更
useEffect(() => {
let temp = 0;
if (typeof scrollY === 'string') {
temp =
(wrap_tableRef.current?.parentNode as HTMLElement)?.offsetHeight ?? 0;
} else {
temp = scrollY;
}
// if (isNumber(tableHeight) && tableHeight < temp) {
// temp = tableHeight;
// }
// 处理tableScrollY <= 0的情况
if (temp <= 0) {
temp = 0;
}
setTableScrollY(temp);
}, [scrollY, tableHeight]);
// 渲染的条数
const renderLen = useMemo<number>(() => {
let temp = 1;
if (rowHeight && totalLen && tableScrollY) {
if (tableScrollY <= 0) {
temp = 0;
} else {
const tempRenderLen = ((tableScrollY / rowHeight) | 0) + 10;
// console.log('tempRenderLen', tempRenderLen)
// temp = tempRenderLen > totalLen ? totalLen : tempRenderLen;
temp = tempRenderLen;
}
}
return temp;
}, [totalLen, tableScrollY]);
// 渲染中的第一条
let start = rowHeight ? (state.curScrollTop / rowHeight) | 0 : 0;
start = start < 5 ? 0 : start - 5 + 1;
// 偏移量
let offsetStart = state.curScrollTop % (rowHeight * 5);
if (start > 0) {
offsetStart = offsetStart % rowHeight;
}
// console.log(offsetStart)
// offsetStart= offsetStart%rowHeight
// 用来优化向上滚动出现的空白
if (state.curScrollTop && state.curScrollTop >= rowHeight * 5) {
// start -= 1
// if (offsetStart >= rowHeight) {
// offsetStart +=
// } else {
offsetStart += rowHeight * 4;
// }
} else {
start = 0;
}
// console.log(state.curScrollTop, start, offsetStart)
// 数据变更 操作scrollTop
useEffect(() => {
const scrollNode = wrap_tableRef.current?.parentNode as HTMLElement;
if (ifChangeRef?.current) {
// console.log(scrollNode)
ifChangeRef.current = false;
if (resetScrollTopWhenDataChange) {
// 重置scrollTop
if (scrollNode) {
scrollNode.scrollTop = 0;
}
dispatch({ type: 'reset', ifScrollTopClear: true });
} else {
// console.log(preData)
// scrollNode.scrollTop = preData+53
// 不重置scrollTop 不清空curScrollTop
dispatch({ type: 'reset', ifScrollTopClear: false });
}
}
if (vidMap.has(vid)) {
vidMap.set(vid, {
...vidMap.get(vid),
scrollNode,
});
}
}, [totalLen, resetScrollTopWhenDataChange, vid, children]);
useEffect(() => {
const throttleScroll = throttle((e) => {
const scrollTop: number = e?.target?.scrollTop ?? 0;
// const scrollHeight: number = e?.target?.scrollHeight ?? 0
// const clientHeight: number = e?.target?.clientHeight ?? 0
if (scrollTop) {
preData = scrollTop;
}
// 到底了 没有滚动条就不会触发reachEnd. 建议设置scrolly高度少点或者数据量多点.
// 若renderLen大于totalLen, 置空curScrollTop. => table paddingTop会置空.
dispatch({
type: 'changeTrs',
curScrollTop: renderLen <= totalLen ? scrollTop : 0,
});
}, 60);
const ref = wrap_tableRef?.current?.parentNode as HTMLElement;
if (ref) {
ref.addEventListener('scroll', throttleScroll, { passive: true });
}
return () => {
ref.removeEventListener('scroll', throttleScroll);
};
}, [renderLen, totalLen]);
return (
<div
className="virtuallist"
ref={wrap_tableRef}
style={{
width: '100%',
position: 'relative',
height: tableHeight,
boxSizing: 'border-box',
paddingTop: state.curScrollTop,
}}
>
<ScrollContext.Provider
value={{
dispatch,
start,
offsetStart,
renderLen,
totalLen,
vid,
rowHeight,
}}
>
<table
{...rest}
ref={tableRef}
style={{
...rest_style,
width,
position: 'relative',
transform: `translateY(-${offsetStart}px)`,
}}
>
{children}
</table>
</ScrollContext.Provider>
</div>
);
}
// ================导出===================
export function VList(props: {
height: number;
// 唯一标识
vid?: string;
rowHeight: number | string;
reset?: boolean;
scrollTop?: number | string;
}): any {
const { vid = DEFAULT_VID, rowHeight, height, reset, scrollTop } = props;
const resetScrollTopWhenDataChange = reset ?? true;
if (!vidMap.has(vid)) {
vidMap.set(vid, { _id: vid });
}
return {
table: (p) =>
VTable(p, {
vid,
scrollY: height,
rowHeight,
resetScrollTopWhenDataChange,
scrollTop,
}),
body: {
wrapper: VWrapper,
row: VRow,
cell: VCell,
},
};
}
+13 -10
View File
@@ -1,16 +1,19 @@
import { MutableRefObject, useLayoutEffect, useState } from 'react'; import { MutableRefObject, useLayoutEffect, useState } from 'react';
import useResizeObserver from '@react-hook/resize-observer' import useResizeObserver from '@react-hook/resize-observer';
import { getTableScroll } from '@/utils'; import { getTableScroll } from '@/utils';
export default <T extends HTMLElement>(target: MutableRefObject<T>, extraHeight?: number) => { export default <T extends HTMLElement>(
const [height, setHeight] = useState<number>() target: MutableRefObject<T>,
extraHeight?: number,
) => {
const [height, setHeight] = useState<number>(0);
useResizeObserver(target, (entry) => { useResizeObserver(target, (entry) => {
let _targe = entry.target as any let _target = entry.target as any;
if (!_targe.classList.contains('ant-table-wrapper')) { if (!_target.classList.contains('ant-table-wrapper')) {
_targe = entry.target.querySelector('.ant-table-wrapper') _target = entry.target.querySelector('.ant-table-wrapper');
} }
setHeight(getTableScroll({ extraHeight, target: _targe as HTMLElement })) setHeight(getTableScroll({ extraHeight, target: _target as HTMLElement }));
}) });
return height return height;
} };
+56 -17
View File
@@ -9,9 +9,25 @@
url('../assets/fonts/SourceCodePro-Regular.ttf') format('truetype'); url('../assets/fonts/SourceCodePro-Regular.ttf') format('truetype');
} }
body {
// 禁止手机页面下拉刷新
overflow: hidden;
// 禁止手机页面弹簧效果
position: fixed;
top: 0;
left: 0;
}
#root {
height: 100vh;
height: calc(100vh - var(--vh-offset, 0px));
-webkit-overflow-scrolling: touch;
}
.ant-modal-body { .ant-modal-body {
max-height: calc(80vh - 110px); max-height: calc(90vh - 110px);
max-height: calc(80vh - var(--vh-offset, 110px)); max-height: calc(90vh - var(--vh-offset, 110px));
overflow-y: auto; overflow-y: auto;
} }
@@ -311,24 +327,19 @@ select:-webkit-autofill:focus {
.side-menu-user-drop-menu { .side-menu-user-drop-menu {
position: relative; position: relative;
text-align: left; text-align: left;
outline: none; padding: 2px 10px;
padding: 4px 0;
border: 1px solid fade(@component-background, 0.12);
border-radius: 4px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
overflow: auto; overflow: auto;
background-color: @component-background;
}
[data-dark='true'] .side-menu-user-drop-menu {
background-color: #373739;
} }
.ant-pro-sider-logo { .ant-pro-sider-logo {
padding: 16px 8px !important; .title {
height: 32px;
h1 { margin: 0 5px;
margin-left: 5px !important; font-weight: 600;
font-size: 16px;
line-height: 32px;
vertical-align: middle;
animation: pro-layout-title-hide 0.3s;
} }
img { img {
@@ -350,6 +361,34 @@ pre {
padding: 0 !important; padding: 0 !important;
} }
.virtuallist {
.ant-table-tbody > tr > td > div {
white-space: unset !important;
}
}
.virtuallist .ant-table-tbody > tr > td > div { .virtuallist .ant-table-tbody > tr > td > div {
white-space: unset !important; box-sizing: border-box;
white-space: nowrap;
vertical-align: middle;
overflow: hidden;
text-overflow: ellipsis;
width: 100%;
}
.virtuallist .ant-table-tbody > tr > td.ant-table-row-expand-icon-cell > div {
overflow: inherit;
}
.ant-table-bordered .virtuallist > table > .ant-table-tbody > tr > td {
border-right: 1px solid #f0f0f0;
}
.ant-table-column-title {
flex: unset;
}
.ant-table-column-sorters,
.ant-table-filter-column {
justify-content: unset;
} }
+24 -11
View File
@@ -98,8 +98,7 @@ export default function () {
}) })
.catch((error) => { .catch((error) => {
console.log(error); console.log(error);
}) });
.finally(() => setInitLoading(false));
}; };
const getUser = (needLoading = true) => { const getUser = (needLoading = true) => {
@@ -120,6 +119,22 @@ export default function () {
}); });
}; };
const getHealthStatus = () => {
request
.get(`${config.apiPrefix}public/health`)
.then((res) => {
if (res?.data?.status === 1) {
getSystemInfo();
} else {
history.push('/error');
}
})
.catch((error) => {
history.push('/error');
})
.finally(() => setInitLoading(false));
};
const reloadUser = (needLoading = false) => { const reloadUser = (needLoading = false) => {
getUser(needLoading); getUser(needLoading);
}; };
@@ -131,10 +146,8 @@ export default function () {
}, [location.pathname]); }, [location.pathname]);
useEffect(() => { useEffect(() => {
if (!systemInfo) { getHealthStatus();
getSystemInfo(); }, []);
}
}, [systemInfo]);
useEffect(() => { useEffect(() => {
if (theme === 'vs-dark') { if (theme === 'vs-dark') {
@@ -267,11 +280,10 @@ export default function () {
selectedKeys={[location.pathname]} selectedKeys={[location.pathname]}
loading={loading} loading={loading}
ErrorBoundary={Sentry.ErrorBoundary} ErrorBoundary={Sentry.ErrorBoundary}
logo={<Image preview={false} src="https://qn.whyour.cn/logo.png" />} logo={
// @ts-ignore
title={
<> <>
<span style={{ fontSize: 16 }}></span> <Image preview={false} src="https://qn.whyour.cn/logo.png" />
<span className="title"></span>
<a <a
href={systemInfo?.changeLogLink} href={systemInfo?.changeLogLink}
target="_blank" target="_blank"
@@ -300,6 +312,7 @@ export default function () {
</a> </a>
</> </>
} }
title={false}
menuItemRender={(menuItemProps: any, defaultDom: any) => { menuItemRender={(menuItemProps: any, defaultDom: any) => {
if ( if (
menuItemProps.isUrl || menuItemProps.isUrl ||
@@ -313,7 +326,7 @@ export default function () {
pageTitleRender={(props, pageName, info) => { pageTitleRender={(props, pageName, info) => {
const title = const title =
(config.documentTitleMap as any)[location.pathname] || '未找到'; (config.documentTitleMap as any)[location.pathname] || '未找到';
return `${title} - 控制面板`; return `${title} - 青龙`;
}} }}
onCollapse={setCollapsed} onCollapse={setCollapsed}
collapsed={collapsed} collapsed={collapsed}
+13 -3
View File
@@ -6,8 +6,9 @@
.card-wrapper { .card-wrapper {
.ant-card:last-child { .ant-card:last-child {
.ant-card-body { .ant-card-body {
height: calc(80vh - 367px); min-height: 300px;
height: calc(80vh - var(--vh-offset, 0px) - 367px); height: calc(90vh - 367px);
height: calc(90vh - var(--vh-offset, 0px) - 367px);
overflow-y: auto; overflow-y: auto;
} }
} }
@@ -155,7 +156,7 @@
.view-create-modal-sorts { .view-create-modal-sorts {
display: flex; display: flex;
.ant-space-item:nth-child(2) { .ant-space-item:nth-child(1) {
flex: 1; flex: 1;
} }
} }
@@ -177,6 +178,7 @@ tr.drop-over-upward td {
.view-filters-container.active { .view-filters-container.active {
.filter-item > div > .ant-form-item-control { .filter-item > div > .ant-form-item-control {
margin-left: 40px; margin-left: 40px;
width: calc(100% - 40px);
} }
} }
@@ -191,3 +193,11 @@ tr.drop-over-upward td {
margin: -24px; margin: -24px;
} }
} }
body[data-mode='desktop'] {
.crontab-wrapper {
tbody .ant-table-cell {
height: 69px !important;
}
}
}
+9 -28
View File
@@ -53,7 +53,7 @@ import { SharedContext } from '@/layouts';
import useTableScrollHeight from '@/hooks/useTableScrollHeight'; import useTableScrollHeight from '@/hooks/useTableScrollHeight';
import { getCommandScript, parseCrontab } from '@/utils'; import { getCommandScript, parseCrontab } from '@/utils';
import { ColumnProps } from 'antd/lib/table'; import { ColumnProps } from 'antd/lib/table';
import { VList } from 'virtuallist-antd'; import { useVT } from 'virtualizedtableforantd4';
const { Text, Paragraph } = Typography; const { Text, Paragraph } = Typography;
const { Search } = Input; const { Search } = Input;
@@ -107,7 +107,6 @@ const Crontab = () => {
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
width: 150, width: 150,
align: 'center' as const,
render: (text: string, record: any) => ( render: (text: string, record: any) => (
<> <>
<a <a
@@ -163,14 +162,12 @@ const Crontab = () => {
dataIndex: 'command', dataIndex: 'command',
key: 'command', key: 'command',
width: 300, width: 300,
align: 'center' as const,
render: (text, record) => { render: (text, record) => {
return ( return (
<Paragraph <Paragraph
style={{ style={{
wordBreak: 'break-all', wordBreak: 'break-all',
marginBottom: 0, marginBottom: 0,
textAlign: 'left',
}} }}
ellipsis={{ tooltip: text, rows: 2 }} ellipsis={{ tooltip: text, rows: 2 }}
> >
@@ -193,14 +190,12 @@ const Crontab = () => {
dataIndex: 'schedule', dataIndex: 'schedule',
key: 'schedule', key: 'schedule',
width: 110, width: 110,
align: 'center' as const,
sorter: { sorter: {
compare: (a, b) => a.schedule.localeCompare(b.schedule), compare: (a, b) => a.schedule.localeCompare(b.schedule),
}, },
}, },
{ {
title: '最后运行时间', title: '最后运行时间',
align: 'center' as const,
dataIndex: 'last_execution_time', dataIndex: 'last_execution_time',
key: 'last_execution_time', key: 'last_execution_time',
width: 150, width: 150,
@@ -230,7 +225,6 @@ const Crontab = () => {
}, },
{ {
title: '最后运行时长', title: '最后运行时长',
align: 'center' as const,
width: 120, width: 120,
dataIndex: 'last_running_time', dataIndex: 'last_running_time',
key: 'last_running_time', key: 'last_running_time',
@@ -247,7 +241,6 @@ const Crontab = () => {
}, },
{ {
title: '下次运行时间', title: '下次运行时间',
align: 'center' as const,
width: 150, width: 150,
sorter: { sorter: {
compare: (a: any, b: any) => { compare: (a: any, b: any) => {
@@ -267,7 +260,6 @@ const Crontab = () => {
title: '状态', title: '状态',
key: 'status', key: 'status',
dataIndex: 'status', dataIndex: 'status',
align: 'center' as const,
width: 88, width: 88,
filters: [ filters: [
{ {
@@ -287,13 +279,6 @@ const Crontab = () => {
value: 3, value: 3,
}, },
], ],
onFilter: (value, record) => {
if (record.isDisabled && record.status !== 0) {
return value === 2;
} else {
return record.status === value;
}
},
render: (text, record) => ( render: (text, record) => (
<> <>
{(!record.isDisabled || record.status !== CrontabStatus.idle) && ( {(!record.isDisabled || record.status !== CrontabStatus.idle) && (
@@ -329,8 +314,7 @@ const Crontab = () => {
{ {
title: '操作', title: '操作',
key: 'action', key: 'action',
align: 'center' as const, width: 130,
width: 100,
render: (text, record, index) => { render: (text, record, index) => {
const isPc = !isPhone; const isPc = !isPhone;
return ( return (
@@ -424,9 +408,9 @@ const Crontab = () => {
}crons?searchValue=${searchText}&page=${page}&size=${size}&filters=${JSON.stringify( }crons?searchValue=${searchText}&page=${page}&size=${size}&filters=${JSON.stringify(
filters, filters,
)}`; )}`;
if (sorter && sorter.field) { if (sorter && sorter.column && sorter.order) {
url += `&sorter=${JSON.stringify({ url += `&sorter=${JSON.stringify({
field: sorter.field, field: sorter.column.key,
type: sorter.order === 'ascend' ? 'ASC' : 'DESC', type: sorter.order === 'ascend' ? 'ASC' : 'DESC',
})}`; })}`;
} }
@@ -681,7 +665,6 @@ const Crontab = () => {
index: number; index: number;
}> = ({ record, index }) => ( }> = ({ record, index }) => (
<Dropdown <Dropdown
arrow={{ pointAtCenter: true }}
placement="bottomRight" placement="bottomRight"
trigger={['click']} trigger={['click']}
menu={{ menu={{
@@ -921,12 +904,10 @@ const Crontab = () => {
setViewConf(view ? view : null); setViewConf(view ? view : null);
}; };
const vComponents = useMemo(() => { const [vt] = useVT(
return VList({ () => ({ scroll: { y: tableScrollHeight } }),
height: tableScrollHeight!, [tableScrollHeight],
resetTopWhenDataChange: false, );
});
}, [tableScrollHeight]);
return ( return (
<PageContainer <PageContainer
@@ -1062,7 +1043,7 @@ const Crontab = () => {
rowSelection={rowSelection} rowSelection={rowSelection}
rowClassName={getRowClassName} rowClassName={getRowClassName}
onChange={onPageChange} onChange={onPageChange}
components={vComponents} // components={isPhone ? undefined : vt}
/> />
</div> </div>
<CronLogModal <CronLogModal
+1 -1
View File
@@ -54,7 +54,7 @@ const CronLogModal = ({
log && log &&
!logEnded(log) && !logEnded(log) &&
!log.includes('重启面板') && !log.includes('重启面板') &&
!log.includes('任务未运行或运行失败,请尝试手动运行'), !log.includes('任务未运行'),
); );
setExecuting(hasNext); setExecuting(hasNext);
autoScroll(); autoScroll();
+84 -85
View File
@@ -70,6 +70,7 @@ const ViewCreateModal = ({
const [form] = Form.useForm(); const [form] = Form.useForm();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [filterRelation, setFilterRelation] = useState<'and' | 'or'>('and'); const [filterRelation, setFilterRelation] = useState<'and' | 'or'>('and');
const filtersValue = Form.useWatch('filters', form);
const handleOk = async (values: any) => { const handleOk = async (values: any) => {
setLoading(true); setLoading(true);
@@ -126,7 +127,7 @@ const ViewCreateModal = ({
}; };
const typeElement = ( const typeElement = (
<Select> <Select style={{ width: 80 }}>
{SORTTYPES.map((x) => ( {SORTTYPES.map((x) => (
<Select.Option key={x.name} value={x.value}> <Select.Option key={x.name} value={x.value}>
{x.name} {x.name}
@@ -204,7 +205,7 @@ const ViewCreateModal = ({
position: 'absolute', position: 'absolute',
top: '50%', top: '50%',
translate: '-50% -50%', translate: '-50% -50%',
padding: '0 0 0 3px', padding: '0 3px',
cursor: 'pointer', cursor: 'pointer',
}} }}
onClick={() => { onClick={() => {
@@ -221,9 +222,9 @@ const ViewCreateModal = ({
</div> </div>
)} )}
<div> <div>
{fields.map(({ key, name, ...restField }, index) => ( {fields.map(({ key, name, ...restField }) => (
<Form.Item <Form.Item
label={index === 0 ? '筛选条件' : ''} label={name === 0 ? '筛选条件' : ''}
key={key} key={key}
style={{ marginBottom: 0 }} style={{ marginBottom: 0 }}
required required
@@ -232,9 +233,6 @@ const ViewCreateModal = ({
<Space <Space
className="view-create-modal-filters" className="view-create-modal-filters"
align="baseline" align="baseline"
style={
fields.length > 1 ? { width: 'calc(100% - 40px)' } : {}
}
> >
<Form.Item <Form.Item
{...restField} {...restField}
@@ -251,55 +249,18 @@ const ViewCreateModal = ({
{operationElement} {operationElement}
</Form.Item> </Form.Item>
<Form.Item <Form.Item
noStyle {...restField}
shouldUpdate={(prevValues, nextValues) => { name={[name, 'value']}
const preOperation = rules={[{ required: true, message: '请输入内容' }]}
EOperation[
get(prevValues, ['filters', name, 'operation'])
];
const nextOperation =
EOperation[
get(nextValues, ['filters', name, 'operation'])
];
const flag = preOperation !== nextOperation;
if (flag) {
form.setFieldValue(
['filters', name, 'value'],
nextOperation === 'select' ? [] : '',
);
}
return flag;
}}
> >
{() => { {EOperation[filtersValue?.[name]['operation']] ===
const property = form.getFieldValue([ 'select' ? (
'filters', statusElement(filtersValue?.[name]['property'])
index, ) : (
'property', <Input placeholder="请输入内容" />
]) as 'status'; )}
const operate = form.getFieldValue([
'filters',
name,
'operation',
]);
return (
<Form.Item
{...restField}
name={[name, 'value']}
rules={[
{ required: true, message: '请输入内容' },
]}
>
{EOperation[operate] === 'select' ? (
statusElement(property)
) : (
<Input placeholder="请输入内容" />
)}
</Form.Item>
);
}}
</Form.Item> </Form.Item>
{index !== 0 && ( {name !== 0 && (
<MinusCircleOutlined onClick={() => remove(name)} /> <MinusCircleOutlined onClick={() => remove(name)} />
)} )}
</Space> </Space>
@@ -321,39 +282,77 @@ const ViewCreateModal = ({
</Form.List> </Form.List>
<Form.List name="sorts"> <Form.List name="sorts">
{(fields, { add, remove }) => ( {(fields, { add, remove }) => (
<> <div
{fields.map(({ key, name, ...restField }, index) => ( style={{ position: 'relative' }}
<Form.Item className={`view-filters-container ${
label={index === 0 ? '排序方式' : ''} fields.length > 1 ? 'active' : ''
key={key} }`}
style={{ marginBottom: 0 }} >
{fields.length > 1 && (
<div
style={{
position: 'absolute',
width: 50,
borderRadius: 10,
border: '1px solid rgb(190, 220, 255)',
borderRight: 'none',
height: 56 * (fields.length - 1),
top: 46,
left: 15,
}}
> >
<Space className="view-create-modal-sorts" align="baseline"> <Button
<Form.Item type="primary"
{...restField} size="small"
name={[name, 'property']} style={{
rules={[{ required: true }]} position: 'absolute',
> top: '50%',
{propertyElement(PROPERTIES, { width: 240 })} translate: '-50% -50%',
</Form.Item> padding: '0 3px',
<Form.Item cursor: 'pointer',
{...restField} }}
name={[name, 'type']} >
rules={[{ required: true }]} <>
> <span>{ViewFilterRelation[filterRelation]}</span>
{typeElement} </>
</Form.Item> </Button>
<MinusCircleOutlined onClick={() => remove(name)} /> </div>
</Space> )}
<div>
{fields.map(({ key, name, ...restField }) => (
<Form.Item
label={name === 0 ? '排序方式' : ''}
key={key}
style={{ marginBottom: 0 }}
className="filter-item"
>
<Space className="view-create-modal-sorts" align="baseline">
<Form.Item
{...restField}
name={[name, 'property']}
rules={[{ required: true }]}
>
{propertyElement(PROPERTIES)}
</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.Item>
))} </div>
<Form.Item> </div>
<a onClick={() => add({ property: 'command', type: 'ASC' })}>
<PlusOutlined />
</a>
</Form.Item>
</>
)} )}
</Form.List> </Form.List>
</Form> </Form>
-7
View File
@@ -80,23 +80,17 @@ const ViewManageModal = ({
title: '名称', title: '名称',
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
align: 'center' as const,
render: (text) => (
<div style={{ textAlign: 'left', paddingLeft: 30 }}>{text}</div>
),
}, },
{ {
title: '类型', title: '类型',
dataIndex: 'type', dataIndex: 'type',
key: 'type', key: 'type',
align: 'center' as const,
render: (v) => (v === 1 ? '系统' : '个人'), render: (v) => (v === 1 ? '系统' : '个人'),
}, },
{ {
title: '显示', title: '显示',
key: 'isDisabled', key: 'isDisabled',
dataIndex: 'isDisabled', dataIndex: 'isDisabled',
align: 'center' as const,
width: 100, width: 100,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
return ( return (
@@ -111,7 +105,6 @@ const ViewManageModal = ({
title: '操作', title: '操作',
key: 'action', key: 'action',
width: 100, width: 100,
align: 'center' as const,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
return record.type !== 1 ? ( return record.type !== 1 ? (
<Space size="middle"> <Space size="middle">
+55 -10
View File
@@ -19,6 +19,8 @@ import {
DeleteFilled, DeleteFilled,
BugOutlined, BugOutlined,
FileTextOutlined, FileTextOutlined,
CloseCircleOutlined,
ClockCircleOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import config from '@/utils/config'; import config from '@/utils/config';
import { PageContainer } from '@ant-design/pro-layout'; import { PageContainer } from '@ant-design/pro-layout';
@@ -32,7 +34,6 @@ import { useOutletContext } from '@umijs/max';
import { SharedContext } from '@/layouts'; import { SharedContext } from '@/layouts';
import useTableScrollHeight from '@/hooks/useTableScrollHeight'; import useTableScrollHeight from '@/hooks/useTableScrollHeight';
const { Text } = Typography; const { Text } = Typography;
const { Search } = Input; const { Search } = Input;
@@ -43,6 +44,7 @@ enum Status {
'删除中', '删除中',
'已删除', '已删除',
'删除失败', '删除失败',
'队列中',
} }
enum StatusColor { enum StatusColor {
@@ -51,13 +53,43 @@ enum StatusColor {
'error', 'error',
} }
const StatusMap: Record<number, { icon: React.ReactNode; color: string }> = {
0: {
icon: <SyncOutlined spin />,
color: 'processing',
},
1: {
icon: <CheckCircleOutlined />,
color: 'success',
},
2: {
icon: <CloseCircleOutlined />,
color: 'error',
},
3: {
icon: <SyncOutlined spin />,
color: 'processing',
},
4: {
icon: <CheckCircleOutlined />,
color: 'success',
},
5: {
icon: <CloseCircleOutlined />,
color: 'error',
},
6: {
icon: <ClockCircleOutlined />,
color: 'default',
},
};
const Dependence = () => { const Dependence = () => {
const { headerStyle, isPhone, socketMessage } = const { headerStyle, isPhone, socketMessage } =
useOutletContext<SharedContext>(); useOutletContext<SharedContext>();
const columns: any = [ const columns: any = [
{ {
title: '序号', title: '序号',
align: 'center' as const,
width: 50, width: 50,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
return <span style={{ cursor: 'text' }}>{index + 1} </span>; return <span style={{ cursor: 'text' }}>{index + 1} </span>;
@@ -67,18 +99,17 @@ const Dependence = () => {
title: '名称', title: '名称',
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
align: 'center' as const,
}, },
{ {
title: '状态', title: '状态',
key: 'status', key: 'status',
dataIndex: 'status', dataIndex: 'status',
align: 'center' as const,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
return ( return (
<Space size="middle" style={{ cursor: 'text' }}> <Space size="middle" style={{ cursor: 'text' }}>
<Tag <Tag
color={StatusColor[record.status % 3]} color={StatusMap[record.status].color}
icon={StatusMap[record.status].icon}
style={{ marginRight: 0 }} style={{ marginRight: 0 }}
> >
{Status[record.status]} {Status[record.status]}
@@ -91,13 +122,11 @@ const Dependence = () => {
title: '备注', title: '备注',
dataIndex: 'remark', dataIndex: 'remark',
key: 'remark', key: 'remark',
align: 'center' as const,
}, },
{ {
title: '创建时间', title: '创建时间',
key: 'timestamp', key: 'timestamp',
dataIndex: 'timestamp', dataIndex: 'timestamp',
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
const language = navigator.language || navigator.languages[0]; const language = navigator.language || navigator.languages[0];
const time = record.createdAt || record.timestamp; const time = record.createdAt || record.timestamp;
@@ -120,7 +149,6 @@ const Dependence = () => {
{ {
title: '操作', title: '操作',
key: 'action', key: 'action',
align: 'center' as const,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
const isPc = !isPhone; const isPc = !isPhone;
return ( return (
@@ -169,7 +197,7 @@ const Dependence = () => {
const [isLogModalVisible, setIsLogModalVisible] = useState(false); const [isLogModalVisible, setIsLogModalVisible] = useState(false);
const [type, setType] = useState('nodejs'); const [type, setType] = useState('nodejs');
const tableRef = useRef<any>(); const tableRef = useRef<any>();
const tableScrollHeight = useTableScrollHeight(tableRef, 59) const tableScrollHeight = useTableScrollHeight(tableRef, 59);
const getDependencies = () => { const getDependencies = () => {
setLoading(true); setLoading(true);
@@ -218,7 +246,7 @@ const Dependence = () => {
}) })
.then(({ code, data }) => { .then(({ code, data }) => {
if (code === 200 && force) { if (code === 200 && force) {
const i = value.findIndex((x) => x.id === data.data[0].id); const i = value.findIndex((x) => x.id === data[0].id);
if (i !== -1) { if (i !== -1) {
const result = [...value]; const result = [...value];
result.splice(i, 1); result.splice(i, 1);
@@ -373,6 +401,23 @@ const Dependence = () => {
useEffect(() => { useEffect(() => {
if (!socketMessage) return; if (!socketMessage) return;
const { type, message, references } = socketMessage; const { type, message, references } = socketMessage;
if (
type === 'installDependence' &&
message.includes('开始时间') &&
references.length > 0
) {
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],
status: message.includes('安装') ? Status.安装中 : Status.删除中,
});
}
}
setValue(result);
}
if ( if (
type === 'installDependence' && type === 'installDependence' &&
message.includes('结束时间') && message.includes('结束时间') &&
+90 -103
View File
@@ -39,7 +39,7 @@ import { useOutletContext } from '@umijs/max';
import { SharedContext } from '@/layouts'; import { SharedContext } from '@/layouts';
import useTableScrollHeight from '@/hooks/useTableScrollHeight'; import useTableScrollHeight from '@/hooks/useTableScrollHeight';
import Copy from '../../components/copy'; import Copy from '../../components/copy';
import { VList } from 'virtuallist-antd'; import { useVT } from 'virtualizedtableforantd4';
const { Text } = Typography; const { Text } = Typography;
const { Search } = Input; const { Search } = Input;
@@ -71,7 +71,6 @@ const Env = () => {
const columns: any = [ const columns: any = [
{ {
title: '序号', title: '序号',
align: 'center' as const,
width: 60, width: 60,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
return <span style={{ cursor: 'text' }}>{index + 1} </span>; return <span style={{ cursor: 'text' }}>{index + 1} </span>;
@@ -81,14 +80,12 @@ const Env = () => {
title: '名称', title: '名称',
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
align: 'center' as const,
sorter: (a: any, b: any) => a.name.localeCompare(b.name), sorter: (a: any, b: any) => a.name.localeCompare(b.name),
}, },
{ {
title: '值', title: '值',
dataIndex: 'value', dataIndex: 'value',
key: 'value', key: 'value',
align: 'center' as const,
width: '35%', width: '35%',
render: (text: string, record: any) => { render: (text: string, record: any) => {
return ( return (
@@ -105,7 +102,6 @@ const Env = () => {
title: '备注', title: '备注',
dataIndex: 'remarks', dataIndex: 'remarks',
key: 'remarks', key: 'remarks',
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return ( return (
<Tooltip title={text} placement="topLeft"> <Tooltip title={text} placement="topLeft">
@@ -118,7 +114,6 @@ const Env = () => {
title: '更新时间', title: '更新时间',
dataIndex: 'timestamp', dataIndex: 'timestamp',
key: 'timestamp', key: 'timestamp',
align: 'center' as const,
width: 165, width: 165,
ellipsis: { ellipsis: {
showTitle: false, showTitle: false,
@@ -153,7 +148,6 @@ const Env = () => {
title: '状态', title: '状态',
key: 'status', key: 'status',
dataIndex: 'status', dataIndex: 'status',
align: 'center' as const,
width: 70, width: 70,
filters: [ filters: [
{ {
@@ -180,7 +174,6 @@ const Env = () => {
title: '操作', title: '操作',
key: 'action', key: 'action',
width: 120, width: 120,
align: 'center' as const,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
const isPc = !isPhone; const isPc = !isPhone;
return ( return (
@@ -331,16 +324,13 @@ const Env = () => {
getEnvs(); getEnvs();
}; };
const vComponents = useMemo(() => { const [vt, setVT] = useVT(
return VList({ () => ({ scroll: { y: tableScrollHeight } }),
height: tableScrollHeight!, [tableScrollHeight],
resetTopWhenDataChange: false, );
});
}, [tableScrollHeight]);
const DragableBodyRow = (props: any) => { const DragableBodyRow = React.forwardRef((props: any, ref) => {
const { index, moveRow, className, style, ...restProps } = props; const { index, moveRow, className, style, ...restProps } = props;
const ref = useRef();
const [{ isOver, dropClassName }, drop] = useDrop({ const [{ isOver, dropClassName }, drop] = useDrop({
accept: type, accept: type,
collect: (monitor) => { collect: (monitor) => {
@@ -368,31 +358,27 @@ const Env = () => {
useEffect(() => { useEffect(() => {
drop(drag(ref)); drop(drag(ref));
}, [drag, drop]); }, [ref]);
const components = useMemo(() => vComponents.body.row, []); return (
<tr
ref={ref}
className={`${className}${isOver ? dropClassName : ''}`}
style={{ cursor: 'move', ...style }}
{...restProps}
/>
);
});
const tempProps = useMemo(() => { useEffect(
return { () =>
ref: ref, setVT({
className: `${className}${isOver ? dropClassName : ''}`, body: {
style: { cursor: 'move', ...style }, row: DragableBodyRow,
...restProps, },
}; }),
}, [className, dropClassName, restProps, style, isOver]); [],
);
return <> {components(tempProps, ref)} </>;
};
const components = useMemo(() => {
return {
...vComponents,
body: {
...vComponents.body,
row: DragableBodyRow,
},
};
}, [vComponents]);
const moveRow = useCallback( const moveRow = useCallback(
(dragIndex: number, hoverIndex: number) => { (dragIndex: number, hoverIndex: number) => {
@@ -408,7 +394,7 @@ const Env = () => {
if (code === 200) { if (code === 200) {
const newData = [...value]; const newData = [...value];
newData.splice(dragIndex, 1); newData.splice(dragIndex, 1);
newData.splice(hoverIndex, 0, { ...dragRow, ...data.data }); newData.splice(hoverIndex, 0, { ...dragRow, ...data });
setValue([...newData]); setValue([...newData]);
} }
}); });
@@ -542,69 +528,70 @@ const Env = () => {
style: headerStyle, style: headerStyle,
}} }}
> >
{selectedRowIds.length > 0 && ( <div ref={tableRef}>
<div style={{ marginBottom: 16 }}> {selectedRowIds.length > 0 && (
<Button <div style={{ marginBottom: 16 }}>
type="primary" <Button
style={{ marginBottom: 5 }} type="primary"
onClick={modifyName} style={{ marginBottom: 5 }}
> onClick={modifyName}
>
</Button>
<Button </Button>
type="primary" <Button
style={{ marginBottom: 5, marginLeft: 8 }} type="primary"
onClick={delEnvs} style={{ marginBottom: 5, marginLeft: 8 }}
> onClick={delEnvs}
>
</Button>
<Button </Button>
type="primary" <Button
onClick={() => exportEnvs()} type="primary"
style={{ marginLeft: 8, marginRight: 8 }} onClick={() => exportEnvs()}
> style={{ marginLeft: 8, marginRight: 8 }}
>
</Button>
<Button </Button>
type="primary" <Button
onClick={() => operateEnvs(0)} type="primary"
style={{ marginLeft: 8, marginBottom: 5 }} onClick={() => operateEnvs(0)}
> style={{ marginLeft: 8, marginBottom: 5 }}
>
</Button>
<Button </Button>
type="primary" <Button
onClick={() => operateEnvs(1)} type="primary"
style={{ marginLeft: 8, marginRight: 8 }} onClick={() => operateEnvs(1)}
> style={{ marginLeft: 8, marginRight: 8 }}
>
</Button>
<span style={{ marginLeft: 8 }}> </Button>
<span style={{ marginLeft: 8 }}>
<a>{selectedRowIds?.length}</a>
</span> <a>{selectedRowIds?.length}</a>
</div> </span>
)} </div>
<DndProvider backend={HTML5Backend}> )}
<Table <DndProvider backend={HTML5Backend}>
ref={tableRef} <Table
columns={columns} columns={columns}
rowSelection={rowSelection} rowSelection={rowSelection}
pagination={false} pagination={false}
dataSource={value} dataSource={value}
rowKey="id" rowKey="id"
size="middle" size="middle"
scroll={{ x: 1000, y: tableScrollHeight }} scroll={{ x: 1000, y: tableScrollHeight }}
components={components} components={vt}
loading={loading} loading={loading}
onRow={(record: any, index: number | undefined) => { onRow={(record: any, index: number | undefined) => {
return { return {
index, index,
moveRow, moveRow,
} as any; } as any;
}} }}
/> />
</DndProvider> </DndProvider>
</div>
<EnvModal <EnvModal
visible={isModalVisible} visible={isModalVisible}
handleCancel={handleCancel} handleCancel={handleCancel}
+42
View File
@@ -9,4 +9,46 @@
height: calc(100vh - 80px); height: calc(100vh - 80px);
overflow-y: auto; overflow-y: auto;
} }
.code-box {
position: relative;
display: inline-block;
width: 80vw;
height: 90vh;
margin: 16px;
background-color: #ffffff;
border: 1px solid rgba(5, 5, 5, 0.06);
border-radius: 6px;
-webkit-transition: all 0.2s;
transition: all 0.2s;
border-radius: 6px 6px 0 0;
color: rgba(0, 0, 0, 0.88);
border-bottom: 1px solid rgba(5, 5, 5, 0.06);
.browser-markup {
position: relative;
border-top: 2em solid rgba(230, 230, 230, 0.7);
border-radius: 3px 3px 0 0;
&::before {
position: absolute;
top: -1.25em;
left: 1em;
display: block;
width: 0.5em;
height: 0.5em;
background-color: #f44;
border-radius: 50%;
box-shadow: 0 0 0 2px #f44, 1.5em 0 0 2px #9b3, 3em 0 0 2px #fb5;
content: '';
}
}
.log {
height: calc(90vh - 150px);
overflow-y: auto;
padding: 12px;
white-space: pre-line;
}
}
} }
+48 -42
View File
@@ -1,43 +1,34 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import config from '@/utils/config'; import config from '@/utils/config';
import { request } from '@/utils/http'; import { request } from '@/utils/http';
import Terminal, { ColorMode, LineType } from '../../components/terminal';
import { PageLoading } from '@ant-design/pro-layout'; import { PageLoading } from '@ant-design/pro-layout';
import { history, useOutletContext } from '@umijs/max'; import { history, useOutletContext } from '@umijs/max';
import Ansi from 'ansi-to-react';
import './index.less'; import './index.less';
import { SharedContext } from '@/layouts'; import { SharedContext } from '@/layouts';
import { Alert, Typography } from 'antd';
const Error = () => { const Error = () => {
const { user, theme, reloadUser } = useOutletContext<SharedContext>(); const { user, theme, reloadUser } = useOutletContext<SharedContext>();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [data, setData] = useState('暂无日志'); const [data, setData] = useState('暂无日志');
const retryTimes = useRef(1);
const getTimes = () => {
return parseInt(localStorage.getItem('error_retry_times') || '0', 10);
};
let times = getTimes();
const getLog = (needLoading: boolean = true) => { const getLog = (needLoading: boolean = true) => {
needLoading && setLoading(true); needLoading && setLoading(true);
request request
.get(`${config.apiPrefix}public/panel/log`) .get(`${config.apiPrefix}public/health`)
.then(({ code, data }) => { .then(({ error, data }) => {
if (code === 200) { if (data?.status === 1) {
setData(data); return;
if (!data) {
times = getTimes();
if (times > 5) {
return;
}
localStorage.setItem('error_retry_times', `${times + 1}`);
setTimeout(() => {
reloadUser();
getLog(false);
}, 3000);
}
} }
if (retryTimes.current > 3) {
setData(error?.details);
return;
}
retryTimes.current += 1;
setTimeout(() => {
getLog(false);
}, 3000);
}) })
.finally(() => needLoading && setLoading(false)); .finally(() => needLoading && setLoading(false));
}; };
@@ -56,24 +47,39 @@ const Error = () => {
<div className="error-wrapper"> <div className="error-wrapper">
{loading ? ( {loading ? (
<PageLoading /> <PageLoading />
) : data ? ( ) : retryTimes.current > 3 ? (
<Terminal <div className="code-box">
name="服务错误" <div className="browser-markup"></div>
colorMode={theme === 'vs-dark' ? ColorMode.Dark : ColorMode.Light} <Alert
lineData={[ type="error"
{ type: LineType.Input, value: 'pm2 logs panel' }, message={
{ <Typography.Title level={5} type="danger">
type: LineType.Output,
value: ( </Typography.Title>
<pre> }
<Ansi>{data}</Ansi> description={
</pre> <Typography.Text type="danger">
), <div></div>
}, <div>
]} 1. 宿 docker run --rm -v
/> /var/run/docker.sock:/var/run/docker.sock
) : times > 5 ? ( containrrr/watchtower -cR &lt;&gt;
<> ql -l check </> </div>
<div>2. ql -l checkql -l update</div>
<div>
3. pm2 logs
<Typography.Link href="https://github.com/whyour/qinglong/issues/new?assignees=&labels=&template=bug_report.yml">
issue
</Typography.Link>
</div>
</Typography.Text>
}
banner
/>
<Typography.Paragraph code className="log">
{data}
</Typography.Paragraph>
</div>
) : ( ) : (
<PageLoading tip="启动中,请稍后..." /> <PageLoading tip="启动中,请稍后..." />
)} )}
+8 -3
View File
@@ -78,9 +78,14 @@ const Initialization = () => {
{ {
title: '欢迎使用', title: '欢迎使用',
content: ( content: (
<div className={styles.top} style={{ marginTop: 100 }}> <div className={styles.top} style={{ marginTop: 30 }}>
<div className={styles.header}> <div className={styles.header}>
<span className={styles.title}>使</span> <span className={styles.title}>使</span>
<span className={styles.desc}>
python3javaScriptshelltypescript A
timed task management panel that supports typescript, javaScript,
python3, and shell.
</span>
</div> </div>
<div className={styles.action}> <div className={styles.action}>
<Button <Button
@@ -214,7 +219,7 @@ const Initialization = () => {
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
history.push('/login'); window.location.reload();
}} }}
> >
+3 -3
View File
@@ -47,9 +47,8 @@ const CheckUpdate = ({ socketMessage, systemInfo }: any) => {
</div> </div>
</> </>
), ),
okText: '确认', okText: '强制更新',
cancelText: '强制更新', onOk() {
onCancel() {
showUpdatingModal(); showUpdatingModal();
request request
.put(`${config.apiPrefix}system/update`) .put(`${config.apiPrefix}system/update`)
@@ -103,6 +102,7 @@ const CheckUpdate = ({ socketMessage, systemInfo }: any) => {
width: 600, width: 600,
maskClosable: false, maskClosable: false,
closable: false, closable: false,
keyboard: false,
okButtonProps: { disabled: true }, okButtonProps: { disabled: true },
title: '更新中...', title: '更新中...',
centered: true, centered: true,
-8
View File
@@ -27,11 +27,3 @@
} }
} }
} }
.ql-setting-container {
.ant-tabs-content-holder {
max-height: calc(100vh - 114px);
max-height: calc(100vh - var(--vh-offset, 114px));
overflow-y: auto;
}
}
+3 -12
View File
@@ -49,13 +49,11 @@ const Setting = () => {
title: '名称', title: '名称',
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
align: 'center' as const,
}, },
{ {
title: 'Client ID', title: 'Client ID',
dataIndex: 'client_id', dataIndex: 'client_id',
key: 'client_id', key: 'client_id',
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return <Text copyable>{record.client_id}</Text>; return <Text copyable>{record.client_id}</Text>;
}, },
@@ -64,7 +62,6 @@ const Setting = () => {
title: 'Client Secret', title: 'Client Secret',
dataIndex: 'client_secret', dataIndex: 'client_secret',
key: 'client_secret', key: 'client_secret',
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return <Text copyable={{ text: record.client_secret }}>*******</Text>; return <Text copyable={{ text: record.client_secret }}>*******</Text>;
}, },
@@ -73,22 +70,16 @@ const Setting = () => {
title: '权限', title: '权限',
dataIndex: 'scopes', dataIndex: 'scopes',
key: 'scopes', key: 'scopes',
align: 'center' as const,
width: '40%', width: '40%',
render: (text: string, record: any) => { render: (text: string, record: any) => {
return ( return record.scopes.map((scope: any) => {
<div style={{ textAlign: 'left' }}> return <Tag key={scope}>{(config.scopesMap as any)[scope]}</Tag>;
{record.scopes.map((scope: any) => { });
return <Tag key={scope}>{(config.scopesMap as any)[scope]}</Tag>;
})}
</div>
);
}, },
}, },
{ {
title: '操作', title: '操作',
key: 'action', key: 'action',
align: 'center' as const,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
const isPc = !isPhone; const isPc = !isPhone;
return ( return (
+3 -6
View File
@@ -18,7 +18,6 @@ enum LoginStatusColor {
const columns = [ const columns = [
{ {
title: '序号', title: '序号',
align: 'center' as const,
width: 50, width: 50,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
return index + 1; return index + 1;
@@ -28,7 +27,6 @@ const columns = [
title: '登录时间', title: '登录时间',
dataIndex: 'timestamp', dataIndex: 'timestamp',
key: 'timestamp', key: 'timestamp',
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return new Date(record.timestamp).toLocaleString(); return new Date(record.timestamp).toLocaleString();
}, },
@@ -37,25 +35,23 @@ const columns = [
title: '登录地址', title: '登录地址',
dataIndex: 'address', dataIndex: 'address',
key: 'address', key: 'address',
align: 'center' as const,
}, },
{ {
title: '登录IP', title: '登录IP',
dataIndex: 'ip', dataIndex: 'ip',
key: 'ip', key: 'ip',
align: 'center' as const,
}, },
{ {
title: '登录设备', title: '登录设备',
dataIndex: 'platform', dataIndex: 'platform',
key: 'platform', key: 'platform',
align: 'center' as const, width: 80,
}, },
{ {
title: '登录状态', title: '登录状态',
dataIndex: 'status', dataIndex: 'status',
key: 'status', key: 'status',
align: 'center' as const, width: 80,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return ( return (
<Tag color={LoginStatusColor[record.status]} style={{ marginRight: 0 }}> <Tag color={LoginStatusColor[record.status]} style={{ marginRight: 0 }}>
@@ -76,6 +72,7 @@ const LoginLog = ({ data }: any) => {
rowKey="id" rowKey="id"
size="middle" size="middle"
scroll={{ x: 768 }} scroll={{ x: 768 }}
sticky
/> />
</> </>
); );
+11 -5
View File
@@ -12,6 +12,7 @@ const NotificationSetting = ({ data }: any) => {
const [form] = Form.useForm(); const [form] = Form.useForm();
const handleOk = (values: any) => { const handleOk = (values: any) => {
setLoading(true);
const { type } = values; const { type } = values;
if (type == 'closed') { if (type == 'closed') {
values.type = ''; values.type = '';
@@ -30,7 +31,8 @@ const NotificationSetting = ({ data }: any) => {
}) })
.catch((error: any) => { .catch((error: any) => {
console.log(error); console.log(error);
}); })
.finally(() => setLoading(false));
}; };
const notificationModeChange = (value: string) => { const notificationModeChange = (value: string) => {
@@ -56,7 +58,7 @@ const NotificationSetting = ({ data }: any) => {
style={{ maxWidth: 400 }} style={{ maxWidth: 400 }}
initialValue={notificationMode} initialValue={notificationMode}
> >
<Select onChange={notificationModeChange}> <Select onChange={notificationModeChange} disabled={loading}>
{config.notificationModes.map((x) => ( {config.notificationModes.map((x) => (
<Option key={x.value} value={x.value}> <Option key={x.value} value={x.value}>
{x.label} {x.label}
@@ -74,7 +76,10 @@ const NotificationSetting = ({ data }: any) => {
style={{ maxWidth: 400 }} style={{ maxWidth: 400 }}
> >
{x.items ? ( {x.items ? (
<Select placeholder={x.placeholder || `请选择${x.label}`}> <Select
placeholder={x.placeholder || `请选择${x.label}`}
disabled={loading}
>
{x.items.map((y) => ( {x.items.map((y) => (
<Option key={y.value} value={y.value}> <Option key={y.value} value={y.value}>
{y.label || y.value} {y.label || y.value}
@@ -83,14 +88,15 @@ const NotificationSetting = ({ data }: any) => {
</Select> </Select>
) : ( ) : (
<Input.TextArea <Input.TextArea
disabled={loading}
autoSize={true} autoSize={true}
placeholder={x.placeholder || `请输入${x.label}`} placeholder={x.placeholder || `请输入${x.label}`}
/> />
)} )}
</Form.Item> </Form.Item>
))} ))}
<Button type="primary" htmlType="submit"> <Button type="primary" htmlType="submit" disabled={loading}>
{loading ? '测试中...' : '保存'}
</Button> </Button>
</Form> </Form>
</div> </div>
-9
View File
@@ -68,7 +68,6 @@ const Subscription = () => {
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
width: 150, width: 150,
align: 'center' as const,
sorter: { sorter: {
compare: (a: any, b: any) => a.name.localeCompare(b.name), compare: (a: any, b: any) => a.name.localeCompare(b.name),
multiple: 2, multiple: 2,
@@ -78,7 +77,6 @@ const Subscription = () => {
title: '链接', title: '链接',
dataIndex: 'url', dataIndex: 'url',
key: 'url', key: 'url',
align: 'center' as const,
sorter: { sorter: {
compare: (a: any, b: any) => a.name.localeCompare(b.name), compare: (a: any, b: any) => a.name.localeCompare(b.name),
multiple: 2, multiple: 2,
@@ -89,7 +87,6 @@ const Subscription = () => {
style={{ style={{
wordBreak: 'break-all', wordBreak: 'break-all',
marginBottom: 0, marginBottom: 0,
textAlign: 'left',
}} }}
ellipsis={{ tooltip: text, rows: 2 }} ellipsis={{ tooltip: text, rows: 2 }}
> >
@@ -103,7 +100,6 @@ const Subscription = () => {
dataIndex: 'type', dataIndex: 'type',
key: 'type', key: 'type',
width: 130, width: 130,
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return (SubscriptionType as any)[record.type]; return (SubscriptionType as any)[record.type];
}, },
@@ -113,7 +109,6 @@ const Subscription = () => {
dataIndex: 'branch', dataIndex: 'branch',
key: 'branch', key: 'branch',
width: 130, width: 130,
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return record.branch || '-'; return record.branch || '-';
}, },
@@ -121,7 +116,6 @@ const Subscription = () => {
{ {
title: '定时规则', title: '定时规则',
width: 180, width: 180,
align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
if (record.schedule_type === 'interval') { if (record.schedule_type === 'interval') {
const { type, value } = record.interval_schedule; const { type, value } = record.interval_schedule;
@@ -134,7 +128,6 @@ const Subscription = () => {
title: '状态', title: '状态',
key: 'status', key: 'status',
dataIndex: 'status', dataIndex: 'status',
align: 'center' as const,
width: 110, width: 110,
filters: [ filters: [
{ {
@@ -189,7 +182,6 @@ const Subscription = () => {
{ {
title: '操作', title: '操作',
key: 'action', key: 'action',
align: 'center' as const,
width: 130, width: 130,
render: (text: string, record: any, index: number) => { render: (text: string, record: any, index: number) => {
const isPc = !isPhone; const isPc = !isPhone;
@@ -424,7 +416,6 @@ const Subscription = () => {
index: number; index: number;
}> = ({ record, index }) => ( }> = ({ record, index }) => (
<Dropdown <Dropdown
arrow={{ pointAtCenter: true }}
placement="bottomRight" placement="bottomRight"
trigger={['click']} trigger={['click']}
menu={{ menu={{
+3 -2
View File
@@ -243,6 +243,7 @@ const SubscriptionModal = ({
if (text.startsWith('ql ')) { if (text.startsWith('ql ')) {
e.preventDefault(); e.preventDefault();
} }
onPaste(e);
}, []); }, []);
const formatParams = (sub) => { const formatParams = (sub) => {
@@ -294,9 +295,9 @@ const SubscriptionModal = ({
confirmLoading={loading} confirmLoading={loading}
> >
<Form form={form} name="form_in_modal" layout="vertical"> <Form form={form} name="form_in_modal" layout="vertical">
<Form.Item name="name" label="名称"> <Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input <Input
placeholder="支持拷贝ql repo/raw命令,粘贴导入" placeholder="支持拷贝 ql repo/raw 命令,粘贴导入"
onPaste={onNamePaste} onPaste={onNamePaste}
/> />
</Form.Item> </Form.Item>
+5 -3
View File
@@ -1,6 +1,8 @@
const baseUrl = window.__ENV__QlBaseUrl || '/';
export default { export default {
siteName: '青龙控制面板', siteName: '青龙',
apiPrefix: '/api/', apiPrefix: `${baseUrl}api/`,
authKey: 'token', authKey: 'token',
/* Layout configuration, specify which layout to use for route. */ /* Layout configuration, specify which layout to use for route. */
@@ -91,7 +93,7 @@ export default {
{ value: 'aibotk', label: '智能微秘书' }, { value: 'aibotk', label: '智能微秘书' },
{ value: 'iGot', label: 'IGot' }, { value: 'iGot', label: 'IGot' },
{ value: 'pushPlus', label: 'PushPlus' }, { value: 'pushPlus', label: 'PushPlus' },
{ value: 'chat', label: '群chat' }, { value: 'chat', label: '群chat' },
{ value: 'email', label: '邮箱' }, { value: 'email', label: '邮箱' },
{ value: 'lark', label: '飞书机器人' }, { value: 'lark', label: '飞书机器人' },
{ value: 'webhook', label: '自定义通知' }, { value: 'webhook', label: '自定义通知' },
+4 -2
View File
@@ -4,7 +4,7 @@ import browserType from './index';
export const useCtx = () => { export const useCtx = () => {
const [width, setWidth] = useState('100%'); const [width, setWidth] = useState('100%');
const [marginLeft, setMarginLeft] = useState(0); const [marginLeft, setMarginLeft] = useState(0);
const [marginTop, setMarginTop] = useState(-72); const [marginTop, setMarginTop] = useState(-48);
const [isPhone, setIsPhone] = useState(false); const [isPhone, setIsPhone] = useState(false);
const { platform } = useMemo(() => browserType(), []); const { platform } = useMemo(() => browserType(), []);
@@ -14,11 +14,13 @@ export const useCtx = () => {
setMarginLeft(0); setMarginLeft(0);
setMarginTop(0); setMarginTop(0);
setIsPhone(true); setIsPhone(true);
document.body.setAttribute('data-mode', 'phone');
} else { } else {
setWidth('100%'); setWidth('100%');
setMarginLeft(0); setMarginLeft(0);
setMarginTop(-72); setMarginTop(-48);
setIsPhone(false); setIsPhone(false);
document.body.setAttribute('data-mode', 'desktop');
} }
}, []); }, []);
+10 -3
View File
@@ -4,7 +4,7 @@ import config from './config';
import { history } from '@umijs/max'; import { history } from '@umijs/max';
message.config({ message.config({
duration: 1.5, duration: 2,
}); });
const time = Date.now(); const time = Date.now();
@@ -23,7 +23,10 @@ const errorHandler = function (error: any) {
history.push('/login'); history.push('/login');
} }
} else { } else {
message.error(msg); message.error({
content: msg,
style: { maxWidth: 500, margin: '0 auto' },
});
} }
} else { } else {
console.log(error.message); console.log(error.message);
@@ -66,7 +69,11 @@ _request.interceptors.response.use(async (response) => {
const res = await response.clone().json(); const res = await response.clone().json();
if (res.code !== 200) { if (res.code !== 200) {
const msg = res.message || res.data; const msg = res.message || res.data;
msg && message.error(msg); msg &&
message.error({
content: msg,
style: { maxWidth: 500, margin: '0 auto' },
});
} }
return res; return res;
} }
+1 -1
View File
@@ -183,7 +183,7 @@ export function getTableScroll({
extraHeight, extraHeight,
target, target,
}: { extraHeight?: number; target?: HTMLElement } = {}) { }: { extraHeight?: number; target?: HTMLElement } = {}) {
if (typeof extraHeight == 'undefined') { if (typeof extraHeight === 'undefined') {
// 47 + 40 + 12 // 47 + 40 + 12
extraHeight = 99; extraHeight = 99;
} }
+3 -2
View File
@@ -1,7 +1,6 @@
import * as Sentry from '@sentry/react'; import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing'; import { Integrations } from '@sentry/tracing';
import { loader } from '@monaco-editor/react'; import { loader } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
export function init(version: string) { export function init(version: string) {
// sentry监控 init // sentry监控 init
@@ -27,7 +26,9 @@ export function init(version: string) {
// monaco 编辑器配置cdn和locale // monaco 编辑器配置cdn和locale
loader.config({ loader.config({
monaco, paths: {
vs: 'https://cdn.staticfile.org/monaco-editor/0.33.0/min/vs',
},
'vs/nls': { 'vs/nls': {
availableLanguages: { availableLanguages: {
'*': 'zh-cn', '*': 'zh-cn',
+4
View File
@@ -10,3 +10,7 @@ declare module '*.svg' {
} }
declare module 'pstree.remy'; declare module 'pstree.remy';
interface Window {
__ENV__QlBaseUrl: string;
}
+5 -9
View File
@@ -1,10 +1,6 @@
version: 2.15.8 version: 2.15.15
changeLogLink: https://t.me/jiao_long/364 changeLogLink: https://t.me/jiao_long/376
changeLog: | changeLog: |
1. 修复环境变量位置重置逻辑 1. 支持非跟目录部署,启动时增加参数 -e QlBaseUrl="/test/",参数前后需要斜杠
2. 日志名称增加毫秒 2. 修复 task 执行可执行文件路径,感谢 https://github.com/jzksnsjswkw
3. 修复添加文件类型订阅 3. 其他 bug 修复
4. 修复订阅生成 ssh 配置逻辑
5. 任务增加关联订阅
6. 修复订阅自动增加/删除任务参数默认值
7. 其他优化