Compare commits

..

4 Commits

Author SHA1 Message Date
whyour 09a5652556 测试 2024-03-10 21:00:44 +08:00
whyour 9c47a3c5d2 测试 2024-03-10 20:13:03 +08:00
whyour 7b8ad601f8 测试 2024-03-10 19:50:07 +08:00
whyour ac90b24607 增加 update 服务 2024-03-10 19:16:51 +08:00
24 changed files with 293 additions and 435 deletions
+2 -74
View File
@@ -2,15 +2,8 @@ name: Build And Push Docker Image
on:
push:
paths-ignore:
- "*.md"
branches:
- "master"
- "develop"
tags:
- "v*"
schedule:
- cron: "00 20 * * *"
- "npm-debug"
workflow_dispatch:
jobs:
@@ -163,73 +156,8 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=registry,ref=whyour/qinglong:cache
cache-to: type=registry,ref=whyour/qinglong:cache,mode=max
- name: Image digest
run: |
echo ${{ steps.docker_build.outputs.digest }}
build310:
if: ${{ github.ref_name == 'master' }}
needs: build-static
runs-on: ubuntu-20.04
permissions:
packages: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: "8.3.1"
- uses: actions/setup-node@v4
with:
cache: "pnpm"
- name: Setup timezone
uses: szenius/set-timezone@v1.2
with:
timezoneLinux: Asia/Shanghai
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push python3.10
id: docker_build_310
uses: docker/build-push-action@v5
with:
build-args: |
MAINTAINER=${{ github.repository_owner }}
QL_BRANCH=${{ github.ref_name }}
SOURCE_COMMIT=${{ github.sha }}
network: host
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
context: .
file: ./docker/310.Dockerfile
push: true
tags: whyour/qinglong:python3.10
cache-from: type=registry,ref=whyour/qinglong:cache-python3.10
cache-to: type=registry,ref=whyour/qinglong:cache-python3.10,mode=max
- name: Image digest
run: |
echo ${{ steps.docker_build_310.outputs.digest }}
+3 -8
View File
@@ -360,10 +360,7 @@ export function parseHeaders(headers: string) {
return parsed;
}
function parseString(
input: string,
valueFormatFn?: (v: string) => string,
): Record<string, string> {
function parseString(input: string): Record<string, string> {
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
const matches: Record<string, string> = {};
@@ -375,10 +372,9 @@ function parseString(
continue;
}
let _value = value.trim();
const _value = value.trim();
try {
_value = valueFormatFn ? valueFormatFn(_value) : _value;
const jsonValue = JSON.parse(_value);
matches[_key] = jsonValue;
} catch (error) {
@@ -396,13 +392,12 @@ export function parseBody(
| 'multipart/form-data'
| 'application/x-www-form-urlencoded'
| 'text/plain',
valueFormatFn?: (v: string) => string,
) {
if (contentType === 'text/plain' || !body) {
return body;
}
const parsed = parseString(body, valueFormatFn);
const parsed = parseString(body);
switch (contentType) {
case 'multipart/form-data':
+22
View File
@@ -5,6 +5,28 @@ import Sock from './sock';
export default async ({ server }: { server: Server }) => {
await Sock({ server });
Logger.info('✌️ Sock loaded');
let exitTime = 0;
let timer: NodeJS.Timeout;
process.on('SIGINT', (singal) => {
Logger.warn(`Server need close, singal ${singal}`);
console.warn(`Server need close, singal ${singal}`);
exitTime++;
if (exitTime >= 3) {
Logger.warn('Forcing server close');
console.warn('Forcing server close');
clearTimeout(timer);
process.exit(1);
}
server.close(() => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
process.exit();
}, 15000);
});
});
process.on('uncaughtException', (error) => {
Logger.error('Uncaught exception:', error);
+5 -18
View File
@@ -4,9 +4,9 @@ import cors from 'cors';
import { Application, NextFunction, Request, Response } from 'express';
import jwt from 'express-jwt';
import Container from 'typedi';
import { Logger } from 'winston';
import config from '../config';
import SystemService from '../services/system';
import Logger from './logger';
export default ({ app }: { app: Application }) => {
app.set('trust proxy', 'loopback');
@@ -22,43 +22,30 @@ export default ({ app }: { app: Application }) => {
}),
);
app.put(
'/api/reload',
async (req: Request, res: Response, next: NextFunction) => {
try {
const systemService = Container.get(SystemService);
const result = await systemService.reloadSystem();
res.send(result);
} catch (e) {
Logger.error('🔥 error: %o', e);
return next(e);
}
},
);
app.put(
'/api/system',
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
const systemService = Container.get(SystemService);
const result = await systemService.reloadSystem('system');
res.send(result);
} catch (e) {
Logger.error('🔥 error: %o', e);
logger.error('🔥 error: %o', e);
return next(e);
}
},
);
app.put(
'/api/data',
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
const systemService = Container.get(SystemService);
const result = await systemService.reloadSystem('data');
res.send(result);
} catch (e) {
Logger.error('🔥 error: %o', e);
logger.error('🔥 error: %o', e);
return next(e);
}
},
+22 -7
View File
@@ -656,14 +656,17 @@ export default class NotificationService {
webhookContentType,
} = this.params;
if (!webhookUrl.includes('$title') && !webhookBody.includes('$title')) {
const { formatBody, formatUrl } = this.formatNotifyContent(
webhookUrl,
webhookBody,
);
if (!formatUrl && !formatBody) {
throw new Error('Url 或者 Body 中必须包含 $title');
}
const headers = parseHeaders(webhookHeaders);
const body = parseBody(webhookBody, webhookContentType, (v) =>
v?.replaceAll('$title', this.title)?.replaceAll('$content', this.content),
);
const body = parseBody(formatBody, webhookContentType);
const bodyParam = this.formatBody(webhookContentType, body);
const options = {
method: webhookMethod,
@@ -673,9 +676,6 @@ export default class NotificationService {
...bodyParam,
};
try {
const formatUrl = webhookUrl
?.replaceAll('$title', encodeURIComponent(this.title))
?.replaceAll('$content', encodeURIComponent(this.content));
const res = await got(formatUrl, options);
if (String(res.statusCode).startsWith('20')) {
return true;
@@ -700,4 +700,19 @@ export default class NotificationService {
}
return {};
}
private formatNotifyContent(url: string, body: string) {
if (!url.includes('$title') && !body.includes('$title')) {
return {};
}
return {
formatUrl: url
?.replaceAll('$title', encodeURIComponent(this.title))
?.replaceAll('$content', encodeURIComponent(this.content)),
formatBody: body
?.replaceAll('$title', this.title)
?.replaceAll('$content', this.content),
};
}
}
+50 -34
View File
@@ -1,13 +1,20 @@
import { spawn } from 'cross-spawn';
import { Response } from 'express';
import fs from 'fs';
import got from 'got';
import sum from 'lodash/sum';
import path from 'path';
import { Inject, Service } from 'typedi';
import { Service, Inject } from 'typedi';
import winston from 'winston';
import config from '../config';
import { TASK_COMMAND } from '../config/const';
import {
AuthDataType,
AuthInfo,
SystemInstance,
SystemModel,
SystemModelInfo,
} from '../data/system';
import { NotificationInfo } from '../data/notify';
import NotificationService from './notify';
import ScheduleService, { TaskCallbacks } from './schedule';
import { spawn } from 'cross-spawn';
import SockService from './sock';
import got from 'got';
import {
getPid,
killTask,
@@ -16,23 +23,13 @@ import {
promiseExec,
readDirs,
} from '../config/util';
import {
DependenceModel,
DependenceStatus,
DependenceTypes,
} from '../data/dependence';
import { NotificationInfo } from '../data/notify';
import {
AuthDataType,
AuthInfo,
SystemInstance,
SystemModel,
SystemModelInfo,
} from '../data/system';
import { TASK_COMMAND } from '../config/const';
import taskLimit from '../shared/pLimit';
import NotificationService from './notify';
import ScheduleService, { TaskCallbacks } from './schedule';
import SockService from './sock';
import tar from 'tar';
import path from 'path';
import fs from 'fs';
import sum from 'lodash/sum';
import { DependenceModel, DependenceStatus, DependenceTypes } from '../data/dependence';
@Service()
export default class SystemService {
@@ -142,10 +139,7 @@ export default class SystemService {
}
let command = `cd && ${cmd}`;
const docs = await DependenceModel.findAll({
where: {
type: DependenceTypes.nodejs,
status: DependenceStatus.installed,
},
where: { type: DependenceTypes.nodejs, status: DependenceStatus.installed },
});
if (docs.length > 0) {
command += ` && pnpm i -g`;
@@ -332,10 +326,31 @@ export default class SystemService {
return { code: 200 };
}
public async reloadSystem(target?: 'system' | 'data') {
public async reloadSystem(target: 'system' | 'data') {
const cmd = `real_time=true ql reload ${target || ''}`;
const cp = spawn(cmd, { shell: '/bin/bash' });
cp.unref();
cp.stdout.on('data', (data) => {
this.sockService.sendMessage({
type: 'reloadSystem',
message: data.toString(),
});
});
cp.stderr.on('data', (data) => {
this.sockService.sendMessage({
type: 'reloadSystem',
message: data.toString(),
});
});
cp.on('error', (err) => {
this.sockService.sendMessage({
type: 'reloadSystem',
message: JSON.stringify(err),
});
});
return { code: 200 };
}
@@ -388,7 +403,10 @@ export default class SystemService {
public async exportData(res: Response) {
try {
await promiseExec(`cd ${config.rootPath} && tar -zcvf ${config.dataTgzFile} data/`);
await tar.create(
{ gzip: true, file: config.dataTgzFile, cwd: config.rootPath },
['data'],
);
res.download(config.dataTgzFile);
} catch (error: any) {
return res.send({ code: 400, message: error.message });
@@ -398,10 +416,8 @@ export default class SystemService {
public async importData() {
try {
await promiseExec(`rm -rf ${path.join(config.tmpPath, 'data')}`);
const res = await promiseExec(
`cd ${config.tmpPath} && tar -zxvf data.tgz`,
);
return { code: 200, data: res };
await tar.x({ file: config.dataTgzFile, cwd: config.tmpPath });
return { code: 200 };
} catch (error: any) {
return { code: 400, message: error.message };
}
-3
View File
@@ -1,13 +1,10 @@
import 'reflect-metadata'; // We need this in order to use @Decorators
import config from './config';
import express from 'express';
import depInjectorLoader from './loaders/depInjector';
import Logger from './loaders/logger';
async function startServer() {
const app = express();
depInjectorLoader();
await require('./loaders/update').default({ app });
+4 -9
View File
@@ -3,11 +3,11 @@ COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
RUN set -x \
&& apk update \
&& apk add nodejs npm git \
&& npm i -g pnpm@8.3.1 pm2 tsx \
&& npm i -g pnpm@8.3.1 \
&& cd /tmp/build \
&& pnpm install --prod
FROM python:3.10-alpine
FROM python:3.10-alpine3.18
ARG QL_MAINTAINER="whyour"
LABEL maintainer="${QL_MAINTAINER}"
@@ -23,13 +23,6 @@ ENV PNPM_HOME=/root/.local/share/pnpm \
QL_DIR=/ql \
QL_BRANCH=${QL_BRANCH}
VOLUME /ql/data
EXPOSE 5700
COPY --from=builder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
COPY --from=builder /usr/local/bin/. /usr/local/bin/
RUN set -x \
&& apk update -f \
&& apk upgrade \
@@ -56,9 +49,11 @@ RUN set -x \
&& git config --global user.email "qinglong@@users.noreply.github.com" \
&& git config --global user.name "qinglong" \
&& git config --global http.postBuffer 524288000 \
&& npm install -g pnpm@8.3.1 pm2 tsx \
&& rm -rf /root/.pnpm-store \
&& rm -rf /root/.local/share/pnpm/store \
&& rm -rf /root/.cache \
&& rm -rf /root/.npm \
&& ulimit -c 0
ARG SOURCE_COMMIT
-1
View File
@@ -21,7 +21,6 @@ nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
echo -e "nginx启动成功...\n"
echo -e "======================4. 启动pm2服务========================\n"
reload_update
reload_pm2
if [[ $AutoStartBot == true ]]; then
+9
View File
@@ -1,5 +1,14 @@
module.exports = {
apps: [
{
name: 'update',
max_restarts: 10,
kill_timeout: 15000,
wait_ready: true,
listen_timeout: 10000,
time: true,
script: 'static/build/update.js',
},
{
name: 'schedule',
max_restarts: 10,
-13
View File
@@ -1,13 +0,0 @@
module.exports = {
apps: [
{
name: 'update',
max_restarts: 10,
kill_timeout: 15000,
wait_ready: true,
listen_timeout: 10000,
time: true,
script: 'static/build/update.js',
},
],
};
+2
View File
@@ -92,6 +92,7 @@
"serve-handler": "^6.1.3",
"sockjs": "^0.3.24",
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
"tar": "^6.1.15",
"toad-scheduler": "^1.6.0",
"typedi": "^0.10.0",
"uuid": "^8.3.2",
@@ -129,6 +130,7 @@
"@types/serve-handler": "^6.1.1",
"@types/sockjs": "^0.3.33",
"@types/sockjs-client": "^1.5.1",
"@types/tar": "^6.1.5",
"@types/uuid": "^8.3.4",
"@types/request-ip": "0.0.41",
"@uiw/codemirror-extensions-langs": "^4.21.9",
+18
View File
@@ -112,6 +112,9 @@ dependencies:
sqlite3:
specifier: git+https://github.com/whyour/node-sqlite3.git#v1.0.3
version: github.com/whyour/node-sqlite3/3a00af0b5d7603b7f1b290032507320b18a6b741
tar:
specifier: ^6.1.15
version: 6.1.15
toad-scheduler:
specifier: ^1.6.0
version: 1.6.1
@@ -216,6 +219,9 @@ devDependencies:
'@types/sockjs-client':
specifier: ^1.5.1
version: 1.5.1
'@types/tar':
specifier: ^6.1.5
version: 6.1.5
'@types/uuid':
specifier: ^8.3.4
version: 8.3.4
@@ -5122,6 +5128,13 @@ packages:
'@types/node': 17.0.45
dev: true
/@types/tar@6.1.5:
resolution: {integrity: sha512-qm2I/RlZij5RofuY7vohTpYNaYcrSQlN2MyjucQc7ZweDwaEWkdN/EeNh6e9zjK6uEm6PwjdMXkcj05BxZdX1Q==}
dependencies:
'@types/node': 17.0.45
minipass: 4.2.8
dev: true
/@types/triple-beam@1.3.2:
resolution: {integrity: sha512-txGIh+0eDFzKGC25zORnswy+br1Ha7hj5cMVwKIU7+s0U2AxxJru/jZSMU6OC9MJWP6+pc/hc6ZjyZShpsyY2g==}
dev: false
@@ -11077,6 +11090,11 @@ packages:
yallist: 4.0.0
dev: false
/minipass@4.2.8:
resolution: {integrity: sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==}
engines: {node: '>=8'}
dev: true
/minipass@5.0.0:
resolution: {integrity: sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==}
engines: {node: '>=8'}
+8 -19
View File
@@ -148,15 +148,6 @@ export AIBOTK_TYPE=""
## aibotk_name (必填)填写群名或用户昵称,和上面的type类型要对应
export AIBOTK_NAME=""
## 13. CHRONOCAT
## CHRONOCAT_URL 推送 http://127.0.0.1:16530
## CHRONOCAT_TOKEN 填写在CHRONOCAT文件生成的访问密钥
## CHRONOCAT_QQ 个人:user_id=个人QQ 群则填入group_id=QQ群 多个用英文;隔开同时支持个人和群 如:user_id=xxx;group_id=xxxx;group_id=xxxxx
## CHRONOCAT相关API https://chronocat.vercel.app/install/docker/official/
export CHRONOCAT_URL=""
export CHRONOCAT_QQ=""
export CHRONOCAT_TOKEN=""
## 14. SMTP
## 邮箱服务名称,比如126、163、Gmail、QQ等,支持列表 https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json
export SMTP_SERVICE=""
@@ -172,15 +163,13 @@ export SMTP_NAME=""
## PUSHME_KEY (必填)填写PushMe APP上获取的push_key
export PUSHME_KEY=""
## 15. 自定义通知
## 自定义通知 接收回调的URL
export WEBHOOK_URL=""
## WEBHOOK_BODY 和 WEBHOOK_HEADERS 多个参数时,直接换行或者使用 $'\n' 连接多行字符串,比如 export dd="line 1"$'\n'"line 2"
export WEBHOOK_BODY=""
export WEBHOOK_HEADERS=""
## 支持 GET/POST/PUT
export WEBHOOK_METHOD=""
## 支持 text/plain、application/json、multipart/form-data、application/x-www-form-urlencoded
export WEBHOOK_CONTENT_TYPE=""
## 13. CHRONOCAT
## CHRONOCAT_URL 推送 http://127.0.0.1:16530
## CHRONOCAT_TOKEN 填写在CHRONOCAT文件生成的访问密钥
## CHRONOCAT_QQ 个人:user_id=个人QQ 群则填入group_id=QQ群 多个用英文;隔开同时支持个人和群 如:user_id=xxx;group_id=xxxx;group_id=xxxxx
## CHRONOCAT相关API https://chronocat.vercel.app/install/docker/official/
export CHRONOCAT_URL=""
export CHRONOCAT_QQ=""
export CHRONOCAT_TOKEN=""
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
+14 -16
View File
@@ -819,11 +819,11 @@ function ChangeUserId(desp) {
async function qywxamNotify(text, desp) {
const MAX_LENGTH = 900;
if (desp.length > MAX_LENGTH) {
let d = desp.substr(0, MAX_LENGTH) + '\n==More==';
let d = desp.substr(0, MAX_LENGTH) + "\n==More==";
await do_qywxamNotify(text, d);
await qywxamNotify(text, desp.substr(MAX_LENGTH));
} else {
return await do_qywxamNotify(text, desp);
return await do_qywxamNotify(text,desp);
}
}
@@ -1284,15 +1284,18 @@ function chronocatNotify(title, desp) {
function webhookNotify(text, desp) {
return new Promise((resolve) => {
if (!WEBHOOK_URL.includes('$title') && !WEBHOOK_BODY.includes('$title')) {
const { formatBody, formatUrl } = formatNotifyContentFun(
WEBHOOK_URL,
WEBHOOK_BODY,
text,
desp,
);
if (!formatUrl && !formatBody) {
resolve();
return;
}
const headers = parseHeaders(WEBHOOK_HEADERS);
const body = parseBody(WEBHOOK_BODY, WEBHOOK_CONTENT_TYPE, (v) =>
v?.replaceAll('$title', text)?.replaceAll('$content', desp),
);
const body = parseBody(formatBody, WEBHOOK_CONTENT_TYPE);
const bodyParam = formatBodyFun(WEBHOOK_CONTENT_TYPE, body);
const options = {
method: WEBHOOK_METHOD,
@@ -1304,10 +1307,6 @@ function webhookNotify(text, desp) {
};
if (WEBHOOK_METHOD) {
const formatUrl = WEBHOOK_URL.replaceAll(
'$title',
encodeURIComponent(text),
).replaceAll('$content', encodeURIComponent(desp));
got(formatUrl, options).then((resp) => {
try {
if (resp.statusCode !== 200) {
@@ -1327,7 +1326,7 @@ function webhookNotify(text, desp) {
});
}
function parseString(input, valueFormatFn) {
function parseString(input) {
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
const matches = {};
@@ -1339,10 +1338,9 @@ function parseString(input, valueFormatFn) {
continue;
}
let _value = value.trim();
const _value = value.trim();
try {
_value = valueFormatFn ? valueFormatFn(_value) : _value;
const jsonValue = JSON.parse(_value);
matches[_key] = jsonValue;
} catch (error) {
@@ -1377,12 +1375,12 @@ function parseHeaders(headers) {
return parsed;
}
function parseBody(body, contentType, valueFormatFn) {
function parseBody(body, contentType) {
if (contentType === 'text/plain' || !body) {
return body;
}
const parsed = parseString(body, valueFormatFn);
const parsed = parseString(body);
switch (contentType) {
case 'multipart/form-data':
+73 -101
View File
@@ -133,9 +133,9 @@ def bark(title: str, content: str, **kwargs) -> None:
print("bark 服务启动")
BARK_PUSH = kwargs.get("BARK_PUSH", push_config.get("BARK_PUSH"))
if BARK_PUSH.startswith("http"):
url = f"{BARK_PUSH}/{urllib.parse.quote_plus(title)}/{urllib.parse.quote_plus(content)}"
url = f'{BARK_PUSH}/{urllib.parse.quote_plus(title)}/{urllib.parse.quote_plus(content)}'
else:
url = f"https://api.day.app/{BARK_PUSH}/{urllib.parse.quote_plus(title)}/{urllib.parse.quote_plus(content)}"
url = f'https://api.day.app/{BARK_PUSH}/{urllib.parse.quote_plus(title)}/{urllib.parse.quote_plus(content)}'
bark_params = {
"BARK_ARCHIVE": "isArchive",
@@ -176,10 +176,7 @@ def dingding_bot(title: str, content: str, **kwargs) -> None:
"""
使用 钉钉机器人 推送消息。
"""
if not (
(kwargs.get("DD_BOT_SECRET") and kwargs.get("DD_BOT_TOKEN"))
or (push_config.get("DD_BOT_SECRET") and push_config.get("DD_BOT_TOKEN"))
):
if not ((kwargs.get("DD_BOT_SECRET") and kwargs.get("DD_BOT_TOKEN")) or (push_config.get("DD_BOT_SECRET") and push_config.get("DD_BOT_TOKEN"))):
print("钉钉机器人 服务的 DD_BOT_SECRET 或者 DD_BOT_TOKEN 未设置!!\n取消推送")
return
print("钉钉机器人 服务启动")
@@ -198,7 +195,7 @@ def dingding_bot(title: str, content: str, **kwargs) -> None:
secret_enc, string_to_sign_enc, digestmod=hashlib.sha256
).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
url = f"https://oapi.dingtalk.com/robot/send?access_token={DD_BOT_TOKEN}&timestamp={timestamp}&sign={sign}"
url = f'https://oapi.dingtalk.com/robot/send?access_token={DD_BOT_TOKEN}&timestamp={timestamp}&sign={sign}'
headers = {"Content-Type": "application/json;charset=utf-8"}
data = {"msgtype": "text", "text": {"content": f"{title}\n\n{content}"}}
response = requests.post(
@@ -220,7 +217,7 @@ def feishu_bot(title: str, content: str, **kwargs) -> None:
return
print("飞书 服务启动")
FSKEY = kwargs.get("DD_BOT_SECRET", push_config.get("FSKEY"))
url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{FSKEY}"
url = f'https://open.feishu.cn/open-apis/bot/v2/hook/{FSKEY}'
data = {"msg_type": "text", "content": {"text": f"{title}\n\n{content}"}}
response = requests.post(url, data=json.dumps(data)).json()
@@ -234,10 +231,7 @@ def go_cqhttp(title: str, content: str, **kwargs) -> None:
"""
使用 go_cqhttp 推送消息。
"""
if not (
(kwargs.get("GOBOT_URL") and kwargs.get("GOBOT_QQ"))
or (push_config.get("GOBOT_URL") and push_config.get("GOBOT_QQ"))
):
if not ((kwargs.get("GOBOT_URL") and kwargs.get("GOBOT_QQ")) or (push_config.get("GOBOT_URL") and push_config.get("GOBOT_QQ"))):
print("go-cqhttp 服务的 GOBOT_URL 或 GOBOT_QQ 未设置!!\n取消推送")
return
print("go-cqhttp 服务启动")
@@ -250,7 +244,7 @@ def go_cqhttp(title: str, content: str, **kwargs) -> None:
GOBOT_QQ = push_config.get("GOBOT_QQ")
GOBOT_TOKEN = push_config.get("GOBOT_TOKEN")
url = f"{GOBOT_URL}?access_token={GOBOT_TOKEN}&{GOBOT_QQ}&message=标题:{title}\n内容:{content}"
url = f'{GOBOT_URL}?access_token={GOBOT_TOKEN}&{GOBOT_QQ}&message=标题:{title}\n内容:{content}'
response = requests.get(url).json()
if response["status"] == "ok":
@@ -263,10 +257,7 @@ def gotify(title: str, content: str, **kwargs) -> None:
"""
使用 gotify 推送消息。
"""
if not (
(kwargs.get("GOTIFY_URL") and kwargs.get("GOTIFY_TOKEN"))
or (push_config.get("GOTIFY_URL") and push_config.get("GOTIFY_TOKEN"))
):
if not ((kwargs.get("GOTIFY_URL") and kwargs.get("GOTIFY_TOKEN")) or (push_config.get("GOTIFY_URL") and push_config.get("GOTIFY_TOKEN"))):
print("gotify 服务的 GOTIFY_URL 或 GOTIFY_TOKEN 未设置!!\n取消推送")
return
print("gotify 服务启动")
@@ -279,7 +270,7 @@ def gotify(title: str, content: str, **kwargs) -> None:
GOTIFY_TOKEN = push_config.get("GOTIFY_TOKEN")
GOTIFY_PRIORITY = kwargs.get("GOTIFY_PRIORITY")
url = f"{GOTIFY_URL}/message?token={GOTIFY_TOKEN}"
url = f'{GOTIFY_URL}/message?token={GOTIFY_TOKEN}'
data = {
"title": title,
"message": content,
@@ -302,7 +293,7 @@ def iGot(title: str, content: str, **kwargs) -> None:
return
print("iGot 服务启动")
IGOT_PUSH_KEY = kwargs.get("IGOT_PUSH_KEY", push_config.get("IGOT_PUSH_KEY"))
url = f"https://push.hellyw.com/{IGOT_PUSH_KEY}"
url = f'https://push.hellyw.com/{IGOT_PUSH_KEY}'
data = {"title": title, "content": content}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
response = requests.post(url, data=data, headers=headers).json()
@@ -325,9 +316,9 @@ def serverJ(title: str, content: str, **kwargs) -> None:
data = {"text": title, "desp": content.replace("\n", "\n\n")}
if PUSH_KEY.find("SCT") != -1:
url = f"https://sctapi.ftqq.com/{PUSH_KEY}.send"
url = f'https://sctapi.ftqq.com/{PUSH_KEY}.send'
else:
url = f"https://sc.ftqq.com/{PUSH_KEY}.send"
url = f'https://sc.ftqq.com/{PUSH_KEY}.send'
response = requests.post(url, data=data).json()
if response.get("errno") == 0 or response.get("code") == 0:
@@ -370,10 +361,7 @@ def chat(title: str, content: str, **kwargs) -> None:
"""
通过Chat 推送消息
"""
if not (
(kwargs.get("CHAT_URL") and kwargs.get("CHAT_TOKEN"))
or (push_config.get("CHAT_URL") and push_config.get("CHAT_TOKEN"))
):
if not ((kwargs.get("CHAT_URL") and kwargs.get("CHAT_TOKEN")) or (push_config.get("CHAT_URL") and push_config.get("CHAT_TOKEN"))):
print("chat 服务的 CHAT_URL或CHAT_TOKEN 未设置!!\n取消推送")
return
print("chat 服务启动")
@@ -435,10 +423,7 @@ def qmsg_bot(title: str, content: str, **kwargs) -> None:
"""
使用 qmsg 推送消息。
"""
if not (
(kwargs.get("QMSG_KEY") and kwargs.get("QMSG_TYPE"))
or (push_config.get("QMSG_KEY") and push_config.get("QMSG_TYPE"))
):
if not ((kwargs.get("QMSG_KEY") and kwargs.get("QMSG_TYPE")) or (push_config.get("QMSG_KEY") and push_config.get("QMSG_TYPE"))):
print("qmsg 的 QMSG_KEY 或者 QMSG_TYPE 未设置!!\n取消推送")
return
print("qmsg 服务启动")
@@ -449,7 +434,7 @@ def qmsg_bot(title: str, content: str, **kwargs) -> None:
QMSG_KEY = push_config.get("QMSG_KEY")
QMSG_TYPE = push_config.get("QMSG_TYPE")
url = f"https://qmsg.zendee.cn/{QMSG_TYPE}/{QMSG_KEY}"
url = f'https://qmsg.zendee.cn/{QMSG_TYPE}/{QMSG_KEY}'
payload = {"msg": f'{title}\n\n{content.replace("----", "-")}'.encode("utf-8")}
response = requests.post(url=url, params=payload).json()
@@ -590,10 +575,7 @@ def telegram_bot(title: str, content: str, **kwargs) -> None:
"""
使用 telegram 机器人 推送消息。
"""
if not (
(kwargs.get("TG_BOT_TOKEN") and kwargs.get("TG_USER_ID"))
or (push_config.get("TG_BOT_TOKEN") and push_config.get("TG_USER_ID"))
):
if not ((kwargs.get("TG_BOT_TOKEN") and kwargs.get("TG_USER_ID")) or (push_config.get("TG_BOT_TOKEN") and push_config.get("TG_USER_ID"))):
print("tg 服务的 TG_BOT_TOKEN 或者 TG_USER_ID 未设置!!\n取消推送")
return
print("tg 服务启动")
@@ -608,7 +590,9 @@ def telegram_bot(title: str, content: str, **kwargs) -> None:
TG_API_HOST = kwargs.get("TG_API_HOST", push_config.get("TG_API_HOST"))
url = f"{TG_API_HOST}/bot{TG_BOT_TOKEN}/sendMessage"
else:
url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendMessage"
url = (
f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendMessage"
)
headers = {"Content-Type": "application/x-www-form-urlencoded"}
payload = {
"chat_id": str(TG_USER_ID),
@@ -616,10 +600,7 @@ def telegram_bot(title: str, content: str, **kwargs) -> None:
"disable_web_page_preview": "true",
}
proxies = None
if not (
(kwargs.get("TG_PROXY_HOST") and kwargs.get("TG_PROXY_PORT"))
or (push_config.get("TG_PROXY_HOST") and push_config.get("TG_PROXY_PORT"))
):
if not ((kwargs.get("TG_PROXY_HOST") and kwargs.get("TG_PROXY_PORT")) or (push_config.get("TG_PROXY_HOST") and push_config.get("TG_PROXY_PORT"))):
if kwargs.get("TG_PROXY_HOST") and kwargs.get("TG_PROXY_PORT"):
TG_PROXY_HOST = kwargs.get("TG_PROXY_HOST")
TG_PROXY_PORT = kwargs.get("TG_PROXY_PORT")
@@ -627,12 +608,16 @@ def telegram_bot(title: str, content: str, **kwargs) -> None:
TG_PROXY_HOST = kwargs.get("TG_PROXY_HOST")
TG_PROXY_PORT = kwargs.get("TG_PROXY_PORT")
if kwargs.get("TG_PROXY_AUTH") or push_config.get("TG_PROXY_AUTH"):
TG_PROXY_AUTH = kwargs.get(
"TG_PROXY_AUTH", push_config.get("TG_PROXY_AUTH")
)
TG_PROXY_AUTH = kwargs.get("TG_PROXY_AUTH", push_config.get("TG_PROXY_AUTH"))
if TG_PROXY_AUTH is not None and "@" not in TG_PROXY_HOST:
TG_PROXY_HOST = TG_PROXY_AUTH + "@" + TG_PROXY_HOST
proxyStr = "http://{}:{}".format(TG_PROXY_HOST, TG_PROXY_PORT)
TG_PROXY_HOST = (
TG_PROXY_AUTH
+ "@"
+ TG_PROXY_HOST
)
proxyStr = "http://{}:{}".format(
TG_PROXY_HOST, TG_PROXY_PORT
)
proxies = {"http": proxyStr, "https": proxyStr}
response = requests.post(
url=url, headers=headers, params=payload, proxies=proxies
@@ -653,23 +638,20 @@ def aibotk(title: str, content: str, **kwargs) -> None:
kwargs.get("AIBOTK_KEY")
and kwargs.get("AIBOTK_TYPE")
and kwargs.get("AIBOTK_NAME")
)
or (
)
or
(
push_config.get("AIBOTK_KEY")
and push_config.get("AIBOTK_TYPE")
and push_config.get("AIBOTK_NAME")
)
):
):
print(
"智能微秘书 的 AIBOTK_KEY 或者 AIBOTK_TYPE 或者 AIBOTK_NAME 未设置!!\n取消推送"
)
return
print("智能微秘书 服务启动")
if (
kwargs.get("AIBOTK_KEY")
and kwargs.get("AIBOTK_TYPE")
and kwargs.get("AIBOTK_NAME")
):
if kwargs.get("AIBOTK_KEY") and kwargs.get("AIBOTK_TYPE") and kwargs.get("AIBOTK_NAME"):
AIBOTK_KEY = kwargs.get("AIBOTK_KEY")
AIBOTK_TYPE = kwargs.get("AIBOTK_TYPE")
AIBOTK_NAME = kwargs.get("AIBOTK_NAME")
@@ -705,22 +687,19 @@ def smtp(title: str, content: str, **kwargs) -> None:
"""
使用 SMTP 邮件 推送消息。
"""
if not (
(
kwargs.get("SMTP_SERVER")
and kwargs.get("SMTP_SSL")
and kwargs.get("SMTP_EMAIL")
and kwargs.get("SMTP_PASSWORD")
and kwargs.get("SMTP_NAME")
)
or (
push_config.get("SMTP_SERVER")
and push_config.get("SMTP_SSL")
and push_config.get("SMTP_EMAIL")
and push_config.get("SMTP_PASSWORD")
and push_config.get("SMTP_NAME")
)
):
if not ((
kwargs.get("SMTP_SERVER")
and kwargs.get("SMTP_SSL")
and kwargs.get("SMTP_EMAIL")
and kwargs.get("SMTP_PASSWORD")
and kwargs.get("SMTP_NAME")
) or (
push_config.get("SMTP_SERVER")
and push_config.get("SMTP_SSL")
and push_config.get("SMTP_EMAIL")
and push_config.get("SMTP_PASSWORD")
and push_config.get("SMTP_NAME")
)):
print(
"SMTP 邮件 的 SMTP_SERVER 或者 SMTP_SSL 或者 SMTP_EMAIL 或者 SMTP_PASSWORD 或者 SMTP_NAME 未设置!!\n取消推送"
)
@@ -766,7 +745,9 @@ def smtp(title: str, content: str, **kwargs) -> None:
if SMTP_SSL == "true"
else smtplib.SMTP(SMTP_SERVER)
)
smtp_server.login(SMTP_EMAIL, SMTP_PASSWORD)
smtp_server.login(
SMTP_EMAIL, SMTP_PASSWORD
)
smtp_server.sendmail(
SMTP_EMAIL,
SMTP_EMAIL,
@@ -788,7 +769,7 @@ def pushme(title: str, content: str, **kwargs) -> None:
print("PushMe 服务启动")
PUSHME_KEY = kwargs.get("PUSHME_KEY", push_config.get("PUSHME_KEY"))
url = f"https://push.i-i.me/?push_key={PUSHME_KEY}"
url = f'https://push.i-i.me/?push_key={PUSHME_KEY}'
data = {
"title": title,
"content": content,
@@ -805,18 +786,15 @@ def chronocat(title: str, content: str, **kwargs) -> None:
"""
使用 CHRONOCAT 推送消息。
"""
if not (
(
push_config.get("CHRONOCAT_URL")
and push_config.get("CHRONOCAT_QQ")
and push_config.get("CHRONOCAT_TOKEN")
)
or (
push_config.get("CHRONOCAT_URL")
and push_config.get("CHRONOCAT_QQ")
and push_config.get("CHRONOCAT_TOKEN")
)
):
if not ((
push_config.get("CHRONOCAT_URL")
and push_config.get("CHRONOCAT_QQ")
and push_config.get("CHRONOCAT_TOKEN")
) or (
push_config.get("CHRONOCAT_URL")
and push_config.get("CHRONOCAT_QQ")
and push_config.get("CHRONOCAT_TOKEN")
)):
print("CHRONOCAT 服务的 CHRONOCAT_URL 或 CHRONOCAT_QQ 未设置!!\n取消推送")
return
print("CHRONOCAT 服务启动")
@@ -836,10 +814,10 @@ def chronocat(title: str, content: str, **kwargs) -> None:
user_ids = re.findall(r"user_id=(\d+)", CHRONOCAT_QQ)
group_ids = re.findall(r"group_id=(\d+)", CHRONOCAT_QQ)
url = f"{CHRONOCAT_URL}/api/message/send"
url = f'{CHRONOCAT_URL}/api/message/send'
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {CHRONOCAT_TOKEN}",
"Authorization": f'Bearer {CHRONOCAT_TOKEN}',
}
for chat_type, ids in [(1, user_ids), (2, group_ids)]:
@@ -887,14 +865,13 @@ def parse_headers(headers):
return parsed
def parse_string(input_string, value_format_fn=None):
def parse_string(input_string):
matches = {}
pattern = r"(\w+):\s*((?:(?!\n\w+:).)*)"
pattern = r'(\w+):\s*((?:(?!\n\w+:).)*)'
regex = re.compile(pattern)
for match in regex.finditer(input_string):
key, value = match.group(1).strip(), match.group(2).strip()
try:
value = value_format_fn(value) if value_format_fn else value
json_value = json.loads(value)
matches[key] = json_value
except:
@@ -902,11 +879,11 @@ def parse_string(input_string, value_format_fn=None):
return matches
def parse_body(body, content_type, value_format_fn=None):
def parse_body(body, content_type):
if not body or content_type == "text/plain":
return body
parsed = parse_string(input_string, value_format_fn)
parsed = parse_string(input_string)
if content_type == "application/x-www-form-urlencoded":
data = urlencode(parsed, doseq=True)
@@ -947,19 +924,16 @@ def custom_notify(title: str, content: str) -> None:
WEBHOOK_BODY = push_config.get("WEBHOOK_BODY")
WEBHOOK_HEADERS = push_config.get("WEBHOOK_HEADERS")
if "$title" not in WEBHOOK_URL and "$title" not in WEBHOOK_BODY:
formatUrl, formatBody = format_notify_content(
WEBHOOK_URL, WEBHOOK_BODY, title, content
)
if not formatUrl and not formatBody:
print("请求头或者请求体中必须包含 $title 和 $content")
return
headers = parse_headers(WEBHOOK_HEADERS)
body = parse_body(
WEBHOOK_BODY,
WEBHOOK_CONTENT_TYPE,
lambda v: v.replace("$title", title).replace("$content", content),
)
formatted_url = WEBHOOK_URL.replace(
"$title", urllib.parse.quote_plus(title)
).replace("$content", urllib.parse.quote_plus(content))
body = parse_body(formatBody, WEBHOOK_CONTENT_TYPE)
response = requests.request(
method=WEBHOOK_METHOD, url=formatUrl, headers=headers, timeout=15, data=body
)
@@ -1054,9 +1028,7 @@ def send(title: str, content: str, **kwargs) -> None:
add_notify_function()
ts = [
threading.Thread(
target=mode, args=(title, content), kwargs=kwargs, name=mode.__name__
)
threading.Thread(target=mode, args=(title, content),kwargs=kwargs, name=mode.__name__)
for mode in notify_function
]
[t.start() for t in ts]
-1
View File
@@ -81,7 +81,6 @@ main() {
check_ql
check_nginx
check_pm2
reload_update
reload_pm2
echo -e "\n=====> 检测结束\n"
}
+1 -13
View File
@@ -293,7 +293,7 @@ git_clone_scripts() {
set_proxy "$proxy"
git clone -q --depth=1 $part_cmd $url $dir
git clone --depth=1 $part_cmd $url $dir
exit_status=$?
unset_proxy
@@ -305,11 +305,6 @@ random_range() {
echo $((RANDOM % ($end - $beg) + $beg))
}
delete_pm2() {
cd $dir_root
pm2 delete ecosystem.config.js
}
reload_pm2() {
cd $dir_root
restore_env_vars
@@ -317,13 +312,6 @@ reload_pm2() {
pm2 startOrGracefulReload ecosystem.config.js
}
reload_update() {
cd $dir_root
restore_env_vars
pm2 flush &>/dev/null
pm2 startOrGracefulReload other.config.js
}
diff_time() {
local format="$1"
local begin_time="$2"
+22 -34
View File
@@ -34,6 +34,7 @@ output_list_add_drop() {
if [[ -s $list ]]; then
echo -e "检测到有${type}的定时任务:"
cat $list
echo
fi
}
@@ -44,7 +45,7 @@ del_cron() {
local path=$2
local detail=""
local ids=""
echo -e "\n开始尝试自动删除失效的定时任务..."
echo -e "开始尝试自动删除失效的定时任务..."
for cron in $(cat $list_drop); do
local id=$(cat $list_crontab_user | grep -E "$cmd_task.* $cron" | perl -pe "s|.*ID=(.*) $cmd_task.* $cron\.*|\1|" | head -1 | awk -F " " '{print $1}')
if [[ $ids ]]; then
@@ -75,7 +76,7 @@ del_cron() {
add_cron() {
local list_add=$1
local path=$2
echo -e "\n开始尝试自动添加定时任务..."
echo -e "开始尝试自动添加定时任务..."
local detail=""
cd $dir_scripts
for file in $(cat $list_add); do
@@ -85,20 +86,19 @@ add_cron() {
cron_line=$(
perl -ne "{
print if /.*([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*]( |,|\").*$file_name/
}" $file 2>/dev/null |
}" $file |
perl -pe "{
s|[^\d\*]*(([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*])( \|,\|\").*/?$file_name.*|\1|g;
s|\*([\d\*])(.*)|\1\2|g;
s| | |g;
}" 2>/dev/null | sort -u | head -1
}" | sort -u | head -1
)
cron_name=$(grep "new Env" $file | awk -F "\(" '{print $2}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
[[ -z $cron_name ]] && cron_name="$file_name"
[[ -z $cron_line ]] && cron_line=$(grep "cron:" $file | awk -F ":" '{print $2}' | head -1 | xargs)
[[ -z $cron_line ]] && cron_line=$(grep "cron " $file | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
[[ -z $cron_line ]] && cron_line="$default_cron"
cron_name=$(grep "new Env" $file | awk -F "\(" '{print $2}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
[[ -z $cron_name ]] && cron_name=$(grep "name:" $file | awk -F ":" '{print $2}' | head -1 | xargs)
[[ -z $cron_name ]] && cron_name=$(basename "$file_name")
result=$(add_cron_api "${cron_line}:${cmd_task} ${file}:${cron_name}:${SUB_ID}")
result=$(add_cron_api "$cron_line:$cmd_task $file:$cron_name:$SUB_ID")
echo -e "$result"
if [[ $detail ]]; then
detail="${detail}${result}\n"
@@ -135,10 +135,10 @@ update_repo() {
git_clone_scripts "${formatUrl}" ${repo_path} "${branch}" "${proxy}"
if [[ $exit_status -eq 0 ]]; then
echo -e "拉取 ${uniq_path} 成功...\n"
echo -e "\n拉取 ${uniq_path} 成功...\n"
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
else
echo -e "拉取 ${uniq_path} 失败,请检查日志...\n"
echo -e "\n拉取 ${uniq_path} 失败,请检查日志...\n"
fi
}
@@ -195,7 +195,7 @@ update_raw() {
[[ -z $cron_line ]] && cron_line=$(grep "cron:" $raw_file_name | awk -F ":" '{print $2}' | head -1 | xargs)
[[ -z $cron_line ]] && cron_line=$(grep "cron " $raw_file_name | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
[[ -z $cron_line ]] && cron_line="$default_cron"
result=$(add_cron_api "${cron_line}:${cmd_task} ${filename}:${cron_name}:${SUB_ID}")
result=$(add_cron_api "$cron_line:$cmd_task $filename:$cron_name:$SUB_ID")
echo -e "$result\n"
notify_api "新增任务通知" "\n$result"
# update_cron_api "$cron_line:$cmd_task $filename:$cron_name:$cron_id"
@@ -231,25 +231,22 @@ usage() {
}
reload_qinglong() {
delete_pm2
local reload_target="${1}"
local primary_branch="master"
if [[ "${QL_BRANCH}" == "develop" ]] || [[ "${QL_BRANCH}" == "debian" ]] || [[ "${QL_BRANCH}" == "debian-dev" ]]; then
primary_branch="${QL_BRANCH}"
if [[ "${QL_BRANCH}" == "develop" ]]; then
primary_branch="develop"
fi
if [[ "$reload_target" == 'system' ]]; then
rm -rf ${dir_root}/back ${dir_root}/cli ${dir_root}/docker ${dir_root}/sample ${dir_root}/shell ${dir_root}/src
mv -f ${dir_tmp}/qinglong-${primary_branch}/* ${dir_root}/
cp -rf ${dir_tmp}/qinglong-${primary_branch}/* ${dir_root}/
rm -rf $dir_static/*
mv -f ${dir_tmp}/qinglong-static-${primary_branch}/* ${dir_static}/
cp -rf ${dir_tmp}/qinglong-static-${primary_branch}/* ${dir_static}/
cp -f $file_config_sample $dir_config/config.sample.sh
fi
if [[ "$reload_target" == 'data' ]]; then
rm -rf ${dir_root}/data/*
mv -f ${dir_tmp}/data/* ${dir_root}/data/
rm -rf ${dir_root}/data
cp -rf ${dir_tmp}/data ${dir_root}/
fi
reload_pm2
@@ -261,7 +258,7 @@ update_qinglong() {
local mirror="gitee"
local downloadQLUrl="https://gitee.com/whyour/qinglong/repository/archive"
local downloadStaticUrl="https://gitee.com/whyour/qinglong-static/repository/archive"
local githubStatus=$(curl -s --noproxy "*" -m 2 -IL "https://google.com" | grep 200)
local githubStatus=$(curl -s -m 2 -IL "https://google.com" | grep 200)
if [[ ! -z $githubStatus ]]; then
mirror="github"
downloadQLUrl="https://github.com/whyour/qinglong/archive/refs/heads"
@@ -313,12 +310,9 @@ check_update_dep() {
echo -e "更新包下载成功..."
if [[ "$needRestart" == 'true' ]]; then
delete_pm2
rm -rf ${dir_root}/back ${dir_root}/cli ${dir_root}/docker ${dir_root}/sample ${dir_root}/shell ${dir_root}/src
mv -f ${dir_tmp}/qinglong-${primary_branch}/* ${dir_root}/
cp -rf ${dir_tmp}/qinglong-${primary_branch}/* ${dir_root}/
rm -rf $dir_static/*
mv -f ${dir_tmp}/qinglong-static-${primary_branch}/* ${dir_static}/
cp -rf ${dir_tmp}/qinglong-static-${primary_branch}/* ${dir_static}/
cp -f $file_config_sample $dir_config/config.sample.sh
reload_pm2
@@ -423,15 +417,9 @@ gen_list_repo() {
fi
for file in ${files}; do
dirPath=$(dirname "$file")
filename=$(basename "$file")
filePath="${uniq_path}/${filename}"
if [[ $dirPath ]] && [[ $dirPath != '.' ]]; then
mkdir -p "${dir_scripts}/${uniq_path}/${dirPath}"
filePath="${uniq_path}/${dirPath}/${filename}"
fi
cp -f $file "${dir_scripts}/$filePath"
echo "$filePath" >>"$dir_list_tmp/${uniq_path}_scripts.list"
cp -f $file "$dir_scripts/${uniq_path}/${filename}"
echo "${uniq_path}/${filename}" >>"$dir_list_tmp/${uniq_path}_scripts.list"
# cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* ${uniq_path}_${filename}" | perl -pe "s|.*ID=(.*) $cmd_task.* ${uniq_path}_${filename}\.*|\1|" | head -1 | awk -F " " '{print $1}')
# if [[ $cron_id ]]; then
# result=$(update_cron_command_api "$cmd_task ${uniq_path}/${filename}:$cron_id")
+5 -7
View File
@@ -1,11 +1,10 @@
import { disableBody } from '@/utils';
import config from '@/utils/config';
import intl from 'react-intl-universal';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { Statistic, Modal, Tag, Button, Spin, message } from 'antd';
import { request } from '@/utils/http';
import config from '@/utils/config';
import WebSocketManager from '@/utils/websocket';
import Ansi from 'ansi-to-react';
import { Button, Modal, Statistic, message } from 'antd';
import { useCallback, useEffect, useRef, useState } from 'react';
import intl from 'react-intl-universal';
const { Countdown } = Statistic;
@@ -133,7 +132,6 @@ const CheckUpdate = ({ systemInfo }: any) => {
),
duration: 30,
});
disableBody();
setTimeout(() => {
window.location.reload();
}, 30000);
@@ -222,7 +220,7 @@ const CheckUpdate = ({ systemInfo }: any) => {
</Button>
<Button
type="primary"
onClick={() => reloadSystem('reload')}
onClick={() => reloadSystem('system')}
style={{ marginLeft: 8 }}
>
{intl.get('重新启动')}
+6 -14
View File
@@ -22,7 +22,6 @@ import { UploadOutlined } from '@ant-design/icons';
import Countdown from 'antd/lib/statistic/Countdown';
import useProgress from './progress';
import pick from 'lodash/pick';
import { disableBody } from '@/utils';
const dataMap = {
'log-remove-frequency': 'logRemoveFrequency',
@@ -158,7 +157,6 @@ const Other = ({
),
duration: 30,
});
disableBody();
setTimeout(() => {
window.location.reload();
}, 30000);
@@ -273,18 +271,12 @@ const Other = ({
showUploadList={false}
maxCount={1}
action={`${config.apiPrefix}system/data/import`}
onChange={({ file, event }) => {
if (event?.percent) {
showUploadProgress(
Math.min(parseFloat(event?.percent.toFixed(1)), 99),
);
}
if (file.status === 'done') {
showUploadProgress(100);
showReloadModal();
}
if (file.status === 'error') {
message.error('上传失败');
onChange={(e) => {
if (e.event?.percent) {
showUploadProgress(parseFloat(e.event?.percent.toFixed(1)));
if (e.event?.percent === 100) {
showReloadModal();
}
}
}}
name="data"
+11 -23
View File
@@ -2,42 +2,30 @@ import intl from 'react-intl-universal';
import { Modal, Progress } from 'antd';
import { useRef } from 'react';
const ProgressElement = ({ percent }: { percent: number }) => (
<Progress
style={{ display: 'flex', justifyContent: 'center' }}
type="circle"
percent={percent}
/>
);
export default function useProgress(title: string) {
const modalRef = useRef<ReturnType<typeof Modal.info> | null>();
const modalRef = useRef<ReturnType<typeof Modal.info>>();
const ProgressElement = ({ percent }: { percent: number }) => (
<Progress
style={{ display: 'flex', justifyContent: 'center' }}
type="circle"
percent={percent}
/>
);
const showProgress = (percent: number) => {
if (modalRef.current) {
modalRef.current.update({
title: `${title}${
percent >= 100 ? intl.get('成功') : intl.get('中...')
}`,
title: `${title}${percent >= 100 ? intl.get('成功') : intl.get('中...')}`,
content: <ProgressElement percent={percent} />,
okButtonProps: { disabled: percent !== 100 },
});
if (percent === 100) {
setTimeout(() => {
modalRef.current?.destroy();
modalRef.current = null;
});
}
} else {
modalRef.current = Modal.info({
width: 600,
maskClosable: false,
title: `${title}${
percent >= 100 ? intl.get('成功') : intl.get('中...')
}`,
title: `${title}${percent >= 100 ? intl.get('成功') : intl.get('中...')}`,
centered: true,
content: <ProgressElement percent={percent} />,
okButtonProps: { disabled: true },
});
}
};
+10 -32
View File
@@ -154,9 +154,9 @@ export default function browserType() {
shell === 'none'
? {}
: {
shell, // wechat qq uc 360 2345 sougou liebao maxthon
shellVs,
},
shell, // wechat qq uc 360 2345 sougou liebao maxthon
shellVs,
},
);
console.log(
@@ -335,23 +335,20 @@ export function parseCrontab(schedule: string): Date | null {
if (time) {
return time.next().toDate();
}
} catch (error) {}
} catch (error) { }
return null;
}
export function getCrontabsNextDate(
schedule: string,
extra_schedules: string[],
): Date | null {
let date = parseCrontab(schedule);
export function getCrontabsNextDate(schedule: string, extra_schedules: string[]): Date | null {
let date = parseCrontab(schedule)
if (extra_schedules?.length) {
extra_schedules.forEach((x) => {
const _date = parseCrontab(x);
extra_schedules.forEach(x => {
const _date = parseCrontab(x)
if (_date && (!date || _date < date)) {
date = _date;
}
});
})
}
return date;
}
@@ -365,23 +362,4 @@ export function getExtension(filename: string) {
export function getEditorMode(filename: string) {
const extension = getExtension(filename) as keyof typeof LANG_MAP;
return LANG_MAP[extension];
}
export function disableBody() {
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0px';
overlay.style.left = '0px';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'transparent';
overlay.style.zIndex = '9999';
document.body.appendChild(overlay);
overlay.addEventListener('click', function (event) {
event.stopPropagation();
event.preventDefault();
});
document.body.style.overflow = 'hidden';
}
}
+6 -8
View File
@@ -1,9 +1,7 @@
version: 2.17.3
changeLogLink: https://t.me/jiao_long/404
publishTime: 2024-03-29 23:30
version: 2.17.2
changeLogLink: https://t.me/jiao_long/403
publishTime: 2024-03-02 17:00
changeLog: |
1. python 通知文件支持自定义参数,可由每个脚本控制通知参数配置
2. ql repo 命令复制仓库任务时,保留仓库脚本原始目录层级
3. 修改自定义通知 body 解析逻辑
4. 修改系统重启逻辑
5. 修改 latest 基础镜像 node 版本为 v20
1. 依赖管理支持队列中依赖取消安装,支持状态筛选
2. 修复 webhook 通知 body 拆分逻辑
3. 企业微信有长度限制,超长的进行分段提交 https://github.com/pharaoh2012