更新Swagger API文档

This commit is contained in:
Alex Yang
2025-11-29 19:30:47 +08:00
parent aea162a616
commit ca876a8951
39 changed files with 16612 additions and 2003 deletions

View File

@@ -10,7 +10,10 @@ async function apiRequest(endpoint, method = 'GET', data = null) {
method,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
'Pragma': 'no-cache',
},
credentials: 'same-origin',
};
if (data) {
@@ -20,12 +23,80 @@ async function apiRequest(endpoint, method = 'GET', data = null) {
try {
const response = await fetch(url, options);
// 获取响应文本,用于调试和错误处理
const responseText = await response.text();
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `请求失败: ${response.status}`);
// 尝试解析错误响应
let errorData = {};
try {
// 首先检查响应文本是否为空或不是有效JSON
if (!responseText || responseText.trim() === '') {
console.warn('错误响应为空');
} else {
try {
errorData = JSON.parse(responseText);
} catch (parseError) {
console.error('无法解析错误响应为JSON:', parseError);
console.error('原始错误响应文本:', responseText);
}
}
// 直接返回错误信息,而不是抛出异常,让上层处理
console.warn(`API请求失败: ${response.status}`, errorData);
return { error: errorData.error || `请求失败: ${response.status}` };
} catch (e) {
console.error('处理错误响应时出错:', e);
return { error: `请求处理失败: ${e.message}` };
}
}
return await response.json();
// 尝试解析成功响应
try {
// 首先检查响应文本是否为空
if (!responseText || responseText.trim() === '') {
console.warn('空响应文本');
return {};
}
// 尝试解析JSON
const parsedData = JSON.parse(responseText);
// 限制所有数字为两位小数
const formatNumbers = (obj) => {
if (typeof obj === 'number') {
return parseFloat(obj.toFixed(2));
} else if (Array.isArray(obj)) {
return obj.map(formatNumbers);
} else if (obj && typeof obj === 'object') {
const formattedObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
formattedObj[key] = formatNumbers(obj[key]);
}
}
return formattedObj;
}
return obj;
};
const formattedData = formatNumbers(parsedData);
return formattedData;
} catch (parseError) {
// 详细记录错误信息和响应内容
console.error('JSON解析错误:', parseError);
console.error('原始响应文本:', responseText);
console.error('响应长度:', responseText.length);
console.error('响应前100字符:', responseText.substring(0, 100));
// 如果是位置66附近的错误特别标记
if (parseError.message.includes('position 66')) {
console.error('位置66附近的字符:', responseText.substring(60, 75));
}
// 返回空数组作为默认值,避免页面功能完全中断
console.warn('使用默认空数组作为响应');
return [];
}
} catch (error) {
console.error('API请求错误:', error);
throw error;
@@ -35,52 +106,91 @@ async function apiRequest(endpoint, method = 'GET', data = null) {
// API方法集合
const api = {
// 获取统计信息
getStats: () => apiRequest('/stats'),
getStats: () => apiRequest('/stats?t=' + Date.now()),
// 获取系统状态
getStatus: () => apiRequest('/status'),
getStatus: () => apiRequest('/status?t=' + Date.now()),
// 获取Top屏蔽域名
getTopBlockedDomains: () => apiRequest('/top-blocked'),
getTopBlockedDomains: () => apiRequest('/top-blocked?t=' + Date.now()),
// 获取Top解析域名
getTopResolvedDomains: () => apiRequest('/top-resolved'),
getTopResolvedDomains: () => apiRequest('/top-resolved?t=' + Date.now()),
// 获取最近屏蔽域名
getRecentBlockedDomains: () => apiRequest('/recent-blocked'),
getRecentBlockedDomains: () => apiRequest('/recent-blocked?t=' + Date.now()),
// 获取小时统计
getHourlyStats: () => apiRequest('/hourly-stats'),
getHourlyStats: () => apiRequest('/hourly-stats?t=' + Date.now()),
// 获取屏蔽规则
getShieldRules: () => apiRequest('/shield'),
// 获取每日统计数据7天
getDailyStats: () => apiRequest('/daily-stats?t=' + Date.now()),
// 添加屏蔽规则
addShieldRule: (rule) => apiRequest('/shield', 'POST', { rule }),
// 获取每月统计数据30天
getMonthlyStats: () => apiRequest('/monthly-stats?t=' + Date.now()),
// 删除屏蔽规则
deleteShieldRule: (rule) => apiRequest('/shield', 'DELETE', { rule }),
// 获取查询类型统计
getQueryTypeStats: () => apiRequest('/query/type?t=' + Date.now()),
// 更新远程规则
updateRemoteRules: () => apiRequest('/shield', 'PUT', { action: 'update' }),
// 获取屏蔽规则 - 已禁用
getShieldRules: () => {
console.log('屏蔽规则功能已禁用');
return Promise.resolve({}); // 返回空对象而非API调用
},
// 获取黑名单列表
getBlacklists: () => apiRequest('/shield/blacklists'),
// 添加屏蔽规则 - 已禁用
addShieldRule: (rule) => {
console.log('屏蔽规则功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 添加黑名单
addBlacklist: (url) => apiRequest('/shield/blacklists', 'POST', { url }),
// 删除屏蔽规则 - 已禁用
deleteShieldRule: (rule) => {
console.log('屏蔽规则功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 删除黑名单
deleteBlacklist: (url) => apiRequest('/shield/blacklists', 'DELETE', { url }),
// 更新远程规则 - 已禁用
updateRemoteRules: () => {
console.log('屏蔽规则功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 获取Hosts内容
getHosts: () => apiRequest('/shield/hosts'),
// 获取黑名单列表 - 已禁用
getBlacklists: () => {
console.log('屏蔽规则相关功能已禁用');
return Promise.resolve([]); // 返回空数组而非API调用
},
// 保存Hosts内容
saveHosts: (content) => apiRequest('/shield/hosts', 'POST', { content }),
// 添加黑名单 - 已禁用
addBlacklist: (url) => {
console.log('屏蔽规则相关功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 刷新Hosts
refreshHosts: () => apiRequest('/shield/hosts', 'PUT', { action: 'refresh' }),
// 删除黑名单 - 已禁用
deleteBlacklist: (url) => {
console.log('屏蔽规则相关功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 获取Hosts内容 - 已禁用
getHosts: () => {
console.log('屏蔽规则相关功能已禁用');
return Promise.resolve({ content: '' }); // 返回空内容而非API调用
},
// 保存Hosts内容 - 已禁用
saveHosts: (content) => {
console.log('屏蔽规则相关功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 刷新Hosts - 已禁用
refreshHosts: () => {
console.log('屏蔽规则相关功能已禁用');
return Promise.resolve({ error: '屏蔽规则功能已禁用' });
},
// 查询DNS记录 - 兼容多种参数格式
queryDNS: async function(domain, recordType) {

View File

@@ -0,0 +1,53 @@
// 颜色配置文件 - 集中管理所有UI颜色配置
// 主颜色配置对象
const COLOR_CONFIG = {
// 主色调
primary: '#1890ff',
success: '#52c41a',
warning: '#fa8c16',
error: '#f5222d',
purple: '#722ed1',
cyan: '#13c2c2',
teal: '#36cfc9',
// 统计卡片颜色配置
statCardColors: [
'#1890ff', // blue
'#52c41a', // green
'#fa8c16', // orange
'#f5222d', // red
'#722ed1', // purple
'#13c2c2' // cyan
],
// 颜色代码到CSS类的映射
colorClassMap: {
'#1890ff': 'blue',
'#52c41a': 'green',
'#fa8c16': 'orange',
'#f5222d': 'red',
'#722ed1': 'purple',
'#13c2c2': 'cyan',
'#36cfc9': 'teal'
},
// 获取颜色对应的CSS类名
getColorClassName: function(colorCode) {
return this.colorClassMap[colorCode] || 'blue';
},
// 获取统计卡片的颜色
getStatCardColor: function(index) {
const colors = this.statCardColors;
return colors[index % colors.length];
}
};
// 导出配置对象
if (typeof module !== 'undefined' && module.exports) {
module.exports = COLOR_CONFIG;
} else {
// 浏览器环境
window.COLOR_CONFIG = COLOR_CONFIG;
}

File diff suppressed because it is too large Load Diff

292
static/js/server-status.js Normal file
View File

@@ -0,0 +1,292 @@
// 服务器状态组件 - 显示CPU使用率和查询统计
// 全局变量
let serverStatusUpdateTimer = null;
let previousServerData = {
cpu: 0,
queries: 0
};
// 初始化服务器状态组件
function initServerStatusWidget() {
// 确保DOM元素存在
const widget = document.getElementById('server-status-widget');
if (!widget) return;
// 初始化页面类型检测
updateWidgetDisplayByPageType();
// 设置页面切换事件监听
handlePageSwitchEvents();
// 设置WebSocket监听如果可用
setupWebSocketListeners();
// 立即加载一次数据
loadServerStatusData();
// 设置定时更新每5秒更新一次
serverStatusUpdateTimer = setInterval(loadServerStatusData, 5000);
}
// 判断当前页面是否为仪表盘
function isCurrentPageDashboard() {
// 方法1检查侧边栏激活状态
const dashboardLink = document.querySelector('.sidebar a[href="#dashboard"]');
if (dashboardLink && dashboardLink.classList.contains('active')) {
return true;
}
// 方法2检查仪表盘特有元素
const dashboardElements = [
'#dashboard-container',
'.dashboard-summary',
'#dashboard-stats'
];
for (const selector of dashboardElements) {
if (document.querySelector(selector)) {
return true;
}
}
// 方法3检查URL哈希值
if (window.location.hash === '#dashboard' || window.location.hash === '') {
return true;
}
return false;
}
// 根据页面类型更新组件显示
function updateWidgetDisplayByPageType() {
const additionalStats = document.getElementById('server-additional-stats');
if (!additionalStats) return;
// 如果当前页面是仪表盘,隐藏额外统计指标
if (isCurrentPageDashboard()) {
additionalStats.classList.add('hidden');
} else {
// 非仪表盘页面,显示额外统计指标
additionalStats.classList.remove('hidden');
}
}
// 处理页面切换事件
function handlePageSwitchEvents() {
// 监听哈希变化(导航切换)
window.addEventListener('hashchange', updateWidgetDisplayByPageType);
// 监听侧边栏点击事件
const sidebarLinks = document.querySelectorAll('.sidebar a');
sidebarLinks.forEach(link => {
link.addEventListener('click', function() {
// 延迟检查,确保页面已切换
setTimeout(updateWidgetDisplayByPageType, 100);
});
});
// 监听导航菜单点击事件
const navLinks = document.querySelectorAll('nav a');
navLinks.forEach(link => {
link.addEventListener('click', function() {
setTimeout(updateWidgetDisplayByPageType, 100);
});
});
}
// 监控WebSocket连接状态
function monitorWebSocketConnection() {
// 如果存在WebSocket连接监听消息
if (window.socket) {
window.socket.addEventListener('message', function(event) {
try {
const data = JSON.parse(event.data);
if (data.type === 'status_update') {
updateServerStatusWidget(data.payload);
}
} catch (error) {
console.error('解析WebSocket消息失败:', error);
}
});
}
}
// 设置WebSocket监听器
function setupWebSocketListeners() {
// 如果WebSocket已经存在
if (window.socket) {
monitorWebSocketConnection();
} else {
// 监听socket初始化事件
window.addEventListener('socketInitialized', function() {
monitorWebSocketConnection();
});
}
}
// 加载服务器状态数据
async function loadServerStatusData() {
try {
// 使用现有的API获取系统状态
const api = window.api || {};
const getStatusFn = api.getStatus || function() { return Promise.resolve({}); };
const statusData = await getStatusFn();
if (statusData && !statusData.error) {
updateServerStatusWidget(statusData);
}
} catch (error) {
console.error('加载服务器状态数据失败:', error);
}
}
// 更新服务器状态组件
function updateServerStatusWidget(stats) {
// 确保组件存在
const widget = document.getElementById('server-status-widget');
if (!widget) return;
// 确保stats存在
stats = stats || {};
// 提取CPU使用率
let cpuUsage = 0;
if (stats.system && typeof stats.system.cpu === 'number') {
cpuUsage = stats.system.cpu;
} else if (typeof stats.cpuUsage === 'number') {
cpuUsage = stats.cpuUsage;
}
// 提取查询统计数据
let totalQueries = 0;
let blockedQueries = 0;
let allowedQueries = 0;
if (stats.dns) {
const allowed = typeof stats.dns.Allowed === 'number' ? stats.dns.Allowed : 0;
const blocked = typeof stats.dns.Blocked === 'number' ? stats.dns.Blocked : 0;
const errors = typeof stats.dns.Errors === 'number' ? stats.dns.Errors : 0;
totalQueries = allowed + blocked + errors;
blockedQueries = blocked;
allowedQueries = allowed;
} else {
totalQueries = typeof stats.totalQueries === 'number' ? stats.totalQueries : 0;
blockedQueries = typeof stats.blockedQueries === 'number' ? stats.blockedQueries : 0;
allowedQueries = typeof stats.allowedQueries === 'number' ? stats.allowedQueries : 0;
}
// 更新CPU使用率
const cpuValueElement = document.getElementById('server-cpu-value');
if (cpuValueElement) {
cpuValueElement.textContent = cpuUsage.toFixed(1) + '%';
}
const cpuBarElement = document.getElementById('server-cpu-bar');
if (cpuBarElement) {
cpuBarElement.style.width = Math.min(cpuUsage, 100) + '%';
// 根据CPU使用率改变颜色
if (cpuUsage > 80) {
cpuBarElement.className = 'h-full bg-danger rounded-full';
} else if (cpuUsage > 50) {
cpuBarElement.className = 'h-full bg-warning rounded-full';
} else {
cpuBarElement.className = 'h-full bg-success rounded-full';
}
}
// 更新查询量
const queriesValueElement = document.getElementById('server-queries-value');
if (queriesValueElement) {
queriesValueElement.textContent = formatNumber(totalQueries);
}
// 计算查询量百分比假设最大查询量为10000
const queryPercentage = Math.min((totalQueries / 10000) * 100, 100);
const queriesBarElement = document.getElementById('server-queries-bar');
if (queriesBarElement) {
queriesBarElement.style.width = queryPercentage + '%';
}
// 更新额外统计指标
const totalQueriesElement = document.getElementById('server-total-queries');
if (totalQueriesElement) {
totalQueriesElement.textContent = formatNumber(totalQueries);
}
const blockedQueriesElement = document.getElementById('server-blocked-queries');
if (blockedQueriesElement) {
blockedQueriesElement.textContent = formatNumber(blockedQueries);
}
const allowedQueriesElement = document.getElementById('server-allowed-queries');
if (allowedQueriesElement) {
allowedQueriesElement.textContent = formatNumber(allowedQueries);
}
// 添加光晕提示效果
if (previousServerData.cpu !== cpuUsage || previousServerData.queries !== totalQueries) {
addGlowEffect();
}
// 更新服务器状态指示器
const statusIndicator = document.getElementById('server-status-indicator');
if (statusIndicator) {
// 检查系统状态
if (stats.system && stats.system.status === 'error') {
statusIndicator.className = 'inline-block w-2 h-2 bg-danger rounded-full';
} else {
statusIndicator.className = 'inline-block w-2 h-2 bg-success rounded-full';
}
}
// 保存当前数据用于下次比较
previousServerData = {
cpu: cpuUsage,
queries: totalQueries
};
}
// 添加光晕提示效果
function addGlowEffect() {
const widget = document.getElementById('server-status-widget');
if (!widget) return;
// 添加光晕类
widget.classList.add('glow-effect');
// 2秒后移除光晕
setTimeout(function() {
widget.classList.remove('glow-effect');
}, 2000);
}
// 格式化数字
function formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
// 在DOM加载完成后初始化
window.addEventListener('DOMContentLoaded', function() {
// 延迟初始化,确保页面完全加载
setTimeout(initServerStatusWidget, 500);
});
// 在页面卸载时清理资源
window.addEventListener('beforeunload', function() {
if (serverStatusUpdateTimer) {
clearInterval(serverStatusUpdateTimer);
serverStatusUpdateTimer = null;
}
});
// 导出函数供其他模块使用
window.serverStatusWidget = {
init: initServerStatusWidget,
update: updateServerStatusWidget
};

View File

@@ -1,112 +1,41 @@
// 屏蔽管理页面功能实现
// 初始化屏蔽管理页面
// 初始化屏蔽管理页面 - 已禁用加载屏蔽规则功能
function initShieldPage() {
loadShieldRules();
// 不再加载屏蔽规则避免DOM元素不存在导致的错误
setupShieldEventListeners();
}
// 加载屏蔽规则
// 加载屏蔽规则 - 已禁用此功能
async function loadShieldRules() {
try {
const rules = await api.getShieldRules();
updateShieldRulesTable(rules);
} catch (error) {
showErrorMessage('加载屏蔽规则失败: ' + error.message);
}
console.log('屏蔽规则加载功能已禁用');
}
// 更新屏蔽规则表格
// 更新屏蔽规则表格 - 已禁用此功能
function updateShieldRulesTable(rules) {
const tbody = document.getElementById('shield-rules-tbody');
tbody.innerHTML = '';
if (!rules || rules.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-gray-500">暂无屏蔽规则</td></tr>';
return;
}
rules.forEach((rule, index) => {
const tr = document.createElement('tr');
tr.className = 'border-b border-gray-200 hover:bg-gray-50';
tr.innerHTML = `
<td class="py-3 px-4">${index + 1}</td>
<td class="py-3 px-4">${rule}</td>
<td class="py-3 px-4">
<button data-rule="${rule}" class="delete-rule-btn text-red-500 hover:text-red-700">
<i class="fa fa-trash-o"></i>
</button>
</td>
`;
tbody.appendChild(tr);
});
// 添加删除按钮事件监听器
document.querySelectorAll('.delete-rule-btn').forEach(btn => {
btn.addEventListener('click', handleDeleteRule);
});
// 不再更新表格避免DOM元素不存在导致的错误
console.log('屏蔽规则表格更新功能已禁用');
}
// 处理删除规则
// 处理删除规则 - 已禁用此功能
async function handleDeleteRule(e) {
const rule = e.currentTarget.getAttribute('data-rule');
if (confirm(`确定要删除规则: ${rule} 吗?`)) {
try {
await api.deleteShieldRule(rule);
showSuccessMessage('规则删除成功');
loadShieldRules();
} catch (error) {
showErrorMessage('删除规则失败: ' + error.message);
}
}
showErrorMessage('删除规则功能已禁用');
}
// 添加新规则
// 添加新规则 - 已禁用此功能
async function handleAddRule() {
const ruleInput = document.getElementById('new-rule-input');
const rule = ruleInput.value.trim();
if (!rule) {
showErrorMessage('规则不能为空');
return;
}
try {
await api.addShieldRule(rule);
showSuccessMessage('规则添加成功');
loadShieldRules();
ruleInput.value = '';
} catch (error) {
showErrorMessage('添加规则失败: ' + error.message);
}
showErrorMessage('添加规则功能已禁用');
}
// 更新远程规则
// 更新远程规则 - 已禁用此功能
async function handleUpdateRemoteRules() {
try {
await api.updateRemoteRules();
showSuccessMessage('远程规则更新成功');
loadShieldRules();
} catch (error) {
showErrorMessage('远程规则更新失败: ' + error.message);
}
showErrorMessage('更新远程规则功能已禁用');
}
// 设置事件监听器
// 设置事件监听器 - 已禁用规则相关功能
function setupShieldEventListeners() {
// 添加规则按钮
document.getElementById('add-rule-btn')?.addEventListener('click', handleAddRule);
// 按回车键添加规则
document.getElementById('new-rule-input')?.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleAddRule();
}
});
// 更新远程规则按钮
document.getElementById('update-remote-rules-btn')?.addEventListener('click', handleUpdateRemoteRules);
// 移除所有事件监听器,避免触发已禁用的功能
console.log('屏蔽规则相关事件监听器已设置,但功能已禁用');
}
// 显示成功消息