mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
924dfd6a6f | ||
|
|
07f43538df | ||
|
|
4fa5fa2014 | ||
|
|
f9b9543a6d | ||
|
|
af97543918 | ||
|
|
a508522872 | ||
|
|
f1ca2134b7 | ||
|
|
a9755655b2 | ||
|
|
6a76e82f26 | ||
|
|
6775f5d123 | ||
|
|
ad6e08525c | ||
|
|
51ef4e7476 | ||
|
|
e5b35273f9 | ||
|
|
647ed3b66c | ||
|
|
4667af4ebe | ||
|
|
3f775a0e6c | ||
|
|
fa79de3f05 | ||
|
|
ffa8b25a66 | ||
|
|
05f8bbd26e | ||
|
|
7d43b14f81 | ||
|
|
cecc5aeb15 | ||
|
|
43d6ac2071 | ||
|
|
678e3e2dc6 | ||
|
|
75f91e1473 | ||
|
|
bdc45c538c | ||
|
|
955c7377d7 | ||
|
|
c71abd8c86 | ||
|
|
ab27a4c908 | ||
|
|
026640a757 | ||
|
|
a1501705c1 | ||
|
|
b321530dcf | ||
|
|
02c6ad8004 | ||
|
|
fff572869e |
+11
-11
@@ -2,22 +2,22 @@
|
|||||||
**/*.svg
|
**/*.svg
|
||||||
**/*.ejs
|
**/*.ejs
|
||||||
**/*.html
|
**/*.html
|
||||||
.umi
|
/.umi
|
||||||
.umi-production
|
/.umi-production
|
||||||
.umi-test
|
/.umi-test
|
||||||
.history
|
/.history
|
||||||
.tmp
|
/.tmp
|
||||||
node_modules
|
/node_modules
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-error.log
|
yarn-error.log
|
||||||
yarn.lock
|
yarn.lock
|
||||||
package-lock.json
|
package-lock.json
|
||||||
static
|
/static
|
||||||
data
|
/data
|
||||||
DS_Store
|
DS_Store
|
||||||
src/.umi
|
/src/.umi
|
||||||
src/.umi-production
|
/src/.umi-production
|
||||||
src/.umi-test
|
/src/.umi-test
|
||||||
.env.local
|
.env.local
|
||||||
.env
|
.env
|
||||||
version.ts
|
version.ts
|
||||||
|
|||||||
@@ -43,19 +43,12 @@ export default defineConfig({
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}) as any,
|
}) as any,
|
||||||
externals: {
|
headScripts: [`./api/env.js`],
|
||||||
react: 'window.React',
|
|
||||||
'react-dom': 'window.ReactDOM',
|
|
||||||
},
|
|
||||||
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-dom/18.2.0/umd/react-dom.production.min.js',
|
|
||||||
],
|
|
||||||
copy: [
|
copy: [
|
||||||
{
|
{
|
||||||
from: 'node_modules/monaco-editor/min/vs',
|
from: 'node_modules/monaco-editor/min/vs',
|
||||||
to: 'static/dist/monaco-editor/min/vs',
|
to: 'static/dist/monaco-editor/min/vs',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
npmClient: 'pnpm',
|
||||||
});
|
});
|
||||||
|
|||||||
+4
-127
@@ -56,138 +56,15 @@ npm i @whyour/qinglong
|
|||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
|
|
||||||
### Docker (Recommended)
|
[View Documentation](https://qinglong.online/guide/getting-started/installation-guide)
|
||||||
|
|
||||||
```bash
|
## Built-in API
|
||||||
# curl -sSL get.docker.com | sh
|
|
||||||
docker run -dit \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
# The 5700 after the colon is the default port, if QlPort is set, it needs to be the same as QlPort.
|
|
||||||
-p 5700:5700 \
|
|
||||||
# Deployment paths are not required, e.g. /test.
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# Deployment port is not required, when using host mode, you can set the port after service startup, default 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
--restart unless-stopped \
|
|
||||||
whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### BaoTa Panel one-click deployment (Recommended)
|
[View Documentation](https://qinglong.online/guide/user-guide/built-in-api)
|
||||||
|
|
||||||
1. To install Pagoda Panel, go to the official website of [BaoTa Panel](https://www.bt.cn/u/EcDAFU), select the official version of the script to download and install.
|
|
||||||
|
|
||||||
2. After installation, login to Pagoda Panel, click `Docker` in the menu bar, the first time you enter, you will be prompted to install `Docker` service, click Install Now, follow the prompts to complete the installation.
|
|
||||||
|
|
||||||
3. After the installation is complete, find `Qinglong Panel` in the app shop, click Install, configure the domain name and other basic information to complete the installation.
|
|
||||||
|
|
||||||
### Docker-compose (Recommended)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
|
||||||
mkdir qinglong
|
|
||||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
|
||||||
|
|
||||||
# start
|
|
||||||
docker-compose up -d
|
|
||||||
# stop
|
|
||||||
docker-compose down
|
|
||||||
```
|
|
||||||
|
|
||||||
### Podman (Recommended)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# https://podman.io/getting-started/installation
|
|
||||||
podman run -dit \
|
|
||||||
--network bridge \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
# The 5700 after the colon is the default port, if QlPort is set, it needs to be the same as QlPort.
|
|
||||||
-p 5700:5700 \
|
|
||||||
# Deployment paths are not required, e.g. /test.
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# Deployment port is not required, when using host mode, you can set the port after service startup, default 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
docker.io/whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Npm (Local)
|
|
||||||
|
|
||||||
It is recommended to use a pure system installation to avoid losing the original system data, you need to install node/npm/python3/pip3/pnpm yourself
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Debian/Ubuntu
|
|
||||||
curl -sL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install -g node-pre-gyp pnpm@8.3.1
|
|
||||||
npm install -g @whyour/qinglong
|
|
||||||
qinglong
|
|
||||||
# Add the environment variables QL_DIR and QL_DATA_DIR when prompted
|
|
||||||
export QL_DIR=""
|
|
||||||
export QL_DATA_DIR=""
|
|
||||||
# Run again
|
|
||||||
qinglong
|
|
||||||
```
|
|
||||||
|
|
||||||
## Built-in commands
|
## Built-in commands
|
||||||
|
|
||||||
- task
|
[View Documentation](https://qinglong.online/guide/user-guide/basic-explanation)
|
||||||
|
|
||||||
```bash
|
|
||||||
# Execute in sequence, if a random delay is set, it will be randomly delayed by a certain number of seconds
|
|
||||||
task <file_path>
|
|
||||||
# Execute in sequence, regardless of whether a random delay is set, all run immediately,
|
|
||||||
# and the foreground will output the day, while recorded in the log file
|
|
||||||
task <file_path> now
|
|
||||||
# Concurrent execution, regardless of whether a random delay is set, are run immediately,
|
|
||||||
# the foreground does not generate the day, directly recorded in the log file, and can be specified account execution
|
|
||||||
task <file_path> conc <env_name> <account_number>(Optional)
|
|
||||||
# Specify the account to execute and run immediately regardless of whether a random delay is set
|
|
||||||
task <file_path> desi <env_name> <account_number>
|
|
||||||
# Set task timeout
|
|
||||||
task -m <max_time> <file_path>
|
|
||||||
# Use -- to split, -- followed by a parameter that is passed to the script, as in the following example, the script receives the parameter -u whyour -p password
|
|
||||||
task <file_path> -- -u whyour -p password
|
|
||||||
```
|
|
||||||
|
|
||||||
- ql
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Update and restart Green Dragon
|
|
||||||
ql update
|
|
||||||
# Run custom scripts extra.sh
|
|
||||||
ql extra
|
|
||||||
# Adding a single script file
|
|
||||||
ql raw <file_url>
|
|
||||||
# Add a specific script for a single repository
|
|
||||||
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch>
|
|
||||||
# Delete old logs
|
|
||||||
ql rmlog <days>
|
|
||||||
# Start bot
|
|
||||||
ql bot
|
|
||||||
# Detecting the Green Dragon environment and repairing it
|
|
||||||
ql check
|
|
||||||
# Reset the number of login errors
|
|
||||||
ql resetlet
|
|
||||||
# Disable two-step login
|
|
||||||
ql resettfa
|
|
||||||
```
|
|
||||||
|
|
||||||
| **Parameter** | **Description** |
|
|
||||||
|---|---|
|
|
||||||
| file_url | Script address |
|
|
||||||
| repo_url | Repository address |
|
|
||||||
| whitelist | The whitelist when pulling the repository, i.e., the string contained in the path of the script to be pulled |
|
|
||||||
| blacklist | Blacklisting when pulling repositories, i.e. strings that are not included in the path of the script to be pulled |
|
|
||||||
| dependence | Pulling the dependencies needed for the repository will be copied directly from the repository to the repository directory under scripts, regardless of the blacklist |
|
|
||||||
| extensions | Pull the branch of the repository |
|
|
||||||
| branch | Number of days of logs to be kept |
|
|
||||||
| days | File path for task execution |
|
|
||||||
| file_path | The name of the environment variable that needs to be concurrent or specified at the time of task execution |
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
|
|||||||
@@ -58,136 +58,15 @@ npm i @whyour/qinglong
|
|||||||
|
|
||||||
## 部署
|
## 部署
|
||||||
|
|
||||||
### docker (推荐)
|
[查看文档](https://qinglong.online/guide/getting-started/installation-guide)
|
||||||
|
|
||||||
```bash
|
## 内置 API
|
||||||
# curl -sSL get.docker.com | sh
|
|
||||||
docker run -dit \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
# 冒号后面的 5700 为默认端口,如果设置了 QlPort, 需要跟 QlPort 保持一致
|
|
||||||
-p 5700:5700 \
|
|
||||||
# 部署路径非必须,比如 /test
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# 部署端口非必须,当使用 host 模式时,可以设置服务启动后的端口,默认 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
--restart unless-stopped \
|
|
||||||
whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 宝塔面板一键部署(推荐)
|
[查看文档](https://qinglong.online/guide/user-guide/built-in-api)
|
||||||
|
|
||||||
1. 安装宝塔面板,前往 [宝塔面板](https://www.bt.cn/u/EcDAFU) 官网,选择正式版的脚本下载安装
|
|
||||||
|
|
||||||
2. 安装后登录宝塔面板,在菜单栏中点击 `Docker`,首次进入会提示安装`Docker`服务,点击立即安装,按提示完成安装
|
|
||||||
|
|
||||||
3. 安装完成后在应用商店中找到`青龙面板`,点击安装,配置域名等基本信息即可完成安装
|
|
||||||
|
|
||||||
### docker-compose (推荐)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
|
|
||||||
mkdir qinglong
|
|
||||||
wget https://raw.githubusercontent.com/whyour/qinglong/master/docker/docker-compose.yml
|
|
||||||
|
|
||||||
# 启动
|
|
||||||
docker-compose up -d
|
|
||||||
# 停止
|
|
||||||
docker-compose down
|
|
||||||
```
|
|
||||||
|
|
||||||
### podman (推荐)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# https://podman.io/getting-started/installation
|
|
||||||
podman run -dit \
|
|
||||||
--network bridge \
|
|
||||||
-v $PWD/ql/data:/ql/data \
|
|
||||||
# 冒号后面的 5700 为默认端口,如果设置了 QlPort, 需要跟 QlPort 保持一致
|
|
||||||
-p 5700:5700 \
|
|
||||||
# 部署路径非必须,比如 /test
|
|
||||||
-e QlBaseUrl="/" \
|
|
||||||
# 部署端口非必须,当使用 host 模式时,可以设置服务启动后的端口,默认 5700
|
|
||||||
-e QlPort="5700" \
|
|
||||||
--name qinglong \
|
|
||||||
--hostname qinglong \
|
|
||||||
docker.io/whyour/qinglong:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### npm (本地)
|
|
||||||
|
|
||||||
建议使用纯净系统安装,避免系统原有数据丢失,需要自己安装 node/npm/python3/pip3/pnpm
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Debian/Ubuntu
|
|
||||||
curl -sL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install -g node-pre-gyp pnpm@8.3.1
|
|
||||||
npm install -g @whyour/qinglong
|
|
||||||
qinglong
|
|
||||||
# 根据提示增加环境变量 QL_DIR 和 QL_DATA_DIR
|
|
||||||
export QL_DIR=""
|
|
||||||
export QL_DATA_DIR=""
|
|
||||||
# 再次执行
|
|
||||||
qinglong
|
|
||||||
```
|
|
||||||
|
|
||||||
## 内置命令
|
## 内置命令
|
||||||
|
|
||||||
- task
|
[查看文档](https://qinglong.online/guide/user-guide/basic-explanation)
|
||||||
|
|
||||||
```bash
|
|
||||||
# 依次执行,如果设置了随机延迟,将随机延迟一定秒数
|
|
||||||
task <file_path>
|
|
||||||
# 依次执行,无论是否设置了随机延迟,均立即运行,前台会输出日,同时记录在日志文件中
|
|
||||||
task <file_path> now
|
|
||||||
# 并发执行,无论是否设置了随机延迟,均立即运行,前台不产生日,直接记录在日志文件中,且可指定账号执行
|
|
||||||
task <file_path> conc <env_name> <account_number>(可选的)
|
|
||||||
# 指定账号执行,无论是否设置了随机延迟,均立即运行
|
|
||||||
task <file_path> desi <env_name> <account_number>
|
|
||||||
# 设置任务超时时间
|
|
||||||
task -m <max_time> <file_path>
|
|
||||||
# 使用 -- 分割,-- 后面的参数会传给脚本,下面的例子,脚本就可接收到参数 -u whyour -p password
|
|
||||||
task <file_path> -- -u whyour -p password
|
|
||||||
```
|
|
||||||
|
|
||||||
- ql
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 更新并重启青龙
|
|
||||||
ql update
|
|
||||||
# 运行自定义脚本extra.sh
|
|
||||||
ql extra
|
|
||||||
# 添加单个脚本文件
|
|
||||||
ql raw <file_url>
|
|
||||||
# 添加单个仓库的指定脚本
|
|
||||||
ql repo <repo_url> <whitelist> <blacklist> <dependence> <branch> <extensions>
|
|
||||||
# 删除旧日志
|
|
||||||
ql rmlog <days>
|
|
||||||
# 启动tg-bot
|
|
||||||
ql bot
|
|
||||||
# 检测青龙环境并修复
|
|
||||||
ql check
|
|
||||||
# 重置登录错误次数
|
|
||||||
ql resetlet
|
|
||||||
# 禁用两步登录
|
|
||||||
ql resettfa
|
|
||||||
```
|
|
||||||
|
|
||||||
| **参数** | **说明** |
|
|
||||||
|------------|---------------------------------------------------------------------------------------------|
|
|
||||||
| file_url | 脚本地址 |
|
|
||||||
| repo_url | 仓库地址 |
|
|
||||||
| whitelist | 拉取仓库时的白名单,即就是需要拉取的脚本的路径包含的字符串,多个竖线分割 |
|
|
||||||
| blacklist | 拉取仓库时的黑名单,即就是需要拉取的脚本的路径不包含的字符串,多个竖线分割 |
|
|
||||||
| dependence | 拉取仓库需要的依赖文件,会直接从仓库拷贝到scripts下的仓库目录,不受黑名单影响,多个竖线分割 |
|
|
||||||
| extensions | 拉取仓库的文件后缀,多个竖线分割 |
|
|
||||||
| branch | 拉取仓库的分支 |
|
|
||||||
| days | 需要保留的日志的天数 |
|
|
||||||
| file_path | 任务执行时的文件路径 |
|
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
To report a vulnerability, please open a private vulnerability report at <https://github.com/whyour/qinglong/security>.
|
||||||
|
|
||||||
|
While the discovery of new vulnerabilities is rare, we also recommend always using the latest versions of Qinglong to ensure your application remains as secure as possible.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import 'express';
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
platform: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -7,6 +7,7 @@ import { celebrate, Joi } from 'celebrate';
|
|||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import { SAMPLE_FILES } from '../config/const';
|
import { SAMPLE_FILES } from '../config/const';
|
||||||
import ConfigService from '../services/config';
|
import ConfigService from '../services/config';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
@@ -77,7 +78,7 @@ export default (app: Router) => {
|
|||||||
if (name.startsWith('data/scripts/')) {
|
if (name.startsWith('data/scripts/')) {
|
||||||
path = join(config.rootPath, name);
|
path = join(config.rootPath, name);
|
||||||
}
|
}
|
||||||
await fs.writeFile(path, content);
|
await writeFileWithLock(path, content);
|
||||||
res.send({ code: 200, message: '保存成功' });
|
res.send({ code: 200, message: '保存成功' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
|
|||||||
+2
-2
@@ -2,7 +2,7 @@ import { Router, Request, Response, NextFunction } from 'express';
|
|||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { getFileContentByName, readDirs, rmPath } from '../config/util';
|
import { getFileContentByName, readDirs, removeAnsi, rmPath } from '../config/util';
|
||||||
import { join, resolve } from 'path';
|
import { join, resolve } from 'path';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
@@ -42,7 +42,7 @@ export default (app: Router) => {
|
|||||||
return res.send({ code: 403, message: '暂无权限' });
|
return res.send({ code: 403, message: '暂无权限' });
|
||||||
}
|
}
|
||||||
const content = await getFileContentByName(finalPath);
|
const content = await getFileContentByName(finalPath);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: removeAnsi(content) });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-3
@@ -8,6 +8,7 @@ import { celebrate, Joi } from 'celebrate';
|
|||||||
import path, { join, parse } from 'path';
|
import path, { join, parse } from 'path';
|
||||||
import ScriptService from '../services/script';
|
import ScriptService from '../services/script';
|
||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@@ -156,7 +157,7 @@ export default (app: Router) => {
|
|||||||
await rmPath(originFilePath);
|
await rmPath(originFilePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await fs.writeFile(filePath, content);
|
await writeFileWithLock(filePath, content);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -182,7 +183,7 @@ export default (app: Router) => {
|
|||||||
path: string;
|
path: string;
|
||||||
};
|
};
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
const filePath = join(config.scriptPath, path, filename);
|
||||||
await fs.writeFile(filePath, content);
|
await writeFileWithLock(filePath, content);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -261,7 +262,7 @@ export default (app: Router) => {
|
|||||||
let { filename, content, path } = req.body;
|
let { filename, content, path } = req.body;
|
||||||
const { name, ext } = parse(filename);
|
const { name, ext } = parse(filename);
|
||||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||||
await fs.writeFile(filePath, content || '', { encoding: 'utf8' });
|
await writeFileWithLock(filePath, content || '');
|
||||||
|
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const result = await scriptService.runScript(filePath);
|
const result = await scriptService.runScript(filePath);
|
||||||
|
|||||||
+20
-1
@@ -33,7 +33,7 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
const authInfo = await userService.getUserInfo();
|
const authInfo = await userService.getAuthInfo();
|
||||||
const { version, changeLog, changeLogLink, publishTime } =
|
const { version, changeLog, changeLogLink, publishTime } =
|
||||||
await parseVersion(config.versionFile);
|
await parseVersion(config.versionFile);
|
||||||
|
|
||||||
@@ -377,4 +377,23 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/auth/reset',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
retries: Joi.number().optional(),
|
||||||
|
twoFactorActivated: Joi.boolean().optional(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const userService = Container.get(UserService);
|
||||||
|
await userService.resetAuthInfo(req.body);
|
||||||
|
res.send({ code: 200, message: '更新成功' });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-1
@@ -90,7 +90,7 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
const authInfo = await userService.getUserInfo();
|
const authInfo = await userService.getAuthInfo();
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import './loaders/sentry'
|
|
||||||
import 'reflect-metadata'; // We need this in order to use @Decorators
|
import 'reflect-metadata'; // We need this in order to use @Decorators
|
||||||
import config from './config';
|
import config from './config';
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ const extraFile = path.join(configPath, 'extra.sh');
|
|||||||
const confBakDir = path.join(dataPath, 'config/bak/');
|
const confBakDir = path.join(dataPath, 'config/bak/');
|
||||||
const sampleFile = path.join(samplePath, 'config.sample.sh');
|
const sampleFile = path.join(samplePath, 'config.sample.sh');
|
||||||
const sqliteFile = path.join(samplePath, 'database.sqlite');
|
const sqliteFile = path.join(samplePath, 'database.sqlite');
|
||||||
const systemNotifyFile = path.join(preloadPath, 'system-notify.json');
|
|
||||||
|
|
||||||
const authError = '错误的用户名密码,请重试';
|
const authError = '错误的用户名密码,请重试';
|
||||||
const loginFaild = '请先登录!';
|
const loginFaild = '请先登录!';
|
||||||
@@ -135,5 +134,4 @@ export default {
|
|||||||
sqliteFile,
|
sqliteFile,
|
||||||
sshdPath,
|
sshdPath,
|
||||||
systemLogPath,
|
systemLogPath,
|
||||||
systemNotifyFile,
|
|
||||||
};
|
};
|
||||||
|
|||||||
+18
-6
@@ -10,6 +10,7 @@ import { load } from 'js-yaml';
|
|||||||
import config from './index';
|
import config from './index';
|
||||||
import { TASK_COMMAND } from './const';
|
import { TASK_COMMAND } from './const';
|
||||||
import Logger from '../loaders/logger';
|
import Logger from '../loaders/logger';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
|
|
||||||
export * from './share';
|
export * from './share';
|
||||||
|
|
||||||
@@ -21,6 +22,10 @@ export async function getFileContentByName(fileName: string) {
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function removeAnsi(text: string) {
|
||||||
|
return text.replace(/\x1b\[\d+m/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
export async function getLastModifyFilePath(dir: string) {
|
export async function getLastModifyFilePath(dir: string) {
|
||||||
let filePath = '';
|
let filePath = '';
|
||||||
|
|
||||||
@@ -145,12 +150,19 @@ export function getPlatform(userAgent: string): 'mobile' | 'desktop' {
|
|||||||
system = 'android'; // android系统
|
system = 'android'; // android系统
|
||||||
} else if (testUa(/ios|iphone|ipad|ipod|iwatch/g)) {
|
} else if (testUa(/ios|iphone|ipad|ipod|iwatch/g)) {
|
||||||
system = 'ios'; // ios系统
|
system = 'ios'; // ios系统
|
||||||
|
} else if (testUa(/openharmony/g)) {
|
||||||
|
system = 'openharmony'; // openharmony系统
|
||||||
}
|
}
|
||||||
|
|
||||||
let platform = 'desktop';
|
let platform = 'desktop';
|
||||||
if (system === 'windows' || system === 'macos' || system === 'linux') {
|
if (system === 'windows' || system === 'macos' || system === 'linux') {
|
||||||
platform = 'desktop';
|
platform = 'desktop';
|
||||||
} else if (system === 'android' || system === 'ios' || testUa(/mobile/g)) {
|
} else if (
|
||||||
|
system === 'android' ||
|
||||||
|
system === 'ios' ||
|
||||||
|
system === 'openharmony' ||
|
||||||
|
testUa(/mobile/g)
|
||||||
|
) {
|
||||||
platform = 'mobile';
|
platform = 'mobile';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,7 +180,7 @@ export async function fileExist(file: any) {
|
|||||||
|
|
||||||
export async function createFile(file: string, data: string = '') {
|
export async function createFile(file: string, data: string = '') {
|
||||||
await fs.mkdir(path.dirname(file), { recursive: true });
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||||
await fs.writeFile(file, data);
|
await writeFileWithLock(file, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function handleLogPath(
|
export async function handleLogPath(
|
||||||
@@ -230,14 +242,14 @@ interface IFile {
|
|||||||
key: string;
|
key: string;
|
||||||
type: 'directory' | 'file';
|
type: 'directory' | 'file';
|
||||||
parent: string;
|
parent: string;
|
||||||
mtime: number;
|
createTime: number;
|
||||||
size?: number;
|
size?: number;
|
||||||
children?: IFile[];
|
children?: IFile[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dirSort(a: IFile, b: IFile): number {
|
export function dirSort(a: IFile, b: IFile): number {
|
||||||
if (a.type === 'file' && b.type === 'file') {
|
if (a.type === 'file' && b.type === 'file') {
|
||||||
return b.mtime - a.mtime;
|
return b.createTime - a.createTime;
|
||||||
} else if (a.type === 'directory' && b.type === 'directory') {
|
} else if (a.type === 'directory' && b.type === 'directory') {
|
||||||
return a.title.localeCompare(b.title);
|
return a.title.localeCompare(b.title);
|
||||||
} else {
|
} else {
|
||||||
@@ -271,7 +283,7 @@ export async function readDirs(
|
|||||||
key,
|
key,
|
||||||
type: 'directory',
|
type: 'directory',
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
mtime: stats.mtime.getTime(),
|
createTime: stats.birthtime.getTime(),
|
||||||
children: children.sort(sort),
|
children: children.sort(sort),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -281,7 +293,7 @@ export async function readDirs(
|
|||||||
key,
|
key,
|
||||||
parent: relativePath,
|
parent: relativePath,
|
||||||
size: stats.size,
|
size: stats.size,
|
||||||
mtime: stats.mtime.getTime(),
|
createTime: stats.birthtime.getTime(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -20,7 +20,7 @@ export class Env {
|
|||||||
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;
|
||||||
this.remarks = options.remarks;
|
this.remarks = options.remarks || '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+15
-2
@@ -21,6 +21,7 @@ export enum NotificationMode {
|
|||||||
'webhook' = 'webhook',
|
'webhook' = 'webhook',
|
||||||
'chronocat' = 'Chronocat',
|
'chronocat' = 'Chronocat',
|
||||||
'ntfy' = 'ntfy',
|
'ntfy' = 'ntfy',
|
||||||
|
'wxPusherBot' = 'wxPusherBot',
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class NotificationBaseInfo {
|
abstract class NotificationBaseInfo {
|
||||||
@@ -100,6 +101,11 @@ export class IGotNotification extends NotificationBaseInfo {
|
|||||||
export class PushPlusNotification extends NotificationBaseInfo {
|
export class PushPlusNotification extends NotificationBaseInfo {
|
||||||
public pushPlusToken = '';
|
public pushPlusToken = '';
|
||||||
public pushPlusUser = '';
|
public pushPlusUser = '';
|
||||||
|
public pushPlusTemplate = '';
|
||||||
|
public pushplusChannel = '';
|
||||||
|
public pushplusWebhook = '';
|
||||||
|
public pushplusCallbackUrl = '';
|
||||||
|
public pushplusTo = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WePlusBotNotification extends NotificationBaseInfo {
|
export class WePlusBotNotification extends NotificationBaseInfo {
|
||||||
@@ -145,6 +151,13 @@ export class NtfyNotification extends NotificationBaseInfo {
|
|||||||
public ntfyTopic = '';
|
public ntfyTopic = '';
|
||||||
public ntfyPriority = '';
|
public ntfyPriority = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class WxPusherBotNotification extends NotificationBaseInfo {
|
||||||
|
public wxPusherBotAppToken = '';
|
||||||
|
public wxPusherBotTopicIds = '';
|
||||||
|
public wxPusherBotUids = '';
|
||||||
|
}
|
||||||
|
|
||||||
export interface NotificationInfo
|
export interface NotificationInfo
|
||||||
extends GoCqHttpBotNotification,
|
extends GoCqHttpBotNotification,
|
||||||
GotifyNotification,
|
GotifyNotification,
|
||||||
@@ -165,5 +178,5 @@ export interface NotificationInfo
|
|||||||
WebhookNotification,
|
WebhookNotification,
|
||||||
ChronocatNotification,
|
ChronocatNotification,
|
||||||
LarkNotification,
|
LarkNotification,
|
||||||
NtfyNotification {}
|
NtfyNotification,
|
||||||
|
WxPusherBotNotification {}
|
||||||
|
|||||||
+1
-1
@@ -24,7 +24,7 @@ export interface AppToken {
|
|||||||
expiration: number;
|
expiration: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs';
|
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system';
|
||||||
|
|
||||||
export interface AppInstance extends Model<App, App>, App {}
|
export interface AppInstance extends Model<App, App>, App {}
|
||||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||||
|
|||||||
+22
-2
@@ -27,6 +27,7 @@ export enum AuthDataType {
|
|||||||
'notification' = 'notification',
|
'notification' = 'notification',
|
||||||
'removeLogFrequency' = 'removeLogFrequency',
|
'removeLogFrequency' = 'removeLogFrequency',
|
||||||
'systemConfig' = 'systemConfig',
|
'systemConfig' = 'systemConfig',
|
||||||
|
'authConfig' = 'authConfig',
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SystemConfigInfo {
|
export interface SystemConfigInfo {
|
||||||
@@ -46,11 +47,30 @@ export interface LoginLogInfo {
|
|||||||
status?: LoginStatus;
|
status?: LoginStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuthInfo {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
retries: number;
|
||||||
|
lastlogon: number;
|
||||||
|
lastip: string;
|
||||||
|
lastaddr: string;
|
||||||
|
platform: string;
|
||||||
|
isTwoFactorChecking: boolean;
|
||||||
|
token: string;
|
||||||
|
tokens: Record<string, string>;
|
||||||
|
twoFactorActivated: boolean;
|
||||||
|
twoFactorSecret: string;
|
||||||
|
avatar: string;
|
||||||
|
}
|
||||||
|
|
||||||
export type SystemModelInfo = SystemConfigInfo &
|
export type SystemModelInfo = SystemConfigInfo &
|
||||||
Partial<NotificationInfo> &
|
Partial<NotificationInfo> &
|
||||||
LoginLogInfo;
|
LoginLogInfo &
|
||||||
|
Partial<AuthInfo>;
|
||||||
|
|
||||||
export interface SystemInstance extends Model<SystemInfo, SystemInfo>, SystemInfo { }
|
export interface SystemInstance
|
||||||
|
extends Model<SystemInfo, SystemInfo>,
|
||||||
|
SystemInfo {}
|
||||||
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
|
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
|
||||||
ip: DataTypes.STRING,
|
ip: DataTypes.STRING,
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
|
|||||||
+3
-77
@@ -1,15 +1,11 @@
|
|||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
import path from 'path';
|
|
||||||
import DataStore from 'nedb';
|
|
||||||
import { EnvModel } from '../data/env';
|
import { EnvModel } from '../data/env';
|
||||||
import { CrontabModel } from '../data/cron';
|
import { CrontabModel } from '../data/cron';
|
||||||
import { DependenceModel } from '../data/dependence';
|
import { DependenceModel } from '../data/dependence';
|
||||||
import { AppModel } from '../data/open';
|
import { AppModel } from '../data/open';
|
||||||
import { SystemModel } from '../data/system';
|
import { SystemModel } from '../data/system';
|
||||||
import { fileExist } from '../config/util';
|
|
||||||
import { SubscriptionModel } from '../data/subscription';
|
import { SubscriptionModel } from '../data/subscription';
|
||||||
import { CrontabViewModel } from '../data/cronView';
|
import { CrontabViewModel } from '../data/cronView';
|
||||||
import config from '../config';
|
|
||||||
import { sequelize } from '../data';
|
import { sequelize } from '../data';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
@@ -50,7 +46,9 @@ export default async () => {
|
|||||||
await sequelize.query('alter table Crontabs add column sub_id NUMBER');
|
await sequelize.query('alter table Crontabs add column sub_id NUMBER');
|
||||||
} catch (error) {}
|
} catch (error) {}
|
||||||
try {
|
try {
|
||||||
await sequelize.query('alter table Crontabs add column extra_schedules JSON');
|
await sequelize.query(
|
||||||
|
'alter table Crontabs add column extra_schedules JSON',
|
||||||
|
);
|
||||||
} catch (error) {}
|
} catch (error) {}
|
||||||
try {
|
try {
|
||||||
await sequelize.query('alter table Crontabs add column task_before TEXT');
|
await sequelize.query('alter table Crontabs add column task_before TEXT');
|
||||||
@@ -59,78 +57,6 @@ export default async () => {
|
|||||||
await sequelize.query('alter table Crontabs add column task_after TEXT');
|
await sequelize.query('alter table Crontabs add column task_after TEXT');
|
||||||
} catch (error) {}
|
} catch (error) {}
|
||||||
|
|
||||||
// 2.10-2.11 升级
|
|
||||||
const cronDbFile = path.join(config.rootPath, 'db/crontab.db');
|
|
||||||
const envDbFile = path.join(config.rootPath, 'db/env.db');
|
|
||||||
const appDbFile = path.join(config.rootPath, 'db/app.db');
|
|
||||||
const authDbFile = path.join(config.rootPath, 'db/auth.db');
|
|
||||||
const dependenceDbFile = path.join(config.rootPath, 'db/dependence.db');
|
|
||||||
const crondbExist = await fileExist(cronDbFile);
|
|
||||||
const dependenceDbExist = await fileExist(dependenceDbFile);
|
|
||||||
const envDbExist = await fileExist(envDbFile);
|
|
||||||
const appDbExist = await fileExist(appDbFile);
|
|
||||||
const authDbExist = await fileExist(authDbFile);
|
|
||||||
|
|
||||||
const cronCount = await CrontabModel.count();
|
|
||||||
const dependenceCount = await DependenceModel.count();
|
|
||||||
const envCount = await EnvModel.count();
|
|
||||||
const appCount = await AppModel.count();
|
|
||||||
const authCount = await SystemModel.count();
|
|
||||||
if (crondbExist && cronCount === 0) {
|
|
||||||
const cronDb = new DataStore({
|
|
||||||
filename: cronDbFile,
|
|
||||||
autoload: true,
|
|
||||||
});
|
|
||||||
cronDb.persistence.compactDatafile();
|
|
||||||
cronDb.find({}).exec(async (err, docs) => {
|
|
||||||
await CrontabModel.bulkCreate(docs, { ignoreDuplicates: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dependenceDbExist && dependenceCount === 0) {
|
|
||||||
const dependenceDb = new DataStore({
|
|
||||||
filename: dependenceDbFile,
|
|
||||||
autoload: true,
|
|
||||||
});
|
|
||||||
dependenceDb.persistence.compactDatafile();
|
|
||||||
dependenceDb.find({}).exec(async (err, docs) => {
|
|
||||||
await DependenceModel.bulkCreate(docs, { ignoreDuplicates: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (envDbExist && envCount === 0) {
|
|
||||||
const envDb = new DataStore({
|
|
||||||
filename: envDbFile,
|
|
||||||
autoload: true,
|
|
||||||
});
|
|
||||||
envDb.persistence.compactDatafile();
|
|
||||||
envDb.find({}).exec(async (err, docs) => {
|
|
||||||
await EnvModel.bulkCreate(docs, { ignoreDuplicates: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (appDbExist && appCount === 0) {
|
|
||||||
const appDb = new DataStore({
|
|
||||||
filename: appDbFile,
|
|
||||||
autoload: true,
|
|
||||||
});
|
|
||||||
appDb.persistence.compactDatafile();
|
|
||||||
appDb.find({}).exec(async (err, docs) => {
|
|
||||||
await AppModel.bulkCreate(docs, { ignoreDuplicates: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (authDbExist && authCount === 0) {
|
|
||||||
const authDb = new DataStore({
|
|
||||||
filename: authDbFile,
|
|
||||||
autoload: true,
|
|
||||||
});
|
|
||||||
authDb.persistence.compactDatafile();
|
|
||||||
authDb.find({}).exec(async (err, docs) => {
|
|
||||||
await SystemModel.bulkCreate(docs, { ignoreDuplicates: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('✌️ DB loaded');
|
console.log('✌️ DB loaded');
|
||||||
Logger.info('✌️ DB loaded');
|
Logger.info('✌️ DB loaded');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
+16
-21
@@ -3,19 +3,14 @@ import bodyParser from 'body-parser';
|
|||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
import routes from '../api';
|
import routes from '../api';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import jwt, { UnauthorizedError } from 'express-jwt';
|
import { UnauthorizedError, expressjwt } from 'express-jwt';
|
||||||
import fs from 'fs/promises';
|
import { getPlatform, getToken } from '../config/util';
|
||||||
import { getPlatform, getToken, safeJSONParse } from '../config/util';
|
|
||||||
import Container from 'typedi';
|
|
||||||
import OpenService from '../services/open';
|
|
||||||
import rewrite from 'express-urlrewrite';
|
import rewrite from 'express-urlrewrite';
|
||||||
import UserService from '../services/user';
|
|
||||||
import * as Sentry from '@sentry/node';
|
|
||||||
import { EnvModel } from '../data/env';
|
|
||||||
import { errors } from 'celebrate';
|
import { errors } from 'celebrate';
|
||||||
import { createProxyMiddleware } from 'http-proxy-middleware';
|
import { createProxyMiddleware } from 'http-proxy-middleware';
|
||||||
import { serveEnv } from '../config/serverEnv';
|
import { serveEnv } from '../config/serverEnv';
|
||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
|
import { IKeyvStore, shareStore } from '../shared/store';
|
||||||
|
|
||||||
export default ({ app }: { app: Application }) => {
|
export default ({ app }: { app: Application }) => {
|
||||||
app.set('trust proxy', 'loopback');
|
app.set('trust proxy', 'loopback');
|
||||||
@@ -29,7 +24,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
target: `http://0.0.0.0:${config.publicPort}/api`,
|
target: `http://0.0.0.0:${config.publicPort}/api`,
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
pathRewrite: { '/api/public': '' },
|
pathRewrite: { '/api/public': '' },
|
||||||
logProvider: () => Logger,
|
logger: Logger,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -37,7 +32,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
jwt({
|
expressjwt({
|
||||||
secret: config.secret,
|
secret: config.secret,
|
||||||
algorithms: ['HS384'],
|
algorithms: ['HS384'],
|
||||||
}).unless({
|
}).unless({
|
||||||
@@ -58,8 +53,10 @@ export default ({ app }: { app: Application }) => {
|
|||||||
app.use(async (req, res, next) => {
|
app.use(async (req, res, next) => {
|
||||||
const headerToken = getToken(req);
|
const headerToken = getToken(req);
|
||||||
if (req.path.startsWith('/open/')) {
|
if (req.path.startsWith('/open/')) {
|
||||||
const openService = Container.get(OpenService);
|
const apps = await shareStore.getApps();
|
||||||
const doc = await openService.findTokenByValue(headerToken);
|
const doc = apps?.filter((x) =>
|
||||||
|
x.tokens?.find((y) => y.value === headerToken),
|
||||||
|
)?.[0];
|
||||||
if (doc && doc.tokens && doc.tokens.length > 0) {
|
if (doc && doc.tokens && doc.tokens.length > 0) {
|
||||||
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
||||||
const keyMatch = req.path.match(/\/open\/([a-z]+)\/*/);
|
const keyMatch = req.path.match(/\/open\/([a-z]+)\/*/);
|
||||||
@@ -83,9 +80,9 @@ export default ({ app }: { app: Application }) => {
|
|||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await fs.readFile(config.authConfigFile, 'utf8');
|
const authInfo = await shareStore.getAuthInfo();
|
||||||
if (data && headerToken) {
|
if (authInfo && headerToken) {
|
||||||
const { token = '', tokens = {} } = safeJSONParse(data);
|
const { token = '', tokens = {} } = authInfo;
|
||||||
if (headerToken === token || tokens[req.platform] === headerToken) {
|
if (headerToken === token || tokens[req.platform] === headerToken) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
@@ -103,8 +100,8 @@ export default ({ app }: { app: Application }) => {
|
|||||||
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {
|
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
const userService = Container.get(UserService);
|
const authInfo =
|
||||||
const authInfo = await userService.getUserInfo();
|
(await shareStore.getAuthInfo()) || ({} as IKeyvStore['authInfo']);
|
||||||
|
|
||||||
let isInitialized = true;
|
let isInitialized = true;
|
||||||
if (
|
if (
|
||||||
@@ -133,8 +130,6 @@ export default ({ app }: { app: Application }) => {
|
|||||||
|
|
||||||
app.use(errors());
|
app.use(errors());
|
||||||
|
|
||||||
Sentry.setupExpressErrorHandler(app);
|
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
err: Error & { status: number },
|
err: Error & { status: number },
|
||||||
@@ -164,8 +159,8 @@ export default ({ app }: { app: Application }) => {
|
|||||||
.status(500)
|
.status(500)
|
||||||
.send({
|
.send({
|
||||||
code: 400,
|
code: 400,
|
||||||
message: `${err.name} ${err.message}`,
|
message: `${err.message}`,
|
||||||
validation: err.errors,
|
errors: err.errors,
|
||||||
})
|
})
|
||||||
.end();
|
.end();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,12 @@ import { initPosition } from '../data/env';
|
|||||||
import { AuthDataType, SystemModel } from '../data/system';
|
import { AuthDataType, SystemModel } from '../data/system';
|
||||||
import SystemService from '../services/system';
|
import SystemService from '../services/system';
|
||||||
import UserService from '../services/user';
|
import UserService from '../services/user';
|
||||||
import { writeFile } from 'fs/promises';
|
import { writeFile, readFile } from 'fs/promises';
|
||||||
|
import { createRandomString, safeJSONParse } from '../config/util';
|
||||||
|
import OpenService from '../services/open';
|
||||||
|
import { shareStore } from '../shared/store';
|
||||||
|
import Logger from './logger';
|
||||||
|
import { AppModel } from '../data/open';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
@@ -20,14 +25,48 @@ export default async () => {
|
|||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
|
const openService = Container.get(OpenService);
|
||||||
|
|
||||||
// 初始化增加系统配置
|
// 初始化增加系统配置
|
||||||
await SystemModel.upsert({ type: AuthDataType.systemConfig });
|
let systemApp = (
|
||||||
await SystemModel.upsert({ type: AuthDataType.notification });
|
await AppModel.findOne({
|
||||||
|
where: { name: 'system' },
|
||||||
// 初始化通知配置
|
})
|
||||||
const notifyConfig = await userService.getNotificationMode();
|
)?.get({ plain: true });
|
||||||
await writeFile(config.systemNotifyFile, JSON.stringify(notifyConfig));
|
if (!systemApp) {
|
||||||
|
systemApp = await AppModel.create({
|
||||||
|
name: 'system',
|
||||||
|
scopes: ['crons', 'system'],
|
||||||
|
client_id: createRandomString(12, 12),
|
||||||
|
client_secret: createRandomString(24, 24),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const [systemConfig] = await SystemModel.findOrCreate({
|
||||||
|
where: { type: AuthDataType.systemConfig },
|
||||||
|
});
|
||||||
|
await SystemModel.findOrCreate({
|
||||||
|
where: { type: AuthDataType.notification },
|
||||||
|
});
|
||||||
|
const [authConfig] = await SystemModel.findOrCreate({
|
||||||
|
where: { type: AuthDataType.authConfig },
|
||||||
|
});
|
||||||
|
if (!authConfig?.info) {
|
||||||
|
let authInfo = {
|
||||||
|
username: 'admin',
|
||||||
|
password: 'admin',
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const content = await readFile(config.authConfigFile, 'utf8');
|
||||||
|
authInfo = safeJSONParse(content);
|
||||||
|
} catch (error) {
|
||||||
|
Logger.warn('Failed to read auth config file, using default credentials');
|
||||||
|
}
|
||||||
|
await SystemModel.upsert({
|
||||||
|
id: authConfig?.id,
|
||||||
|
info: authInfo,
|
||||||
|
type: AuthDataType.authConfig,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const installDependencies = () => {
|
const installDependencies = () => {
|
||||||
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
// 初始化时安装所有处于安装中,安装成功,安装失败的依赖
|
||||||
@@ -50,7 +89,6 @@ export default async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 初始化更新 linux/python/nodejs 镜像源配置
|
// 初始化更新 linux/python/nodejs 镜像源配置
|
||||||
const systemConfig = await systemService.getSystemConfig();
|
|
||||||
if (systemConfig.info?.pythonMirror) {
|
if (systemConfig.info?.pythonMirror) {
|
||||||
systemService.updatePythonMirror({
|
systemService.updatePythonMirror({
|
||||||
pythonMirror: systemConfig.info?.pythonMirror,
|
pythonMirror: systemConfig.info?.pythonMirror,
|
||||||
@@ -169,4 +207,11 @@ export default async () => {
|
|||||||
// 初始化保存一次ck和定时任务数据
|
// 初始化保存一次ck和定时任务数据
|
||||||
await cronService.autosave_crontab();
|
await cronService.autosave_crontab();
|
||||||
await envService.set_envs();
|
await envService.set_envs();
|
||||||
|
|
||||||
|
const authInfo = await userService.getAuthInfo();
|
||||||
|
const apps = await openService.findApps();
|
||||||
|
await shareStore.updateAuthInfo(authInfo);
|
||||||
|
if (apps?.length) {
|
||||||
|
await shareStore.updateApps(apps);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
+77
-103
@@ -3,6 +3,7 @@ import path from 'path';
|
|||||||
import os from 'os';
|
import os from 'os';
|
||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
import { fileExist } from '../config/util';
|
import { fileExist } from '../config/util';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
|
|
||||||
const rootPath = process.env.QL_DIR as string;
|
const rootPath = process.env.QL_DIR as string;
|
||||||
let dataPath = path.join(rootPath, 'data/');
|
let dataPath = path.join(rootPath, 'data/');
|
||||||
@@ -20,9 +21,7 @@ const bakPath = path.join(dataPath, 'bak/');
|
|||||||
const samplePath = path.join(rootPath, 'sample/');
|
const samplePath = path.join(rootPath, 'sample/');
|
||||||
const tmpPath = path.join(logPath, '.tmp/');
|
const tmpPath = path.join(logPath, '.tmp/');
|
||||||
const confFile = path.join(configPath, 'config.sh');
|
const confFile = path.join(configPath, 'config.sh');
|
||||||
const authConfigFile = path.join(configPath, 'auth.json');
|
|
||||||
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
||||||
const sampleAuthFile = path.join(samplePath, 'auth.sample.json');
|
|
||||||
const sampleTaskShellFile = path.join(samplePath, 'task.sample.sh');
|
const sampleTaskShellFile = path.join(samplePath, 'task.sample.sh');
|
||||||
const sampleNotifyJsFile = path.join(samplePath, 'notify.js');
|
const sampleNotifyJsFile = path.join(samplePath, 'notify.js');
|
||||||
const sampleNotifyPyFile = path.join(samplePath, 'notify.py');
|
const sampleNotifyPyFile = path.join(samplePath, 'notify.py');
|
||||||
@@ -39,112 +38,87 @@ const sshPath = path.resolve(homedir, '.ssh');
|
|||||||
const sshdPath = path.join(dataPath, 'ssh.d');
|
const sshdPath = path.join(dataPath, 'ssh.d');
|
||||||
const systemLogPath = path.join(dataPath, 'syslog');
|
const systemLogPath = path.join(dataPath, 'syslog');
|
||||||
|
|
||||||
export default async () => {
|
const directories = [
|
||||||
const authFileExist = await fileExist(authConfigFile);
|
configPath,
|
||||||
const confFileExist = await fileExist(confFile);
|
scriptPath,
|
||||||
const scriptDirExist = await fileExist(scriptPath);
|
preloadPath,
|
||||||
const preloadDirExist = await fileExist(preloadPath);
|
logPath,
|
||||||
const logDirExist = await fileExist(logPath);
|
tmpPath,
|
||||||
const configDirExist = await fileExist(configPath);
|
uploadPath,
|
||||||
const uploadDirExist = await fileExist(uploadPath);
|
sshPath,
|
||||||
const sshDirExist = await fileExist(sshPath);
|
bakPath,
|
||||||
const bakDirExist = await fileExist(bakPath);
|
sshdPath,
|
||||||
const sshdDirExist = await fileExist(sshdPath);
|
systemLogPath,
|
||||||
const systemLogDirExist = await fileExist(systemLogPath);
|
];
|
||||||
const tmpDirExist = await fileExist(tmpPath);
|
|
||||||
const scriptNotifyJsFileExist = await fileExist(scriptNotifyJsFile);
|
|
||||||
const scriptNotifyPyFileExist = await fileExist(scriptNotifyPyFile);
|
|
||||||
const TaskBeforeFileExist = await fileExist(TaskBeforeFile);
|
|
||||||
const TaskBeforeJsFileExist = await fileExist(TaskBeforeJsFile);
|
|
||||||
const TaskBeforePyFileExist = await fileExist(TaskBeforePyFile);
|
|
||||||
const TaskAfterFileExist = await fileExist(TaskAfterFile);
|
|
||||||
|
|
||||||
if (!configDirExist) {
|
const files = [
|
||||||
await fs.mkdir(configPath);
|
{
|
||||||
}
|
target: confFile,
|
||||||
|
source: sampleConfigFile,
|
||||||
if (!scriptDirExist) {
|
checkExistence: true,
|
||||||
await fs.mkdir(scriptPath);
|
},
|
||||||
}
|
{
|
||||||
|
target: jsNotifyFile,
|
||||||
if (!preloadDirExist) {
|
source: sampleNotifyJsFile,
|
||||||
await fs.mkdir(preloadPath);
|
checkExistence: false,
|
||||||
}
|
},
|
||||||
|
{
|
||||||
if (!logDirExist) {
|
target: pyNotifyFile,
|
||||||
await fs.mkdir(logPath);
|
source: sampleNotifyPyFile,
|
||||||
}
|
checkExistence: false,
|
||||||
|
},
|
||||||
if (!tmpDirExist) {
|
{
|
||||||
await fs.mkdir(tmpPath);
|
target: scriptNotifyJsFile,
|
||||||
}
|
source: sampleNotifyJsFile,
|
||||||
|
checkExistence: true,
|
||||||
if (!uploadDirExist) {
|
},
|
||||||
await fs.mkdir(uploadPath);
|
{
|
||||||
}
|
target: scriptNotifyPyFile,
|
||||||
|
source: sampleNotifyPyFile,
|
||||||
if (!sshDirExist) {
|
checkExistence: true,
|
||||||
await fs.mkdir(sshPath);
|
},
|
||||||
}
|
{
|
||||||
|
target: TaskBeforeFile,
|
||||||
if (!bakDirExist) {
|
source: sampleTaskShellFile,
|
||||||
await fs.mkdir(bakPath);
|
checkExistence: true,
|
||||||
}
|
},
|
||||||
|
{
|
||||||
if (!sshdDirExist) {
|
target: TaskBeforeJsFile,
|
||||||
await fs.mkdir(sshdPath);
|
content:
|
||||||
}
|
|
||||||
|
|
||||||
if (!systemLogDirExist) {
|
|
||||||
await fs.mkdir(systemLogPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 初始化文件
|
|
||||||
if (!authFileExist) {
|
|
||||||
await fs.writeFile(authConfigFile, await fs.readFile(sampleAuthFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!confFileExist) {
|
|
||||||
await fs.writeFile(confFile, await fs.readFile(sampleConfigFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
await fs.writeFile(jsNotifyFile, await fs.readFile(sampleNotifyJsFile));
|
|
||||||
await fs.writeFile(pyNotifyFile, await fs.readFile(sampleNotifyPyFile));
|
|
||||||
|
|
||||||
if (!scriptNotifyJsFileExist) {
|
|
||||||
await fs.writeFile(
|
|
||||||
scriptNotifyJsFile,
|
|
||||||
await fs.readFile(sampleNotifyJsFile),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!scriptNotifyPyFileExist) {
|
|
||||||
await fs.writeFile(
|
|
||||||
scriptNotifyPyFile,
|
|
||||||
await fs.readFile(sampleNotifyPyFile),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!TaskBeforeFileExist) {
|
|
||||||
await fs.writeFile(TaskBeforeFile, await fs.readFile(sampleTaskShellFile));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!TaskBeforeJsFileExist) {
|
|
||||||
await fs.writeFile(
|
|
||||||
TaskBeforeJsFile,
|
|
||||||
'// The JavaScript code that executes before the JavaScript task execution will execute.',
|
'// The JavaScript code that executes before the JavaScript task execution will execute.',
|
||||||
);
|
checkExistence: true,
|
||||||
}
|
},
|
||||||
|
{
|
||||||
if (!TaskBeforePyFileExist) {
|
target: TaskBeforePyFile,
|
||||||
await fs.writeFile(
|
content:
|
||||||
TaskBeforePyFile,
|
|
||||||
'# The Python code that executes before the Python task execution will execute.',
|
'# The Python code that executes before the Python task execution will execute.',
|
||||||
);
|
checkExistence: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
target: TaskAfterFile,
|
||||||
|
source: sampleTaskShellFile,
|
||||||
|
checkExistence: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async () => {
|
||||||
|
for (const dirPath of directories) {
|
||||||
|
if (!(await fileExist(dirPath))) {
|
||||||
|
await fs.mkdir(dirPath);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!TaskAfterFileExist) {
|
for (const item of files) {
|
||||||
await fs.writeFile(TaskAfterFile, await fs.readFile(sampleTaskShellFile));
|
const exists = await fileExist(item.target);
|
||||||
|
if (!item.checkExistence || !exists) {
|
||||||
|
if (!item.content && !item.source) {
|
||||||
|
throw new Error(
|
||||||
|
`Neither content nor source specified for ${item.target}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const content = item.content || (await fs.readFile(item.source!));
|
||||||
|
await writeFileWithLock(item.target, content);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Logger.info('✌️ Init file down');
|
Logger.info('✌️ Init file down');
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
import * as Sentry from '@sentry/node';
|
|
||||||
import Logger from './logger';
|
|
||||||
import fs from 'fs';
|
|
||||||
import config from '../config';
|
|
||||||
import { parseContentVersion } from '../config/util';
|
|
||||||
|
|
||||||
let version = '1.0.0';
|
|
||||||
try {
|
|
||||||
const content = fs.readFileSync(config.versionFile, 'utf-8');
|
|
||||||
({ version } = parseContentVersion(content));
|
|
||||||
} catch (error) {}
|
|
||||||
|
|
||||||
Sentry.init({
|
|
||||||
ignoreErrors: [
|
|
||||||
/SequelizeUniqueConstraintError/i,
|
|
||||||
/Validation error/i,
|
|
||||||
/UnauthorizedError/i,
|
|
||||||
/celebrate request validation failed/i,
|
|
||||||
],
|
|
||||||
dsn: 'https://8b5c84cfef3e22541bc84de0ed00497b@o1098464.ingest.sentry.io/6122819',
|
|
||||||
tracesSampleRate: 0.5,
|
|
||||||
release: version,
|
|
||||||
});
|
|
||||||
|
|
||||||
Logger.info('✌️ Sentry loaded');
|
|
||||||
console.log('✌️ Sentry loaded');
|
|
||||||
@@ -2,9 +2,8 @@ import sockJs from 'sockjs';
|
|||||||
import { Server } from 'http';
|
import { Server } from 'http';
|
||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import SockService from '../services/sock';
|
import SockService from '../services/sock';
|
||||||
import config from '../config/index';
|
import { getPlatform } from '../config/util';
|
||||||
import fs from 'fs/promises';
|
import { shareStore } from '../shared/store';
|
||||||
import { getPlatform, safeJSONParse } from '../config/util';
|
|
||||||
|
|
||||||
export default async ({ server }: { server: Server }) => {
|
export default async ({ server }: { server: Server }) => {
|
||||||
const echo = sockJs.createServer({ prefix: '/api/ws', log: () => {} });
|
const echo = sockJs.createServer({ prefix: '/api/ws', log: () => {} });
|
||||||
@@ -15,11 +14,11 @@ export default async ({ server }: { server: Server }) => {
|
|||||||
conn.close('404');
|
conn.close('404');
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await fs.readFile(config.authConfigFile, 'utf8');
|
const authInfo = await shareStore.getAuthInfo();
|
||||||
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
||||||
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
||||||
if (data) {
|
if (authInfo) {
|
||||||
const { token = '', tokens = {} } = safeJSONParse(data);
|
const { token = '', tokens = {} } = authInfo;
|
||||||
if (headerToken === token || tokens[platform] === headerToken) {
|
if (headerToken === token || tokens[platform] === headerToken) {
|
||||||
sockService.addClient(conn);
|
sockService.addClient(conn);
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import bodyParser from 'body-parser';
|
|||||||
import { errors } from 'celebrate';
|
import { errors } from 'celebrate';
|
||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
import { Application, NextFunction, Request, Response } from 'express';
|
import { Application, NextFunction, Request, Response } from 'express';
|
||||||
import jwt from 'express-jwt';
|
import { expressjwt } from 'express-jwt';
|
||||||
import Container from 'typedi';
|
import Container from 'typedi';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import SystemService from '../services/system';
|
import SystemService from '../services/system';
|
||||||
@@ -16,7 +16,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
jwt({
|
expressjwt({
|
||||||
secret: config.secret,
|
secret: config.secret,
|
||||||
algorithms: ['HS384'],
|
algorithms: ['HS384'],
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package com.ql.api;
|
||||||
|
|
||||||
|
message EnvItem {
|
||||||
|
optional int32 id = 1;
|
||||||
|
optional string name = 2;
|
||||||
|
optional string value = 3;
|
||||||
|
optional string remarks = 4;
|
||||||
|
optional int32 status = 5;
|
||||||
|
optional int32 position = 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
message GetEnvsRequest { string searchValue = 1; }
|
||||||
|
|
||||||
|
message CreateEnvRequest { repeated EnvItem envs = 1; }
|
||||||
|
|
||||||
|
message UpdateEnvRequest { EnvItem env = 1; }
|
||||||
|
|
||||||
|
message DeleteEnvsRequest { repeated int32 ids = 1; }
|
||||||
|
|
||||||
|
message MoveEnvRequest {
|
||||||
|
int32 id = 1;
|
||||||
|
int32 fromIndex = 2;
|
||||||
|
int32 toIndex = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message DisableEnvsRequest { repeated int32 ids = 1; }
|
||||||
|
|
||||||
|
message EnableEnvsRequest { repeated int32 ids = 1; }
|
||||||
|
|
||||||
|
message UpdateEnvNamesRequest {
|
||||||
|
repeated int32 ids = 1;
|
||||||
|
string name = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message GetEnvByIdRequest { int32 id = 1; }
|
||||||
|
|
||||||
|
message EnvsResponse {
|
||||||
|
int32 code = 1;
|
||||||
|
repeated EnvItem data = 2;
|
||||||
|
optional string message = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message EnvResponse {
|
||||||
|
int32 code = 1;
|
||||||
|
EnvItem data = 2;
|
||||||
|
optional string message = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message Response {
|
||||||
|
int32 code = 1;
|
||||||
|
optional string message = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SystemNotifyRequest {
|
||||||
|
string title = 1;
|
||||||
|
string content = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
service Api {
|
||||||
|
rpc GetEnvs(GetEnvsRequest) returns (EnvsResponse) {}
|
||||||
|
rpc CreateEnv(CreateEnvRequest) returns (EnvsResponse) {}
|
||||||
|
rpc UpdateEnv(UpdateEnvRequest) returns (EnvResponse) {}
|
||||||
|
rpc DeleteEnvs(DeleteEnvsRequest) returns (Response) {}
|
||||||
|
rpc MoveEnv(MoveEnvRequest) returns (EnvResponse) {}
|
||||||
|
rpc DisableEnvs(DisableEnvsRequest) returns (Response) {}
|
||||||
|
rpc EnableEnvs(EnableEnvsRequest) returns (Response) {}
|
||||||
|
rpc UpdateEnvNames(UpdateEnvNamesRequest) returns (Response) {}
|
||||||
|
rpc GetEnvById(GetEnvByIdRequest) returns (EnvResponse) {}
|
||||||
|
rpc SystemNotify(SystemNotifyRequest) returns (Response) {}
|
||||||
|
}
|
||||||
+1451
File diff suppressed because it is too large
Load Diff
+50
-44
@@ -1,15 +1,21 @@
|
|||||||
|
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// protoc-gen-ts_proto v1.181.2
|
||||||
|
// protoc v3.17.3
|
||||||
|
// source: back/protos/cron.proto
|
||||||
|
|
||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
import {
|
import {
|
||||||
CallOptions,
|
type CallOptions,
|
||||||
ChannelCredentials,
|
ChannelCredentials,
|
||||||
Client,
|
Client,
|
||||||
ClientOptions,
|
type ClientOptions,
|
||||||
ClientUnaryCall,
|
type ClientUnaryCall,
|
||||||
handleUnaryCall,
|
type handleUnaryCall,
|
||||||
makeGenericClientConstructor,
|
makeGenericClientConstructor,
|
||||||
Metadata,
|
Metadata,
|
||||||
ServiceError,
|
type ServiceError,
|
||||||
UntypedServiceImplementation,
|
type UntypedServiceImplementation,
|
||||||
} from "@grpc/grpc-js";
|
} from "@grpc/grpc-js";
|
||||||
import _m0 from "protobufjs/minimal";
|
import _m0 from "protobufjs/minimal";
|
||||||
|
|
||||||
@@ -77,19 +83,20 @@ export const ISchedule = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): ISchedule {
|
fromJSON(object: any): ISchedule {
|
||||||
return { schedule: isSet(object.schedule) ? String(object.schedule) : "" };
|
return { schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "" };
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: ISchedule): unknown {
|
toJSON(message: ISchedule): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
message.schedule !== undefined && (obj.schedule = message.schedule);
|
if (message.schedule !== "") {
|
||||||
|
obj.schedule = message.schedule;
|
||||||
|
}
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<ISchedule>, I>>(base?: I): ISchedule {
|
create<I extends Exact<DeepPartial<ISchedule>, I>>(base?: I): ISchedule {
|
||||||
return ISchedule.fromPartial(base ?? {});
|
return ISchedule.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<ISchedule>, I>>(object: I): ISchedule {
|
fromPartial<I extends Exact<DeepPartial<ISchedule>, I>>(object: I): ISchedule {
|
||||||
const message = createBaseISchedule();
|
const message = createBaseISchedule();
|
||||||
message.schedule = object.schedule ?? "";
|
message.schedule = object.schedule ?? "";
|
||||||
@@ -174,34 +181,39 @@ export const ICron = {
|
|||||||
|
|
||||||
fromJSON(object: any): ICron {
|
fromJSON(object: any): ICron {
|
||||||
return {
|
return {
|
||||||
id: isSet(object.id) ? String(object.id) : "",
|
id: isSet(object.id) ? globalThis.String(object.id) : "",
|
||||||
schedule: isSet(object.schedule) ? String(object.schedule) : "",
|
schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "",
|
||||||
command: isSet(object.command) ? String(object.command) : "",
|
command: isSet(object.command) ? globalThis.String(object.command) : "",
|
||||||
extraSchedules: Array.isArray(object?.extraSchedules)
|
extraSchedules: globalThis.Array.isArray(object?.extraSchedules)
|
||||||
? object.extraSchedules.map((e: any) => ISchedule.fromJSON(e))
|
? object.extraSchedules.map((e: any) => ISchedule.fromJSON(e))
|
||||||
: [],
|
: [],
|
||||||
name: isSet(object.name) ? String(object.name) : "",
|
name: isSet(object.name) ? globalThis.String(object.name) : "",
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: ICron): unknown {
|
toJSON(message: ICron): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
message.id !== undefined && (obj.id = message.id);
|
if (message.id !== "") {
|
||||||
message.schedule !== undefined && (obj.schedule = message.schedule);
|
obj.id = message.id;
|
||||||
message.command !== undefined && (obj.command = message.command);
|
}
|
||||||
if (message.extraSchedules) {
|
if (message.schedule !== "") {
|
||||||
obj.extraSchedules = message.extraSchedules.map((e) => e ? ISchedule.toJSON(e) : undefined);
|
obj.schedule = message.schedule;
|
||||||
} else {
|
}
|
||||||
obj.extraSchedules = [];
|
if (message.command !== "") {
|
||||||
|
obj.command = message.command;
|
||||||
|
}
|
||||||
|
if (message.extraSchedules?.length) {
|
||||||
|
obj.extraSchedules = message.extraSchedules.map((e) => ISchedule.toJSON(e));
|
||||||
|
}
|
||||||
|
if (message.name !== "") {
|
||||||
|
obj.name = message.name;
|
||||||
}
|
}
|
||||||
message.name !== undefined && (obj.name = message.name);
|
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<ICron>, I>>(base?: I): ICron {
|
create<I extends Exact<DeepPartial<ICron>, I>>(base?: I): ICron {
|
||||||
return ICron.fromPartial(base ?? {});
|
return ICron.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<ICron>, I>>(object: I): ICron {
|
fromPartial<I extends Exact<DeepPartial<ICron>, I>>(object: I): ICron {
|
||||||
const message = createBaseICron();
|
const message = createBaseICron();
|
||||||
message.id = object.id ?? "";
|
message.id = object.id ?? "";
|
||||||
@@ -249,23 +261,20 @@ export const AddCronRequest = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): AddCronRequest {
|
fromJSON(object: any): AddCronRequest {
|
||||||
return { crons: Array.isArray(object?.crons) ? object.crons.map((e: any) => ICron.fromJSON(e)) : [] };
|
return { crons: globalThis.Array.isArray(object?.crons) ? object.crons.map((e: any) => ICron.fromJSON(e)) : [] };
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: AddCronRequest): unknown {
|
toJSON(message: AddCronRequest): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
if (message.crons) {
|
if (message.crons?.length) {
|
||||||
obj.crons = message.crons.map((e) => e ? ICron.toJSON(e) : undefined);
|
obj.crons = message.crons.map((e) => ICron.toJSON(e));
|
||||||
} else {
|
|
||||||
obj.crons = [];
|
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<AddCronRequest>, I>>(base?: I): AddCronRequest {
|
create<I extends Exact<DeepPartial<AddCronRequest>, I>>(base?: I): AddCronRequest {
|
||||||
return AddCronRequest.fromPartial(base ?? {});
|
return AddCronRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(object: I): AddCronRequest {
|
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(object: I): AddCronRequest {
|
||||||
const message = createBaseAddCronRequest();
|
const message = createBaseAddCronRequest();
|
||||||
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
|
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
|
||||||
@@ -308,9 +317,8 @@ export const AddCronResponse = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<AddCronResponse>, I>>(base?: I): AddCronResponse {
|
create<I extends Exact<DeepPartial<AddCronResponse>, I>>(base?: I): AddCronResponse {
|
||||||
return AddCronResponse.fromPartial(base ?? {});
|
return AddCronResponse.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(_: I): AddCronResponse {
|
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(_: I): AddCronResponse {
|
||||||
const message = createBaseAddCronResponse();
|
const message = createBaseAddCronResponse();
|
||||||
return message;
|
return message;
|
||||||
@@ -353,23 +361,20 @@ export const DeleteCronRequest = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): DeleteCronRequest {
|
fromJSON(object: any): DeleteCronRequest {
|
||||||
return { ids: Array.isArray(object?.ids) ? object.ids.map((e: any) => String(e)) : [] };
|
return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.String(e)) : [] };
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: DeleteCronRequest): unknown {
|
toJSON(message: DeleteCronRequest): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
if (message.ids) {
|
if (message.ids?.length) {
|
||||||
obj.ids = message.ids.map((e) => e);
|
obj.ids = message.ids;
|
||||||
} else {
|
|
||||||
obj.ids = [];
|
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(base?: I): DeleteCronRequest {
|
create<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(base?: I): DeleteCronRequest {
|
||||||
return DeleteCronRequest.fromPartial(base ?? {});
|
return DeleteCronRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(object: I): DeleteCronRequest {
|
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(object: I): DeleteCronRequest {
|
||||||
const message = createBaseDeleteCronRequest();
|
const message = createBaseDeleteCronRequest();
|
||||||
message.ids = object.ids?.map((e) => e) || [];
|
message.ids = object.ids?.map((e) => e) || [];
|
||||||
@@ -412,9 +417,8 @@ export const DeleteCronResponse = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(base?: I): DeleteCronResponse {
|
create<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(base?: I): DeleteCronResponse {
|
||||||
return DeleteCronResponse.fromPartial(base ?? {});
|
return DeleteCronResponse.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(_: I): DeleteCronResponse {
|
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(_: I): DeleteCronResponse {
|
||||||
const message = createBaseDeleteCronResponse();
|
const message = createBaseDeleteCronResponse();
|
||||||
return message;
|
return message;
|
||||||
@@ -484,12 +488,14 @@ export interface CronClient extends Client {
|
|||||||
export const CronClient = makeGenericClientConstructor(CronService, "com.ql.cron.Cron") as unknown as {
|
export const CronClient = makeGenericClientConstructor(CronService, "com.ql.cron.Cron") as unknown as {
|
||||||
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): CronClient;
|
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): CronClient;
|
||||||
service: typeof CronService;
|
service: typeof CronService;
|
||||||
|
serviceName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
||||||
|
|
||||||
export type DeepPartial<T> = T extends Builtin ? T
|
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 globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
|
||||||
|
: T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
|
||||||
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
||||||
: Partial<T>;
|
: Partial<T>;
|
||||||
|
|
||||||
|
|||||||
+24
-14
@@ -1,17 +1,23 @@
|
|||||||
|
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// protoc-gen-ts_proto v1.181.2
|
||||||
|
// protoc v3.17.3
|
||||||
|
// source: back/protos/health.proto
|
||||||
|
|
||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
import {
|
import {
|
||||||
CallOptions,
|
type CallOptions,
|
||||||
ChannelCredentials,
|
ChannelCredentials,
|
||||||
Client,
|
Client,
|
||||||
ClientOptions,
|
type ClientOptions,
|
||||||
ClientReadableStream,
|
ClientReadableStream,
|
||||||
ClientUnaryCall,
|
type ClientUnaryCall,
|
||||||
handleServerStreamingCall,
|
handleServerStreamingCall,
|
||||||
handleUnaryCall,
|
type handleUnaryCall,
|
||||||
makeGenericClientConstructor,
|
makeGenericClientConstructor,
|
||||||
Metadata,
|
Metadata,
|
||||||
ServiceError,
|
type ServiceError,
|
||||||
UntypedServiceImplementation,
|
type UntypedServiceImplementation,
|
||||||
} from "@grpc/grpc-js";
|
} from "@grpc/grpc-js";
|
||||||
import _m0 from "protobufjs/minimal";
|
import _m0 from "protobufjs/minimal";
|
||||||
|
|
||||||
@@ -106,19 +112,20 @@ export const HealthCheckRequest = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): HealthCheckRequest {
|
fromJSON(object: any): HealthCheckRequest {
|
||||||
return { service: isSet(object.service) ? String(object.service) : "" };
|
return { service: isSet(object.service) ? globalThis.String(object.service) : "" };
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: HealthCheckRequest): unknown {
|
toJSON(message: HealthCheckRequest): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
message.service !== undefined && (obj.service = message.service);
|
if (message.service !== "") {
|
||||||
|
obj.service = message.service;
|
||||||
|
}
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(base?: I): HealthCheckRequest {
|
create<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(base?: I): HealthCheckRequest {
|
||||||
return HealthCheckRequest.fromPartial(base ?? {});
|
return HealthCheckRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(object: I): HealthCheckRequest {
|
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(object: I): HealthCheckRequest {
|
||||||
const message = createBaseHealthCheckRequest();
|
const message = createBaseHealthCheckRequest();
|
||||||
message.service = object.service ?? "";
|
message.service = object.service ?? "";
|
||||||
@@ -167,14 +174,15 @@ export const HealthCheckResponse = {
|
|||||||
|
|
||||||
toJSON(message: HealthCheckResponse): unknown {
|
toJSON(message: HealthCheckResponse): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
message.status !== undefined && (obj.status = healthCheckResponse_ServingStatusToJSON(message.status));
|
if (message.status !== 0) {
|
||||||
|
obj.status = healthCheckResponse_ServingStatusToJSON(message.status);
|
||||||
|
}
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(base?: I): HealthCheckResponse {
|
create<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(base?: I): HealthCheckResponse {
|
||||||
return HealthCheckResponse.fromPartial(base ?? {});
|
return HealthCheckResponse.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
|
|
||||||
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(object: I): HealthCheckResponse {
|
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(object: I): HealthCheckResponse {
|
||||||
const message = createBaseHealthCheckResponse();
|
const message = createBaseHealthCheckResponse();
|
||||||
message.status = object.status ?? 0;
|
message.status = object.status ?? 0;
|
||||||
@@ -236,12 +244,14 @@ export interface HealthClient extends Client {
|
|||||||
export const HealthClient = makeGenericClientConstructor(HealthService, "com.ql.health.Health") as unknown as {
|
export const HealthClient = makeGenericClientConstructor(HealthService, "com.ql.health.Health") as unknown as {
|
||||||
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): HealthClient;
|
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): HealthClient;
|
||||||
service: typeof HealthService;
|
service: typeof HealthService;
|
||||||
|
serviceName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
||||||
|
|
||||||
export type DeepPartial<T> = T extends Builtin ? T
|
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 globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
|
||||||
|
: T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
|
||||||
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
||||||
: Partial<T>;
|
: Partial<T>;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { Container } from 'typedi';
|
||||||
|
import EnvService from '../services/env';
|
||||||
|
import { sendUnaryData, ServerUnaryCall } from '@grpc/grpc-js';
|
||||||
|
import {
|
||||||
|
CreateEnvRequest,
|
||||||
|
DeleteEnvsRequest,
|
||||||
|
DisableEnvsRequest,
|
||||||
|
EnableEnvsRequest,
|
||||||
|
EnvItem,
|
||||||
|
EnvResponse,
|
||||||
|
EnvsResponse,
|
||||||
|
GetEnvByIdRequest,
|
||||||
|
GetEnvsRequest,
|
||||||
|
MoveEnvRequest,
|
||||||
|
Response,
|
||||||
|
SystemNotifyRequest,
|
||||||
|
UpdateEnvNamesRequest,
|
||||||
|
UpdateEnvRequest,
|
||||||
|
} from '../protos/api';
|
||||||
|
import LoggerInstance from '../loaders/logger';
|
||||||
|
import pick from 'lodash/pick';
|
||||||
|
import SystemService from '../services/system';
|
||||||
|
|
||||||
|
Container.set('logger', LoggerInstance);
|
||||||
|
|
||||||
|
export const getEnvs = async (
|
||||||
|
call: ServerUnaryCall<GetEnvsRequest, EnvsResponse>,
|
||||||
|
callback: sendUnaryData<EnvsResponse>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.envs(call.request.searchValue);
|
||||||
|
callback(null, {
|
||||||
|
code: 200,
|
||||||
|
data: data.map((x) => ({ ...x, remarks: x.remarks || '' })),
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(null, {
|
||||||
|
code: 500,
|
||||||
|
data: [],
|
||||||
|
message: e.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createEnv = async (
|
||||||
|
call: ServerUnaryCall<CreateEnvRequest, EnvsResponse>,
|
||||||
|
callback: sendUnaryData<EnvsResponse>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.create(call.request.envs);
|
||||||
|
callback(null, { code: 200, data });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateEnv = async (
|
||||||
|
call: ServerUnaryCall<UpdateEnvRequest, EnvResponse>,
|
||||||
|
callback: sendUnaryData<EnvResponse>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.update(
|
||||||
|
pick(call.request.env, ['id', 'name', 'value', 'remark']) as EnvItem,
|
||||||
|
);
|
||||||
|
callback(null, { code: 200, data });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteEnvs = async (
|
||||||
|
call: ServerUnaryCall<DeleteEnvsRequest, Response>,
|
||||||
|
callback: sendUnaryData<Response>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
await envService.remove(call.request.ids);
|
||||||
|
callback(null, { code: 200 });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const moveEnv = async (
|
||||||
|
call: ServerUnaryCall<MoveEnvRequest, EnvResponse>,
|
||||||
|
callback: sendUnaryData<EnvResponse>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.move(call.request.id, {
|
||||||
|
fromIndex: call.request.fromIndex,
|
||||||
|
toIndex: call.request.toIndex,
|
||||||
|
});
|
||||||
|
callback(null, { code: 200, data });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const disableEnvs = async (
|
||||||
|
call: ServerUnaryCall<DisableEnvsRequest, Response>,
|
||||||
|
callback: sendUnaryData<Response>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
await envService.disabled(call.request.ids);
|
||||||
|
callback(null, { code: 200 });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const enableEnvs = async (
|
||||||
|
call: ServerUnaryCall<EnableEnvsRequest, Response>,
|
||||||
|
callback: sendUnaryData<Response>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
await envService.enabled(call.request.ids);
|
||||||
|
callback(null, { code: 200 });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateEnvNames = async (
|
||||||
|
call: ServerUnaryCall<UpdateEnvNamesRequest, Response>,
|
||||||
|
callback: sendUnaryData<Response>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
await envService.updateNames({
|
||||||
|
ids: call.request.ids,
|
||||||
|
name: call.request.name,
|
||||||
|
});
|
||||||
|
callback(null, { code: 200 });
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getEnvById = async (
|
||||||
|
call: ServerUnaryCall<GetEnvByIdRequest, EnvResponse>,
|
||||||
|
callback: sendUnaryData<EnvResponse>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.getDb({ id: call.request.id });
|
||||||
|
callback(null, {
|
||||||
|
code: 200,
|
||||||
|
data: { ...data, remarks: data.remarks || '' },
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const systemNotify = async (
|
||||||
|
call: ServerUnaryCall<SystemNotifyRequest, Response>,
|
||||||
|
callback: sendUnaryData<Response>,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const data = await systemService.notify(call.request);
|
||||||
|
callback(null, data);
|
||||||
|
} catch (e: any) {
|
||||||
|
callback(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -6,10 +6,13 @@ import { HealthService } from '../protos/health';
|
|||||||
import { check } from './health';
|
import { check } from './health';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import Logger from '../loaders/logger';
|
import Logger from '../loaders/logger';
|
||||||
|
import { ApiService } from '../protos/api';
|
||||||
|
import * as Api from './api';
|
||||||
|
|
||||||
const server = new Server({ 'grpc.enable_http_proxy': 0 });
|
const server = new Server({ 'grpc.enable_http_proxy': 0 });
|
||||||
server.addService(HealthService, { check });
|
server.addService(HealthService, { check });
|
||||||
server.addService(CronService, { addCron, delCron });
|
server.addService(CronService, { addCron, delCron });
|
||||||
|
server.addService(ApiService, Api);
|
||||||
server.bindAsync(
|
server.bindAsync(
|
||||||
`0.0.0.0:${config.cronPort}`,
|
`0.0.0.0:${config.cronPort}`,
|
||||||
ServerCredentials.createInsecure(),
|
ServerCredentials.createInsecure(),
|
||||||
@@ -17,7 +20,6 @@ server.bindAsync(
|
|||||||
if (err) {
|
if (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
server.start();
|
|
||||||
Logger.debug(`✌️ 定时服务启动成功!`);
|
Logger.debug(`✌️ 定时服务启动成功!`);
|
||||||
console.debug(`✌️ 定时服务启动成功!`);
|
console.debug(`✌️ 定时服务启动成功!`);
|
||||||
process.send?.('ready');
|
process.send?.('ready');
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { spawn } from 'cross-spawn';
|
|||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import pickBy from 'lodash/pickBy';
|
import pickBy from 'lodash/pickBy';
|
||||||
import omit from 'lodash/omit';
|
import omit from 'lodash/omit';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class CronService {
|
export default class CronService {
|
||||||
@@ -601,7 +602,7 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
await fs.writeFile(config.crontabFile, crontab_string);
|
await writeFileWithLock(config.crontabFile, crontab_string);
|
||||||
|
|
||||||
execSync(`crontab ${config.crontabFile}`);
|
execSync(`crontab ${config.crontabFile}`);
|
||||||
await CrontabModel.update({ saved: true }, { where: {} });
|
await CrontabModel.update({ saved: true }, { where: {} });
|
||||||
|
|||||||
@@ -353,7 +353,7 @@ export default class DependenceService {
|
|||||||
});
|
});
|
||||||
this.updateLog(depIds, message);
|
this.updateLog(depIds, message);
|
||||||
|
|
||||||
let status = null;
|
let status: number;
|
||||||
if (isSucceed) {
|
if (isSucceed) {
|
||||||
status = isInstall
|
status = isInstall
|
||||||
? DependenceStatus.installed
|
? DependenceStatus.installed
|
||||||
|
|||||||
+11
-10
@@ -13,6 +13,7 @@ import {
|
|||||||
} from '../data/env';
|
} from '../data/env';
|
||||||
import groupBy from 'lodash/groupBy';
|
import groupBy from 'lodash/groupBy';
|
||||||
import { FindOptions, Op } from 'sequelize';
|
import { FindOptions, Op } from 'sequelize';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class EnvService {
|
export default class EnvService {
|
||||||
@@ -40,7 +41,7 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async insert(payloads: Env[]): Promise<Env[]> {
|
public async insert(payloads: Env[]): Promise<Env[]> {
|
||||||
const result = [];
|
const result: Env[] = [];
|
||||||
for (const env of payloads) {
|
for (const env of payloads) {
|
||||||
const doc = await EnvModel.create(env, { returning: true });
|
const doc = await EnvModel.create(env, { returning: true });
|
||||||
result.push(doc);
|
result.push(doc);
|
||||||
@@ -61,7 +62,7 @@ export default class EnvService {
|
|||||||
return await this.getDb({ id: payload.id });
|
return await this.getDb({ id: payload.id });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: string[]) {
|
public async remove(ids: number[]) {
|
||||||
await EnvModel.destroy({ where: { id: ids } });
|
await EnvModel.destroy({ where: { id: ids } });
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
@@ -149,7 +150,7 @@ export default class EnvService {
|
|||||||
['position', 'DESC'],
|
['position', 'DESC'],
|
||||||
['createdAt', 'ASC'],
|
['createdAt', 'ASC'],
|
||||||
]);
|
]);
|
||||||
return result as any;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -160,7 +161,7 @@ export default class EnvService {
|
|||||||
where: { ...query },
|
where: { ...query },
|
||||||
order: [...sort],
|
order: [...sort],
|
||||||
});
|
});
|
||||||
return docs;
|
return docs.map((x) => x.get({ plain: true }));
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: FindOptions<Env>['where']): Promise<Env> {
|
public async getDb(query: FindOptions<Env>['where']): Promise<Env> {
|
||||||
@@ -171,7 +172,7 @@ export default class EnvService {
|
|||||||
return doc.get({ plain: true });
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: string[]) {
|
public async disabled(ids: number[]) {
|
||||||
await EnvModel.update(
|
await EnvModel.update(
|
||||||
{ status: EnvStatus.disabled },
|
{ status: EnvStatus.disabled },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
@@ -179,12 +180,12 @@ export default class EnvService {
|
|||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async enabled(ids: string[]) {
|
public async enabled(ids: number[]) {
|
||||||
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateNames({ ids, name }: { ids: string[]; name: string }) {
|
public async updateNames({ ids, name }: { ids: number[]; name: string }) {
|
||||||
await EnvModel.update({ name }, { where: { id: ids } });
|
await EnvModel.update({ name }, { where: { id: ids } });
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
@@ -225,8 +226,8 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await fs.writeFile(config.envFile, env_string);
|
await writeFileWithLock(config.envFile, env_string);
|
||||||
await fs.writeFile(config.jsEnvFile, js_env_string);
|
await writeFileWithLock(config.jsEnvFile, js_env_string);
|
||||||
await fs.writeFile(config.pyEnvFile, py_env_string);
|
await writeFileWithLock(config.pyEnvFile, py_env_string);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+82
-36
@@ -3,12 +3,9 @@ import got from 'got';
|
|||||||
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
|
||||||
import nodemailer from 'nodemailer';
|
import nodemailer from 'nodemailer';
|
||||||
import { Inject, Service } from 'typedi';
|
import { Inject, Service } from 'typedi';
|
||||||
import winston from 'winston';
|
import { parseBody, parseHeaders } from '../config/util';
|
||||||
import { parseBody, parseHeaders, safeJSONParse } from '../config/util';
|
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
import UserService from './user';
|
import UserService from './user';
|
||||||
import { readFile } from 'fs/promises';
|
|
||||||
import config from '../config';
|
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class NotificationService {
|
export default class NotificationService {
|
||||||
@@ -36,6 +33,7 @@ export default class NotificationService {
|
|||||||
['lark', this.lark],
|
['lark', this.lark],
|
||||||
['chronocat', this.chronocat],
|
['chronocat', this.chronocat],
|
||||||
['ntfy', this.ntfy],
|
['ntfy', this.ntfy],
|
||||||
|
['wxPusherBot', this.wxPusherBot],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
private title = '';
|
private title = '';
|
||||||
@@ -48,27 +46,6 @@ export default class NotificationService {
|
|||||||
|
|
||||||
constructor() {}
|
constructor() {}
|
||||||
|
|
||||||
public async externalNotify(
|
|
||||||
title: string,
|
|
||||||
content: string,
|
|
||||||
): Promise<boolean | undefined> {
|
|
||||||
const { type, ...rest } = safeJSONParse(
|
|
||||||
await readFile(config.systemNotifyFile, 'utf-8'),
|
|
||||||
);
|
|
||||||
if (type) {
|
|
||||||
this.title = title;
|
|
||||||
this.content = content;
|
|
||||||
this.params = rest;
|
|
||||||
const notificationModeAction = this.modeMap.get(type);
|
|
||||||
try {
|
|
||||||
return await notificationModeAction?.call(this);
|
|
||||||
} catch (error: any) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async notify(
|
public async notify(
|
||||||
title: string,
|
title: string,
|
||||||
content: string,
|
content: string,
|
||||||
@@ -153,7 +130,8 @@ export default class NotificationService {
|
|||||||
private async serverChan() {
|
private async serverChan() {
|
||||||
const { serverChanKey } = this.params;
|
const { serverChanKey } = this.params;
|
||||||
const matchResult = serverChanKey.match(/^sctp(\d+)t/i);
|
const matchResult = serverChanKey.match(/^sctp(\d+)t/i);
|
||||||
const url = matchResult && matchResult[1]
|
const url =
|
||||||
|
matchResult && matchResult[1]
|
||||||
? `https://${matchResult[1]}.push.ft07.com/send/${serverChanKey}.send`
|
? `https://${matchResult[1]}.push.ft07.com/send/${serverChanKey}.send`
|
||||||
: `https://sctapi.ftqq.com/${serverChanKey}.send`;
|
: `https://sctapi.ftqq.com/${serverChanKey}.send`;
|
||||||
|
|
||||||
@@ -161,7 +139,9 @@ export default class NotificationService {
|
|||||||
const res: any = await got
|
const res: any = await got
|
||||||
.post(url, {
|
.post(url, {
|
||||||
...this.gotOption,
|
...this.gotOption,
|
||||||
body: `title=${encodeURIComponent(this.title)}&desp=${encodeURIComponent(this.content)}`,
|
body: `title=${encodeURIComponent(
|
||||||
|
this.title,
|
||||||
|
)}&desp=${encodeURIComponent(this.content)}`,
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
})
|
})
|
||||||
.json();
|
.json();
|
||||||
@@ -522,20 +502,33 @@ export default class NotificationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async pushPlus() {
|
private async pushPlus() {
|
||||||
const { pushPlusToken, pushPlusUser } = this.params;
|
const {
|
||||||
|
pushPlusToken,
|
||||||
|
pushPlusUser,
|
||||||
|
pushplusWebhook,
|
||||||
|
pushPlusTemplate,
|
||||||
|
pushplusChannel,
|
||||||
|
pushplusCallbackUrl,
|
||||||
|
pushplusTo,
|
||||||
|
} = this.params;
|
||||||
const url = `https://www.pushplus.plus/send`;
|
const url = `https://www.pushplus.plus/send`;
|
||||||
try {
|
try {
|
||||||
const res: any = await got
|
let body = {
|
||||||
.post(url, {
|
|
||||||
...this.gotOption,
|
...this.gotOption,
|
||||||
json: {
|
json: {
|
||||||
token: `${pushPlusToken}`,
|
token: `${pushPlusToken}`,
|
||||||
title: `${this.title}`,
|
title: `${this.title}`,
|
||||||
content: `${this.content.replace(/[\n\r]/g, '<br>')}`,
|
content: `${this.content.replace(/[\n\r]/g, '<br>')}`,
|
||||||
topic: `${pushPlusUser || ''}`,
|
topic: `${pushPlusUser || ''}`,
|
||||||
|
template: `${pushPlusTemplate || 'html'}`,
|
||||||
|
channel: `${pushplusChannel || 'wechat'}`,
|
||||||
|
webhook: `${pushplusWebhook || ''}`,
|
||||||
|
callbackUrl: `${pushplusCallbackUrl || ''}`,
|
||||||
|
to: `${pushplusTo || ''}`,
|
||||||
},
|
},
|
||||||
})
|
};
|
||||||
.json();
|
|
||||||
|
const res: any = await got.post(url, body).json();
|
||||||
|
|
||||||
if (res.code === 200) {
|
if (res.code === 200) {
|
||||||
return true;
|
return true;
|
||||||
@@ -673,12 +666,14 @@ export default class NotificationService {
|
|||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const encodedTitle = encodeRfc2047(this.title);
|
const encodedTitle = encodeRfc2047(this.title);
|
||||||
const res: any = await got
|
const res: any = await got.post(
|
||||||
.post(`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`, {
|
`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`,
|
||||||
|
{
|
||||||
...this.gotOption,
|
...this.gotOption,
|
||||||
body: `${this.content}`,
|
body: `${this.content}`,
|
||||||
headers: { 'Title': encodedTitle, 'Priority': `${ntfyPriority || '3'}` },
|
headers: { Title: encodedTitle, Priority: `${ntfyPriority || '3'}` },
|
||||||
});
|
},
|
||||||
|
);
|
||||||
if (res.statusCode === 200) {
|
if (res.statusCode === 200) {
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
@@ -689,6 +684,57 @@ export default class NotificationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async wxPusherBot() {
|
||||||
|
const { wxPusherBotAppToken, wxPusherBotTopicIds, wxPusherBotUids } =
|
||||||
|
this.params;
|
||||||
|
// 处理 topicIds,将分号分隔的字符串转为数组
|
||||||
|
const topicIds = wxPusherBotTopicIds
|
||||||
|
? wxPusherBotTopicIds
|
||||||
|
.split(';')
|
||||||
|
.map((id) => id.trim())
|
||||||
|
.filter((id) => id)
|
||||||
|
.map((id) => parseInt(id))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// 处理 uids,将分号分隔的字符串转为数组
|
||||||
|
const uids = wxPusherBotUids
|
||||||
|
? wxPusherBotUids
|
||||||
|
.split(';')
|
||||||
|
.map((uid) => uid.trim())
|
||||||
|
.filter((uid) => uid)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// topic_ids 和 uids 至少要有一个
|
||||||
|
if (!topicIds.length && !uids.length) {
|
||||||
|
throw new Error('wxPusher 服务的 TopicIds 和 Uids 至少配置一个才行');
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = `https://wxpusher.zjiecode.com/api/send/message`;
|
||||||
|
try {
|
||||||
|
const res: any = await got
|
||||||
|
.post(url, {
|
||||||
|
...this.gotOption,
|
||||||
|
json: {
|
||||||
|
appToken: wxPusherBotAppToken,
|
||||||
|
content: `<h1>${this.title}</h1><br/><div style='white-space: pre-wrap;'>${this.content}</div>`,
|
||||||
|
summary: this.title,
|
||||||
|
contentType: 2,
|
||||||
|
topicIds: topicIds,
|
||||||
|
uids: uids,
|
||||||
|
verifyPayType: 0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json();
|
||||||
|
|
||||||
|
if (res.code === 1000) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
throw new Error(JSON.stringify(res));
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
throw new Error(error.response ? error.response.body : error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async chronocat() {
|
private async chronocat() {
|
||||||
const { chronocatURL, chronocatQQ, chronocatToken } = this.params;
|
const { chronocatURL, chronocatQQ, chronocatToken } = this.params;
|
||||||
|
|||||||
+27
-19
@@ -1,19 +1,18 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import { createRandomString } from '../config/util';
|
import { createRandomString } from '../config/util';
|
||||||
import config from '../config';
|
|
||||||
import { App, AppModel } from '../data/open';
|
import { App, AppModel } from '../data/open';
|
||||||
import { v4 as uuidV4 } from 'uuid';
|
import { v4 as uuidV4 } from 'uuid';
|
||||||
import sequelize, { Op } from 'sequelize';
|
import sequelize, { Op } from 'sequelize';
|
||||||
|
import { shareStore } from '../shared/store';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class OpenService {
|
export default class OpenService {
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
public async findTokenByValue(token: string): Promise<App | null> {
|
public async findApps(): Promise<App[] | null> {
|
||||||
const docs = await this.find({});
|
const docs = await this.find({});
|
||||||
const doc = docs.filter((x) => x.tokens?.find((y) => y.value === token));
|
return docs;
|
||||||
return doc[0];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async create(payload: App): Promise<App> {
|
public async create(payload: App): Promise<App> {
|
||||||
@@ -21,6 +20,8 @@ export default class OpenService {
|
|||||||
tab.client_id = createRandomString(12, 12);
|
tab.client_id = createRandomString(12, 12);
|
||||||
tab.client_secret = createRandomString(24, 24);
|
tab.client_secret = createRandomString(24, 24);
|
||||||
const doc = await this.insert(tab);
|
const doc = await this.insert(tab);
|
||||||
|
const apps = await this.find({});
|
||||||
|
await shareStore.updateApps(apps);
|
||||||
return { ...doc, tokens: [] };
|
return { ...doc, tokens: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,17 +35,19 @@ export default class OpenService {
|
|||||||
name: payload.name,
|
name: payload.name,
|
||||||
scopes: payload.scopes,
|
scopes: payload.scopes,
|
||||||
id: payload.id,
|
id: payload.id,
|
||||||
} as any);
|
} as App);
|
||||||
return { ...newDoc, tokens: [] };
|
return { ...newDoc, tokens: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateDb(payload: App): Promise<App> {
|
private async updateDb(payload: Partial<App>): Promise<App> {
|
||||||
await AppModel.update(payload, { where: { id: payload.id } });
|
await AppModel.update(payload, { where: { id: payload.id } });
|
||||||
return await this.getDb({ id: payload.id });
|
const apps = await this.find({});
|
||||||
|
await shareStore.updateApps(apps);
|
||||||
|
return apps?.find((x) => x.id === payload.id) as App;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<App> {
|
public async getDb(query: Record<string, any>): Promise<App> {
|
||||||
const doc: any = await AppModel.findOne({ where: query });
|
const doc = await AppModel.findOne({ where: query });
|
||||||
if (!doc) {
|
if (!doc) {
|
||||||
throw new Error(`App ${JSON.stringify(query)} not found`);
|
throw new Error(`App ${JSON.stringify(query)} not found`);
|
||||||
}
|
}
|
||||||
@@ -53,10 +56,12 @@ export default class OpenService {
|
|||||||
|
|
||||||
public async remove(ids: number[]) {
|
public async remove(ids: number[]) {
|
||||||
await AppModel.destroy({ where: { id: ids } });
|
await AppModel.destroy({ where: { id: ids } });
|
||||||
|
const apps = await this.find({});
|
||||||
|
await shareStore.updateApps(apps);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async resetSecret(id: number): Promise<App> {
|
public async resetSecret(id: number): Promise<App> {
|
||||||
const tab: any = {
|
const tab: Partial<App> = {
|
||||||
client_secret: createRandomString(24, 24),
|
client_secret: createRandomString(24, 24),
|
||||||
tokens: [],
|
tokens: [],
|
||||||
id,
|
id,
|
||||||
@@ -74,7 +79,7 @@ export default class OpenService {
|
|||||||
public async list(
|
public async list(
|
||||||
searchText: string = '',
|
searchText: string = '',
|
||||||
sort: any = {},
|
sort: any = {},
|
||||||
query: any = {},
|
query: Record<string, any> = {},
|
||||||
): Promise<App[]> {
|
): Promise<App[]> {
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
@@ -101,7 +106,7 @@ export default class OpenService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async find(query: any, sort?: any): Promise<App[]> {
|
private async find(query: Record<string, any>, sort?: any): Promise<App[]> {
|
||||||
const docs = await AppModel.findAll({ where: { ...query } });
|
const docs = await AppModel.findAll({ where: { ...query } });
|
||||||
return docs.map((x) => x.get({ plain: true }));
|
return docs.map((x) => x.get({ plain: true }));
|
||||||
}
|
}
|
||||||
@@ -135,6 +140,8 @@ export default class OpenService {
|
|||||||
{ tokens },
|
{ tokens },
|
||||||
{ where: { client_id, client_secret } },
|
{ where: { client_id, client_secret } },
|
||||||
);
|
);
|
||||||
|
const apps = await this.find({});
|
||||||
|
await shareStore.updateApps(apps);
|
||||||
return {
|
return {
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: {
|
||||||
@@ -152,14 +159,15 @@ export default class OpenService {
|
|||||||
value: string;
|
value: string;
|
||||||
expiration: number;
|
expiration: number;
|
||||||
}> {
|
}> {
|
||||||
let systemApp = (await AppModel.findOne({
|
const apps = await shareStore.getApps();
|
||||||
where: { name: 'system' },
|
const systemApp = apps?.find((x) => x.name === 'system');
|
||||||
})) as App;
|
|
||||||
if (!systemApp) {
|
if (!systemApp) {
|
||||||
systemApp = await this.create({
|
throw new Error('system app not found');
|
||||||
name: 'system',
|
}
|
||||||
scopes: ['crons', 'system'],
|
const now = Math.round(Date.now() / 1000);
|
||||||
} as App);
|
const currentToken = systemApp.tokens?.find((x) => x.expiration > now);
|
||||||
|
if (currentToken) {
|
||||||
|
return currentToken;
|
||||||
}
|
}
|
||||||
const { data } = await this.authToken({
|
const { data } = await this.authToken({
|
||||||
client_id: systemApp.client_id,
|
client_id: systemApp.client_id,
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ export default class ScheduleService {
|
|||||||
const job = new LongIntervalJob(
|
const job = new LongIntervalJob(
|
||||||
{ runImmediately: false, ...schedule },
|
{ runImmediately: false, ...schedule },
|
||||||
task,
|
task,
|
||||||
_id,
|
{ id: _id },
|
||||||
);
|
);
|
||||||
|
|
||||||
this.intervalSchedule.addIntervalJob(job);
|
this.intervalSchedule.addIntervalJob(job);
|
||||||
|
|||||||
+15
-10
@@ -7,6 +7,7 @@ import { Subscription } from '../data/subscription';
|
|||||||
import { formatUrl } from '../config/subscription';
|
import { formatUrl } from '../config/subscription';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { fileExist, rmPath } from '../config/util';
|
import { fileExist, rmPath } from '../config/util';
|
||||||
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class SshKeyService {
|
export default class SshKeyService {
|
||||||
@@ -25,13 +26,12 @@ export default class SshKeyService {
|
|||||||
if (_exist) {
|
if (_exist) {
|
||||||
config = await fs.readFile(this.sshConfigFilePath, { encoding: 'utf-8' });
|
config = await fs.readFile(this.sshConfigFilePath, { encoding: 'utf-8' });
|
||||||
} else {
|
} else {
|
||||||
await fs.writeFile(this.sshConfigFilePath, '');
|
await writeFileWithLock(this.sshConfigFilePath, '');
|
||||||
}
|
}
|
||||||
if (!config.includes(this.sshConfigHeader)) {
|
if (!config.includes(this.sshConfigHeader)) {
|
||||||
await fs.writeFile(
|
await writeFileWithLock(
|
||||||
this.sshConfigFilePath,
|
this.sshConfigFilePath,
|
||||||
`${this.sshConfigHeader}\n\n${config}`,
|
`${this.sshConfigHeader}\n\n${config}`,
|
||||||
{ encoding: 'utf-8' },
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -41,10 +41,14 @@ export default class SshKeyService {
|
|||||||
key: string,
|
key: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await fs.writeFile(path.join(this.sshPath, alias), `${key}${os.EOL}`, {
|
await writeFileWithLock(
|
||||||
|
path.join(this.sshPath, alias),
|
||||||
|
`${key}${os.EOL}`,
|
||||||
|
{
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
mode: '400',
|
mode: '400',
|
||||||
});
|
},
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('生成私钥文件失败', error);
|
this.logger.error('生成私钥文件失败', error);
|
||||||
}
|
}
|
||||||
@@ -74,12 +78,9 @@ export default class SshKeyService {
|
|||||||
this.sshPath,
|
this.sshPath,
|
||||||
alias,
|
alias,
|
||||||
)}\n StrictHostKeyChecking no\n${proxyStr}`;
|
)}\n StrictHostKeyChecking no\n${proxyStr}`;
|
||||||
await fs.writeFile(
|
await writeFileWithLock(
|
||||||
`${path.join(this.sshPath, `${alias}.config`)}`,
|
`${path.join(this.sshPath, `${alias}.config`)}`,
|
||||||
config,
|
config,
|
||||||
{
|
|
||||||
encoding: 'utf8',
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +103,11 @@ export default class SshKeyService {
|
|||||||
await this.generateSingleSshConfig(alias, host, proxy);
|
await this.generateSingleSshConfig(alias, host, proxy);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async removeSSHKey(alias: string, host: string, proxy?: string): Promise<void> {
|
public async removeSSHKey(
|
||||||
|
alias: string,
|
||||||
|
host: string,
|
||||||
|
proxy?: string,
|
||||||
|
): Promise<void> {
|
||||||
await this.removePrivateKeyFile(alias);
|
await this.removePrivateKeyFile(alias);
|
||||||
await this.removeSshConfig(alias);
|
await this.removeSshConfig(alias);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,13 +54,14 @@ export default class SystemService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async updateAuthDb(payload: SystemInfo): Promise<SystemInfo> {
|
private async updateAuthDb(payload: SystemInfo): Promise<SystemInfo> {
|
||||||
await SystemModel.upsert({ ...payload });
|
const { id, ...others } = payload;
|
||||||
const doc = await this.getDb({ type: payload.type });
|
await SystemModel.update(others, { where: { id } });
|
||||||
|
const doc = await this.getDb({ id });
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getDb(query: any): Promise<SystemInfo> {
|
public async getDb(query: any): Promise<SystemInfo> {
|
||||||
const doc = await SystemModel.findOne({ where: { ...query } });
|
const doc = await SystemModel.findOne({ where: query });
|
||||||
if (!doc) {
|
if (!doc) {
|
||||||
throw new Error(`System ${JSON.stringify(query)} not found`);
|
throw new Error(`System ${JSON.stringify(query)} not found`);
|
||||||
}
|
}
|
||||||
@@ -402,7 +403,7 @@ export default class SystemService {
|
|||||||
public async exportData(res: Response) {
|
public async exportData(res: Response) {
|
||||||
try {
|
try {
|
||||||
await promiseExec(
|
await promiseExec(
|
||||||
`cd ${config.rootPath} && tar -zcvf ${config.dataTgzFile} data/`,
|
`cd ${config.dataPath} && cd ../ && tar -zcvf ${config.dataTgzFile} data/`,
|
||||||
);
|
);
|
||||||
res.download(config.dataTgzFile);
|
res.download(config.dataTgzFile);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -414,7 +415,7 @@ export default class SystemService {
|
|||||||
try {
|
try {
|
||||||
await promiseExec(`rm -rf ${path.join(config.tmpPath, 'data')}`);
|
await promiseExec(`rm -rf ${path.join(config.tmpPath, 'data')}`);
|
||||||
const res = await promiseExec(
|
const res = await promiseExec(
|
||||||
`cd ${config.tmpPath} && tar -zxvf data.tgz`,
|
`cd ${config.tmpPath} && tar -zxvf ${config.dataTgzFile}`,
|
||||||
);
|
);
|
||||||
return { code: 200, data: res };
|
return { code: 200, data: res };
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -439,7 +440,7 @@ export default class SystemService {
|
|||||||
const logs = result
|
const logs = result
|
||||||
.reverse()
|
.reverse()
|
||||||
.filter((x) => x.title.endsWith('.log'))
|
.filter((x) => x.title.endsWith('.log'))
|
||||||
.filter((x) => x.mtime >= startTime && x.mtime <= endTime);
|
.filter((x) => x.createTime >= startTime && x.createTime <= endTime);
|
||||||
|
|
||||||
res.set({
|
res.set({
|
||||||
'Content-Length': sum(logs.map((x) => x.size)),
|
'Content-Length': sum(logs.map((x) => x.size)),
|
||||||
|
|||||||
+38
-81
@@ -1,15 +1,7 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import {
|
import { createRandomString, getNetIp } from '../config/util';
|
||||||
createFile,
|
|
||||||
createRandomString,
|
|
||||||
fileExist,
|
|
||||||
getNetIp,
|
|
||||||
getPlatform,
|
|
||||||
safeJSONParse,
|
|
||||||
} from '../config/util';
|
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs/promises';
|
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
import { authenticator } from '@otplib/preset-default';
|
import { authenticator } from '@otplib/preset-default';
|
||||||
import {
|
import {
|
||||||
@@ -18,6 +10,7 @@ import {
|
|||||||
SystemModel,
|
SystemModel,
|
||||||
SystemModelInfo,
|
SystemModelInfo,
|
||||||
LoginStatus,
|
LoginStatus,
|
||||||
|
AuthInfo,
|
||||||
} from '../data/system';
|
} from '../data/system';
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
import NotificationService from './notify';
|
import NotificationService from './notify';
|
||||||
@@ -28,6 +21,7 @@ import dayjs from 'dayjs';
|
|||||||
import IP2Region from 'ip2region';
|
import IP2Region from 'ip2region';
|
||||||
import requestIp from 'request-ip';
|
import requestIp from 'request-ip';
|
||||||
import uniq from 'lodash/uniq';
|
import uniq from 'lodash/uniq';
|
||||||
|
import { shareStore } from '../shared/store';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class UserService {
|
export default class UserService {
|
||||||
@@ -48,15 +42,9 @@ export default class UserService {
|
|||||||
req: Request,
|
req: Request,
|
||||||
needTwoFactor = true,
|
needTwoFactor = true,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
const _exist = await fileExist(config.authConfigFile);
|
|
||||||
if (!_exist) {
|
|
||||||
return this.initAuthInfo();
|
|
||||||
}
|
|
||||||
|
|
||||||
let { username, password } = payloads;
|
let { username, password } = payloads;
|
||||||
const content = await this.getAuthInfo();
|
const content = await this.getAuthInfo();
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
if (content) {
|
|
||||||
let {
|
let {
|
||||||
username: cUsername,
|
username: cUsername,
|
||||||
password: cPassword,
|
password: cPassword,
|
||||||
@@ -65,21 +53,9 @@ export default class UserService {
|
|||||||
lastip,
|
lastip,
|
||||||
lastaddr,
|
lastaddr,
|
||||||
twoFactorActivated,
|
twoFactorActivated,
|
||||||
twoFactorActived,
|
|
||||||
tokens = {},
|
tokens = {},
|
||||||
platform,
|
platform,
|
||||||
} = content;
|
} = content;
|
||||||
// patch old field
|
|
||||||
twoFactorActivated = twoFactorActivated || twoFactorActived;
|
|
||||||
|
|
||||||
if (
|
|
||||||
(cUsername === 'admin' && cPassword === 'admin') ||
|
|
||||||
!cUsername ||
|
|
||||||
!cPassword
|
|
||||||
) {
|
|
||||||
return this.initAuthInfo();
|
|
||||||
}
|
|
||||||
|
|
||||||
const retriesTime = Math.pow(3, retries) * 1000;
|
const retriesTime = Math.pow(3, retries) * 1000;
|
||||||
if (retries > 2 && timestamp - lastlogon < retriesTime) {
|
if (retries > 2 && timestamp - lastlogon < retriesTime) {
|
||||||
const waitTime = Math.ceil(
|
const waitTime = Math.ceil(
|
||||||
@@ -98,7 +74,7 @@ export default class UserService {
|
|||||||
twoFactorActivated &&
|
twoFactorActivated &&
|
||||||
needTwoFactor
|
needTwoFactor
|
||||||
) {
|
) {
|
||||||
this.updateAuthInfo(content, {
|
await this.updateAuthInfo(content, {
|
||||||
isTwoFactorChecking: true,
|
isTwoFactorChecking: true,
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
@@ -113,9 +89,7 @@ export default class UserService {
|
|||||||
let address = '';
|
let address = '';
|
||||||
if (ipAddress) {
|
if (ipAddress) {
|
||||||
const { country, province, city, isp } = ipAddress;
|
const { country, province, city, isp } = ipAddress;
|
||||||
address = uniq([country, province, city, isp])
|
address = uniq([country, province, city, isp]).filter(Boolean).join(' ');
|
||||||
.filter(Boolean)
|
|
||||||
.join(' ');
|
|
||||||
}
|
}
|
||||||
if (username === cUsername && password === cPassword) {
|
if (username === cUsername && password === cPassword) {
|
||||||
const data = createRandomString(50, 100);
|
const data = createRandomString(50, 100);
|
||||||
@@ -125,7 +99,7 @@ export default class UserService {
|
|||||||
algorithm: 'HS384',
|
algorithm: 'HS384',
|
||||||
});
|
});
|
||||||
|
|
||||||
this.updateAuthInfo(content, {
|
await this.updateAuthInfo(content, {
|
||||||
token,
|
token,
|
||||||
tokens: {
|
tokens: {
|
||||||
...tokens,
|
...tokens,
|
||||||
@@ -160,7 +134,7 @@ export default class UserService {
|
|||||||
data: { token, lastip, lastaddr, lastlogon, retries, platform },
|
data: { token, lastip, lastaddr, lastlogon, retries, platform },
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
this.updateAuthInfo(content, {
|
await this.updateAuthInfo(content, {
|
||||||
retries: retries + 1,
|
retries: retries + 1,
|
||||||
lastlogon: timestamp,
|
lastlogon: timestamp,
|
||||||
lastip: ip,
|
lastip: ip,
|
||||||
@@ -195,14 +169,11 @@ export default class UserService {
|
|||||||
return { code: 400, message: config.authError };
|
return { code: 400, message: config.authError };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
return this.initAuthInfo();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async logout(platform: string): Promise<any> {
|
public async logout(platform: string): Promise<any> {
|
||||||
const authInfo = await this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, {
|
await this.updateAuthInfo(authInfo, {
|
||||||
token: '',
|
token: '',
|
||||||
tokens: { ...authInfo.tokens, [platform]: '' },
|
tokens: { ...authInfo.tokens, [platform]: '' },
|
||||||
});
|
});
|
||||||
@@ -232,20 +203,6 @@ export default class UserService {
|
|||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async initAuthInfo() {
|
|
||||||
await fs.writeFile(
|
|
||||||
config.authConfigFile,
|
|
||||||
JSON.stringify({
|
|
||||||
username: 'admin',
|
|
||||||
password: 'admin',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
code: 100,
|
|
||||||
message: '未找到认证文件,重新初始化',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public async updateUsernameAndPassword({
|
public async updateUsernameAndPassword({
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
@@ -257,35 +214,21 @@ export default class UserService {
|
|||||||
return { code: 400, message: '密码不能设置为admin' };
|
return { code: 400, message: '密码不能设置为admin' };
|
||||||
}
|
}
|
||||||
const authInfo = await this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, { username, password });
|
await this.updateAuthInfo(authInfo, { username, password });
|
||||||
return { code: 200, message: '更新成功' };
|
return { code: 200, message: '更新成功' };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateAvatar(avatar: string) {
|
public async updateAvatar(avatar: string) {
|
||||||
const authInfo = await this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, { avatar });
|
await this.updateAuthInfo(authInfo, { avatar });
|
||||||
return { code: 200, data: avatar, message: '更新成功' };
|
return { code: 200, data: avatar, message: '更新成功' };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getUserInfo(): Promise<any> {
|
|
||||||
const authFileExist = await fileExist(config.authConfigFile);
|
|
||||||
if (!authFileExist) {
|
|
||||||
await createFile(
|
|
||||||
config.authConfigFile,
|
|
||||||
JSON.stringify({
|
|
||||||
username: 'admin',
|
|
||||||
password: 'admin',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return await this.getAuthInfo();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async initTwoFactor() {
|
public async initTwoFactor() {
|
||||||
const secret = authenticator.generateSecret();
|
const secret = authenticator.generateSecret();
|
||||||
const authInfo = await this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
const otpauth = authenticator.keyuri(authInfo.username, 'qinglong', secret);
|
const otpauth = authenticator.keyuri(authInfo.username, 'qinglong', secret);
|
||||||
this.updateAuthInfo(authInfo, { twoFactorSecret: secret });
|
await this.updateAuthInfo(authInfo, { twoFactorSecret: secret });
|
||||||
return { secret, url: otpauth };
|
return { secret, url: otpauth };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,7 +239,7 @@ export default class UserService {
|
|||||||
secret: authInfo.twoFactorSecret,
|
secret: authInfo.twoFactorSecret,
|
||||||
});
|
});
|
||||||
if (isValid) {
|
if (isValid) {
|
||||||
this.updateAuthInfo(authInfo, { twoFactorActivated: true });
|
await this.updateAuthInfo(authInfo, { twoFactorActivated: true });
|
||||||
}
|
}
|
||||||
return isValid;
|
return isValid;
|
||||||
}
|
}
|
||||||
@@ -322,7 +265,7 @@ export default class UserService {
|
|||||||
return this.login({ username, password }, req, false);
|
return this.login({ username, password }, req, false);
|
||||||
} else {
|
} else {
|
||||||
const { ip, address } = await getNetIp(req);
|
const { ip, address } = await getNetIp(req);
|
||||||
this.updateAuthInfo(authInfo, {
|
await this.updateAuthInfo(authInfo, {
|
||||||
lastip: ip,
|
lastip: ip,
|
||||||
lastaddr: address,
|
lastaddr: address,
|
||||||
platform: req.platform,
|
platform: req.platform,
|
||||||
@@ -333,24 +276,29 @@ export default class UserService {
|
|||||||
|
|
||||||
public async deactiveTwoFactor() {
|
public async deactiveTwoFactor() {
|
||||||
const authInfo = await this.getAuthInfo();
|
const authInfo = await this.getAuthInfo();
|
||||||
this.updateAuthInfo(authInfo, {
|
await this.updateAuthInfo(authInfo, {
|
||||||
twoFactorActivated: false,
|
twoFactorActivated: false,
|
||||||
twoFactorActived: false,
|
|
||||||
twoFactorSecret: '',
|
twoFactorSecret: '',
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getAuthInfo() {
|
public async getAuthInfo() {
|
||||||
const content = await fs.readFile(config.authConfigFile, 'utf8');
|
const authInfo = await shareStore.getAuthInfo();
|
||||||
return safeJSONParse(content);
|
if (authInfo) {
|
||||||
|
return authInfo;
|
||||||
|
}
|
||||||
|
const doc = await this.getDb({ type: AuthDataType.authConfig });
|
||||||
|
return (doc.info || {}) as AuthInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateAuthInfo(authInfo: any, info: any) {
|
private async updateAuthInfo(authInfo: AuthInfo, info: Partial<AuthInfo>) {
|
||||||
await fs.writeFile(
|
const result = { ...authInfo, ...info };
|
||||||
config.authConfigFile,
|
await shareStore.updateAuthInfo(result);
|
||||||
JSON.stringify({ ...authInfo, ...info }),
|
await this.updateAuthDb({
|
||||||
);
|
type: AuthDataType.authConfig,
|
||||||
|
info: result,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getNotificationMode(): Promise<NotificationInfo> {
|
public async getNotificationMode(): Promise<NotificationInfo> {
|
||||||
@@ -359,7 +307,7 @@ export default class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async updateAuthDb(payload: SystemInfo): Promise<any> {
|
private async updateAuthDb(payload: SystemInfo): Promise<any> {
|
||||||
let doc = await SystemModel.findOne({ type: payload.type });
|
let doc = await SystemModel.findOne({ where: { type: payload.type } });
|
||||||
if (doc) {
|
if (doc) {
|
||||||
const updateResult = await SystemModel.update(payload, {
|
const updateResult = await SystemModel.update(payload, {
|
||||||
where: { id: doc.id },
|
where: { id: doc.id },
|
||||||
@@ -397,4 +345,13 @@ export default class UserService {
|
|||||||
return { code: 400, message: '通知发送失败,请检查参数' };
|
return { code: 400, message: '通知发送失败,请检查参数' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async resetAuthInfo(info: Partial<AuthInfo>) {
|
||||||
|
const { retries, twoFactorActivated } = info;
|
||||||
|
const authInfo = await this.getAuthInfo();
|
||||||
|
await this.updateAuthInfo(authInfo, {
|
||||||
|
retries,
|
||||||
|
twoFactorActivated,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-3
@@ -11,6 +11,9 @@ import {
|
|||||||
IScheduleFn,
|
IScheduleFn,
|
||||||
TCron,
|
TCron,
|
||||||
} from './interface';
|
} from './interface';
|
||||||
|
import config from '../config';
|
||||||
|
import { credentials } from '@grpc/grpc-js';
|
||||||
|
import { ApiClient } from '../protos/api';
|
||||||
|
|
||||||
class TaskLimit {
|
class TaskLimit {
|
||||||
private dependenyLimit = new PQueue({ concurrency: 1 });
|
private dependenyLimit = new PQueue({ concurrency: 1 });
|
||||||
@@ -33,6 +36,11 @@ class TaskLimit {
|
|||||||
private systemLimit = new PQueue({
|
private systemLimit = new PQueue({
|
||||||
concurrency: Math.max(os.cpus().length, 4),
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
});
|
});
|
||||||
|
private client = new ApiClient(
|
||||||
|
`0.0.0.0:${config.cronPort}`,
|
||||||
|
credentials.createInsecure(),
|
||||||
|
{ 'grpc.enable_http_proxy': 0 },
|
||||||
|
);
|
||||||
|
|
||||||
get cronLimitActiveCount() {
|
get cronLimitActiveCount() {
|
||||||
return this.cronLimit.pending;
|
return this.cronLimit.pending;
|
||||||
@@ -126,9 +134,18 @@ class TaskLimit {
|
|||||||
if (result?.length > 5) {
|
if (result?.length > 5) {
|
||||||
if (repeatTimes < 3) {
|
if (repeatTimes < 3) {
|
||||||
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
||||||
this.notificationService.externalNotify(
|
this.client.systemNotify(
|
||||||
'任务重复运行',
|
{
|
||||||
`任务:${cron.name},命令:${cron.command},定时:${cron.schedule},处于运行中的超过 5 个,请检查定时设置`,
|
title: '任务重复运行',
|
||||||
|
content: `任务:${cron.name},命令:${cron.command},定时:${cron.schedule},处于运行中的超过 5 个,请检查定时设置`,
|
||||||
|
},
|
||||||
|
(err, res) => {
|
||||||
|
if (err) {
|
||||||
|
Logger.error(
|
||||||
|
`[schedule][任务重复运行] 通知失败 ${JSON.stringify(err)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Logger.warn(`[schedule][任务重复运行] 参数 ${JSON.stringify(cron)}`);
|
Logger.warn(`[schedule][任务重复运行] 参数 ${JSON.stringify(cron)}`);
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { AuthInfo } from '../data/system';
|
||||||
|
import { App } from '../data/open';
|
||||||
|
import Keyv from 'keyv';
|
||||||
|
import KeyvSqlite from '@keyv/sqlite';
|
||||||
|
import config from '../config';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
export enum EKeyv {
|
||||||
|
'apps' = 'apps',
|
||||||
|
'authInfo' = 'authInfo',
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IKeyvStore {
|
||||||
|
apps: App[];
|
||||||
|
authInfo: AuthInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keyvSqlite = new KeyvSqlite(path.join(config.dbPath, 'keyv.sqlite'));
|
||||||
|
export const keyvStore = new Keyv<IKeyvStore>({ store: keyvSqlite });
|
||||||
|
|
||||||
|
export const shareStore = {
|
||||||
|
getAuthInfo() {
|
||||||
|
return keyvStore.get<IKeyvStore['authInfo']>(EKeyv.authInfo);
|
||||||
|
},
|
||||||
|
updateAuthInfo(value: IKeyvStore['authInfo']) {
|
||||||
|
return keyvStore.set<IKeyvStore['authInfo']>(EKeyv.authInfo, value);
|
||||||
|
},
|
||||||
|
getApps() {
|
||||||
|
return keyvStore.get<IKeyvStore['apps']>(EKeyv.apps);
|
||||||
|
},
|
||||||
|
updateApps(apps: App[]) {
|
||||||
|
return keyvStore.set<IKeyvStore['apps']>(EKeyv.apps, apps);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { lock } from 'proper-lockfile';
|
||||||
|
import os from 'os';
|
||||||
|
import path from 'path';
|
||||||
|
import { writeFile, open, chmod } from 'fs/promises';
|
||||||
|
import { fileExist } from '../config/util';
|
||||||
|
|
||||||
|
function getUniqueLockPath(filePath: string) {
|
||||||
|
const sanitizedPath = filePath
|
||||||
|
.replace(/[<>:"/\\|?*]/g, '_')
|
||||||
|
.replace(/^_/, '');
|
||||||
|
return path.join(os.tmpdir(), `${sanitizedPath}.ql_lock`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function writeFileWithLock(
|
||||||
|
filePath: string,
|
||||||
|
content: string | Buffer,
|
||||||
|
options: Parameters<typeof writeFile>[2] = {},
|
||||||
|
) {
|
||||||
|
if (typeof options === 'string') {
|
||||||
|
options = { encoding: options };
|
||||||
|
}
|
||||||
|
if (!(await fileExist(filePath))) {
|
||||||
|
const fileHandle = await open(filePath, 'w');
|
||||||
|
fileHandle.close();
|
||||||
|
}
|
||||||
|
const lockfilePath = getUniqueLockPath(filePath);
|
||||||
|
|
||||||
|
const release = await lock(filePath, {
|
||||||
|
retries: {
|
||||||
|
retries: 10,
|
||||||
|
factor: 2,
|
||||||
|
minTimeout: 100,
|
||||||
|
maxTimeout: 3000,
|
||||||
|
},
|
||||||
|
lockfilePath,
|
||||||
|
});
|
||||||
|
await writeFile(filePath, content, { encoding: 'utf8', ...options });
|
||||||
|
if (options?.mode) {
|
||||||
|
await chmod(filePath, options.mode);
|
||||||
|
}
|
||||||
|
await release();
|
||||||
|
}
|
||||||
+2
-10
@@ -6,6 +6,7 @@ import fs from 'fs';
|
|||||||
import config from './config';
|
import config from './config';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
|
import { writeFileWithLock } from './shared/utils';
|
||||||
|
|
||||||
const tokenFile = path.join(config.configPath, 'token.json');
|
const tokenFile = path.join(config.configPath, 'token.json');
|
||||||
|
|
||||||
@@ -25,16 +26,7 @@ async function getToken() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function writeFile(data: any) {
|
async function writeFile(data: any) {
|
||||||
return new Promise<void>((resolve, reject) => {
|
await writeFileWithLock(tokenFile, `${JSON.stringify(data)}${os.EOL}`);
|
||||||
fs.writeFile(
|
|
||||||
tokenFile,
|
|
||||||
`${JSON.stringify(data)}${os.EOL}`,
|
|
||||||
{ encoding: 'utf8' },
|
|
||||||
() => {
|
|
||||||
resolve();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getToken();
|
getToken();
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
import { CommandModule } from 'yargs';
|
|
||||||
export const updateCommand: CommandModule = {
|
|
||||||
command: 'update',
|
|
||||||
describe: 'Update and restart qinglong',
|
|
||||||
builder: (yargs) => {
|
|
||||||
return yargs.option('repositority', {
|
|
||||||
type: 'string',
|
|
||||||
alias: 'r',
|
|
||||||
describe: `Specify the release warehouse address of the package`,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
handler: async (argv) => {},
|
|
||||||
};
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import * as yargs from 'yargs';
|
|
||||||
import { green, red } from 'chalk';
|
|
||||||
import { updateCommand } from './commands/update';
|
|
||||||
|
|
||||||
yargs
|
|
||||||
.usage('Usage: ql [command] <options>')
|
|
||||||
.command(updateCommand)
|
|
||||||
.fail((err) => {
|
|
||||||
console.error(`${red(err)}`);
|
|
||||||
})
|
|
||||||
.alias('h', 'help')
|
|
||||||
.showHelp()
|
|
||||||
.recommendCommands().argv;
|
|
||||||
@@ -1,15 +1,10 @@
|
|||||||
version: '2'
|
|
||||||
services:
|
services:
|
||||||
web:
|
web:
|
||||||
# alpine 基础镜像版本
|
image: whyour/qinglong:latest # 基于 Debian 的版本:whyour/qinglong:debian
|
||||||
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"
|
- "5700:5700"
|
||||||
environment:
|
environment:
|
||||||
# 部署路径非必须,以斜杠开头和结尾,比如 /test/
|
QlBaseUrl: '/' # 部署路径非必须,以斜杠开头和结尾,比如 /test/
|
||||||
QlBaseUrl: '/'
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+45
-43
@@ -14,6 +14,7 @@
|
|||||||
"public": "npm run build:back && node static/build/public.js",
|
"public": "npm run build:back && node static/build/public.js",
|
||||||
"update": "npm run build:back && node static/build/update.js",
|
"update": "npm run build:back && node static/build/update.js",
|
||||||
"gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true",
|
"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",
|
||||||
|
"gen:api": "python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./back/protos/api.proto",
|
||||||
"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",
|
||||||
@@ -54,64 +55,66 @@
|
|||||||
"react-dom": "18",
|
"react-dom": "18",
|
||||||
"dva-core": "2"
|
"dva-core": "2"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"overrides": {
|
||||||
|
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@grpc/grpc-js": "^1.8.13",
|
"@grpc/grpc-js": "^1.12.3",
|
||||||
|
"@grpc/proto-loader": "^0.7.13",
|
||||||
"@otplib/preset-default": "^12.0.1",
|
"@otplib/preset-default": "^12.0.1",
|
||||||
"@sentry/node": "^8.26.0",
|
"body-parser": "^1.20.3",
|
||||||
"body-parser": "^1.19.2",
|
"celebrate": "^15.0.3",
|
||||||
"celebrate": "^15.0.1",
|
"chokidar": "^4.0.1",
|
||||||
"chokidar": "^3.5.3",
|
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"cron-parser": "^4.2.1",
|
"cron-parser": "^4.9.0",
|
||||||
"cross-spawn": "^7.0.3",
|
"cross-spawn": "^7.0.6",
|
||||||
"dayjs": "^1.11.2",
|
"dayjs": "^1.11.13",
|
||||||
"dotenv": "^16.0.0",
|
"dotenv": "^16.4.6",
|
||||||
"express": "^4.17.3",
|
"express": "^4.21.2",
|
||||||
"express-jwt": "^6.1.1",
|
"express-jwt": "^8.4.1",
|
||||||
"express-rate-limit": "^7.0.0",
|
"express-rate-limit": "^7.4.1",
|
||||||
"express-urlrewrite": "^1.4.0",
|
"express-urlrewrite": "^2.0.3",
|
||||||
"form-data": "^4.0.0",
|
"form-data": "^4.0.0",
|
||||||
"got": "^11.8.2",
|
"got": "^11.8.2",
|
||||||
"hpagent": "^1.2.0",
|
"hpagent": "^1.2.0",
|
||||||
"http-proxy-middleware": "^2.0.6",
|
"http-proxy-middleware": "^3.0.3",
|
||||||
"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": "^9.0.2",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"multer": "1.4.5-lts.1",
|
"multer": "1.4.5-lts.1",
|
||||||
"nedb": "^1.8.0",
|
|
||||||
"node-schedule": "^2.1.0",
|
"node-schedule": "^2.1.0",
|
||||||
"nodemailer": "^6.7.2",
|
"nodemailer": "^6.9.16",
|
||||||
"p-queue-cjs": "7.3.4",
|
"p-queue-cjs": "7.3.4",
|
||||||
"protobufjs": "^7.3.0",
|
"protobufjs": "^7.4.0",
|
||||||
"pstree.remy": "^1.1.8",
|
"pstree.remy": "^1.1.8",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.2.2",
|
||||||
"sequelize": "^6.25.5",
|
"sequelize": "^6.37.5",
|
||||||
"serve-handler": "^6.1.3",
|
"serve-handler": "^6.1.6",
|
||||||
"sockjs": "^0.3.24",
|
"sockjs": "^0.3.24",
|
||||||
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
||||||
"toad-scheduler": "^1.6.0",
|
"toad-scheduler": "^3.0.1",
|
||||||
"typedi": "^0.10.0",
|
"typedi": "^0.10.0",
|
||||||
"uuid": "^8.3.2",
|
"uuid": "^11.0.3",
|
||||||
"winston": "^3.6.0",
|
"winston": "^3.17.0",
|
||||||
"winston-daily-rotate-file": "^4.7.1",
|
"winston-daily-rotate-file": "^5.0.0",
|
||||||
"yargs": "^17.3.1",
|
|
||||||
"tough-cookie": "^4.0.0",
|
|
||||||
"request-ip": "3.3.0",
|
"request-ip": "3.3.0",
|
||||||
"ip2region": "2.3.0"
|
"ip2region": "2.3.0",
|
||||||
|
"keyv": "^5.2.3",
|
||||||
|
"@keyv/sqlite": "^4.0.1",
|
||||||
|
"proper-lockfile": "^4.1.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"moment": "2.30.1",
|
"moment": "2.30.1",
|
||||||
"@ant-design/icons": "^4.7.0",
|
"@ant-design/icons": "^5.0.1",
|
||||||
"@ant-design/pro-layout": "6.38.22",
|
"@ant-design/pro-layout": "6.38.22",
|
||||||
"@codemirror/view": "^6.34.1",
|
"@codemirror/view": "^6.34.1",
|
||||||
"@codemirror/state": "^6.4.1",
|
"@codemirror/state": "^6.4.1",
|
||||||
"@monaco-editor/react": "4.2.1",
|
"@monaco-editor/react": "4.2.1",
|
||||||
"@react-hook/resize-observer": "^1.2.6",
|
"@react-hook/resize-observer": "^2.0.2",
|
||||||
"react-router-dom": "6.26.1",
|
"react-router-dom": "6.26.1",
|
||||||
"@sentry/react": "^8.26.0",
|
|
||||||
"@types/body-parser": "^1.19.2",
|
"@types/body-parser": "^1.19.2",
|
||||||
"@types/cors": "^2.8.12",
|
"@types/cors": "^2.8.12",
|
||||||
"@types/cross-spawn": "^6.0.2",
|
"@types/cross-spawn": "^6.0.2",
|
||||||
@@ -122,7 +125,6 @@
|
|||||||
"@types/jsonwebtoken": "^8.5.8",
|
"@types/jsonwebtoken": "^8.5.8",
|
||||||
"@types/lodash": "^4.14.185",
|
"@types/lodash": "^4.14.185",
|
||||||
"@types/multer": "^1.4.7",
|
"@types/multer": "^1.4.7",
|
||||||
"@types/nedb": "^1.8.12",
|
|
||||||
"@types/node": "^17.0.21",
|
"@types/node": "^17.0.21",
|
||||||
"@types/node-schedule": "^1.3.2",
|
"@types/node-schedule": "^1.3.2",
|
||||||
"@types/nodemailer": "^6.4.4",
|
"@types/nodemailer": "^6.4.4",
|
||||||
@@ -135,18 +137,19 @@
|
|||||||
"@types/sockjs-client": "^1.5.1",
|
"@types/sockjs-client": "^1.5.1",
|
||||||
"@types/uuid": "^8.3.4",
|
"@types/uuid": "^8.3.4",
|
||||||
"@types/request-ip": "0.0.41",
|
"@types/request-ip": "0.0.41",
|
||||||
|
"@types/proper-lockfile": "^4.1.4",
|
||||||
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
||||||
"@uiw/react-codemirror": "^4.21.9",
|
"@uiw/react-codemirror": "^4.21.9",
|
||||||
"@umijs/max": "^4.0.72",
|
"@umijs/max": "^4.4.4",
|
||||||
"@umijs/ssr-darkreader": "^4.9.45",
|
"@umijs/ssr-darkreader": "^4.9.45",
|
||||||
"ahooks": "^3.7.8",
|
"ahooks": "^3.7.8",
|
||||||
"ansi-to-react": "^6.1.6",
|
"ansi-to-react": "^6.1.6",
|
||||||
"antd": "^4.24.8",
|
"antd": "^4.24.16",
|
||||||
"antd-img-crop": "^4.2.3",
|
"antd-img-crop": "^4.23.0",
|
||||||
"axios": "^1.4.0",
|
"axios": "^1.4.0",
|
||||||
"compression-webpack-plugin": "9.2.0",
|
"compression-webpack-plugin": "9.2.0",
|
||||||
"concurrently": "^7.0.0",
|
"concurrently": "^7.0.0",
|
||||||
"react-hotkeys-hook": "^4.4.1",
|
"react-hotkeys-hook": "^4.6.1",
|
||||||
"file-saver": "2.0.2",
|
"file-saver": "2.0.2",
|
||||||
"lint-staged": "^13.0.3",
|
"lint-staged": "^13.0.3",
|
||||||
"monaco-editor": "0.33.0",
|
"monaco-editor": "0.33.0",
|
||||||
@@ -157,14 +160,14 @@
|
|||||||
"qrcode.react": "^1.0.1",
|
"qrcode.react": "^1.0.1",
|
||||||
"query-string": "^7.1.1",
|
"query-string": "^7.1.1",
|
||||||
"rc-tween-one": "^3.0.6",
|
"rc-tween-one": "^3.0.6",
|
||||||
"rc-virtual-list": "3.5.3",
|
"rc-virtual-list": "3.15.0",
|
||||||
"react": "18.2.0",
|
"react": "18.3.1",
|
||||||
"react-copy-to-clipboard": "^5.1.0",
|
"react-copy-to-clipboard": "^5.1.0",
|
||||||
"react-diff-viewer": "^3.1.1",
|
"react-diff-viewer": "^3.1.1",
|
||||||
"react-dnd": "^14.0.2",
|
"react-dnd": "^16.0.1",
|
||||||
"react-dnd-html5-backend": "^14.0.0",
|
"react-dnd-html5-backend": "^16.0.1",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "18.3.1",
|
||||||
"react-intl-universal": "^2.6.21",
|
"react-intl-universal": "^2.12.0",
|
||||||
"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.9.2",
|
"ts-node": "^10.9.2",
|
||||||
@@ -173,7 +176,6 @@
|
|||||||
"typescript": "5.2.2",
|
"typescript": "5.2.2",
|
||||||
"vh-check": "^2.0.5",
|
"vh-check": "^2.0.5",
|
||||||
"virtualizedtableforantd4": "1.3.0",
|
"virtualizedtableforantd4": "1.3.0",
|
||||||
"webpack": "^5.70.0",
|
|
||||||
"yorkie": "^2.0.0"
|
"yorkie": "^2.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+4883
-6529
File diff suppressed because it is too large
Load Diff
+20
-1
@@ -117,6 +117,16 @@ export PUSH_PLUS_TOKEN=""
|
|||||||
## 下方填写您的一对多推送的 "群组编码" ,(一对多推送下面->您的群组(如无则新建)->群组编码)
|
## 下方填写您的一对多推送的 "群组编码" ,(一对多推送下面->您的群组(如无则新建)->群组编码)
|
||||||
## 1. 需订阅者扫描二维码 2、如果您是创建群组所属人,也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送
|
## 1. 需订阅者扫描二维码 2、如果您是创建群组所属人,也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送
|
||||||
export PUSH_PLUS_USER=""
|
export PUSH_PLUS_USER=""
|
||||||
|
## 发送模板,支持html,txt,json,markdown,cloudMonitor,jenkins,route,pay
|
||||||
|
export PUSH_PLUS_TEMPLATE="html"
|
||||||
|
## 发送渠道,支持wechat,webhook,cp,mail,sms
|
||||||
|
export PUSH_PLUS_CHANNEL="wechat"
|
||||||
|
## webhook编码,可在pushplus公众号上扩展配置出更多渠道
|
||||||
|
export PUSH_PLUS_WEBHOOK=""
|
||||||
|
## 发送结果回调地址,会把推送最终结果通知到这个地址上
|
||||||
|
export PUSH_PLUS_CALLBACKURL=""
|
||||||
|
## 好友令牌,微信公众号渠道填写好友令牌,企业微信渠道填写企业微信用户id
|
||||||
|
export PUSH_PLUS_TO=""
|
||||||
|
|
||||||
## 9. 微加机器人
|
## 9. 微加机器人
|
||||||
## 官方网站:http://www.weplusbot.com
|
## 官方网站:http://www.weplusbot.com
|
||||||
@@ -220,8 +230,17 @@ export NTFY_URL=""
|
|||||||
export NTFY_TOPIC=""
|
export NTFY_TOPIC=""
|
||||||
export NTFY_PRIORITY="3"
|
export NTFY_PRIORITY="3"
|
||||||
|
|
||||||
|
## 21. wxPusher
|
||||||
|
## 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||||
|
## 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||||
|
## wxPusher 的 appToken
|
||||||
|
export WXPUSHER_APP_TOKEN=""
|
||||||
|
## wxPusher 的 topicIds,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
|
export WXPUSHER_TOPIC_IDS=""
|
||||||
|
## wxPusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
|
export WXPUSHER_UIDS=""
|
||||||
|
|
||||||
## 21. 自定义通知
|
## 22. 自定义通知
|
||||||
## 自定义通知 接收回调的URL
|
## 自定义通知 接收回调的URL
|
||||||
export WEBHOOK_URL=""
|
export WEBHOOK_URL=""
|
||||||
## WEBHOOK_BODY 和 WEBHOOK_HEADERS 多个参数时,直接换行或者使用 $'\n' 连接多行字符串,比如 export dd="line 1"$'\n'"line 2"
|
## WEBHOOK_BODY 和 WEBHOOK_HEADERS 多个参数时,直接换行或者使用 $'\n' 连接多行字符串,比如 export dd="line 1"$'\n'"line 2"
|
||||||
|
|||||||
+116
-17
@@ -40,9 +40,14 @@ const push_config = {
|
|||||||
CHAT_URL: '', // synology chat url
|
CHAT_URL: '', // synology chat url
|
||||||
CHAT_TOKEN: '', // synology chat token
|
CHAT_TOKEN: '', // synology chat token
|
||||||
|
|
||||||
// 官方文档:http://www.pushplus.plus/
|
// 官方文档:https://www.pushplus.plus/
|
||||||
PUSH_PLUS_TOKEN: '', // push+ 微信推送的用户令牌
|
PUSH_PLUS_TOKEN: '', // pushplus 推送的用户令牌
|
||||||
PUSH_PLUS_USER: '', // push+ 微信推送的群组编码
|
PUSH_PLUS_USER: '', // pushplus 推送的群组编码
|
||||||
|
PUSH_PLUS_TEMPLATE: 'html', // pushplus 发送模板,支持html,txt,json,markdown,cloudMonitor,jenkins,route,pay
|
||||||
|
PUSH_PLUS_CHANNEL: 'wechat', // pushplus 发送渠道,支持wechat,webhook,cp,mail,sms
|
||||||
|
PUSH_PLUS_WEBHOOK: '', // pushplus webhook编码,可在pushplus公众号上扩展配置出更多渠道
|
||||||
|
PUSH_PLUS_CALLBACKURL: '', // pushplus 发送结果回调地址,会把推送最终结果通知到这个地址上
|
||||||
|
PUSH_PLUS_TO: '', // pushplus 好友令牌,微信公众号渠道填写好友令牌,企业微信渠道填写企业微信用户id
|
||||||
|
|
||||||
// 微加机器人,官方网站:https://www.weplusbot.com/
|
// 微加机器人,官方网站:https://www.weplusbot.com/
|
||||||
WE_PLUS_BOT_TOKEN: '', // 微加机器人的用户令牌
|
WE_PLUS_BOT_TOKEN: '', // 微加机器人的用户令牌
|
||||||
@@ -99,6 +104,12 @@ const push_config = {
|
|||||||
NTFY_URL: '', // ntfy地址,如https://ntfy.sh,默认为https://ntfy.sh
|
NTFY_URL: '', // ntfy地址,如https://ntfy.sh,默认为https://ntfy.sh
|
||||||
NTFY_TOPIC: '', // ntfy的消息应用topic
|
NTFY_TOPIC: '', // ntfy的消息应用topic
|
||||||
NTFY_PRIORITY: '3', // 推送消息优先级,默认为3
|
NTFY_PRIORITY: '3', // 推送消息优先级,默认为3
|
||||||
|
|
||||||
|
// 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||||
|
// 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||||
|
WXPUSHER_APP_TOKEN: '', // wxpusher 的 appToken
|
||||||
|
WXPUSHER_TOPIC_IDS: '', // wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
|
WXPUSHER_UIDS: '', // wxpusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const key in push_config) {
|
for (const key in push_config) {
|
||||||
@@ -231,10 +242,13 @@ function serverNotify(text, desp) {
|
|||||||
|
|
||||||
const matchResult = PUSH_KEY.match(/^sctp(\d+)t/i);
|
const matchResult = PUSH_KEY.match(/^sctp(\d+)t/i);
|
||||||
const options = {
|
const options = {
|
||||||
url: matchResult && matchResult[1]
|
url:
|
||||||
|
matchResult && matchResult[1]
|
||||||
? `https://${matchResult[1]}.push.ft07.com/send/${PUSH_KEY}.send`
|
? `https://${matchResult[1]}.push.ft07.com/send/${PUSH_KEY}.send`
|
||||||
: `https://sctapi.ftqq.com/${PUSH_KEY}.send`,
|
: `https://sctapi.ftqq.com/${PUSH_KEY}.send`,
|
||||||
body: `text=${encodeURIComponent(text)}&desp=${encodeURIComponent(desp)}`,
|
body: `text=${encodeURIComponent(text)}&desp=${encodeURIComponent(
|
||||||
|
desp,
|
||||||
|
)}`,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
},
|
},
|
||||||
@@ -414,7 +428,7 @@ function tgBotNotify(text, desp) {
|
|||||||
TG_PROXY_AUTH,
|
TG_PROXY_AUTH,
|
||||||
} = push_config;
|
} = push_config;
|
||||||
if (TG_BOT_TOKEN && TG_USER_ID) {
|
if (TG_BOT_TOKEN && TG_USER_ID) {
|
||||||
const options = {
|
let options = {
|
||||||
url: `${TG_API_HOST}/bot${TG_BOT_TOKEN}/sendMessage`,
|
url: `${TG_API_HOST}/bot${TG_BOT_TOKEN}/sendMessage`,
|
||||||
json: {
|
json: {
|
||||||
chat_id: `${TG_USER_ID}`,
|
chat_id: `${TG_USER_ID}`,
|
||||||
@@ -428,20 +442,20 @@ function tgBotNotify(text, desp) {
|
|||||||
};
|
};
|
||||||
if (TG_PROXY_HOST && TG_PROXY_PORT) {
|
if (TG_PROXY_HOST && TG_PROXY_PORT) {
|
||||||
const { HttpProxyAgent, HttpsProxyAgent } = require('hpagent');
|
const { HttpProxyAgent, HttpsProxyAgent } = require('hpagent');
|
||||||
const options = {
|
const _options = {
|
||||||
keepAlive: true,
|
keepAlive: true,
|
||||||
keepAliveMsecs: 1000,
|
keepAliveMsecs: 1000,
|
||||||
maxSockets: 256,
|
maxSockets: 256,
|
||||||
maxFreeSockets: 256,
|
maxFreeSockets: 256,
|
||||||
proxy: `http://${TG_PROXY_AUTH}${TG_PROXY_HOST}:${TG_PROXY_PORT}`,
|
proxy: `http://${TG_PROXY_AUTH}${TG_PROXY_HOST}:${TG_PROXY_PORT}`,
|
||||||
};
|
};
|
||||||
const httpAgent = new HttpProxyAgent(options);
|
const httpAgent = new HttpProxyAgent(_options);
|
||||||
const httpsAgent = new HttpsProxyAgent(options);
|
const httpsAgent = new HttpsProxyAgent(_options);
|
||||||
const agent = {
|
const agent = {
|
||||||
http: httpAgent,
|
http: httpAgent,
|
||||||
https: httpsAgent,
|
https: httpsAgent,
|
||||||
};
|
};
|
||||||
Object.assign(options, { agent });
|
options.agent = agent;
|
||||||
}
|
}
|
||||||
$.post(options, (err, resp, data) => {
|
$.post(options, (err, resp, data) => {
|
||||||
try {
|
try {
|
||||||
@@ -765,7 +779,15 @@ function iGotNotify(text, desp, params = {}) {
|
|||||||
|
|
||||||
function pushPlusNotify(text, desp) {
|
function pushPlusNotify(text, desp) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const { PUSH_PLUS_TOKEN, PUSH_PLUS_USER } = push_config;
|
const {
|
||||||
|
PUSH_PLUS_TOKEN,
|
||||||
|
PUSH_PLUS_USER,
|
||||||
|
PUSH_PLUS_TEMPLATE,
|
||||||
|
PUSH_PLUS_CHANNEL,
|
||||||
|
PUSH_PLUS_WEBHOOK,
|
||||||
|
PUSH_PLUS_CALLBACKURL,
|
||||||
|
PUSH_PLUS_TO,
|
||||||
|
} = push_config;
|
||||||
if (PUSH_PLUS_TOKEN) {
|
if (PUSH_PLUS_TOKEN) {
|
||||||
desp = desp.replace(/[\n\r]/g, '<br>'); // 默认为html, 不支持plaintext
|
desp = desp.replace(/[\n\r]/g, '<br>'); // 默认为html, 不支持plaintext
|
||||||
const body = {
|
const body = {
|
||||||
@@ -773,6 +795,11 @@ function pushPlusNotify(text, desp) {
|
|||||||
title: `${text}`,
|
title: `${text}`,
|
||||||
content: `${desp}`,
|
content: `${desp}`,
|
||||||
topic: `${PUSH_PLUS_USER}`,
|
topic: `${PUSH_PLUS_USER}`,
|
||||||
|
template: `${PUSH_PLUS_TEMPLATE}`,
|
||||||
|
channel: `${PUSH_PLUS_CHANNEL}`,
|
||||||
|
webhook: `${PUSH_PLUS_WEBHOOK}`,
|
||||||
|
callbackUrl: `${PUSH_PLUS_CALLBACKURL}`,
|
||||||
|
to: `${PUSH_PLUS_TO}`,
|
||||||
};
|
};
|
||||||
const options = {
|
const options = {
|
||||||
url: `https://www.pushplus.plus/send`,
|
url: `https://www.pushplus.plus/send`,
|
||||||
@@ -786,7 +813,7 @@ function pushPlusNotify(text, desp) {
|
|||||||
try {
|
try {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log(
|
console.log(
|
||||||
`Push+ 发送${
|
`pushplus 发送${
|
||||||
PUSH_PLUS_USER ? '一对多' : '一对一'
|
PUSH_PLUS_USER ? '一对多' : '一对一'
|
||||||
}通知消息失败😞\n`,
|
}通知消息失败😞\n`,
|
||||||
err,
|
err,
|
||||||
@@ -794,13 +821,15 @@ function pushPlusNotify(text, desp) {
|
|||||||
} else {
|
} else {
|
||||||
if (data.code === 200) {
|
if (data.code === 200) {
|
||||||
console.log(
|
console.log(
|
||||||
`Push+ 发送${
|
`pushplus 发送${
|
||||||
PUSH_PLUS_USER ? '一对多' : '一对一'
|
PUSH_PLUS_USER ? '一对多' : '一对一'
|
||||||
}通知消息完成🎉\n`,
|
}通知请求成功🎉,可根据流水号查询推送结果:${
|
||||||
|
data.data
|
||||||
|
}\n注意:请求成功并不代表推送成功,如未收到消息,请到pushplus官网使用流水号查询推送最终结果`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
console.log(
|
||||||
`Push+ 发送${
|
`pushplus 发送${
|
||||||
PUSH_PLUS_USER ? '一对多' : '一对一'
|
PUSH_PLUS_USER ? '一对多' : '一对一'
|
||||||
}通知消息异常 ${data.msg}\n`,
|
}通知消息异常 ${data.msg}\n`,
|
||||||
);
|
);
|
||||||
@@ -1207,8 +1236,8 @@ function ntfyNotify(text, desp) {
|
|||||||
url: `${NTFY_URL || 'https://ntfy.sh'}/${NTFY_TOPIC}`,
|
url: `${NTFY_URL || 'https://ntfy.sh'}/${NTFY_TOPIC}`,
|
||||||
body: `${desp}`,
|
body: `${desp}`,
|
||||||
headers: {
|
headers: {
|
||||||
'Title': `${encodeRFC2047(text)}`,
|
Title: `${encodeRFC2047(text)}`,
|
||||||
'Priority': NTFY_PRIORITY || '3'
|
Priority: NTFY_PRIORITY || '3',
|
||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
};
|
};
|
||||||
@@ -1235,6 +1264,75 @@ function ntfyNotify(text, desp) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function wxPusherNotify(text, desp) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const { WXPUSHER_APP_TOKEN, WXPUSHER_TOPIC_IDS, WXPUSHER_UIDS } =
|
||||||
|
push_config;
|
||||||
|
if (WXPUSHER_APP_TOKEN) {
|
||||||
|
// 处理topic_ids,将分号分隔的字符串转为数组
|
||||||
|
const topicIds = WXPUSHER_TOPIC_IDS
|
||||||
|
? WXPUSHER_TOPIC_IDS.split(';')
|
||||||
|
.map((id) => id.trim())
|
||||||
|
.filter((id) => id)
|
||||||
|
.map((id) => parseInt(id))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// 处理uids,将分号分隔的字符串转为数组
|
||||||
|
const uids = WXPUSHER_UIDS
|
||||||
|
? WXPUSHER_UIDS.split(';')
|
||||||
|
.map((uid) => uid.trim())
|
||||||
|
.filter((uid) => uid)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// topic_ids uids 至少有一个
|
||||||
|
if (!topicIds.length && !uids.length) {
|
||||||
|
console.log(
|
||||||
|
'wxpusher 服务的 WXPUSHER_TOPIC_IDS 和 WXPUSHER_UIDS 至少设置一个!!',
|
||||||
|
);
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
appToken: WXPUSHER_APP_TOKEN,
|
||||||
|
content: `<h1>${text}</h1><br/><div style='white-space: pre-wrap;'>${desp}</div>`,
|
||||||
|
summary: text,
|
||||||
|
contentType: 2,
|
||||||
|
topicIds: topicIds,
|
||||||
|
uids: uids,
|
||||||
|
verifyPayType: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
url: 'https://wxpusher.zjiecode.com/api/send/message',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
timeout,
|
||||||
|
};
|
||||||
|
|
||||||
|
$.post(options, (err, resp, data) => {
|
||||||
|
try {
|
||||||
|
if (err) {
|
||||||
|
console.log('wxpusher发送通知消息失败!\n', err);
|
||||||
|
} else {
|
||||||
|
if (data.code === 1000) {
|
||||||
|
console.log('wxpusher发送通知消息完成!');
|
||||||
|
} else {
|
||||||
|
console.log(`wxpusher发送通知消息异常:${data.msg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
$.logErr(e, resp);
|
||||||
|
} finally {
|
||||||
|
resolve(data);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function parseString(input, valueFormatFn) {
|
function parseString(input, valueFormatFn) {
|
||||||
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
|
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
|
||||||
@@ -1365,6 +1463,7 @@ async function sendNotify(text, desp, params = {}) {
|
|||||||
webhookNotify(text, desp), // 自定义通知
|
webhookNotify(text, desp), // 自定义通知
|
||||||
qmsgNotify(text, desp), // 自定义通知
|
qmsgNotify(text, desp), // 自定义通知
|
||||||
ntfyNotify(text, desp), // Ntfy
|
ntfyNotify(text, desp), // Ntfy
|
||||||
|
wxPusherNotify(text, desp), // wxpusher
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+96
-42
@@ -72,8 +72,13 @@ push_config = {
|
|||||||
'CHAT_URL': '', # synology chat url
|
'CHAT_URL': '', # synology chat url
|
||||||
'CHAT_TOKEN': '', # synology chat token
|
'CHAT_TOKEN': '', # synology chat token
|
||||||
|
|
||||||
'PUSH_PLUS_TOKEN': '', # push+ 微信推送的用户令牌
|
'PUSH_PLUS_TOKEN': '', # pushplus 推送的用户令牌
|
||||||
'PUSH_PLUS_USER': '', # push+ 微信推送的群组编码
|
'PUSH_PLUS_USER': '', # pushplus 推送的群组编码
|
||||||
|
'PUSH_PLUS_TEMPLATE': 'html', # pushplus 发送模板,支持html,txt,json,markdown,cloudMonitor,jenkins,route,pay
|
||||||
|
'PUSH_PLUS_CHANNEL': 'wechat', # pushplus 发送渠道,支持wechat,webhook,cp,mail,sms
|
||||||
|
'PUSH_PLUS_WEBHOOK': '', # pushplus webhook编码,可在pushplus公众号上扩展配置出更多渠道
|
||||||
|
'PUSH_PLUS_CALLBACKURL': '', # pushplus 发送结果回调地址,会把推送最终结果通知到这个地址上
|
||||||
|
'PUSH_PLUS_TO': '', # pushplus 好友令牌,微信公众号渠道填写好友令牌,企业微信渠道填写企业微信用户id
|
||||||
|
|
||||||
'WE_PLUS_BOT_TOKEN': '', # 微加机器人的用户令牌
|
'WE_PLUS_BOT_TOKEN': '', # 微加机器人的用户令牌
|
||||||
'WE_PLUS_BOT_RECEIVER': '', # 微加机器人的消息接收者
|
'WE_PLUS_BOT_RECEIVER': '', # 微加机器人的消息接收者
|
||||||
@@ -121,6 +126,10 @@ push_config = {
|
|||||||
'NTFY_URL': '', # ntfy地址,如https://ntfy.sh
|
'NTFY_URL': '', # ntfy地址,如https://ntfy.sh
|
||||||
'NTFY_TOPIC': '', # ntfy的消息应用topic
|
'NTFY_TOPIC': '', # ntfy的消息应用topic
|
||||||
'NTFY_PRIORITY':'3', # 推送消息优先级,默认为3
|
'NTFY_PRIORITY':'3', # 推送消息优先级,默认为3
|
||||||
|
|
||||||
|
'WXPUSHER_APP_TOKEN': '', # wxpusher 的 appToken 官方文档: https://wxpusher.zjiecode.com/docs/ 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||||
|
'WXPUSHER_TOPIC_IDS': '', # wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
|
'WXPUSHER_UIDS': '', # wxpusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
}
|
}
|
||||||
# fmt: on
|
# fmt: on
|
||||||
|
|
||||||
@@ -135,7 +144,6 @@ def bark(title: str, content: str) -> None:
|
|||||||
使用 bark 推送消息。
|
使用 bark 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("BARK_PUSH"):
|
if not push_config.get("BARK_PUSH"):
|
||||||
print("bark 服务的 BARK_PUSH 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("bark 服务启动")
|
print("bark 服务启动")
|
||||||
|
|
||||||
@@ -187,7 +195,6 @@ def dingding_bot(title: str, content: str) -> None:
|
|||||||
使用 钉钉机器人 推送消息。
|
使用 钉钉机器人 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("DD_BOT_SECRET") or not push_config.get("DD_BOT_TOKEN"):
|
if not push_config.get("DD_BOT_SECRET") or not push_config.get("DD_BOT_TOKEN"):
|
||||||
print("钉钉机器人 服务的 DD_BOT_SECRET 或者 DD_BOT_TOKEN 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("钉钉机器人 服务启动")
|
print("钉钉机器人 服务启动")
|
||||||
|
|
||||||
@@ -217,7 +224,6 @@ def feishu_bot(title: str, content: str) -> None:
|
|||||||
使用 飞书机器人 推送消息。
|
使用 飞书机器人 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("FSKEY"):
|
if not push_config.get("FSKEY"):
|
||||||
print("飞书 服务的 FSKEY 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("飞书 服务启动")
|
print("飞书 服务启动")
|
||||||
|
|
||||||
@@ -236,7 +242,6 @@ def go_cqhttp(title: str, content: str) -> None:
|
|||||||
使用 go_cqhttp 推送消息。
|
使用 go_cqhttp 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("GOBOT_URL") or not push_config.get("GOBOT_QQ"):
|
if not push_config.get("GOBOT_URL") or not push_config.get("GOBOT_QQ"):
|
||||||
print("go-cqhttp 服务的 GOBOT_URL 或 GOBOT_QQ 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("go-cqhttp 服务启动")
|
print("go-cqhttp 服务启动")
|
||||||
|
|
||||||
@@ -254,7 +259,6 @@ def gotify(title: str, content: str) -> None:
|
|||||||
使用 gotify 推送消息。
|
使用 gotify 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("GOTIFY_URL") or not push_config.get("GOTIFY_TOKEN"):
|
if not push_config.get("GOTIFY_URL") or not push_config.get("GOTIFY_TOKEN"):
|
||||||
print("gotify 服务的 GOTIFY_URL 或 GOTIFY_TOKEN 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("gotify 服务启动")
|
print("gotify 服务启动")
|
||||||
|
|
||||||
@@ -277,7 +281,6 @@ def iGot(title: str, content: str) -> None:
|
|||||||
使用 iGot 推送消息。
|
使用 iGot 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("IGOT_PUSH_KEY"):
|
if not push_config.get("IGOT_PUSH_KEY"):
|
||||||
print("iGot 服务的 IGOT_PUSH_KEY 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("iGot 服务启动")
|
print("iGot 服务启动")
|
||||||
|
|
||||||
@@ -297,13 +300,12 @@ def serverJ(title: str, content: str) -> None:
|
|||||||
通过 serverJ 推送消息。
|
通过 serverJ 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("PUSH_KEY"):
|
if not push_config.get("PUSH_KEY"):
|
||||||
print("serverJ 服务的 PUSH_KEY 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("serverJ 服务启动")
|
print("serverJ 服务启动")
|
||||||
|
|
||||||
data = {"text": title, "desp": content.replace("\n", "\n\n")}
|
data = {"text": title, "desp": content.replace("\n", "\n\n")}
|
||||||
|
|
||||||
match = re.match(r'sctp(\d+)t', push_config.get("PUSH_KEY"))
|
match = re.match(r"sctp(\d+)t", push_config.get("PUSH_KEY"))
|
||||||
if match:
|
if match:
|
||||||
num = match.group(1)
|
num = match.group(1)
|
||||||
url = f'https://{num}.push.ft07.com/send/{push_config.get("PUSH_KEY")}.send'
|
url = f'https://{num}.push.ft07.com/send/{push_config.get("PUSH_KEY")}.send'
|
||||||
@@ -323,7 +325,6 @@ def pushdeer(title: str, content: str) -> None:
|
|||||||
通过PushDeer 推送消息
|
通过PushDeer 推送消息
|
||||||
"""
|
"""
|
||||||
if not push_config.get("DEER_KEY"):
|
if not push_config.get("DEER_KEY"):
|
||||||
print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("PushDeer 服务启动")
|
print("PushDeer 服务启动")
|
||||||
data = {
|
data = {
|
||||||
@@ -349,7 +350,6 @@ def chat(title: str, content: str) -> None:
|
|||||||
通过Chat 推送消息
|
通过Chat 推送消息
|
||||||
"""
|
"""
|
||||||
if not push_config.get("CHAT_URL") or not push_config.get("CHAT_TOKEN"):
|
if not push_config.get("CHAT_URL") or not push_config.get("CHAT_TOKEN"):
|
||||||
print("chat 服务的 CHAT_URL或CHAT_TOKEN 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("chat 服务启动")
|
print("chat 服务启动")
|
||||||
data = "payload=" + json.dumps({"text": title + "\n" + content})
|
data = "payload=" + json.dumps({"text": title + "\n" + content})
|
||||||
@@ -364,26 +364,36 @@ def chat(title: str, content: str) -> None:
|
|||||||
|
|
||||||
def pushplus_bot(title: str, content: str) -> None:
|
def pushplus_bot(title: str, content: str) -> None:
|
||||||
"""
|
"""
|
||||||
通过 push+ 推送消息。
|
通过 pushplus 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("PUSH_PLUS_TOKEN"):
|
if not push_config.get("PUSH_PLUS_TOKEN"):
|
||||||
print("PUSHPLUS 服务的 PUSH_PLUS_TOKEN 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("PUSHPLUS 服务启动")
|
print("PUSHPLUS 服务启动")
|
||||||
|
|
||||||
url = "http://www.pushplus.plus/send"
|
url = "https://www.pushplus.plus/send"
|
||||||
data = {
|
data = {
|
||||||
"token": push_config.get("PUSH_PLUS_TOKEN"),
|
"token": push_config.get("PUSH_PLUS_TOKEN"),
|
||||||
"title": title,
|
"title": title,
|
||||||
"content": content,
|
"content": content,
|
||||||
"topic": push_config.get("PUSH_PLUS_USER"),
|
"topic": push_config.get("PUSH_PLUS_USER"),
|
||||||
|
"template": push_config.get("PUSH_PLUS_TEMPLATE"),
|
||||||
|
"channel": push_config.get("PUSH_PLUS_CHANNEL"),
|
||||||
|
"webhook": push_config.get("PUSH_PLUS_WEBHOOK"),
|
||||||
|
"callbackUrl": push_config.get("PUSH_PLUS_CALLBACKURL"),
|
||||||
|
"to": push_config.get("PUSH_PLUS_TO"),
|
||||||
}
|
}
|
||||||
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"}
|
||||||
response = requests.post(url=url, data=body, headers=headers).json()
|
response = requests.post(url=url, data=body, headers=headers).json()
|
||||||
|
|
||||||
if response["code"] == 200:
|
code = response["code"]
|
||||||
print("PUSHPLUS 推送成功!")
|
if code == 200:
|
||||||
|
print("PUSHPLUS 推送请求成功,可根据流水号查询推送结果:" + response["data"])
|
||||||
|
print(
|
||||||
|
"注意:请求成功并不代表推送成功,如未收到消息,请到pushplus官网使用流水号查询推送最终结果"
|
||||||
|
)
|
||||||
|
elif code == 900 or code == 903 or code == 905 or code == 999:
|
||||||
|
print(response["msg"])
|
||||||
|
|
||||||
else:
|
else:
|
||||||
url_old = "http://pushplus.hxtrip.com/send"
|
url_old = "http://pushplus.hxtrip.com/send"
|
||||||
@@ -402,7 +412,6 @@ def weplus_bot(title: str, content: str) -> None:
|
|||||||
通过 微加机器人 推送消息。
|
通过 微加机器人 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("WE_PLUS_BOT_TOKEN"):
|
if not push_config.get("WE_PLUS_BOT_TOKEN"):
|
||||||
print("微加机器人 服务的 WE_PLUS_BOT_TOKEN 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("微加机器人 服务启动")
|
print("微加机器人 服务启动")
|
||||||
|
|
||||||
@@ -434,7 +443,6 @@ def qmsg_bot(title: str, content: str) -> None:
|
|||||||
使用 qmsg 推送消息。
|
使用 qmsg 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("QMSG_KEY") or not push_config.get("QMSG_TYPE"):
|
if not push_config.get("QMSG_KEY") or not push_config.get("QMSG_TYPE"):
|
||||||
print("qmsg 的 QMSG_KEY 或者 QMSG_TYPE 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("qmsg 服务启动")
|
print("qmsg 服务启动")
|
||||||
|
|
||||||
@@ -453,11 +461,10 @@ def wecom_app(title: str, content: str) -> None:
|
|||||||
通过 企业微信 APP 推送消息。
|
通过 企业微信 APP 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("QYWX_AM"):
|
if not push_config.get("QYWX_AM"):
|
||||||
print("QYWX_AM 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
QYWX_AM_AY = re.split(",", push_config.get("QYWX_AM"))
|
QYWX_AM_AY = re.split(",", push_config.get("QYWX_AM"))
|
||||||
if 4 < len(QYWX_AM_AY) > 5:
|
if 4 < len(QYWX_AM_AY) > 5:
|
||||||
print("QYWX_AM 设置错误!!\n取消推送")
|
print("QYWX_AM 设置错误!!")
|
||||||
return
|
return
|
||||||
print("企业微信 APP 服务启动")
|
print("企业微信 APP 服务启动")
|
||||||
|
|
||||||
@@ -550,7 +557,6 @@ def wecom_bot(title: str, content: str) -> None:
|
|||||||
通过 企业微信机器人 推送消息。
|
通过 企业微信机器人 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("QYWX_KEY"):
|
if not push_config.get("QYWX_KEY"):
|
||||||
print("企业微信机器人 服务的 QYWX_KEY 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("企业微信机器人服务启动")
|
print("企业微信机器人服务启动")
|
||||||
|
|
||||||
@@ -576,7 +582,6 @@ def telegram_bot(title: str, content: str) -> None:
|
|||||||
使用 telegram 机器人 推送消息。
|
使用 telegram 机器人 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("TG_BOT_TOKEN") or not push_config.get("TG_USER_ID"):
|
if not push_config.get("TG_BOT_TOKEN") or not push_config.get("TG_USER_ID"):
|
||||||
print("tg 服务的 bot_token 或者 user_id 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("tg 服务启动")
|
print("tg 服务启动")
|
||||||
|
|
||||||
@@ -625,9 +630,6 @@ def aibotk(title: str, content: str) -> None:
|
|||||||
or not push_config.get("AIBOTK_TYPE")
|
or not push_config.get("AIBOTK_TYPE")
|
||||||
or not push_config.get("AIBOTK_NAME")
|
or not push_config.get("AIBOTK_NAME")
|
||||||
):
|
):
|
||||||
print(
|
|
||||||
"智能微秘书 的 AIBOTK_KEY 或者 AIBOTK_TYPE 或者 AIBOTK_NAME 未设置!!\n取消推送"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
print("智能微秘书 服务启动")
|
print("智能微秘书 服务启动")
|
||||||
|
|
||||||
@@ -666,9 +668,6 @@ def smtp(title: str, content: str) -> None:
|
|||||||
or not push_config.get("SMTP_PASSWORD")
|
or not push_config.get("SMTP_PASSWORD")
|
||||||
or not push_config.get("SMTP_NAME")
|
or not push_config.get("SMTP_NAME")
|
||||||
):
|
):
|
||||||
print(
|
|
||||||
"SMTP 邮件 的 SMTP_SERVER 或者 SMTP_SSL 或者 SMTP_EMAIL 或者 SMTP_PASSWORD 或者 SMTP_NAME 未设置!!\n取消推送"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
print("SMTP 邮件 服务启动")
|
print("SMTP 邮件 服务启动")
|
||||||
|
|
||||||
@@ -712,7 +711,6 @@ def pushme(title: str, content: str) -> None:
|
|||||||
使用 PushMe 推送消息。
|
使用 PushMe 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("PUSHME_KEY"):
|
if not push_config.get("PUSHME_KEY"):
|
||||||
print("PushMe 服务的 PUSHME_KEY 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("PushMe 服务启动")
|
print("PushMe 服务启动")
|
||||||
|
|
||||||
@@ -745,7 +743,6 @@ def chronocat(title: str, content: str) -> None:
|
|||||||
or not push_config.get("CHRONOCAT_QQ")
|
or not push_config.get("CHRONOCAT_QQ")
|
||||||
or not push_config.get("CHRONOCAT_TOKEN")
|
or not push_config.get("CHRONOCAT_TOKEN")
|
||||||
):
|
):
|
||||||
print("CHRONOCAT 服务的 CHRONOCAT_URL 或 CHRONOCAT_QQ 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
print("CHRONOCAT 服务启动")
|
print("CHRONOCAT 服务启动")
|
||||||
@@ -789,17 +786,17 @@ def ntfy(title: str, content: str) -> None:
|
|||||||
"""
|
"""
|
||||||
通过 Ntfy 推送消息
|
通过 Ntfy 推送消息
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def encode_rfc2047(text: str) -> str:
|
def encode_rfc2047(text: str) -> str:
|
||||||
"""将文本编码为符合 RFC 2047 标准的格式"""
|
"""将文本编码为符合 RFC 2047 标准的格式"""
|
||||||
encoded_bytes = base64.b64encode(text.encode('utf-8'))
|
encoded_bytes = base64.b64encode(text.encode("utf-8"))
|
||||||
encoded_str = encoded_bytes.decode('utf-8')
|
encoded_str = encoded_bytes.decode("utf-8")
|
||||||
return f'=?utf-8?B?{encoded_str}?='
|
return f"=?utf-8?B?{encoded_str}?="
|
||||||
|
|
||||||
if not push_config.get("NTFY_TOPIC"):
|
if not push_config.get("NTFY_TOPIC"):
|
||||||
print("ntfy 服务的 NTFY_TOPIC 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
print("ntfy 服务启动")
|
print("ntfy 服务启动")
|
||||||
priority = '3'
|
priority = "3"
|
||||||
if not push_config.get("NTFY_PRIORITY"):
|
if not push_config.get("NTFY_PRIORITY"):
|
||||||
print("ntfy 服务的NTFY_PRIORITY 未设置!!默认设置为3")
|
print("ntfy 服务的NTFY_PRIORITY 未设置!!默认设置为3")
|
||||||
else:
|
else:
|
||||||
@@ -808,11 +805,8 @@ def ntfy(title: str, content: str) -> None:
|
|||||||
# 使用 RFC 2047 编码 title
|
# 使用 RFC 2047 编码 title
|
||||||
encoded_title = encode_rfc2047(title)
|
encoded_title = encode_rfc2047(title)
|
||||||
|
|
||||||
data = content.encode(encoding='utf-8')
|
data = content.encode(encoding="utf-8")
|
||||||
headers = {
|
headers = {"Title": encoded_title, "Priority": priority} # 使用编码后的 title
|
||||||
"Title": encoded_title, # 使用编码后的 title
|
|
||||||
"Priority": priority
|
|
||||||
}
|
|
||||||
|
|
||||||
url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC")
|
url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC")
|
||||||
response = requests.post(url, data=data, headers=headers)
|
response = requests.post(url, data=data, headers=headers)
|
||||||
@@ -821,6 +815,63 @@ def ntfy(title: str, content: str) -> None:
|
|||||||
else:
|
else:
|
||||||
print("Ntfy 推送失败!错误信息:", response.text)
|
print("Ntfy 推送失败!错误信息:", response.text)
|
||||||
|
|
||||||
|
|
||||||
|
def wxpusher_bot(title: str, content: str) -> None:
|
||||||
|
"""
|
||||||
|
通过 wxpusher 推送消息。
|
||||||
|
支持的环境变量:
|
||||||
|
- WXPUSHER_APP_TOKEN: appToken
|
||||||
|
- WXPUSHER_TOPIC_IDS: 主题ID, 多个用英文分号;分隔
|
||||||
|
- WXPUSHER_UIDS: 用户ID, 多个用英文分号;分隔
|
||||||
|
"""
|
||||||
|
if not push_config.get("WXPUSHER_APP_TOKEN"):
|
||||||
|
return
|
||||||
|
|
||||||
|
url = "https://wxpusher.zjiecode.com/api/send/message"
|
||||||
|
|
||||||
|
# 处理topic_ids和uids,将分号分隔的字符串转为数组
|
||||||
|
topic_ids = []
|
||||||
|
if push_config.get("WXPUSHER_TOPIC_IDS"):
|
||||||
|
topic_ids = [
|
||||||
|
int(id.strip())
|
||||||
|
for id in push_config.get("WXPUSHER_TOPIC_IDS").split(";")
|
||||||
|
if id.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
uids = []
|
||||||
|
if push_config.get("WXPUSHER_UIDS"):
|
||||||
|
uids = [
|
||||||
|
uid.strip()
|
||||||
|
for uid in push_config.get("WXPUSHER_UIDS").split(";")
|
||||||
|
if uid.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
# topic_ids uids 至少有一个
|
||||||
|
if not topic_ids and not uids:
|
||||||
|
print("wxpusher 服务的 WXPUSHER_TOPIC_IDS 和 WXPUSHER_UIDS 至少设置一个!!")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("wxpusher 服务启动")
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"appToken": push_config.get("WXPUSHER_APP_TOKEN"),
|
||||||
|
"content": f"<h1>{title}</h1><br/><div style='white-space: pre-wrap;'>{content}</div>",
|
||||||
|
"summary": title,
|
||||||
|
"contentType": 2,
|
||||||
|
"topicIds": topic_ids,
|
||||||
|
"uids": uids,
|
||||||
|
"verifyPayType": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
response = requests.post(url=url, json=data, headers=headers).json()
|
||||||
|
|
||||||
|
if response.get("code") == 1000:
|
||||||
|
print("wxpusher 推送成功!")
|
||||||
|
else:
|
||||||
|
print(f"wxpusher 推送失败!错误信息:{response.get('msg')}")
|
||||||
|
|
||||||
|
|
||||||
def parse_headers(headers):
|
def parse_headers(headers):
|
||||||
if not headers:
|
if not headers:
|
||||||
return {}
|
return {}
|
||||||
@@ -877,7 +928,6 @@ def custom_notify(title: str, content: str) -> None:
|
|||||||
通过 自定义通知 推送消息。
|
通过 自定义通知 推送消息。
|
||||||
"""
|
"""
|
||||||
if not push_config.get("WEBHOOK_URL") or not push_config.get("WEBHOOK_METHOD"):
|
if not push_config.get("WEBHOOK_URL") or not push_config.get("WEBHOOK_METHOD"):
|
||||||
print("自定义通知的 WEBHOOK_URL 或 WEBHOOK_METHOD 未设置!!\n取消推送")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
print("自定义通知服务启动")
|
print("自定义通知服务启动")
|
||||||
@@ -983,6 +1033,10 @@ def add_notify_function():
|
|||||||
notify_function.append(custom_notify)
|
notify_function.append(custom_notify)
|
||||||
if push_config.get("NTFY_TOPIC"):
|
if push_config.get("NTFY_TOPIC"):
|
||||||
notify_function.append(ntfy)
|
notify_function.append(ntfy)
|
||||||
|
if push_config.get("WXPUSHER_APP_TOKEN") and (
|
||||||
|
push_config.get("WXPUSHER_TOPIC_IDS") or push_config.get("WXPUSHER_UIDS")
|
||||||
|
):
|
||||||
|
notify_function.append(wxpusher_bot)
|
||||||
if not notify_function:
|
if not notify_function:
|
||||||
print(f"无推送渠道,请检查通知变量是否正确")
|
print(f"无推送渠道,请检查通知变量是否正确")
|
||||||
return notify_function
|
return notify_function
|
||||||
|
|||||||
@@ -6,4 +6,10 @@
|
|||||||
*/
|
*/
|
||||||
console.log('test scripts');
|
console.log('test scripts');
|
||||||
QLAPI.notify('test scripts', 'test desc');
|
QLAPI.notify('test scripts', 'test desc');
|
||||||
|
QLAPI.getEnvs({ searchValue: 'dddd' }).then((x) => {
|
||||||
|
console.log('getEnvs', x);
|
||||||
|
});
|
||||||
|
QLAPI.systemNotify({ title: '123', content: '231' }).then((x) => {
|
||||||
|
console.log('systemNotify', x);
|
||||||
|
});
|
||||||
console.log('test desc');
|
console.log('test desc');
|
||||||
|
|||||||
+6
-1
@@ -4,6 +4,11 @@ name: script name
|
|||||||
定时规则
|
定时规则
|
||||||
cron: 1 9 * * *
|
cron: 1 9 * * *
|
||||||
"""
|
"""
|
||||||
|
|
||||||
print("test script")
|
print("test script")
|
||||||
QLAPI.notify('test script', 'test desc')
|
print(QLAPI.notify("test script", "test desc"))
|
||||||
|
print("test systemNotify")
|
||||||
|
print(QLAPI.systemNotify({"title": "test script", "content": "dddd"}))
|
||||||
|
print("test getEnvs")
|
||||||
|
print(QLAPI.getEnvs({"searchValue": "1"}))
|
||||||
print("test desc")
|
print("test desc")
|
||||||
|
|||||||
+30
-1
@@ -178,7 +178,10 @@ 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"
|
if [[ ! $message ]]; then
|
||||||
|
message="$api"
|
||||||
|
fi
|
||||||
|
echo -e "${message}"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,4 +234,30 @@ find_cron_api() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
update_auth_config() {
|
||||||
|
local body="$1"
|
||||||
|
local tip="$2"
|
||||||
|
local currentTimeStamp=$(date +%s)
|
||||||
|
local api=$(
|
||||||
|
curl -s --noproxy "*" "http://0.0.0.0:5600/open/system/auth/reset?t=$currentTimeStamp" \
|
||||||
|
-X 'PUT' \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
|
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
||||||
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
|
-H "Origin: http://0.0.0.0:5700" \
|
||||||
|
-H "Referer: http://0.0.0.0:5700/crontab" \
|
||||||
|
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
||||||
|
--data-raw "{$body}" \
|
||||||
|
--compressed
|
||||||
|
)
|
||||||
|
code=$(echo "$api" | jq -r .code)
|
||||||
|
message=$(echo "$api" | jq -r .message)
|
||||||
|
if [[ $code == 200 ]]; then
|
||||||
|
echo -e "${tip}成功🎉"
|
||||||
|
else
|
||||||
|
echo -e "${tip}失败(${message})"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
get_token
|
get_token
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
const grpc = require('@grpc/grpc-js');
|
||||||
|
const protoLoader = require('@grpc/proto-loader');
|
||||||
|
|
||||||
|
const PROTO_PATH = `${process.env.QL_DIR}/back/protos/api.proto`;
|
||||||
|
const options = {
|
||||||
|
keepCase: true,
|
||||||
|
longs: String,
|
||||||
|
enums: String,
|
||||||
|
defaults: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const packageDefinition = protoLoader.loadSync(PROTO_PATH, options);
|
||||||
|
const apiProto = grpc.loadPackageDefinition(packageDefinition).com.ql.api;
|
||||||
|
|
||||||
|
const client = new apiProto.Api(
|
||||||
|
`0.0.0.0:5500`,
|
||||||
|
grpc.credentials.createInsecure(),
|
||||||
|
{ 'grpc.enable_http_proxy': 0 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const promisify = (fn) => {
|
||||||
|
return (...args) => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
fn.call(client, ...args, (err, response) => {
|
||||||
|
if (err) return reject(err);
|
||||||
|
resolve(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const api = {
|
||||||
|
getEnvs: promisify(client.GetEnvs),
|
||||||
|
createEnv: promisify(client.CreateEnv),
|
||||||
|
updateEnv: promisify(client.UpdateEnv),
|
||||||
|
deleteEnvs: promisify(client.DeleteEnvs),
|
||||||
|
moveEnv: promisify(client.MoveEnv),
|
||||||
|
disableEnvs: promisify(client.DisableEnvs),
|
||||||
|
enableEnvs: promisify(client.EnableEnvs),
|
||||||
|
updateEnvNames: promisify(client.UpdateEnvNames),
|
||||||
|
getEnvById: promisify(client.GetEnvById),
|
||||||
|
systemNotify: promisify(client.SystemNotify),
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = api;
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import subprocess
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import os
|
||||||
|
from typing import Dict, List
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
|
||||||
|
def error_handler(func):
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
try:
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
raise Exception(f"parse json error: {str(e)}")
|
||||||
|
except subprocess.SubprocessError as e:
|
||||||
|
raise Exception(f"node process error: {str(e)}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"unknown error: {str(e)}")
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def __init__(self):
|
||||||
|
self.temp_dir = tempfile.mkdtemp(prefix="node_client_")
|
||||||
|
self.temp_script = os.path.join(self.temp_dir, "temp_script.js")
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
try:
|
||||||
|
if os.path.exists(self.temp_script):
|
||||||
|
os.remove(self.temp_script)
|
||||||
|
os.rmdir(self.temp_dir)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def _execute_node(self, method: str, params: Dict = None) -> Dict:
|
||||||
|
node_code = f"""
|
||||||
|
const api = require('{os.getenv("QL_DIR")}/shell/preload/client.js');
|
||||||
|
|
||||||
|
(async () => {{
|
||||||
|
try {{
|
||||||
|
const result = await api.{method}({json.dumps(params) if params else ''});
|
||||||
|
console.log(JSON.stringify(result));
|
||||||
|
}} catch (error) {{
|
||||||
|
console.error(JSON.stringify({{
|
||||||
|
error: error.message,
|
||||||
|
stack: error.stack
|
||||||
|
}}));
|
||||||
|
process.exit(1);
|
||||||
|
}}
|
||||||
|
}})();
|
||||||
|
"""
|
||||||
|
|
||||||
|
with open(self.temp_script, "w", encoding="utf-8") as f:
|
||||||
|
f.write(node_code)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["node", self.temp_script],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
error_data = json.loads(result.stderr)
|
||||||
|
raise Exception(f"{error_data.get('stack')}")
|
||||||
|
|
||||||
|
return json.loads(result.stdout)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise Exception("node process timeout")
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def getEnvs(self, params: Dict = None) -> Dict:
|
||||||
|
return self._execute_node("getEnvs", params)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def createEnv(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("createEnv", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def updateEnv(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("updateEnv", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def deleteEnvs(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("deleteEnvs", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def moveEnv(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("moveEnv", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def disableEnvs(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("disableEnvs", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def enableEnvs(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("enableEnvs", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def updateEnvNames(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("updateEnvNames", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def getEnvById(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("getEnvById", data)
|
||||||
|
|
||||||
|
@error_handler
|
||||||
|
def systemNotify(self, data: Dict) -> Dict:
|
||||||
|
return self._execute_node("systemNotify", data)
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
const { execSync } = require('child_process');
|
const { execSync } = require('child_process');
|
||||||
|
const client = require('./client.js');
|
||||||
require(`./env.js`);
|
require(`./env.js`);
|
||||||
|
|
||||||
function expandRange(rangeStr, max) {
|
function expandRange(rangeStr, max) {
|
||||||
@@ -56,7 +57,9 @@ function run() {
|
|||||||
for (const key in newEnvObject) {
|
for (const key in newEnvObject) {
|
||||||
process.env[key] = newEnvObject[key];
|
process.env[key] = newEnvObject[key];
|
||||||
}
|
}
|
||||||
|
if (output) {
|
||||||
console.log(output);
|
console.log(output);
|
||||||
|
}
|
||||||
if (task_before) {
|
if (task_before) {
|
||||||
console.log('执行前置命令结束\n');
|
console.log('执行前置命令结束\n');
|
||||||
}
|
}
|
||||||
@@ -89,11 +92,16 @@ try {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
process.on('SIGTERM', (code) => {
|
||||||
|
process.exit(15);
|
||||||
|
});
|
||||||
|
|
||||||
run();
|
run();
|
||||||
|
|
||||||
const { sendNotify } = require('./notify.js');
|
const { sendNotify } = require('./notify.js');
|
||||||
global.QLAPI = {
|
global.QLAPI = {
|
||||||
notify: sendNotify,
|
notify: sendNotify,
|
||||||
|
...client,
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`run builtin code error: `, error, '\n');
|
console.log(`run builtin code error: `, error, '\n');
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import json
|
|||||||
import builtins
|
import builtins
|
||||||
import sys
|
import sys
|
||||||
import env
|
import env
|
||||||
|
import signal
|
||||||
|
from client import Client
|
||||||
|
|
||||||
|
|
||||||
def try_parse_int(value):
|
def try_parse_int(value):
|
||||||
@@ -63,6 +65,7 @@ def run():
|
|||||||
for key, value in env_json.items():
|
for key, value in env_json.items():
|
||||||
os.environ[key] = value
|
os.environ[key] = value
|
||||||
|
|
||||||
|
if len(output) > 0:
|
||||||
print(output)
|
print(output)
|
||||||
if task_before:
|
if task_before:
|
||||||
print("执行前置命令结束")
|
print("执行前置命令结束")
|
||||||
@@ -95,12 +98,18 @@ def run():
|
|||||||
os.environ[env_param] = env_str
|
os.environ[env_param] = env_str
|
||||||
|
|
||||||
|
|
||||||
|
def handle_sigterm(signum, frame):
|
||||||
|
sys.exit(15)
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
signal.signal(signal.SIGTERM, handle_sigterm)
|
||||||
|
|
||||||
run()
|
run()
|
||||||
|
|
||||||
from notify import send
|
from notify import send
|
||||||
|
|
||||||
class BaseApi:
|
class BaseApi(Client):
|
||||||
def notify(self, *args, **kwargs):
|
def notify(self, *args, **kwargs):
|
||||||
return send(*args, **kwargs)
|
return send(*args, **kwargs)
|
||||||
|
|
||||||
|
|||||||
+17
-10
@@ -193,12 +193,6 @@ fix_config() {
|
|||||||
echo
|
echo
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ ! -s $file_auth_user ]]; then
|
|
||||||
echo -e "复制一份 $file_auth_sample 为 $file_auth_user\n"
|
|
||||||
cp -fv $file_auth_sample $file_auth_user
|
|
||||||
echo
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -s $file_notify_py ]]; then
|
if [[ ! -s $file_notify_py ]]; then
|
||||||
echo -e "复制一份 $file_notify_py_sample 为 $file_notify_py\n"
|
echo -e "复制一份 $file_notify_py_sample 为 $file_notify_py\n"
|
||||||
cp -fv $file_notify_py_sample $file_notify_py
|
cp -fv $file_notify_py_sample $file_notify_py
|
||||||
@@ -444,8 +438,14 @@ clear_env() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handle_task_start() {
|
handle_task_start() {
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
local error_message=""
|
||||||
echo -e "## 开始执行... $begin_time\n"
|
if [[ $ID ]]; then
|
||||||
|
local error=$(update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp")
|
||||||
|
if [[ $error ]]; then
|
||||||
|
error_message=", 任务状态更新失败(${error})"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
echo -e "## 开始执行... ${begin_time}${error_message}\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
run_task_before() {
|
run_task_before() {
|
||||||
@@ -473,11 +473,18 @@ handle_task_end() {
|
|||||||
local end_time=$(format_time "$time_format" "$etime")
|
local end_time=$(format_time "$time_format" "$etime")
|
||||||
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
||||||
local diff_time=$(($end_timestamp - $begin_timestamp))
|
local diff_time=$(($end_timestamp - $begin_timestamp))
|
||||||
|
local suffix=""
|
||||||
|
[[ "${MANUAL:=}" == "true" ]] && suffix="(手动停止)"
|
||||||
|
|
||||||
[[ "$diff_time" == 0 ]] && diff_time=1
|
[[ "$diff_time" == 0 ]] && diff_time=1
|
||||||
|
|
||||||
echo -e "\n## 执行结束... $end_time 耗时 $diff_time 秒 "
|
if [[ $ID ]]; then
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time"
|
local error=$(update_cron "\"$ID\"" "1" "" "$log_path" "$begin_timestamp" "$diff_time")
|
||||||
|
if [[ $error ]]; then
|
||||||
|
error_message=", 任务状态更新失败(${error})"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
echo -e "\n## 执行结束$suffix... $end_time 耗时 $diff_time 秒${error_message:=} "
|
||||||
}
|
}
|
||||||
|
|
||||||
init_env
|
init_env
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@ dir_shell=$QL_DIR/shell
|
|||||||
|
|
||||||
trap "single_hanle" 2 3 20 15 14 19 1
|
trap "single_hanle" 2 3 20 15 14 19 1
|
||||||
single_hanle() {
|
single_hanle() {
|
||||||
eval handle_task_end "$@" "$cmd"
|
eval MANUAL=true handle_task_end "$@" "$cmd"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-7
@@ -489,7 +489,6 @@ main() {
|
|||||||
local time_format="%Y-%m-%d %H:%M:%S"
|
local time_format="%Y-%m-%d %H:%M:%S"
|
||||||
local time=$(date "+$time_format")
|
local time=$(date "+$time_format")
|
||||||
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
local begin_timestamp=$(format_timestamp "$time_format" "$time")
|
||||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
|
||||||
|
|
||||||
local begin_time=$(format_time "$time_format" "$time")
|
local begin_time=$(format_time "$time_format" "$time")
|
||||||
|
|
||||||
@@ -497,6 +496,8 @@ main() {
|
|||||||
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
eval echo -e "\#\# 开始执行... $begin_time\\\n" $cmd
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||||
|
|
||||||
case $p1 in
|
case $p1 in
|
||||||
update)
|
update)
|
||||||
fix_config
|
fix_config
|
||||||
@@ -537,14 +538,10 @@ main() {
|
|||||||
eval . $dir_shell/check.sh $cmd
|
eval . $dir_shell/check.sh $cmd
|
||||||
;;
|
;;
|
||||||
resetlet)
|
resetlet)
|
||||||
auth_value=$(cat $file_auth_user | jq '.retries =0' -c)
|
eval update_auth_config "\\\"retries\\\":0" "重置登录错误次数" $cmd
|
||||||
echo "$auth_value" >$file_auth_user
|
|
||||||
eval echo -e "重置登录错误次数成功" $cmd
|
|
||||||
;;
|
;;
|
||||||
resettfa)
|
resettfa)
|
||||||
auth_value=$(cat $file_auth_user | jq '.twoFactorActivated =false' | jq '.twoFactorActived =false' -c)
|
eval update_auth_config "\\\"twoFactorActivated\\\":false" "禁用两步验证" $cmd
|
||||||
echo "$auth_value" >$file_auth_user
|
|
||||||
eval echo -e "禁用两步验证成功" $cmd
|
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
eval echo -e "命令输入错误...\\\n" $cmd
|
eval echo -e "命令输入错误...\\\n" $cmd
|
||||||
|
|||||||
+25
-39
@@ -1,35 +1,21 @@
|
|||||||
import intl from 'react-intl-universal';
|
import config from '@/utils/config';
|
||||||
import React, { useEffect, useState } from 'react';
|
import { useCtx, useTheme } from '@/utils/hooks';
|
||||||
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
|
import { request } from '@/utils/http';
|
||||||
import * as DarkReader from '@umijs/ssr-darkreader';
|
|
||||||
import defaultProps from './defaultProps';
|
|
||||||
import { Link, history, Outlet, useLocation } from '@umijs/max';
|
|
||||||
import {
|
import {
|
||||||
LogoutOutlined,
|
LogoutOutlined,
|
||||||
MenuFoldOutlined,
|
MenuFoldOutlined,
|
||||||
MenuUnfoldOutlined,
|
MenuUnfoldOutlined,
|
||||||
UserOutlined,
|
UserOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import config from '@/utils/config';
|
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
|
||||||
import { request } from '@/utils/http';
|
import { history, Link, Outlet, useLocation } from '@umijs/max';
|
||||||
import './index.less';
|
import * as DarkReader from '@umijs/ssr-darkreader';
|
||||||
|
import { Avatar, Badge, Dropdown, Image, MenuProps, Tooltip } from 'antd';
|
||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import intl from 'react-intl-universal';
|
||||||
import vhCheck from 'vh-check';
|
import vhCheck from 'vh-check';
|
||||||
import { useCtx, useTheme } from '@/utils/hooks';
|
import defaultProps from './defaultProps';
|
||||||
import {
|
import './index.less';
|
||||||
message,
|
|
||||||
Badge,
|
|
||||||
Modal,
|
|
||||||
Avatar,
|
|
||||||
Dropdown,
|
|
||||||
Menu,
|
|
||||||
Image,
|
|
||||||
Popover,
|
|
||||||
Descriptions,
|
|
||||||
Tooltip,
|
|
||||||
MenuProps,
|
|
||||||
} from 'antd';
|
|
||||||
// @ts-ignore
|
|
||||||
import * as Sentry from '@sentry/react';
|
|
||||||
import { init } from '../utils/init';
|
import { init } from '../utils/init';
|
||||||
import WebSocketManager from '../utils/websocket';
|
import WebSocketManager from '../utils/websocket';
|
||||||
|
|
||||||
@@ -178,9 +164,9 @@ export default function () {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user || !user.username) return;
|
if (!user || !user.username) return;
|
||||||
const ws = WebSocketManager.getInstance(
|
const ws = WebSocketManager.getInstance(
|
||||||
`${window.location.origin}${config.apiPrefix}ws?token=${localStorage.getItem(
|
`${window.location.origin}${
|
||||||
config.authKey,
|
config.apiPrefix
|
||||||
)}`,
|
}ws?token=${localStorage.getItem(config.authKey)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -201,9 +187,6 @@ export default function () {
|
|||||||
console.log(
|
console.log(
|
||||||
`从开始至load总耗时: ${timing.loadEventEnd - timing.navigationStart}`,
|
`从开始至load总耗时: ${timing.loadEventEnd - timing.navigationStart}`,
|
||||||
);
|
);
|
||||||
Sentry.captureMessage(
|
|
||||||
`白屏时间 ${timing.responseStart - timing.navigationStart}`,
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -254,18 +237,15 @@ export default function () {
|
|||||||
<ProLayout
|
<ProLayout
|
||||||
selectedKeys={[location.pathname]}
|
selectedKeys={[location.pathname]}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
ErrorBoundary={Sentry.ErrorBoundary}
|
|
||||||
logo={
|
logo={
|
||||||
<>
|
<>
|
||||||
<Image preview={false} src="https://qn.whyour.cn/logo.png" />
|
<Image preview={false} src="https://qn.whyour.cn/logo.png" />
|
||||||
<div className="title">
|
<div className="title">
|
||||||
<span className="title">{intl.get('青龙')}</span>
|
<span className="title">{intl.get('青龙')}</span>
|
||||||
<a
|
<span
|
||||||
href={systemInfo?.changeLogLink}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
window.open(systemInfo?.changeLogLink, '_blank');
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Tooltip
|
<Tooltip
|
||||||
@@ -289,7 +269,7 @@ export default function () {
|
|||||||
</span>
|
</span>
|
||||||
</Badge>
|
</Badge>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</a>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
@@ -320,7 +300,9 @@ export default function () {
|
|||||||
shape="square"
|
shape="square"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<UserOutlined />}
|
icon={<UserOutlined />}
|
||||||
src={user.avatar ? `${config.apiPrefix}static/${user.avatar}` : ''}
|
src={
|
||||||
|
user.avatar ? `${config.apiPrefix}static/${user.avatar}` : ''
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||||
</span>
|
</span>
|
||||||
@@ -342,7 +324,11 @@ export default function () {
|
|||||||
shape="square"
|
shape="square"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<UserOutlined />}
|
icon={<UserOutlined />}
|
||||||
src={user.avatar ? `${config.apiPrefix}static/${user.avatar}` : ''}
|
src={
|
||||||
|
user.avatar
|
||||||
|
? `${config.apiPrefix}static/${user.avatar}`
|
||||||
|
: ''
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
<span style={{ marginLeft: 5 }}>{user.username}</span>
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -379,6 +379,11 @@
|
|||||||
"iGot的信息推送key,例如:https://push.hellyw.com/XXXXXXXX": "iGot information push key, e.g., https://push.hellyw.com/XXXXXXXX",
|
"iGot的信息推送key,例如:https://push.hellyw.com/XXXXXXXX": "iGot information push key, e.g., https://push.hellyw.com/XXXXXXXX",
|
||||||
"微信扫码登录后一对一推送或一对多推送下面的token(您的Token),不提供PUSH_PLUS_USER则默认为一对一推送,参考 https://www.pushplus.plus/": "After WeChat scan login, one-to-one or one-to-many push using the provided token (your Token). If PUSH_PLUS_USER is not provided, it defaults to one-to-one push. See reference at https://www.pushplus.plus/",
|
"微信扫码登录后一对一推送或一对多推送下面的token(您的Token),不提供PUSH_PLUS_USER则默认为一对一推送,参考 https://www.pushplus.plus/": "After WeChat scan login, one-to-one or one-to-many push using the provided token (your Token). If PUSH_PLUS_USER is not provided, it defaults to one-to-one push. See reference at https://www.pushplus.plus/",
|
||||||
"一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)": "The 'group code' for one-to-many push (one-to-many push -> your group (if none, create one) -> group code). If you are the creator of the group, you need to click 'View QR code' to scan and bind, otherwise, you won't receive group messages.",
|
"一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)": "The 'group code' for one-to-many push (one-to-many push -> your group (if none, create one) -> group code). If you are the creator of the group, you need to click 'View QR code' to scan and bind, otherwise, you won't receive group messages.",
|
||||||
|
"发送模板": "send template, can use type: 'html,txt,json,markdown,cloudMonitor,jenkins,route,pay'",
|
||||||
|
"发送渠道": "send channel, can use type: 'wechat,webhook,cp,mail,sms'",
|
||||||
|
"webhook编码": "webhook code",
|
||||||
|
"发送结果回调地址": "send result callback url",
|
||||||
|
"好友令牌": "friend token",
|
||||||
"用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "Token, which can be obtained after scanning and logging in, is available under 'My Account' -> 'Settings' -> 'Tokens'. Please refer to the instructions for detailed steps: https://www.weplusbot.com/",
|
"用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "Token, which can be obtained after scanning and logging in, is available under 'My Account' -> 'Settings' -> 'Tokens'. Please refer to the instructions for detailed steps: https://www.weplusbot.com/",
|
||||||
"消息接收人": "message recipient",
|
"消息接收人": "message recipient",
|
||||||
"调用版本;专业版填写pro,个人版填写personal,为空默认使用专业版": "Version, you can specify 'pro' for the Professional version and 'personal' for the Personal version. If left blank, it will default to the Professional version.",
|
"调用版本;专业版填写pro,个人版填写personal,为空默认使用专业版": "Version, you can specify 'pro' for the Professional version and 'personal' for the Personal version. If left blank, it will default to the Professional version.",
|
||||||
@@ -388,8 +393,11 @@
|
|||||||
"SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定": "The SMTP login password may also be a special passphrase, depending on the specific email service provider's instructions",
|
"SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定": "The SMTP login password may also be a special passphrase, depending on the specific email service provider's instructions",
|
||||||
"PushMe的Key,https://push.i-i.me/": "PushMe key, https://push.i-i.me/",
|
"PushMe的Key,https://push.i-i.me/": "PushMe key, https://push.i-i.me/",
|
||||||
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "The self built PushMeServer message interface address, for example: http://127.0.0.1:3010 If left blank, use the official message interface",
|
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "The self built PushMeServer message interface address, for example: http://127.0.0.1:3010 If left blank, use the official message interface",
|
||||||
"ntfy的url地址,例如 https://ntfy.sh'": "The URL address of ntfy, for example, https://ntfy.sh.",
|
"ntfy的url地址,例如 https://ntfy.sh": "The URL address of ntfy, for example, https://ntfy.sh.",
|
||||||
"ntfy的消息应用topic": "The topic for ntfy's messaging application.",
|
"ntfy的消息应用topic": "The topic for ntfy's messaging application.",
|
||||||
|
"wxPusherBot的appToken": "wxPusherBot's appToken, obtain according to docs https://wxpusher.zjiecode.com/docs/",
|
||||||
|
"wxPusherBot的topicIds": "wxPusherBot's topicIds, at least one of topicIds or uids must be configured",
|
||||||
|
"wxPusherBot的uids": "wxPusherBot's uids, at least one of topicIds or uids must be configured",
|
||||||
"请求方法": "Request Method",
|
"请求方法": "Request Method",
|
||||||
"请求头Content-Type": "Request Header Content-Type",
|
"请求头Content-Type": "Request Header Content-Type",
|
||||||
"请求链接以http或者https开头。url或者body中必须包含$title,$content可选,对应api内容的位置": "Request URL should start with http or https. URL or body must contain $title, $content is optional and corresponds to the API content position.",
|
"请求链接以http或者https开头。url或者body中必须包含$title,$content可选,对应api内容的位置": "Request URL should start with http or https. URL or body must contain $title, $content is optional and corresponds to the API content position.",
|
||||||
|
|||||||
@@ -377,8 +377,13 @@
|
|||||||
"好友": "好友",
|
"好友": "好友",
|
||||||
"要发送的用户昵称或群名,如果目标是群,需要填群名,如果目标是好友,需要填好友昵称": "要发送的用户昵称或群名,如果目标是群,需要填群名,如果目标是好友,需要填好友昵称",
|
"要发送的用户昵称或群名,如果目标是群,需要填群名,如果目标是好友,需要填好友昵称": "要发送的用户昵称或群名,如果目标是群,需要填群名,如果目标是好友,需要填好友昵称",
|
||||||
"iGot的信息推送key,例如:https://push.hellyw.com/XXXXXXXX": "iGot的信息推送key,例如:https://push.hellyw.com/XXXXXXXX",
|
"iGot的信息推送key,例如:https://push.hellyw.com/XXXXXXXX": "iGot的信息推送key,例如:https://push.hellyw.com/XXXXXXXX",
|
||||||
"微信扫码登录后一对一推送或一对多推送下面的token(您的Token),不提供PUSH_PLUS_USER则默认为一对一推送,参考 https://www.pushplus.plus/": "微信扫码登录后一对一推送或一对多推送下面的token(您的Token),不提供PUSH_PLUS_USER则默认为一对一推送,参考 https://www.pushplus.plus/",
|
"微信扫码登录后一对一推送或一对多推送下面的token(您的Token),不提供PUSH_PLUS_USER则默认为一对一推送,参考 https://www.pushplus.plus/": "微信扫码登录后一对一推送或一对多推送下面的token(你的Token),不提供PUSH_PLUS_USER则默认为一对一推送,参考 https://www.pushplus.plus/",
|
||||||
"一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)": "一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)",
|
"一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)": "一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)",
|
||||||
|
"发送模板": "发送模板,支持html,txt,json,markdown,cloudMonitor,jenkins,route,pay",
|
||||||
|
"发送渠道": "发送渠道,支持wechat,webhook,cp,mail,sms",
|
||||||
|
"webhook编码": "webhook编码,可在pushplus公众号上扩展配置出更多渠道",
|
||||||
|
"发送结果回调地址": "发送结果回调地址,会把推送最终结果通知到这个地址上",
|
||||||
|
"好友令牌": "好友令牌,微信公众号渠道填写好友令牌,企业微信渠道填写企业微信用户id",
|
||||||
"用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/",
|
"用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/",
|
||||||
"消息接收人": "消息接收人",
|
"消息接收人": "消息接收人",
|
||||||
"调用版本;专业版填写pro,个人版填写personal,为空默认使用专业版": "调用版本;专业版填写pro,个人版填写personal,为空默认使用专业版",
|
"调用版本;专业版填写pro,个人版填写personal,为空默认使用专业版": "调用版本;专业版填写pro,个人版填写personal,为空默认使用专业版",
|
||||||
@@ -390,6 +395,9 @@
|
|||||||
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口",
|
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口",
|
||||||
"ntfy的url地址,例如 https://ntfy.sh": "ntfy的url地址,例如 https://ntfy.sh",
|
"ntfy的url地址,例如 https://ntfy.sh": "ntfy的url地址,例如 https://ntfy.sh",
|
||||||
"ntfy的消息应用topic": "ntfy的消息应用topic",
|
"ntfy的消息应用topic": "ntfy的消息应用topic",
|
||||||
|
"wxPusherBot的appToken": "wxPusherBot的appToken, 按照文档获取 https://wxpusher.zjiecode.com/docs/",
|
||||||
|
"wxPusherBot的topicIds": "wxPusherBot的topicIds, topicIds 和 uids 至少配置一个才行",
|
||||||
|
"wxPusherBot的uids": "wxPusherBot的uids, topicIds 和 uids 至少配置一个才行",
|
||||||
"请求方法": "请求方法",
|
"请求方法": "请求方法",
|
||||||
"请求头Content-Type": "请求头Content-Type",
|
"请求头Content-Type": "请求头Content-Type",
|
||||||
"请求链接以http或者https开头。url或者body中必须包含$title,$content可选,对应api内容的位置": "请求链接以http或者https开头。url或者body中必须包含$title,$content可选,对应api内容的位置",
|
"请求链接以http或者https开头。url或者body中必须包含$title,$content可选,对应api内容的位置": "请求链接以http或者https开头。url或者body中必须包含$title,$content可选,对应api内容的位置",
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ export default {
|
|||||||
{ value: 'iGot', label: 'IGot' },
|
{ value: 'iGot', label: 'IGot' },
|
||||||
{ value: 'pushPlus', label: 'PushPlus' },
|
{ value: 'pushPlus', label: 'PushPlus' },
|
||||||
{ value: 'wePlusBot', label: intl.get('微加机器人') },
|
{ value: 'wePlusBot', label: intl.get('微加机器人') },
|
||||||
|
{ value: 'wxPusherBot', label: 'wxPusher' },
|
||||||
{ value: 'chat', label: intl.get('群晖chat') },
|
{ value: 'chat', label: intl.get('群晖chat') },
|
||||||
{ value: 'email', label: intl.get('邮箱') },
|
{ value: 'email', label: intl.get('邮箱') },
|
||||||
{ value: 'lark', label: intl.get('飞书机器人') },
|
{ value: 'lark', label: intl.get('飞书机器人') },
|
||||||
@@ -326,6 +327,36 @@ export default {
|
|||||||
'一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)',
|
'一对多推送的“群组编码”(一对多推送下面->您的群组(如无则创建)->群组编码,如果您是创建群组人。也需点击“查看二维码”扫描绑定,否则不能接受群组消息推送)',
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
label: 'pushplusTemplate',
|
||||||
|
tip: intl.get(
|
||||||
|
'发送模板',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'pushplusChannel',
|
||||||
|
tip: intl.get(
|
||||||
|
'发送渠道',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'pushplusWebhook',
|
||||||
|
tip: intl.get(
|
||||||
|
'webhook编码',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'pushplusCallbackUrl',
|
||||||
|
tip: intl.get(
|
||||||
|
'发送结果回调地址',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'pushplusTo',
|
||||||
|
tip: intl.get(
|
||||||
|
'好友令牌',
|
||||||
|
),
|
||||||
|
},
|
||||||
],
|
],
|
||||||
wePlusBot: [
|
wePlusBot: [
|
||||||
{
|
{
|
||||||
@@ -348,6 +379,23 @@ export default {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
wxPusherBot: [
|
||||||
|
{
|
||||||
|
label: 'wxPusherBotAppToken',
|
||||||
|
tip: intl.get('wxPusherBot的appToken'),
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'wxPusherBotTopicIds',
|
||||||
|
tip: intl.get('wxPusherBot的topicIds'),
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'wxPusherBotUids',
|
||||||
|
tip: intl.get('wxPusherBot的uids'),
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
lark: [
|
lark: [
|
||||||
{
|
{
|
||||||
label: 'larkKey',
|
label: 'larkKey',
|
||||||
|
|||||||
@@ -6,4 +6,6 @@ export const LANG_MAP = {
|
|||||||
'.mjs': 'javascript',
|
'.mjs': 'javascript',
|
||||||
'.sh': 'shell',
|
'.sh': 'shell',
|
||||||
'.ts': 'typescript',
|
'.ts': 'typescript',
|
||||||
|
'.ini': 'ini',
|
||||||
|
'.json': 'json'
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import intl from 'react-intl-universal';
|
import intl from 'react-intl-universal';
|
||||||
import { message } from 'antd';
|
import { message, notification } from 'antd';
|
||||||
import config from './config';
|
import config from './config';
|
||||||
import { history } from '@umijs/max';
|
import { history } from '@umijs/max';
|
||||||
import axios, {
|
import axios, {
|
||||||
@@ -14,7 +14,7 @@ export interface IResponseData {
|
|||||||
code?: number;
|
code?: number;
|
||||||
data?: any;
|
data?: any;
|
||||||
message?: string;
|
message?: string;
|
||||||
error?: any;
|
errors?: any[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Override<
|
export type Override<
|
||||||
@@ -41,7 +41,7 @@ const errorHandler = function (
|
|||||||
) {
|
) {
|
||||||
if (error.response) {
|
if (error.response) {
|
||||||
const msg = error.response.data
|
const msg = error.response.data
|
||||||
? error.response.data.message || error.message || error.response.data
|
? error.response.data.message || error.message
|
||||||
: error.response.statusText;
|
: error.response.statusText;
|
||||||
const responseStatus = error.response.status;
|
const responseStatus = error.response.status;
|
||||||
if ([502, 504].includes(responseStatus)) {
|
if ([502, 504].includes(responseStatus)) {
|
||||||
@@ -57,9 +57,17 @@ const errorHandler = function (
|
|||||||
return error.config?.onError(error.response);
|
return error.config?.onError(error.response);
|
||||||
}
|
}
|
||||||
|
|
||||||
message.error({
|
notification.error({
|
||||||
content: msg,
|
message: msg,
|
||||||
style: { maxWidth: 500, margin: '0 auto' },
|
description: (
|
||||||
|
<>
|
||||||
|
{error.response?.data?.errors?.map((item: any) => (
|
||||||
|
<div>
|
||||||
|
{item.message} ({item.value})
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -107,9 +115,15 @@ _request.interceptors.response.use(async (response) => {
|
|||||||
if (res.code !== 200) {
|
if (res.code !== 200) {
|
||||||
const msg = res.message || res.data;
|
const msg = res.message || res.data;
|
||||||
msg &&
|
msg &&
|
||||||
message.error({
|
notification.error({
|
||||||
content: msg,
|
message: msg,
|
||||||
style: { maxWidth: 500, margin: '0 auto' },
|
description: (
|
||||||
|
<>
|
||||||
|
{res?.errors.map((item: any) => (
|
||||||
|
<div>{item.message}</div>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
+3
-2
@@ -1,6 +1,7 @@
|
|||||||
import intl from 'react-intl-universal';
|
import intl from 'react-intl-universal';
|
||||||
import { LANG_MAP, LOG_END_SYMBOL } from './const';
|
import { LANG_MAP, LOG_END_SYMBOL } from './const';
|
||||||
import cron_parser from 'cron-parser';
|
import cron_parser from 'cron-parser';
|
||||||
|
import { ICrontab } from '@/pages/crontab/type';
|
||||||
|
|
||||||
export default function browserType() {
|
export default function browserType() {
|
||||||
// 权重:系统 + 系统版本 > 平台 > 内核 + 载体 + 内核版本 + 载体版本 > 外壳 + 外壳版本
|
// 权重:系统 + 系统版本 > 平台 > 内核 + 载体 + 内核版本 + 载体版本 > 外壳 + 外壳版本
|
||||||
@@ -343,12 +344,12 @@ export function parseCrontab(schedule: string): Date | null {
|
|||||||
|
|
||||||
export function getCrontabsNextDate(
|
export function getCrontabsNextDate(
|
||||||
schedule: string,
|
schedule: string,
|
||||||
extra_schedules: string[],
|
extra_schedules: ICrontab['extra_schedules'],
|
||||||
): Date | null {
|
): Date | null {
|
||||||
let date = parseCrontab(schedule);
|
let date = parseCrontab(schedule);
|
||||||
if (extra_schedules?.length) {
|
if (extra_schedules?.length) {
|
||||||
extra_schedules.forEach((x) => {
|
extra_schedules.forEach((x) => {
|
||||||
const _date = parseCrontab(x);
|
const _date = parseCrontab(x.schedule);
|
||||||
if (_date && (!date || _date < date)) {
|
if (_date && (!date || _date < date)) {
|
||||||
date = _date;
|
date = _date;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,7 @@
|
|||||||
import * as Sentry from '@sentry/react';
|
|
||||||
import { loader } from '@monaco-editor/react';
|
import { loader } from '@monaco-editor/react';
|
||||||
import config from './config';
|
import config from './config';
|
||||||
import { useEffect } from 'react';
|
|
||||||
import {
|
|
||||||
createRoutesFromChildren,
|
|
||||||
matchRoutes,
|
|
||||||
useLocation,
|
|
||||||
useNavigationType,
|
|
||||||
} from 'react-router-dom';
|
|
||||||
|
|
||||||
export function init(version: string) {
|
export function init(version: string) {
|
||||||
// sentry监控 init
|
|
||||||
Sentry.init({
|
|
||||||
dsn: 'https://49b9ad1a6201bfe027db296ab7c6d672@o1098464.ingest.sentry.io/6122818',
|
|
||||||
integrations: [
|
|
||||||
Sentry.reactRouterV6BrowserTracingIntegration({
|
|
||||||
useEffect,
|
|
||||||
useLocation,
|
|
||||||
useNavigationType,
|
|
||||||
createRoutesFromChildren,
|
|
||||||
matchRoutes,
|
|
||||||
}),
|
|
||||||
Sentry.replayIntegration(),
|
|
||||||
],
|
|
||||||
beforeBreadcrumb(breadcrumb) {
|
|
||||||
if (breadcrumb.data && breadcrumb.data.url) {
|
|
||||||
const url = breadcrumb.data.url.replace(/token=.*/, '');
|
|
||||||
breadcrumb.data.url = url;
|
|
||||||
}
|
|
||||||
return breadcrumb;
|
|
||||||
},
|
|
||||||
tracesSampleRate: 0.1,
|
|
||||||
tracePropagationTargets: [/^(?!\/api\/(ws|static)).*$/],
|
|
||||||
replaysSessionSampleRate: 0.1,
|
|
||||||
replaysOnErrorSampleRate: 0.1,
|
|
||||||
release: version,
|
|
||||||
});
|
|
||||||
|
|
||||||
// monaco 编辑器配置cdn和locale
|
// monaco 编辑器配置cdn和locale
|
||||||
loader.config({
|
loader.config({
|
||||||
paths: {
|
paths: {
|
||||||
|
|||||||
+1
-4
@@ -3,9 +3,6 @@
|
|||||||
"target": "es2017",
|
"target": "es2017",
|
||||||
"lib": ["ESNext"],
|
"lib": ["ESNext"],
|
||||||
"typeRoots": ["./node_modules/celebrate/lib", "./node_modules/@types"],
|
"typeRoots": ["./node_modules/celebrate/lib", "./node_modules/@types"],
|
||||||
"paths": {
|
|
||||||
"@/*": ["./back/*"]
|
|
||||||
},
|
|
||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"experimentalDecorators": true,
|
"experimentalDecorators": true,
|
||||||
"emitDecoratorMetadata": true,
|
"emitDecoratorMetadata": true,
|
||||||
@@ -21,7 +18,7 @@
|
|||||||
"noEmit": false,
|
"noEmit": false,
|
||||||
"esModuleInterop": true
|
"esModuleInterop": true
|
||||||
},
|
},
|
||||||
"include": ["./back/**/*"],
|
"include": ["./back/**/*", "./back.d.ts"],
|
||||||
"exclude": ["node_modules"],
|
"exclude": ["node_modules"],
|
||||||
"files": ["./back/index.d.ts"]
|
"files": ["./back/index.d.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-6
@@ -22,10 +22,6 @@
|
|||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"noEmit": false
|
"noEmit": false
|
||||||
},
|
},
|
||||||
"include": ["src/**/*", ".umirc.ts", "typings.d.ts", "back/**/*"],
|
"include": ["src/**/*", ".umirc.ts", "typings.d.ts"],
|
||||||
"exclude": [
|
"exclude": ["node_modules", "static", "data"]
|
||||||
"node_modules",
|
|
||||||
"static",
|
|
||||||
"data",
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-10
@@ -1,11 +1,7 @@
|
|||||||
version: 2.17.12
|
version: 2.18.1
|
||||||
changeLogLink: https://t.me/jiao_long/422
|
changeLogLink: https://t.me/jiao_long/426
|
||||||
publishTime: 2024-10-26 15:30
|
publishTime: 2025-01-15 08:00
|
||||||
changeLog: |
|
changeLog: |
|
||||||
1. 定时任务支持复制
|
1. 内置 QLAPI 增加环境变量和系统通知 api
|
||||||
2. 增加 ntfy 通知
|
2. 移除 nedb 和 sentry,不再支持 2.10.x 版本自动迁移
|
||||||
3. 适配Server酱APP分支(Server酱³),移除已废弃的旧版api入口
|
3. 修复多语言翻译
|
||||||
4. 修复任务命令带有 -m 参数时,日志目录生成异常
|
|
||||||
5. 修复登录日志无法自动保存
|
|
||||||
6. 移除任务执行前后的脚本参数
|
|
||||||
7. 定时任务外漏视图改为 10 个
|
|
||||||
|
|||||||
Reference in New Issue
Block a user