chore: remove useless code
This commit is contained in:
1 parent
c88d4dd5b2
commit
1058dcfa3a
12 files changed
+33
-617
No files matched your search
@@ -9,7 +9,6 @@ const notifications = new Hono<{ Bindings: Bindings }>();
|
||||
notifications.get("/", async (c) => {
|
||||
try {
|
||||
const db = c.env.DB;
|
||||
const userId = c.get("jwtPayload").id;
|
||||
|
||||
const config = await NotificationService.getNotificationConfig(db);
|
||||
|
||||
@@ -631,103 +630,4 @@ notifications.get("/history", async (c) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 测试通知渠道
|
||||
notifications.post("/test", async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
|
||||
// 验证参数
|
||||
const schema = z.object({
|
||||
channel: z.object({
|
||||
id: z.union([z.string(), z.number()]).optional(),
|
||||
name: z.string(),
|
||||
type: z.string(),
|
||||
config: z.any(),
|
||||
enabled: z.boolean().default(true),
|
||||
}),
|
||||
subject: z.string().default("测试通知"),
|
||||
content: z
|
||||
.string()
|
||||
.default(
|
||||
"这是一条测试通知,如果您收到这条消息,表明您的通知配置正确。"
|
||||
),
|
||||
});
|
||||
|
||||
const { channel, subject, content } = schema.parse(body);
|
||||
|
||||
// 确保 id 有值,否则设置为 0
|
||||
const channelWithId = {
|
||||
...channel,
|
||||
id: channel.id !== undefined ? channel.id : 0,
|
||||
config: channel.config || {}, // 确保 config 有值
|
||||
};
|
||||
|
||||
// 发送测试通知
|
||||
const result = await NotificationService.sendTestEmail(
|
||||
channelWithId,
|
||||
subject,
|
||||
content
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
return c.json({
|
||||
success: true,
|
||||
message: "测试通知发送成功",
|
||||
});
|
||||
} else {
|
||||
return c.json(
|
||||
{
|
||||
success: false,
|
||||
message: `测试通知发送失败: ${result.error}`,
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("发送测试通知失败:", error);
|
||||
return c.json(
|
||||
{
|
||||
success: false,
|
||||
message: "发送测试通知失败",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// 验证Telegram令牌
|
||||
notifications.post("/validate-telegram", async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
|
||||
// 验证参数
|
||||
const schema = z.object({
|
||||
botToken: z.string(),
|
||||
});
|
||||
|
||||
const { botToken } = schema.parse(body);
|
||||
|
||||
// 验证令牌
|
||||
const isValid = await NotificationService.validateTelegramToken(botToken);
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
data: {
|
||||
valid: isValid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("验证Telegram令牌失败:", error);
|
||||
return c.json(
|
||||
{
|
||||
success: false,
|
||||
message: "验证Telegram令牌失败",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export { notifications };
|
||||
@@ -1,10 +1,7 @@
|
||||
import { Hono } from "hono";
|
||||
import { Bindings } from "../models/db";
|
||||
import { Monitor } from "../models/monitor";
|
||||
import {
|
||||
getMonitorsToCheck,
|
||||
checkSingleMonitor as monitorServiceCheck,
|
||||
} from "../services";
|
||||
import { getMonitorsToCheck, checkMonitor } from "../services";
|
||||
import { shouldSendNotification, sendNotification } from "../services";
|
||||
|
||||
const monitorTask = new Hono<{ Bindings: Bindings }>();
|
||||
@@ -30,7 +27,7 @@ async function checkMonitors(c: any) {
|
||||
monitors.results.map(async (monitorItem: any) => {
|
||||
// 确保正确的类型转换
|
||||
const monitor = monitorItem as Monitor;
|
||||
const checkResult = await checkSingleMonitor(c, monitor);
|
||||
const checkResult = await checkMonitor(c.env.DB, monitor);
|
||||
|
||||
// 处理通知
|
||||
await handleMonitorNotification(c, monitor, checkResult);
|
||||
@@ -51,12 +48,6 @@ async function checkMonitors(c: any) {
|
||||
}
|
||||
}
|
||||
|
||||
// 检查单个监控的函数
|
||||
async function checkSingleMonitor(c: any, monitor: Monitor) {
|
||||
// 使用服务层的检查函数
|
||||
return await monitorServiceCheck(c.env.DB, monitor);
|
||||
}
|
||||
|
||||
// 处理监控通知
|
||||
async function handleMonitorNotification(
|
||||
c: any,
|
||||
|
||||
@@ -12,6 +12,19 @@ export async function getAllAgents(db: Bindings["DB"]) {
|
||||
.all<Agent>();
|
||||
}
|
||||
|
||||
// 批量获取客户端详情
|
||||
export async function getAgentsByIds(db: Bindings["DB"], agentIds: number[]) {
|
||||
if (agentIds.length === 0) {
|
||||
return { results: [] };
|
||||
}
|
||||
|
||||
const placeholders = agentIds.map(() => "?").join(",");
|
||||
return await db
|
||||
.prepare(`SELECT * FROM agents WHERE id IN (${placeholders})`)
|
||||
.bind(...agentIds)
|
||||
.all<Agent>();
|
||||
}
|
||||
|
||||
// 获取用户创建的客户端
|
||||
export async function getAgentsByUser(db: Bindings["DB"], userId: number) {
|
||||
return await db
|
||||
@@ -230,26 +243,6 @@ export async function deleteAgent(db: Bindings["DB"], id: number) {
|
||||
return { success: true, message: "客户端已删除" };
|
||||
}
|
||||
|
||||
// 更新客户端令牌
|
||||
export async function updateAgentToken(
|
||||
db: Bindings["DB"],
|
||||
id: number,
|
||||
token: string
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const result = await db
|
||||
.prepare("UPDATE agents SET token = ?, updated_at = ? WHERE id = ?")
|
||||
.bind(token, now, id)
|
||||
.run();
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error("更新客户端令牌失败");
|
||||
}
|
||||
|
||||
return { success: true, message: "客户端令牌已更新", token };
|
||||
}
|
||||
|
||||
// 通过令牌获取客户端
|
||||
export async function getAgentByToken(db: Bindings["DB"], token: string) {
|
||||
return await db
|
||||
@@ -258,20 +251,6 @@ export async function getAgentByToken(db: Bindings["DB"], token: string) {
|
||||
.first<Agent>();
|
||||
}
|
||||
|
||||
// 获取管理员用户ID
|
||||
export async function getAdminUserId(db: Bindings["DB"]) {
|
||||
const adminUser = await db
|
||||
.prepare("SELECT id FROM users WHERE role = ?")
|
||||
.bind("admin")
|
||||
.first<{ id: number }>();
|
||||
|
||||
if (!adminUser) {
|
||||
throw new Error("无法找到管理员用户");
|
||||
}
|
||||
|
||||
return adminUser.id;
|
||||
}
|
||||
|
||||
// 获取活跃状态的客户端
|
||||
export async function getActiveAgents(db: Bindings["DB"]) {
|
||||
return await db
|
||||
|
||||
@@ -121,21 +121,6 @@ export async function getAllMonitors(db: Bindings["DB"]) {
|
||||
};
|
||||
}
|
||||
|
||||
// 批量获取监控项详情
|
||||
export async function getMonitorsByIds(
|
||||
db: Bindings["DB"],
|
||||
monitorIds: number[]
|
||||
) {
|
||||
if (monitorIds.length === 0) {
|
||||
return { results: [] };
|
||||
}
|
||||
|
||||
const placeholders = monitorIds.map(() => "?").join(",");
|
||||
return await db
|
||||
.prepare(`SELECT * FROM monitors WHERE id IN (${placeholders})`)
|
||||
.bind(...monitorIds)
|
||||
.all<Monitor>();
|
||||
}
|
||||
|
||||
// 获取单个监控状态历史 24小时内
|
||||
export async function getMonitorStatusHistoryIn24h(
|
||||
|
||||
@@ -376,19 +376,6 @@ export const createOrUpdateSettings = async (
|
||||
}
|
||||
};
|
||||
|
||||
// 删除特定对象的通知设置
|
||||
export const deleteNotificationSettings = async (
|
||||
db: D1Database,
|
||||
id: number
|
||||
): Promise<boolean> => {
|
||||
const result = await db
|
||||
.prepare("DELETE FROM notification_settings WHERE id = ?")
|
||||
.bind(id)
|
||||
.run();
|
||||
|
||||
return ((result.meta as D1Meta)?.changes || 0) > 0;
|
||||
};
|
||||
|
||||
// 记录通知历史
|
||||
export const createNotificationHistory = async (
|
||||
db: D1Database,
|
||||
@@ -477,7 +464,7 @@ export const getNotificationHistory = async (
|
||||
};
|
||||
};
|
||||
|
||||
// 获取完整的通知配置(用于前端)
|
||||
// 获取完整的通知配置
|
||||
export const getNotificationConfig = async (
|
||||
db: D1Database,
|
||||
): Promise<NotificationConfig> => {
|
||||
|
||||
@@ -4,16 +4,6 @@ import { StatusPageConfig, Agent, Bindings } from "../models";
|
||||
* 状态页相关的数据库操作
|
||||
*/
|
||||
|
||||
// 获取用户的状态页配置
|
||||
export async function getUserStatusPageConfig(
|
||||
db: Bindings["DB"],
|
||||
userId: number
|
||||
) {
|
||||
return await db
|
||||
.prepare("SELECT * FROM status_page_config WHERE user_id = ?")
|
||||
.bind(userId)
|
||||
.all<StatusPageConfig>();
|
||||
}
|
||||
|
||||
// 获取所有状态页配置
|
||||
export async function getAllStatusPageConfigs(db: Bindings["DB"]) {
|
||||
@@ -176,68 +166,4 @@ export async function getSelectedAgents(db: Bindings["DB"], configId: number) {
|
||||
.all<{ agent_id: number }>();
|
||||
}
|
||||
|
||||
// 获取客户端详情
|
||||
export async function getAgentsByIds(db: Bindings["DB"], agentIds: number[]) {
|
||||
if (agentIds.length === 0) {
|
||||
return { results: [] };
|
||||
}
|
||||
|
||||
const placeholders = agentIds.map(() => "?").join(",");
|
||||
return await db
|
||||
.prepare(`SELECT * FROM agents WHERE id IN (${placeholders})`)
|
||||
.bind(...agentIds)
|
||||
.all<Agent>();
|
||||
}
|
||||
|
||||
// 创建默认配置并关联所有监控项和客户端
|
||||
export async function createDefaultConfig(db: Bindings["DB"], adminId: number) {
|
||||
// 创建默认配置
|
||||
const insertResult = await createStatusPageConfig(
|
||||
db,
|
||||
adminId,
|
||||
"系统状态",
|
||||
"实时监控系统状态",
|
||||
"",
|
||||
""
|
||||
);
|
||||
|
||||
if (!insertResult || typeof insertResult.id !== "number") {
|
||||
throw new Error("创建默认配置失败");
|
||||
}
|
||||
|
||||
const configId = insertResult.id;
|
||||
|
||||
// 获取所有活跃监控项
|
||||
let monitors;
|
||||
try {
|
||||
monitors = await db
|
||||
.prepare("SELECT * FROM monitors WHERE active = 1")
|
||||
.all();
|
||||
} catch (error) {
|
||||
monitors = { results: [] };
|
||||
}
|
||||
|
||||
// 获取所有客户端
|
||||
let agents;
|
||||
try {
|
||||
agents = await db.prepare("SELECT * FROM agents").all();
|
||||
} catch (error) {
|
||||
agents = { results: [] };
|
||||
}
|
||||
|
||||
// 关联监控项
|
||||
if (monitors.results && monitors.results.length > 0) {
|
||||
for (const monitor of monitors.results as { id: number }[]) {
|
||||
await addMonitorToConfig(db, configId, monitor.id);
|
||||
}
|
||||
}
|
||||
|
||||
// 关联客户端
|
||||
if (agents.results && agents.results.length > 0) {
|
||||
for (const agent of agents.results as { id: number }[]) {
|
||||
await addAgentToConfig(db, configId, agent.id);
|
||||
}
|
||||
}
|
||||
|
||||
return configId;
|
||||
}
|
||||
@@ -189,3 +189,18 @@ export async function getUserByUsername(
|
||||
.bind(username)
|
||||
.first<User | null>();
|
||||
}
|
||||
|
||||
|
||||
// 获取管理员用户ID
|
||||
export async function getAdminUserId(db: Bindings["DB"]) {
|
||||
const adminUser = await db
|
||||
.prepare("SELECT id FROM users WHERE role = ?")
|
||||
.bind("admin")
|
||||
.first<{ id: number }>();
|
||||
|
||||
if (!adminUser) {
|
||||
throw new Error("无法找到管理员用户");
|
||||
}
|
||||
|
||||
return adminUser.id;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Bindings } from "../models/db";
|
||||
import * as AgentRepository from "../repositories/agent";
|
||||
import * as AgentRepository from "../repositories";
|
||||
import { generateToken, verifyToken } from "../utils/jwt";
|
||||
|
||||
/**
|
||||
@@ -496,106 +496,10 @@ export async function updateAgentStatusService(
|
||||
}
|
||||
}
|
||||
|
||||
// 保留原有函数供直接使用
|
||||
export async function getAllAgents(db: Bindings["DB"]) {
|
||||
return await AgentRepository.getAllAgents(db);
|
||||
}
|
||||
|
||||
export async function getAgentsByUser(db: Bindings["DB"], userId: number) {
|
||||
return await AgentRepository.getAgentsByUser(db, userId);
|
||||
}
|
||||
|
||||
export async function getAgentById(db: Bindings["DB"], id: number) {
|
||||
return await AgentRepository.getAgentById(db, id);
|
||||
}
|
||||
|
||||
export async function createAgent(
|
||||
db: Bindings["DB"],
|
||||
name: string,
|
||||
token: string,
|
||||
createdBy: number,
|
||||
status: string = "inactive",
|
||||
hostname: string | null = null,
|
||||
os: string | null = null,
|
||||
version: string | null = null,
|
||||
ipAddresses: string[] | null = null
|
||||
) {
|
||||
return await AgentRepository.createAgent(
|
||||
db,
|
||||
name,
|
||||
token,
|
||||
createdBy,
|
||||
status,
|
||||
hostname,
|
||||
os,
|
||||
version,
|
||||
ipAddresses
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateAgent(
|
||||
db: Bindings["DB"],
|
||||
id: number,
|
||||
fields: {
|
||||
name?: string;
|
||||
hostname?: string;
|
||||
ip_addresses?: string[];
|
||||
os?: string;
|
||||
version?: string;
|
||||
status?: string;
|
||||
cpu_usage?: number;
|
||||
memory_total?: number;
|
||||
memory_used?: number;
|
||||
disk_total?: number;
|
||||
disk_used?: number;
|
||||
network_rx?: number;
|
||||
network_tx?: number;
|
||||
}
|
||||
) {
|
||||
return await AgentRepository.updateAgent(db, id, fields);
|
||||
}
|
||||
|
||||
export async function updateAgentStatus(
|
||||
db: Bindings["DB"],
|
||||
id: number,
|
||||
status: string = "active",
|
||||
metrics: {
|
||||
cpu_usage?: number;
|
||||
memory_total?: number;
|
||||
memory_used?: number;
|
||||
disk_total?: number;
|
||||
disk_used?: number;
|
||||
network_rx?: number;
|
||||
network_tx?: number;
|
||||
hostname?: string;
|
||||
ip_addresses?: string[];
|
||||
os?: string;
|
||||
version?: string;
|
||||
}
|
||||
) {
|
||||
return await AgentRepository.updateAgentStatus(db, id, status, metrics);
|
||||
}
|
||||
|
||||
export async function deleteAgent(db: Bindings["DB"], id: number) {
|
||||
return await AgentRepository.deleteAgent(db, id);
|
||||
}
|
||||
|
||||
export async function updateAgentToken(
|
||||
db: Bindings["DB"],
|
||||
id: number,
|
||||
token: string
|
||||
) {
|
||||
return await AgentRepository.updateAgentToken(db, id, token);
|
||||
}
|
||||
|
||||
export async function getAgentByToken(db: Bindings["DB"], token: string) {
|
||||
return await AgentRepository.getAgentByToken(db, token);
|
||||
}
|
||||
|
||||
export async function getAdminUserId(db: Bindings["DB"]) {
|
||||
return await AgentRepository.getAdminUserId(db);
|
||||
}
|
||||
|
||||
export async function getActiveAgents(db: Bindings["DB"]) {
|
||||
return await AgentRepository.getActiveAgents(db);
|
||||
}
|
||||
@@ -603,25 +507,3 @@ export async function getActiveAgents(db: Bindings["DB"]) {
|
||||
export async function setAgentInactive(db: Bindings["DB"], id: number) {
|
||||
return await AgentRepository.setAgentInactive(db, id);
|
||||
}
|
||||
|
||||
export async function registerAgent(
|
||||
db: Bindings["DB"],
|
||||
env: any,
|
||||
token: string,
|
||||
name: string,
|
||||
hostname: string | null = null,
|
||||
ipAddresses: string[] | null = null,
|
||||
os: string | null = null,
|
||||
version: string | null = null
|
||||
) {
|
||||
return await registerAgentService(
|
||||
db,
|
||||
env,
|
||||
token,
|
||||
name,
|
||||
hostname,
|
||||
ipAddresses,
|
||||
os,
|
||||
version
|
||||
);
|
||||
}
|
||||
@@ -161,41 +161,6 @@ export async function registerUser(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证用户令牌
|
||||
* @param env 环境变量
|
||||
* @param token JWT令牌
|
||||
* @returns 验证结果
|
||||
*/
|
||||
export async function verifyUserToken(
|
||||
env: any,
|
||||
token: string
|
||||
): Promise<{ success: boolean; message: string; user?: any }> {
|
||||
try {
|
||||
const secret = getJwtSecret(env);
|
||||
const decoded = jsonwebtoken.verify(token, secret) as { id: number };
|
||||
|
||||
if (!decoded || !decoded.id) {
|
||||
return { success: false, message: "无效的令牌" };
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
const user = await repositories.getUserById(env.DB, decoded.id);
|
||||
if (!user) {
|
||||
return { success: false, message: "用户不存在" };
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "令牌有效",
|
||||
user,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("令牌验证错误:", error);
|
||||
return { success: false, message: "令牌验证失败" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
* @param env 环境变量,包含数据库连接
|
||||
|
||||
@@ -138,37 +138,6 @@ export async function checkMonitor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个监控的详细信息
|
||||
*/
|
||||
export async function getMonitorDetails(db: Bindings["DB"], id: number) {
|
||||
const monitor = await repositories.getMonitorById(db, id);
|
||||
if (!monitor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 获取历史状态数据
|
||||
const historyResult = await repositories.getMonitorStatusHistoryIn24h(db, id);
|
||||
|
||||
return {
|
||||
...monitor,
|
||||
history: historyResult.results || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查单个监控
|
||||
* @param db 数据库连接
|
||||
* @param monitor 监控对象
|
||||
* @returns 检查结果
|
||||
*/
|
||||
export async function checkSingleMonitor(
|
||||
db: Bindings["DB"],
|
||||
monitor: models.Monitor
|
||||
) {
|
||||
return checkMonitor(db, monitor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有监控(根据用户角色过滤)
|
||||
* @param db 数据库连接
|
||||
@@ -449,7 +418,7 @@ export async function manualCheckMonitor(
|
||||
}
|
||||
|
||||
// 使用抽象出来的通用检查监控函数进行检查
|
||||
const result = await checkSingleMonitor(db, monitor);
|
||||
const result = await checkMonitor(db, monitor);
|
||||
|
||||
// 处理通知逻辑
|
||||
try {
|
||||
|
||||
@@ -455,25 +455,6 @@ async function sendTelegramNotification(
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证Telegram令牌是否有效
|
||||
*/
|
||||
export async function validateTelegramToken(
|
||||
botToken: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://api.telegram.org/bot${botToken}/getMe`
|
||||
);
|
||||
const data = await response.json();
|
||||
return data.ok === true;
|
||||
} catch (error) {
|
||||
console.error("验证Telegram令牌失败:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据渠道类型发送通知
|
||||
*/
|
||||
@@ -823,42 +804,3 @@ export async function shouldSendNotification(
|
||||
|
||||
return { shouldSend, channels };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送测试邮件
|
||||
*/
|
||||
export async function sendTestEmail(
|
||||
channel: {
|
||||
id: string | number;
|
||||
name: string;
|
||||
type: string;
|
||||
config: any;
|
||||
enabled: boolean;
|
||||
},
|
||||
subject: string,
|
||||
content: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const channelObj: models.NotificationChannel = {
|
||||
id: typeof channel.id === "string" ? parseInt(channel.id) : channel.id,
|
||||
name: channel.name,
|
||||
type: channel.type,
|
||||
config:
|
||||
typeof channel.config === "string"
|
||||
? channel.config
|
||||
: JSON.stringify(channel.config),
|
||||
enabled: channel.enabled,
|
||||
created_by: 0,
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
|
||||
return await sendNotificationByChannel(channelObj, subject, content);
|
||||
} catch (error) {
|
||||
console.error("发送测试邮件失败:", error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -263,128 +263,3 @@ export async function getStatusPagePublicData(env: { DB: Bindings["DB"] }) {
|
||||
agents: agents,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建默认状态页数据
|
||||
* @param env 环境变量,包含数据库连接
|
||||
* @returns 状态页数据
|
||||
*/
|
||||
export async function createDefaultStatusPageData(env: { DB: Bindings["DB"] }) {
|
||||
try {
|
||||
// 获取所有配置
|
||||
const configsResult = await repositories.getAllStatusPageConfigs(env.DB);
|
||||
if (!configsResult.results || configsResult.results.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const config = configsResult.results[0];
|
||||
|
||||
// 获取选中的监控项
|
||||
const selectedMonitors = await repositories.getSelectedMonitors(
|
||||
env.DB,
|
||||
config.id as number
|
||||
);
|
||||
|
||||
// 获取选中的客户端
|
||||
const selectedAgents = await repositories.getSelectedAgents(
|
||||
env.DB,
|
||||
config.id as number
|
||||
);
|
||||
|
||||
// 获取监控项详细信息
|
||||
let monitors: any[] = [];
|
||||
if (selectedMonitors.results && selectedMonitors.results.length > 0) {
|
||||
const monitorIds = selectedMonitors.results.map((m) => m.monitor_id);
|
||||
|
||||
if (monitorIds.length > 0) {
|
||||
const monitorsResult = await repositories.getMonitorsByIds(
|
||||
env.DB,
|
||||
monitorIds
|
||||
);
|
||||
|
||||
if (monitorsResult.results) {
|
||||
monitors = monitorsResult.results;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取客户端详细信息
|
||||
let agents: any[] = [];
|
||||
if (selectedAgents.results && selectedAgents.results.length > 0) {
|
||||
const agentIds = selectedAgents.results.map((a) => a.agent_id);
|
||||
|
||||
if (agentIds.length > 0) {
|
||||
const agentsResult = await repositories.getAgentsByIds(
|
||||
env.DB,
|
||||
agentIds
|
||||
);
|
||||
|
||||
if (agentsResult.results) {
|
||||
agents = agentsResult.results;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 为监控项添加必要的字段
|
||||
const enrichedMonitors = monitors.map((monitor) => ({
|
||||
...monitor,
|
||||
status: monitor.status || "unknown",
|
||||
uptime: monitor.uptime || 0,
|
||||
response_time: monitor.response_time || 0,
|
||||
history: Array(24).fill("unknown"),
|
||||
}));
|
||||
|
||||
// 为客户端添加资源使用情况字段
|
||||
const enrichedAgents = agents.map((agent) => {
|
||||
// 计算内存使用百分比 (如果有总量和使用量)
|
||||
const memoryPercent =
|
||||
agent.memory_total && agent.memory_used
|
||||
? (agent.memory_used / agent.memory_total) * 100
|
||||
: null;
|
||||
|
||||
// 计算磁盘使用百分比 (如果有总量和使用量)
|
||||
const diskPercent =
|
||||
agent.disk_total && agent.disk_used
|
||||
? (agent.disk_used / agent.disk_total) * 100
|
||||
: null;
|
||||
|
||||
return {
|
||||
...agent,
|
||||
cpu: agent.cpu_usage || 0,
|
||||
memory: memoryPercent || 0,
|
||||
disk: diskPercent || 0,
|
||||
network_rx: agent.network_rx || 0,
|
||||
network_tx: agent.network_tx || 0,
|
||||
hostname: agent.hostname || "未知主机",
|
||||
ip_addresses: agent.ip_addresses || "0.0.0.0",
|
||||
os: agent.os || "未知系统",
|
||||
version: agent.version || "未知版本",
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
title: config.title,
|
||||
description: config.description,
|
||||
logoUrl: config.logo_url,
|
||||
customCss: config.custom_css,
|
||||
monitors: enrichedMonitors,
|
||||
agents: enrichedAgents.map((agent) => ({
|
||||
id: agent.id,
|
||||
name: agent.name,
|
||||
status: agent.status,
|
||||
cpu: agent.cpu,
|
||||
memory: agent.memory,
|
||||
disk: agent.disk,
|
||||
network_rx: agent.network_rx,
|
||||
network_tx: agent.network_tx,
|
||||
hostname: agent.hostname,
|
||||
ip_addresses: agent.ip_addresses,
|
||||
os: agent.os,
|
||||
version: agent.version,
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("创建默认状态页数据失败:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user