mirror of
https://github.com/whyour/qinglong.git
synced 2026-06-30 20:35:09 +08:00
添加系统更新操作和设置删除日志频率
This commit is contained in:
@@ -272,4 +272,56 @@ export default (app: Router) => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/system/log/remove',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
frequency: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const result = await userService.updateLogRemoveFrequency(
|
||||
req.body.frequency,
|
||||
);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/system/update-check',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const result = await userService.checkUpdate();
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/system/update',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const result = await userService.updateSystem();
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
+3
-1
@@ -11,7 +11,7 @@ async function startServer() {
|
||||
|
||||
await require('./loaders').default({ expressApp: app });
|
||||
|
||||
app
|
||||
const server = app
|
||||
.listen(config.port, () => {
|
||||
Logger.info(`
|
||||
################################################
|
||||
@@ -23,6 +23,8 @@ async function startServer() {
|
||||
Logger.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
await require('./loaders/sock').default({ server });
|
||||
}
|
||||
|
||||
startServer();
|
||||
|
||||
@@ -4,6 +4,9 @@ import { createRandomString } from './util';
|
||||
|
||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
const lastVersionFile =
|
||||
'https://ghproxy.com/https://raw.githubusercontent.com/whyour/qinglong/master/src/version.ts';
|
||||
|
||||
const envFound = dotenv.config();
|
||||
const rootPath = process.cwd();
|
||||
const envFile = path.join(rootPath, 'config/env.sh');
|
||||
@@ -26,6 +29,7 @@ const cronDbFile = path.join(rootPath, 'db/crontab.db');
|
||||
const envDbFile = path.join(rootPath, 'db/env.db');
|
||||
const appDbFile = path.join(rootPath, 'db/app.db');
|
||||
const authDbFile = path.join(rootPath, 'db/auth.db');
|
||||
const versionFile = path.join(rootPath, 'src/version.ts');
|
||||
|
||||
const configFound = dotenv.config({ path: confFile });
|
||||
|
||||
@@ -84,4 +88,6 @@ export default {
|
||||
'/api/init/user',
|
||||
'/api/init/notification',
|
||||
],
|
||||
versionFile,
|
||||
lastVersionFile,
|
||||
};
|
||||
|
||||
@@ -21,4 +21,5 @@ export enum AuthDataType {
|
||||
'loginLog' = 'loginLog',
|
||||
'authToken' = 'authToken',
|
||||
'notification' = 'notification',
|
||||
'removeLogFrequency' = 'removeLogFrequency',
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export default ({ app }: { app: Application }) => {
|
||||
|
||||
app.use(bodyParser.json({ limit: '50mb' }));
|
||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||
|
||||
app.use(
|
||||
jwt({
|
||||
secret: config.secret as string,
|
||||
|
||||
@@ -2,8 +2,9 @@ import expressLoader from './express';
|
||||
import dependencyInjectorLoader from './dependencyInjector';
|
||||
import Logger from './logger';
|
||||
import initData from './initData';
|
||||
import { Application } from 'express';
|
||||
|
||||
export default async ({ expressApp }: { expressApp: any }) => {
|
||||
export default async ({ expressApp }: { expressApp: Application }) => {
|
||||
Logger.info('✌️ DB loaded and connected!');
|
||||
|
||||
await dependencyInjectorLoader({
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import sockjs from 'sockjs';
|
||||
import { Server } from 'http';
|
||||
import Logger from './logger';
|
||||
import { Container } from 'typedi';
|
||||
import SockService from '../services/sock';
|
||||
import config from '../config/index';
|
||||
import fs from 'fs';
|
||||
import { getPlatform } from '../config/util';
|
||||
|
||||
export default async ({ server }: { server: Server }) => {
|
||||
const echo = sockjs.createServer({ prefix: '/ws' });
|
||||
const sockService = Container.get(SockService);
|
||||
|
||||
echo.on('connection', (conn) => {
|
||||
const data = fs.readFileSync(config.authConfigFile, 'utf8');
|
||||
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
||||
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
||||
if (data) {
|
||||
const { token = '', tokens = {} } = JSON.parse(data);
|
||||
if (headerToken === token || tokens[platform] === headerToken) {
|
||||
Logger.info('✌️ Sockjs connection success');
|
||||
sockService.addClient(conn);
|
||||
|
||||
conn.on('data', (message) => {
|
||||
conn.write(message);
|
||||
});
|
||||
|
||||
conn.on('close', function () {
|
||||
sockService.removeClient(conn);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
conn.close('404');
|
||||
});
|
||||
|
||||
echo.installHandlers(server);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import nodeSchedule from 'node-schedule';
|
||||
import { Crontab } from '../data/cron';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
@Service()
|
||||
export default class ScheduleService {
|
||||
private scheduleStacks = new Map<string, nodeSchedule.Job>();
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
async generateSchedule({ _id = '', command, name, schedule }: Crontab) {
|
||||
this.logger.info(
|
||||
'[创建定时任务],任务ID: %s,cron: %s,任务名: %s,任务方法: %s',
|
||||
_id,
|
||||
schedule,
|
||||
name,
|
||||
);
|
||||
|
||||
this.scheduleStacks.set(
|
||||
_id,
|
||||
nodeSchedule.scheduleJob(_id, schedule, async () => {
|
||||
try {
|
||||
exec(command, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
await this.logger.info(
|
||||
'执行任务`%s`失败,时间:%s, 错误信息:%j',
|
||||
name,
|
||||
new Date().toLocaleString(),
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
if (stderr) {
|
||||
await this.logger.info(
|
||||
'执行任务`%s`失败,时间:%s, 错误信息:%j',
|
||||
name,
|
||||
new Date().toLocaleString(),
|
||||
stderr,
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
await this.logger.info(
|
||||
'执行任务`%s`失败,时间:%s, 错误信息:%j',
|
||||
name,
|
||||
new Date().toLocaleString(),
|
||||
error,
|
||||
);
|
||||
} finally {
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async cancelSchedule(id: string, jobName: string) {
|
||||
this.logger.info('[取消定时任务],任务名:%s', jobName);
|
||||
this.scheduleStacks.has(id) && this.scheduleStacks.get(id)?.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { Connection } from 'sockjs';
|
||||
|
||||
@Service()
|
||||
export default class SockService {
|
||||
private clients: Connection[] = [];
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public getClients() {
|
||||
return this.clients;
|
||||
}
|
||||
|
||||
public addClient(conn: Connection) {
|
||||
if (this.clients.indexOf(conn) === -1) {
|
||||
this.clients.push(conn);
|
||||
}
|
||||
}
|
||||
|
||||
public removeClient(conn: Connection) {
|
||||
const index = this.clients.indexOf(conn);
|
||||
if (index !== -1) {
|
||||
this.clients.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public sendMessage(msg: string) {
|
||||
this.clients.forEach((x) => {
|
||||
x.write(msg);
|
||||
});
|
||||
}
|
||||
}
|
||||
+68
-2
@@ -11,6 +11,10 @@ import { AuthDataType, AuthInfo, LoginStatus } from '../data/auth';
|
||||
import { NotificationInfo } from '../data/notify';
|
||||
import NotificationService from './notify';
|
||||
import { Request } from 'express';
|
||||
import ScheduleService from './schedule';
|
||||
import { spawn } from 'child_process';
|
||||
import SockService from './sock';
|
||||
import got from 'got';
|
||||
|
||||
@Service()
|
||||
export default class UserService {
|
||||
@@ -18,7 +22,11 @@ export default class UserService {
|
||||
private notificationService!: NotificationService;
|
||||
private authDb = new DataStore({ filename: config.authDbFile });
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
private scheduleService: ScheduleService,
|
||||
private sockService: SockService,
|
||||
) {
|
||||
this.authDb.loadDatabase((err) => {
|
||||
if (err) throw err;
|
||||
});
|
||||
@@ -330,7 +338,7 @@ export default class UserService {
|
||||
if (err) {
|
||||
resolve({} as NotificationInfo);
|
||||
} else {
|
||||
resolve(doc.info);
|
||||
resolve({ ...doc.info, _id: doc._id });
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -354,4 +362,62 @@ export default class UserService {
|
||||
return { code: 400, data: '通知发送失败,请检查参数' };
|
||||
}
|
||||
}
|
||||
|
||||
public async updateLogRemoveFrequency(frequency: number) {
|
||||
const result = await this.updateNotificationDb({
|
||||
type: AuthDataType.removeLogFrequency,
|
||||
info: { frequency },
|
||||
});
|
||||
const cron = {
|
||||
_id: result._id,
|
||||
name: '删除日志',
|
||||
command: `ql rmlog ${frequency}`,
|
||||
schedule: `5 23 */${frequency} * *`,
|
||||
};
|
||||
await this.scheduleService.generateSchedule(cron);
|
||||
return { code: 200, data: { ...cron } };
|
||||
}
|
||||
|
||||
public async checkUpdate() {
|
||||
try {
|
||||
const { version } = await import(config.versionFile);
|
||||
const lastVersionFileContent = await got.get(config.lastVersionFile);
|
||||
const filePath = `${config.rootPath}/.version.ts`;
|
||||
fs.writeFileSync(filePath, lastVersionFileContent.body, {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
const result = await import(config.versionFile);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
hasNewVersion: version !== result.version,
|
||||
...result,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
code: 400,
|
||||
data: '获取版本文件失败',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public async updateSystem() {
|
||||
const cp = spawn('ql update', { shell: '/bin/bash' });
|
||||
|
||||
cp.stdout.on('data', (data) => {
|
||||
this.sockService.sendMessage(data.toString());
|
||||
});
|
||||
|
||||
cp.stderr.on('data', (data) => {
|
||||
this.sockService.sendMessage(data.toString());
|
||||
});
|
||||
|
||||
cp.on('error', (err) => {
|
||||
this.sockService.sendMessage(JSON.stringify(err));
|
||||
});
|
||||
|
||||
return { code: 200 };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user