Compare commits

..

3 Commits

22 changed files with 746 additions and 290 deletions
+53
View File
@@ -3,6 +3,7 @@ import { Container } from 'typedi';
import { Logger } from 'winston';
import CronService from '../services/cron';
import CronViewService from '../services/cronView';
import CronStatsService from '../services/cronStats';
import { celebrate, Joi } from 'celebrate';
import { commonCronSchema } from '../validation/schedule';
@@ -141,6 +142,58 @@ export default (app: Router) => {
},
);
route.get(
'/stats',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.stats();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get(
'/stats/trend',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.trend();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get(
'/stats/top-duration',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.topDuration();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get(
'/stats/top-count',
async (req: Request, res: Response, next: NextFunction) => {
try {
const cronStatsService = Container.get(CronStatsService);
const data = await cronStatsService.topCount();
return res.send({ code: 200, data });
} catch (e) {
return next(e);
}
},
);
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
-4
View File
@@ -9,8 +9,6 @@ dotenv.config({
interface Config {
port: number;
grpcPort: number;
bindHost: string;
bindHostGrpc: string;
nodeEnv: string;
isDevelopment: boolean;
isProduction: boolean;
@@ -33,8 +31,6 @@ interface Config {
const config: Config = {
port: parseInt(process.env.BACK_PORT || '5700', 10),
grpcPort: parseInt(process.env.GRPC_PORT || '5500', 10),
bindHost: process.env.BIND_HOST || '::',
bindHostGrpc: process.env.BIND_HOST_GRPC || '::',
nodeEnv: process.env.NODE_ENV || 'development',
isDevelopment: process.env.NODE_ENV === 'development',
isProduction: process.env.NODE_ENV === 'production',
+31
View File
@@ -0,0 +1,31 @@
import { sequelize } from '.';
import { DataTypes, Model } from 'sequelize';
export class CronLog {
id?: number;
cron_id: number;
cron_name: string;
start_time: number;
duration: number;
constructor(options: CronLog) {
this.cron_id = options.cron_id;
this.cron_name = options.cron_name;
this.start_time = options.start_time;
this.duration = options.duration;
}
}
export interface CronLogInstance extends Model<CronLog, CronLog>, CronLog {}
export const CronLogModel = sequelize.define<CronLogInstance>(
'CronLog',
{
cron_id: DataTypes.NUMBER,
cron_name: DataTypes.STRING,
start_time: DataTypes.NUMBER,
duration: DataTypes.NUMBER,
},
{
indexes: [{ fields: ['cron_id'] }, { fields: ['start_time'] }],
},
);
+1 -9
View File
@@ -20,7 +20,6 @@ export enum NotificationMode {
'chronocat' = 'Chronocat',
'ntfy' = 'ntfy',
'wxPusherBot' = 'wxPusherBot',
'openiLink' = 'openiLink',
}
abstract class NotificationBaseInfo {
@@ -162,12 +161,6 @@ export class WxPusherBotNotification extends NotificationBaseInfo {
public wxPusherBotUids = '';
}
export class OpeniLinkNotification extends NotificationBaseInfo {
public openiLinkAppToken = '';
public openiLinkHubUrl = '';
public openiLinkContextToken = '';
}
export interface NotificationInfo
extends GoCqHttpBotNotification,
GotifyNotification,
@@ -189,5 +182,4 @@ export interface NotificationInfo
ChronocatNotification,
LarkNotification,
NtfyNotification,
WxPusherBotNotification,
OpeniLinkNotification {}
WxPusherBotNotification {}
+2
View File
@@ -6,6 +6,7 @@ import { AppModel } from '../data/open';
import { SystemModel } from '../data/system';
import { SubscriptionModel } from '../data/subscription';
import { CrontabViewModel } from '../data/cronView';
import { CronLogModel } from '../data/cronLog';
import { sequelize } from '../data';
export default async () => {
@@ -17,6 +18,7 @@ export default async () => {
await EnvModel.sync();
await SubscriptionModel.sync();
await CrontabViewModel.sync();
await CronLogModel.sync();
// 初始化新增字段
const migrations = [
-2
View File
@@ -20,7 +20,6 @@ const uploadPath = path.join(dataPath, 'upload/');
const bakPath = path.join(dataPath, 'bak/');
const samplePath = path.join(rootPath, 'sample/');
const tmpPath = path.join(logPath, '.tmp/');
const rootTmpPath = path.join(rootPath, '.tmp/');
const confFile = path.join(configPath, 'config.sh');
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
const sampleTaskShellFile = path.join(samplePath, 'task.sample.sh');
@@ -45,7 +44,6 @@ const directories = [
preloadPath,
logPath,
tmpPath,
rootTmpPath,
uploadPath,
sshPath,
bakPath,
+1 -1
View File
@@ -10,7 +10,7 @@ import config from '../config';
class Client {
private client = new CronClient(
`localhost:${config.grpcPort}`,
`0.0.0.0:${config.grpcPort}`,
credentials.createInsecure(),
{ 'grpc.enable_http_proxy': 0 },
);
+13
View File
@@ -2,6 +2,7 @@ import { Service, Inject } from 'typedi';
import winston from 'winston';
import config from '../config';
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
import { CronLog, CronLogModel } from '../data/cronLog';
import { exec, execSync } from 'child_process';
import fs from 'fs/promises';
import CronExpressionParser from 'cron-parser';
@@ -176,6 +177,18 @@ export default class CronService {
{ ...pickBy(options, (v) => v === 0 || !!v) },
{ where: { id } },
);
if (status === CrontabStatus.idle && last_running_time > 0) {
const cronName = (cron.name || cron.command || '').substring(0, 255);
await CronLogModel.create(
new CronLog({
cron_id: id,
cron_name: cronName,
start_time: last_execution_time,
duration: last_running_time,
}),
);
}
}
}
+137
View File
@@ -0,0 +1,137 @@
import { Service, Inject } from 'typedi';
import winston from 'winston';
import { CrontabModel } from '../data/cron';
import { CronLog, CronLogModel } from '../data/cronLog';
import { Op } from 'sequelize';
import dayjs from 'dayjs';
type GroupedLog = {
cron_id: number;
cron_name: string;
durations: number[];
};
@Service()
export default class CronStatsService {
constructor(@Inject('logger') private logger: winston.Logger) {}
private groupLogsByCronId(logs: CronLog[]): Record<number, GroupedLog> {
const grouped: Record<number, GroupedLog> = {};
for (const log of logs) {
if (!grouped[log.cron_id]) {
grouped[log.cron_id] = {
cron_id: log.cron_id,
cron_name: log.cron_name,
durations: [],
};
}
grouped[log.cron_id].durations.push(log.duration);
}
return grouped;
}
private avgOf(nums: number[]): number {
if (nums.length === 0) return 0;
return Math.round(nums.reduce((a, b) => a + b, 0) / nums.length);
}
private getTodayRange() {
return {
start: dayjs().startOf('day').unix(),
end: dayjs().endOf('day').unix(),
};
}
public async stats() {
const { start, end } = this.getTodayRange();
const [allCrons, todayLogs] = await Promise.all([
CrontabModel.findAll({ where: {} }),
CronLogModel.findAll({
where: { start_time: { [Op.between]: [start, end] } },
}),
]);
const total = allCrons.length;
const enabled = allCrons.filter((c: any) => c.isDisabled !== 1).length;
const disabled = allCrons.filter((c: any) => c.isDisabled === 1).length;
const todayCount = todayLogs.length;
const todayTotalDuration = todayLogs.reduce(
(sum: number, l: any) => sum + (l.duration || 0),
0,
);
const todayAvgDuration =
todayCount > 0 ? Math.round(todayTotalDuration / todayCount) : 0;
return {
total,
enabled,
disabled,
today: {
count: todayCount,
avgDuration: todayAvgDuration,
},
};
}
public async trend() {
const days = 7;
const result: Array<{ date: string; count: number }> = [];
for (let i = days - 1; i >= 0; i--) {
const dayStart = dayjs().subtract(i, 'day').startOf('day').unix();
const dayEnd = dayjs().subtract(i, 'day').endOf('day').unix();
const date = dayjs().subtract(i, 'day').format('MM-DD');
const logs = await CronLogModel.findAll({
where: { start_time: { [Op.between]: [dayStart, dayEnd] } },
});
result.push({ date, count: logs.length });
}
return result;
}
public async topDuration(limit = 5) {
const { start, end } = this.getTodayRange();
const logs = await CronLogModel.findAll({
where: { start_time: { [Op.between]: [start, end] } },
});
const grouped = this.groupLogsByCronId(logs as any);
return Object.values(grouped)
.map((g) => ({
cron_id: g.cron_id,
cron_name: g.cron_name,
count: g.durations.length,
avgDuration: this.avgOf(g.durations),
maxDuration: Math.max(...g.durations),
}))
.sort((a, b) => b.avgDuration - a.avgDuration)
.slice(0, limit);
}
public async topCount(limit = 5) {
const { start, end } = this.getTodayRange();
const logs = await CronLogModel.findAll({
where: { start_time: { [Op.between]: [start, end] } },
});
const grouped = this.groupLogsByCronId(logs as any);
return Object.values(grouped)
.map((g) => ({
cron_id: g.cron_id,
cron_name: g.cron_name,
count: g.durations.length,
avgDuration: this.avgOf(g.durations),
}))
.sort((a, b) => b.count - a.count)
.slice(0, limit);
}
}
+3 -3
View File
@@ -27,10 +27,10 @@ export default class EnvService {
envs.length > 0 &&
typeof envs[envs.length - 1].position === 'number'
) {
position = this.getPrecisionPosition(envs[envs.length - 1].position!);
position = envs[envs.length - 1].position!;
}
const tabs = payloads.map((x) => {
position = this.getPrecisionPosition(position - stepPosition);
position = position - stepPosition;
const tab = new Env({ ...x, position });
return tab;
});
@@ -116,7 +116,7 @@ export default class EnvService {
}
private getPrecisionPosition(position: number): number {
return Math.trunc(parseFloat(position.toPrecision(16)));
return parseFloat(position.toPrecision(16));
}
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
+9 -30
View File
@@ -16,13 +16,6 @@ import { Service } from 'typedi';
export class GrpcServerService {
private server: Server = new Server({ 'grpc.enable_http_proxy': 0 });
private formatGrpcAddress(host: string, port: number): string {
if (host === '::') {
return `[::]:${port}`;
}
return `${host}:${port}`;
}
async initialize() {
try {
this.server.addService(HealthService, { check });
@@ -30,32 +23,18 @@ export class GrpcServerService {
this.server.addService(ApiService, Api);
const grpcPort = config.grpcPort;
const hostsToTry = [
config.bindHostGrpc,
...(config.bindHostGrpc !== '0.0.0.0' ? ['0.0.0.0'] : [])
];
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
await bindAsync(
`0.0.0.0:${grpcPort}`,
ServerCredentials.createInsecure(),
);
Logger.debug(`✌️ gRPC service started successfully`);
let lastError: Error | null = null;
metricsService.record('grpc_service_start', 1, {
port: grpcPort.toString(),
});
for (const host of hostsToTry) {
try {
const address = this.formatGrpcAddress(host, grpcPort);
await bindAsync(address, ServerCredentials.createInsecure());
Logger.debug(`✌️ gRPC service started successfully on ${address}`);
metricsService.record('grpc_service_start', 1, {
port: grpcPort.toString(),
host
});
return grpcPort;
} catch (err) {
lastError = err as Error;
Logger.warn(`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`, err);
}
}
Logger.error('Failed to start gRPC service on all hosts');
throw lastError || new Error('Failed to start gRPC service');
return grpcPort;
} catch (err) {
Logger.error('Failed to start gRPC service:', err);
throw err;
+17 -37
View File
@@ -3,51 +3,31 @@ import Logger from '../loaders/logger';
import { metricsService } from './metrics';
import { Service } from 'typedi';
import { Server } from 'http';
import config from '../config';
@Service()
export class HttpServerService {
private server?: Server = undefined;
async initialize(expressApp: express.Application, port: number) {
const hostsToTry = [
config.bindHost,
...(config.bindHost !== '0.0.0.0' ? ['0.0.0.0'] : [])
];
let lastError: Error | null = null;
for (const host of hostsToTry) {
try {
const server = await this.tryListen(expressApp, port, host);
Logger.debug(`✌️ HTTP service started successfully on ${host}:${port}`);
metricsService.record('http_service_start', 1, {
port: port.toString(),
host
try {
return new Promise((resolve, reject) => {
this.server = expressApp.listen(port, '0.0.0.0', () => {
Logger.debug(`✌️ HTTP service started successfully`);
metricsService.record('http_service_start', 1, {
port: port.toString(),
});
resolve(this.server);
});
this.server = server;
return server;
} catch (err) {
lastError = err as Error;
Logger.warn(`Failed to bind HTTP on ${host}:${port}, trying next...`, err);
}
this.server?.on('error', (err: Error) => {
Logger.error('Failed to start HTTP service:', err);
reject(err);
});
});
} catch (err) {
Logger.error('Failed to start HTTP service:', err);
throw err;
}
Logger.error('Failed to start HTTP service on all hosts');
throw lastError || new Error('Failed to start HTTP service');
}
private async tryListen(expressApp: express.Application, port: number, host: string): Promise<Server> {
return new Promise((resolve, reject) => {
const server = expressApp.listen(port, host, () => {
resolve(server);
});
server.on('error', (err: Error) => {
server.close();
reject(err);
});
});
}
async shutdown() {
+1 -42
View File
@@ -34,7 +34,6 @@ export default class NotificationService {
['chronocat', this.chronocat],
['ntfy', this.ntfy],
['wxPusherBot', this.wxPusherBot],
['openiLink', this.openiLink],
]);
private title = '';
@@ -91,14 +90,6 @@ export default class NotificationService {
return true;
}
private parseMailRecipients(value?: string) {
const recipients = (value || '')
.split(/[;]/)
.map((item) => item.trim())
.filter(Boolean);
return recipients.length > 0 ? recipients : undefined;
}
private async gotify() {
const { gotifyUrl, gotifyToken, gotifyPriority = 1 } = this.params;
try {
@@ -600,7 +591,6 @@ export default class NotificationService {
private async email() {
const { emailPass, emailService, emailUser, emailTo } = this.params;
const recipients = this.parseMailRecipients(emailTo) || emailUser;
try {
const transporter = nodemailer.createTransport({
@@ -613,7 +603,7 @@ export default class NotificationService {
const info = await transporter.sendMail({
from: `"青龙快讯" <${emailUser}>`,
to: recipients,
to: emailTo ? emailTo.split(';') : emailUser,
subject: `${this.title}`,
html: `${this.content.replace(/\n/g, '<br/>')}`,
});
@@ -868,35 +858,4 @@ export default class NotificationService {
}
return {};
}
private async openiLink() {
const { openiLinkAppToken, openiLinkHubUrl, openiLinkContextToken } =
this.params;
const baseUrl = openiLinkHubUrl?.replace(/\/$/, '') || 'https://hub.openilink.com';
const url = `${baseUrl}/bot/v1/message/send`;
const body: Record<string, string> = {
type: 'text',
content: `${this.title}\n\n${this.content}`,
};
if (openiLinkContextToken) {
body.context_token = openiLinkContextToken;
}
try {
const res = await httpClient.post(url, {
...this.gotOption,
json: body,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${openiLinkAppToken}`,
},
});
if (res.ok) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
}
}
+1 -12
View File
@@ -195,14 +195,12 @@ export SMTP_SERVER=""
## SMTP 发送邮件服务器是否使用 SSL,填写 true 或 false
export SMTP_SSL=""
## smtp_email 填写 SMTP 发件邮箱
## smtp_email 填写 SMTP 发件邮箱,通知将会由自己发给自己
export SMTP_EMAIL=""
## smtp_password 填写 SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
export SMTP_PASSWORD=""
## smtp_name 填写 SMTP 收发件人姓名,可随意填写
export SMTP_NAME=""
## smtp_email_to 填写 SMTP 收件邮箱,多个用英文;分隔,不填默认发给发件邮箱
export SMTP_EMAIL_TO=""
## 17. PushMe
## 官方说明文档:https://push.i-i.me/
@@ -261,13 +259,4 @@ export WEBHOOK_METHOD=""
## 支持 text/plain、application/json、multipart/form-data、application/x-www-form-urlencoded
export WEBHOOK_CONTENT_TYPE=""
## 23. OpeniLink
## 官方文档: https://openilink.com/docs/hub/apps
## 在 OpeniLink Hub 后台安装 App 后获取 app_token
export OPENILINK_APP_TOKEN=""
## OpeniLink Hub 地址,默认为 https://hub.openilink.com,自建 Hub 时填写自己的地址
export OPENILINK_HUB_URL=""
## OpeniLink 的 context_token,用于标识消息会话上下文,可从消息事件中获取
export OPENILINK_CONTEXT_TOKEN=""
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
+4 -76
View File
@@ -121,8 +121,7 @@ const push_config = {
SMTP_SERVICE: '', // 邮箱服务名称,比如 126、163、Gmail、QQ 等,支持列表 https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json
SMTP_EMAIL: '', // SMTP 发件邮箱
SMTP_TO: '', // SMTP 收件邮箱,兼容旧参数名,默认通知将会发给发件邮箱
SMTP_EMAIL_TO: '', // SMTP 收件邮箱,多个分号分隔,默认发给发件邮箱
SMTP_TO: '', // SMTP 收件邮箱,默认通知将会发给发件邮箱
SMTP_PASSWORD: '', // SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
SMTP_NAME: '', // SMTP 收发件人姓名,可随意填写
@@ -152,11 +151,6 @@ const push_config = {
WXPUSHER_APP_TOKEN: '', // wxpusher 的 appToken
WXPUSHER_TOPIC_IDS: '', // wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
WXPUSHER_UIDS: '', // wxpusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
// 官方文档: https://openilink.com/docs/hub/apps
OPENILINK_APP_TOKEN: '', // OpeniLink 的 app_token,在 OpeniLink Hub 后台安装 App 后获取
OPENILINK_HUB_URL: '', // OpeniLink Hub 地址,默认为 https://hub.openilink.com,自建 Hub 时填写自己的地址
OPENILINK_CONTEXT_TOKEN: '', // OpeniLink 的 context_token,用于标识消息会话上下文,可从消息事件中获取
};
for (const key in push_config) {
@@ -1052,14 +1046,8 @@ function fsBotNotify(text, desp) {
}
async function smtpNotify(text, desp) {
const {
SMTP_EMAIL,
SMTP_TO,
SMTP_EMAIL_TO,
SMTP_PASSWORD,
SMTP_SERVICE,
SMTP_NAME,
} = push_config;
const { SMTP_EMAIL, SMTP_TO, SMTP_PASSWORD, SMTP_SERVICE, SMTP_NAME } =
push_config;
if (![SMTP_EMAIL, SMTP_PASSWORD].every(Boolean) || !SMTP_SERVICE) {
return;
}
@@ -1075,20 +1063,9 @@ async function smtpNotify(text, desp) {
});
const addr = SMTP_NAME ? `"${SMTP_NAME}" <${SMTP_EMAIL}>` : SMTP_EMAIL;
const recipients = [SMTP_EMAIL_TO, SMTP_TO].reduce((list, value) => {
if (!value) {
return list;
}
return list.concat(
value
.split(/[;]/)
.map((item) => item.trim())
.filter(Boolean),
);
}, []);
const info = await transporter.sendMail({
from: addr,
to: recipients.length ? recipients : SMTP_EMAIL,
to: SMTP_TO ? SMTP_TO.split(';') : addr,
subject: text,
html: `${desp.replace(/\n/g, '<br/>')}`,
});
@@ -1431,54 +1408,6 @@ function wxPusherNotify(text, desp) {
});
}
function openiLinkNotify(text, desp) {
return new Promise((resolve) => {
const { OPENILINK_APP_TOKEN, OPENILINK_HUB_URL, OPENILINK_CONTEXT_TOKEN } =
push_config;
if (OPENILINK_APP_TOKEN) {
const baseUrl = OPENILINK_HUB_URL
? OPENILINK_HUB_URL.replace(/\/$/, '')
: 'https://hub.openilink.com';
const body = {
type: 'text',
content: `${text}\n\n${desp}`,
};
if (OPENILINK_CONTEXT_TOKEN) {
body.context_token = OPENILINK_CONTEXT_TOKEN;
}
const options = {
url: `${baseUrl}/bot/v1/message/send`,
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${OPENILINK_APP_TOKEN}`,
},
timeout,
};
$.post(options, (err, resp, data) => {
try {
if (err) {
console.log('OpeniLink 发送通知消息失败!\n', err);
} else {
if (data.ok) {
console.log('OpeniLink 发送通知消息成功!');
} else {
console.log(`OpeniLink 发送通知消息异常:${data.error}`);
}
}
} catch (e) {
$.logErr(e, resp);
} finally {
resolve(data);
}
});
} else {
resolve();
}
});
}
function parseString(input, valueFormatFn) {
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
const matches = {};
@@ -1609,7 +1538,6 @@ async function sendNotify(text, desp, params = {}) {
qmsgNotify(text, desp), // 自定义通知
ntfyNotify(text, desp), // Ntfy
wxPusherNotify(text, desp), // wxpusher
openiLinkNotify(text, desp), // OpeniLink
]);
}
+8 -51
View File
@@ -107,8 +107,7 @@ push_config = {
'SMTP_SERVER': '', # SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
'SMTP_SSL': 'false', # SMTP 发送邮件服务器是否使用 SSL,填写 true 或 false
'SMTP_EMAIL': '', # SMTP 发件邮箱
'SMTP_EMAIL_TO': '', # SMTP 收件邮箱,多个分号分隔,默认发给发件邮箱
'SMTP_EMAIL': '', # SMTP 发件邮箱,通知将会由自己发给自己
'SMTP_PASSWORD': '', # SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
'SMTP_NAME': '', # SMTP 收发件人姓名,可随意填写
@@ -136,10 +135,6 @@ push_config = {
'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 至少配置一个才行
'OPENILINK_APP_TOKEN': '', # OpeniLink 的 app_token,在 OpeniLink Hub 后台安装 App 后获取 官方文档: https://openilink.com/docs/hub/apps
'OPENILINK_HUB_URL': '', # OpeniLink Hub 地址,默认为 https://hub.openilink.com,自建 Hub 时填写自己的地址
'OPENILINK_CONTEXT_TOKEN': '', # OpeniLink 的 context_token,用于标识消息会话上下文,可从消息事件中获取
}
# fmt: on
@@ -695,10 +690,6 @@ def smtp(title: str, content: str) -> None:
return
print("SMTP 邮件 服务启动")
email_to = push_config.get("SMTP_EMAIL_TO") or push_config.get("SMTP_EMAIL")
email_to_list = [
item.strip() for item in re.split(r"[;]", email_to) if item.strip()
]
message = MIMEText(content, "plain", "utf-8")
message["From"] = formataddr(
(
@@ -706,7 +697,12 @@ def smtp(title: str, content: str) -> None:
push_config.get("SMTP_EMAIL"),
)
)
message["To"] = ",".join(email_to_list)
message["To"] = formataddr(
(
Header(push_config.get("SMTP_NAME"), "utf-8").encode(),
push_config.get("SMTP_EMAIL"),
)
)
message["Subject"] = Header(title, "utf-8")
try:
@@ -720,7 +716,7 @@ def smtp(title: str, content: str) -> None:
)
smtp_server.sendmail(
push_config.get("SMTP_EMAIL"),
email_to_list,
push_config.get("SMTP_EMAIL"),
message.as_bytes(),
)
smtp_server.close()
@@ -902,43 +898,6 @@ def wxpusher_bot(title: str, content: str) -> None:
print(f"wxpusher 推送失败!错误信息:{response.get('msg')}")
def openilink(title: str, content: str) -> None:
"""
通过 OpeniLink 推送消息。
支持的环境变量:
- OPENILINK_APP_TOKEN: 在 OpeniLink Hub 后台安装 App 后获取的 app_token
- OPENILINK_HUB_URL: OpeniLink Hub 地址,默认为 https://hub.openilink.com
- OPENILINK_CONTEXT_TOKEN: 消息会话上下文 token,可从消息事件中获取
"""
if not push_config.get("OPENILINK_APP_TOKEN"):
return
print("OpeniLink 服务启动")
base_url = (
push_config.get("OPENILINK_HUB_URL", "").rstrip("/")
or "https://hub.openilink.com"
)
url = f"{base_url}/bot/v1/message/send"
headers = {
"Content-Type": "application/json",
"Authorization": f'Bearer {push_config.get("OPENILINK_APP_TOKEN")}',
}
data = {
"type": "text",
"content": f"{title}\n\n{content}",
}
if push_config.get("OPENILINK_CONTEXT_TOKEN"):
data["context_token"] = push_config.get("OPENILINK_CONTEXT_TOKEN")
response = requests.post(url=url, json=data, headers=headers).json()
if response.get("ok"):
print("OpeniLink 推送成功!")
else:
print(f'OpeniLink 推送失败!错误信息:{response.get("error")}')
def parse_headers(headers):
if not headers:
return {}
@@ -1104,8 +1063,6 @@ def add_notify_function():
push_config.get("WXPUSHER_TOPIC_IDS") or push_config.get("WXPUSHER_UIDS")
):
notify_function.append(wxpusher_bot)
if push_config.get("OPENILINK_APP_TOKEN"):
notify_function.append(openilink)
if not notify_function:
print(f"无推送渠道,请检查通知变量是否正确")
return notify_function
+7 -1
View File
@@ -1,5 +1,5 @@
import intl from 'react-intl-universal';
import { SettingOutlined } from '@ant-design/icons';
import { BarChartOutlined, SettingOutlined } from '@ant-design/icons';
import IconFont from '@/components/iconfont';
import { BasicLayoutProps } from '@ant-design/pro-layout';
@@ -30,6 +30,12 @@ export default {
icon: <IconFont type="ql-icon-crontab" />,
component: '@/pages/crontab/index',
},
{
path: '/statistics',
name: intl.get('统计面板'),
icon: <BarChartOutlined />,
component: '@/pages/statistics/index',
},
{
path: '/subscription',
name: intl.get('订阅管理'),
+19
View File
@@ -18,6 +18,25 @@
"青龙": "Qinglong",
"返回首页": "Return to Home",
"保存": "Save",
"统计面板": "Statistics",
"总体概览": "Overview",
"总任务数量": "Total Tasks",
"启用任务数": "Enabled Tasks",
"禁用任务数": "Disabled Tasks",
"今日总执行次数": "Today's Executions",
"今日平均耗时(秒)": "Today's Avg Duration (s)",
"近7日执行趋势": "7-Day Execution Trend",
"今日平均耗时 Top 5": "Top 5 Slowest Today",
"今日执行次数 Top 5": "Top 5 Most Frequent Today",
"排名": "Rank",
"任务名称": "Task Name",
"平均耗时(秒)": "Avg Duration (s)",
"最长单次(秒)": "Max Duration (s)",
"今日执行次数": "Today's Count",
"今日暂无执行记录": "No execution records today",
"暂无数据": "No data",
"次": "times",
"刷新": "Refresh",
"日志": "Log",
"脚本": "Script",
"确认保存文件": "Confirm to Save File",
+19
View File
@@ -18,6 +18,25 @@
"青龙": "青龙",
"返回首页": "返回首页",
"保存": "保存",
"统计面板": "统计面板",
"总体概览": "总体概览",
"总任务数量": "总任务数量",
"启用任务数": "启用任务数",
"禁用任务数": "禁用任务数",
"今日总执行次数": "今日总执行次数",
"今日平均耗时(秒)": "今日平均耗时(秒)",
"近7日执行趋势": "近7日执行趋势",
"今日平均耗时 Top 5": "今日平均耗时 Top 5",
"今日执行次数 Top 5": "今日执行次数 Top 5",
"排名": "排名",
"任务名称": "任务名称",
"平均耗时(秒)": "平均耗时(秒)",
"最长单次(秒)": "最长单次(秒)",
"今日执行次数": "今日执行次数",
"今日暂无执行记录": "今日暂无执行记录",
"暂无数据": "暂无数据",
"次": "次",
"刷新": "刷新",
"日志": "日志",
"脚本": "脚本",
"确认保存文件": "确认保存文件",
+17
View File
@@ -0,0 +1,17 @@
.stats-section {
margin-bottom: 16px;
}
.trend-chart-wrapper {
width: 100%;
overflow: hidden;
}
.trend-chart-empty {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
color: #999;
font-size: 14px;
}
+402
View File
@@ -0,0 +1,402 @@
import { SharedContext } from '@/layouts';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { BarChartOutlined, ReloadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { useOutletContext } from '@umijs/max';
import {
Button,
Card,
Col,
Row,
Statistic,
Table,
Tooltip,
Typography,
} from 'antd';
import { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useState } from 'react';
import intl from 'react-intl-universal';
import './index.less';
const { Title } = Typography;
interface StatsData {
total: number;
enabled: number;
disabled: number;
today: {
count: number;
avgDuration: number;
};
}
interface TrendItem {
date: string;
count: number;
}
interface TopDurationItem {
cron_id: number;
cron_name: string;
count: number;
avgDuration: number;
maxDuration: number;
}
interface TopCountItem {
cron_id: number;
cron_name: string;
count: number;
avgDuration: number;
}
const TrendChart = ({ data }: { data: TrendItem[] }) => {
if (!data || data.length === 0) {
return (
<div className="trend-chart-empty">
{intl.get('暂无数据')}
</div>
);
}
const width = 600;
const height = 200;
const paddingLeft = 40;
const paddingRight = 20;
const paddingTop = 20;
const paddingBottom = 40;
const chartWidth = width - paddingLeft - paddingRight;
const chartHeight = height - paddingTop - paddingBottom;
const maxCount = Math.max(...data.map((d) => d.count), 1);
const points = data.map((d, i) => ({
x: paddingLeft + (i / Math.max(data.length - 1, 1)) * chartWidth,
y: paddingTop + chartHeight - (d.count / maxCount) * chartHeight,
...d,
}));
const pathD = points
.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
.join(' ');
const areaD =
pathD +
` L ${points[points.length - 1].x.toFixed(1)} ${(paddingTop + chartHeight).toFixed(1)}` +
` L ${points[0].x.toFixed(1)} ${(paddingTop + chartHeight).toFixed(1)} Z`;
const yTicks = [0, Math.ceil(maxCount / 2), maxCount];
return (
<div className="trend-chart-wrapper">
<svg
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="xMidYMid meet"
style={{ width: '100%', height: 200 }}
>
{/* Grid lines */}
{yTicks.map((tick) => {
const y =
paddingTop + chartHeight - (tick / maxCount) * chartHeight;
return (
<g key={tick}>
<line
x1={paddingLeft}
y1={y}
x2={paddingLeft + chartWidth}
y2={y}
stroke="#f0f0f0"
strokeWidth={1}
/>
<text
x={paddingLeft - 6}
y={y + 4}
textAnchor="end"
fontSize={10}
fill="#999"
>
{tick}
</text>
</g>
);
})}
{/* Area fill */}
<path d={areaD} fill="rgba(24, 144, 255, 0.1)" />
{/* Line */}
<path
d={pathD}
fill="none"
stroke="#1890ff"
strokeWidth={2}
strokeLinejoin="round"
strokeLinecap="round"
/>
{/* Points */}
{points.map((p, i) => (
<Tooltip
key={i}
title={`${p.date}: ${p.count} ${intl.get('次')}`}
>
<circle
cx={p.x}
cy={p.y}
r={4}
fill="#1890ff"
stroke="#fff"
strokeWidth={2}
style={{ cursor: 'pointer' }}
/>
</Tooltip>
))}
{/* X axis labels */}
{points.map((p, i) => (
<text
key={i}
x={p.x}
y={height - 8}
textAnchor="middle"
fontSize={10}
fill="#999"
>
{p.date}
</text>
))}
{/* Axes */}
<line
x1={paddingLeft}
y1={paddingTop}
x2={paddingLeft}
y2={paddingTop + chartHeight}
stroke="#e8e8e8"
strokeWidth={1}
/>
<line
x1={paddingLeft}
y1={paddingTop + chartHeight}
x2={paddingLeft + chartWidth}
y2={paddingTop + chartHeight}
stroke="#e8e8e8"
strokeWidth={1}
/>
</svg>
</div>
);
};
const Statistics = () => {
const { headerStyle, isPhone } = useOutletContext<SharedContext>();
const [stats, setStats] = useState<StatsData | null>(null);
const [trend, setTrend] = useState<TrendItem[]>([]);
const [topDuration, setTopDuration] = useState<TopDurationItem[]>([]);
const [topCount, setTopCount] = useState<TopCountItem[]>([]);
const [loading, setLoading] = useState(true);
const loadAll = async () => {
setLoading(true);
try {
const [
statsRes,
trendRes,
topDurationRes,
topCountRes,
] = await Promise.all([
request.get(`${config.apiPrefix}crons/stats`),
request.get(`${config.apiPrefix}crons/stats/trend`),
request.get(`${config.apiPrefix}crons/stats/top-duration`),
request.get(`${config.apiPrefix}crons/stats/top-count`),
]);
if (statsRes.code === 200) setStats(statsRes.data);
if (trendRes.code === 200) setTrend(trendRes.data);
if (topDurationRes.code === 200) setTopDuration(topDurationRes.data);
if (topCountRes.code === 200) setTopCount(topCountRes.data);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadAll();
}, []);
const topDurationColumns: ColumnProps<TopDurationItem>[] = [
{
title: intl.get('排名'),
key: 'rank',
width: 60,
render: (_: any, __: any, index: number) => index + 1,
},
{
title: intl.get('任务名称'),
dataIndex: 'cron_name',
key: 'cron_name',
ellipsis: true,
},
{
title: intl.get('平均耗时(秒)'),
dataIndex: 'avgDuration',
key: 'avgDuration',
width: 120,
render: (v: number) => `${v}s`,
},
{
title: intl.get('最长单次(秒)'),
dataIndex: 'maxDuration',
key: 'maxDuration',
width: 120,
render: (v: number) => `${v}s`,
},
];
const topCountColumns: ColumnProps<TopCountItem>[] = [
{
title: intl.get('排名'),
key: 'rank',
width: 60,
render: (_: any, __: any, index: number) => index + 1,
},
{
title: intl.get('任务名称'),
dataIndex: 'cron_name',
key: 'cron_name',
ellipsis: true,
},
{
title: intl.get('今日执行次数'),
dataIndex: 'count',
key: 'count',
width: 120,
},
{
title: intl.get('平均耗时(秒)'),
dataIndex: 'avgDuration',
key: 'avgDuration',
width: 120,
render: (v: number) => `${v}s`,
},
];
return (
<PageContainer
header={{
style: headerStyle,
}}
title={
<span>
<BarChartOutlined style={{ marginRight: 8 }} />
{intl.get('统计面板')}
</span>
}
extra={[
<Button
key="refresh"
icon={<ReloadOutlined />}
loading={loading}
onClick={loadAll}
>
{intl.get('刷新')}
</Button>,
]}
>
{/* Section 1: Overview Cards */}
<Card
className="stats-section"
title={intl.get('总体概览')}
loading={loading}
>
<Row gutter={[16, 16]}>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('总任务数量')}
value={stats?.total ?? '-'}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('启用任务数')}
value={stats?.enabled ?? '-'}
valueStyle={{ color: '#52c41a' }}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('禁用任务数')}
value={stats?.disabled ?? '-'}
valueStyle={{ color: '#d9d9d9' }}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('今日总执行次数')}
value={stats?.today?.count ?? '-'}
valueStyle={{ color: '#1890ff' }}
/>
</Col>
<Col xs={12} sm={8} md={6} lg={4}>
<Statistic
title={intl.get('今日平均耗时(秒)')}
value={stats?.today?.avgDuration ?? '-'}
suffix="s"
valueStyle={{ color: '#faad14' }}
/>
</Col>
</Row>
</Card>
{/* Section 2: 7-day Trend */}
<Card
className="stats-section"
title={intl.get('近7日执行趋势')}
loading={loading}
>
<TrendChart data={trend} />
</Card>
{/* Section 3 & 4: Top Tables */}
<Row gutter={[16, 16]}>
<Col xs={24} lg={12}>
<Card
className="stats-section"
title={intl.get('今日平均耗时 Top 5')}
loading={loading}
>
<Table
dataSource={topDuration}
columns={topDurationColumns}
rowKey="cron_id"
pagination={false}
size="small"
locale={{ emptyText: intl.get('今日暂无执行记录') }}
/>
</Card>
</Col>
<Col xs={24} lg={12}>
<Card
className="stats-section"
title={intl.get('今日执行次数 Top 5')}
loading={loading}
>
<Table
dataSource={topCount}
columns={topCountColumns}
rowKey="cron_id"
pagination={false}
size="small"
locale={{ emptyText: intl.get('今日暂无执行记录') }}
/>
</Card>
</Col>
</Row>
</PageContainer>
);
};
export default Statistics;
+1 -22
View File
@@ -98,7 +98,6 @@ export default {
{ value: 'pushPlus', label: 'PushPlus' },
{ value: 'wePlusBot', label: intl.get('微加机器人') },
{ value: 'wxPusherBot', label: 'wxPusher' },
{ value: 'openiLink', label: 'OpeniLink' },
{ value: 'chat', label: intl.get('群晖chat') },
{ value: 'email', label: intl.get('邮箱') },
{ value: 'lark', label: intl.get('飞书机器人') },
@@ -388,27 +387,6 @@ export default {
required: false,
},
],
openiLink: [
{
label: 'openiLinkAppToken',
tip: intl.get(
'OpeniLink的app_token,在OpeniLink Hub后台安装App后获取,参考 https://openilink.com/docs/hub/apps',
),
required: true,
},
{
label: 'openiLinkHubUrl',
tip: intl.get(
'OpeniLink Hub地址,默认为 https://hub.openilink.com,自建Hub时填写自己的地址',
),
},
{
label: 'openiLinkContextToken',
tip: intl.get(
'OpeniLink的context_token,用于标识消息会话上下文,可从消息事件中获取',
),
},
],
lark: [
{
label: 'larkKey',
@@ -526,6 +504,7 @@ export default {
'/login': intl.get('登录'),
'/initialization': intl.get('初始化'),
'/crontab': intl.get('定时任务'),
'/statistics': intl.get('统计面板'),
'/env': intl.get('环境变量'),
'/subscription': intl.get('订阅管理'),
'/config': intl.get('配置文件'),