app.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. // 全局变量
  2. let currentPage = 'dashboard';
  3. let currentNodesPage = 1;
  4. let currentResultsPage = 1;
  5. let currentNotificationsPage = 1;
  6. // API基础URL
  7. const API_BASE = '/api';
  8. // 页面加载完成后初始化
  9. document.addEventListener('DOMContentLoaded', function() {
  10. initializeApp();
  11. });
  12. // 初始化应用
  13. async function initializeApp() {
  14. try {
  15. // 设置导航事件
  16. setupNavigation();
  17. // 加载仪表板数据
  18. await loadDashboard();
  19. // 设置定时刷新
  20. setInterval(loadDashboard, 30000); // 每30秒刷新一次
  21. // 设置实时搜索
  22. setupRealTimeSearch();
  23. console.log('应用初始化完成');
  24. } catch (error) {
  25. console.error('应用初始化失败:', error);
  26. showError('应用初始化失败: ' + error.message);
  27. }
  28. }
  29. // 设置导航
  30. function setupNavigation() {
  31. const navLinks = document.querySelectorAll('[data-page]');
  32. navLinks.forEach(link => {
  33. link.addEventListener('click', function(e) {
  34. e.preventDefault();
  35. const page = this.getAttribute('data-page');
  36. showPage(page);
  37. });
  38. });
  39. }
  40. // 显示页面
  41. async function showPage(pageName) {
  42. // 隐藏所有页面
  43. document.querySelectorAll('.page-content').forEach(page => {
  44. page.style.display = 'none';
  45. });
  46. // 移除所有导航激活状态
  47. document.querySelectorAll('.nav-link').forEach(link => {
  48. link.classList.remove('active');
  49. });
  50. // 激活当前导航
  51. document.querySelector(`[data-page="${pageName}"]`).classList.add('active');
  52. // 显示目标页面
  53. const targetPage = document.getElementById(pageName + '-page');
  54. if (targetPage) {
  55. targetPage.style.display = 'block';
  56. targetPage.classList.add('fade-in');
  57. }
  58. // 加载页面数据
  59. switch (pageName) {
  60. case 'dashboard':
  61. await loadDashboard();
  62. break;
  63. case 'nodes':
  64. await loadNodes();
  65. break;
  66. case 'speed-test':
  67. await loadTestResults();
  68. break;
  69. case 'notifications':
  70. await loadNotifications();
  71. break;
  72. case 'settings':
  73. await loadSettings();
  74. break;
  75. }
  76. currentPage = pageName;
  77. }
  78. // 加载仪表板
  79. async function loadDashboard() {
  80. try {
  81. showLoading();
  82. // 加载统计信息
  83. const statsResponse = await fetch(`${API_BASE}/stats`);
  84. const statsData = await statsResponse.json();
  85. if (statsData.success) {
  86. updateDashboardStats(statsData.data);
  87. }
  88. // 加载最近测速结果
  89. const resultsResponse = await fetch(`${API_BASE}/test/results?limit=5`);
  90. const resultsData = await resultsResponse.json();
  91. if (resultsData.success) {
  92. updateRecentResults(resultsData.data.results);
  93. }
  94. hideLoading();
  95. } catch (error) {
  96. console.error('加载仪表板失败:', error);
  97. hideLoading();
  98. showError('加载仪表板失败: ' + error.message);
  99. }
  100. }
  101. // 更新仪表板统计
  102. function updateDashboardStats(stats) {
  103. document.getElementById('total-nodes').textContent = stats.nodes.total;
  104. document.getElementById('online-nodes').textContent = stats.nodes.online;
  105. document.getElementById('success-rate').textContent = stats.tests.successRate + '%';
  106. document.getElementById('today-tests').textContent = stats.tests.recent24h;
  107. }
  108. // 更新最近测速结果
  109. function updateRecentResults(results) {
  110. const container = document.getElementById('recent-results');
  111. if (results.length === 0) {
  112. container.innerHTML = '<div class="text-center text-muted">暂无测速结果</div>';
  113. return;
  114. }
  115. const html = results.map(result => `
  116. <div class="result-item ${result.isSuccess ? 'result-success' : 'result-failure'}">
  117. <div class="result-content">
  118. <div class="result-left">
  119. <div class="result-node">${result.node ? result.node.name : '未知节点'}</div>
  120. <div class="result-info">
  121. <div class="result-status">
  122. <i class="bi ${result.isSuccess ? 'bi-check-circle' : 'bi-x-circle'}"></i>
  123. ${result.isSuccess ? '成功' : '失败'}
  124. </div>
  125. ${result.isSuccess ? `
  126. <div class="result-latency">
  127. <i class="bi bi-speedometer2"></i>
  128. ${(() => {
  129. const avg = result.node && result.node.averageLatency != null ? result.node.averageLatency : null;
  130. const latency = result.latency;
  131. if (avg != null) {
  132. return avg > 2000 ? '超时' : avg + 'ms';
  133. } else {
  134. return latency > 2000 ? '超时' : latency + 'ms';
  135. }
  136. })()}
  137. </div>
  138. ` : `
  139. <div class="result-error">
  140. <i class="bi bi-exclamation-triangle"></i>
  141. ${result.error || '未知错误'}
  142. </div>
  143. `}
  144. </div>
  145. </div>
  146. <div class="result-time">${formatTime(result.testTime)}</div>
  147. </div>
  148. </div>
  149. `).join('');
  150. container.innerHTML = html;
  151. }
  152. // 加载节点列表
  153. async function loadNodes() {
  154. try {
  155. showLoading();
  156. const search = document.getElementById('node-search')?.value || '';
  157. const status = document.getElementById('status-filter')?.value || '';
  158. const params = new URLSearchParams({
  159. limit: 1000, // 设置一个很大的限制,获取所有节点
  160. ...(search && { search }),
  161. ...(status && { status })
  162. });
  163. const response = await fetch(`${API_BASE}/nodes?${params}`);
  164. const data = await response.json();
  165. if (data.success) {
  166. updateNodesList(data.data);
  167. }
  168. hideLoading();
  169. } catch (error) {
  170. console.error('加载节点列表失败:', error);
  171. hideLoading();
  172. showError('加载节点列表失败: ' + error.message);
  173. }
  174. }
  175. // 更新节点列表
  176. function updateNodesList(data) {
  177. const container = document.getElementById('nodes-list');
  178. const { nodes, pagination } = data;
  179. if (nodes.length === 0) {
  180. container.innerHTML = '<div class="row"><div class="col-12"><div class="text-center text-muted">暂无节点</div></div></div>';
  181. return;
  182. }
  183. // 对节点进行排序:故障节点(offline)排在前面
  184. const sortedNodes = [...nodes].sort((a, b) => {
  185. // 首先按状态排序:offline在前,online在后
  186. if (a.status === 'offline' && b.status === 'online') return -1;
  187. if (a.status === 'online' && b.status === 'offline') return 1;
  188. // 如果状态相同,按名称排序
  189. return a.name.localeCompare(b.name);
  190. });
  191. const html = '<div class="row">' + sortedNodes.map((node, index) => `
  192. <div class="col-md-6 mb-3">
  193. <div class="node-item ${node.status === 'offline' ? 'node-offline' : ''}">
  194. <div class="node-header">
  195. <div class="node-name">${node.name}</div>
  196. <div class="node-status ${node.status}">${node.status === 'online' ? '在线' : '离线'}</div>
  197. </div>
  198. <div class="node-info">
  199. <div class="node-info-item">
  200. <i class="bi bi-hdd-network"></i>
  201. 类型: ${node.type}
  202. </div>
  203. <div class="node-info-item server-info">
  204. <i class="bi bi-geo-alt"></i>
  205. 服务器: ${node.server}
  206. </div>
  207. <div class="node-info-item">
  208. <i class="bi bi-arrow-left-right"></i>
  209. 端口: ${node.port}
  210. </div>
  211. ${node.testResults && node.testResults.length > 0 ? `
  212. <div class="node-info-item last-test">
  213. <i class="bi bi-clock"></i>
  214. 最后测速: ${formatTime(node.testResults[0].testTime)}
  215. ${node.testResults[0].isSuccess ? `
  216. <span class="latency-separator">|</span>
  217. <i class="bi bi-speedometer2"></i>
  218. 延迟: <span class="latency-value ${node.testResults[0].latency > 2000 ? 'text-danger' : ''}">${node.testResults[0].latency > 2000 ? '超时' : node.testResults[0].latency + 'ms'}</span>
  219. ` : ''}
  220. </div>
  221. ` : ''}
  222. </div>
  223. <div class="mt-2">
  224. <button class="btn btn-sm btn-outline-primary" onclick="viewNodeDetail(${node.id})">
  225. <i class="bi bi-eye"></i> 详情
  226. </button>
  227. <button class="btn btn-sm btn-outline-success" onclick="testSingleNode(${node.id})">
  228. <i class="bi bi-speedometer"></i> 测速
  229. </button>
  230. </div>
  231. </div>
  232. </div>
  233. `).join('') + '</div>';
  234. container.innerHTML = html;
  235. }
  236. // 更新节点统计信息
  237. function updateNodesStats(nodes) {
  238. const totalNodes = nodes.length;
  239. const onlineNodes = nodes.filter(node => node.status === 'online').length;
  240. const offlineNodes = nodes.filter(node => node.status === 'offline').length;
  241. const onlineRate = totalNodes > 0 ? Math.round((onlineNodes / totalNodes) * 100) : 0;
  242. document.getElementById('total-nodes-count').textContent = totalNodes;
  243. document.getElementById('online-nodes-count').textContent = onlineNodes;
  244. document.getElementById('offline-nodes-count').textContent = offlineNodes;
  245. document.getElementById('online-rate').textContent = onlineRate + '%';
  246. }
  247. // 加载测速结果
  248. async function loadTestResults(page = 1) {
  249. try {
  250. showLoading();
  251. const nodeName = document.getElementById('result-node-filter')?.value || '';
  252. const isSuccess = document.getElementById('result-status-filter')?.value || '';
  253. const startDate = document.getElementById('start-date')?.value || '';
  254. const endDate = document.getElementById('end-date')?.value || '';
  255. const params = new URLSearchParams({
  256. page: page,
  257. limit: 20, // 每页显示20条记录
  258. ...(nodeName && { nodeName }),
  259. ...(isSuccess && { isSuccess }),
  260. ...(startDate && { startDate }),
  261. ...(endDate && { endDate })
  262. });
  263. const response = await fetch(`${API_BASE}/test/results?${params}`);
  264. const data = await response.json();
  265. if (data.success) {
  266. updateTestResults(data.data);
  267. currentResultsPage = page;
  268. }
  269. hideLoading();
  270. } catch (error) {
  271. console.error('加载测速结果失败:', error);
  272. hideLoading();
  273. showError('加载测速结果失败: ' + error.message);
  274. }
  275. }
  276. // 更新测速结果
  277. function updateTestResults(data) {
  278. const container = document.getElementById('test-results');
  279. const { results, pagination } = data;
  280. if (results.length === 0) {
  281. container.innerHTML = '<div class="text-center text-muted">暂无测速结果</div>';
  282. return;
  283. }
  284. const html = results.map((result, index) => `
  285. <div class="result-item ${result.isSuccess ? 'result-success' : 'result-failure'}">
  286. <div class="result-content">
  287. <div class="result-left">
  288. <div class="result-node">${result.node ? result.node.name : '未知节点'}</div>
  289. <div class="result-info">
  290. <div class="result-status">
  291. <i class="bi ${result.isSuccess ? 'bi-check-circle' : 'bi-x-circle'}"></i>
  292. ${result.isSuccess ? '成功' : '失败'}
  293. </div>
  294. ${result.isSuccess ? `
  295. <div class="result-latency">
  296. <i class="bi bi-speedometer2"></i>
  297. ${(() => {
  298. const avg = result.node && result.node.averageLatency != null ? result.node.averageLatency : null;
  299. const latency = result.latency;
  300. if (avg != null) {
  301. return avg > 2000 ? '超时' : avg + 'ms';
  302. } else {
  303. return latency > 2000 ? '超时' : latency + 'ms';
  304. }
  305. })()}
  306. </div>
  307. ` : `
  308. <div class="result-error">
  309. <i class="bi bi-exclamation-triangle"></i>
  310. ${result.error || '未知错误'}
  311. </div>
  312. `}
  313. </div>
  314. </div>
  315. <div class="result-time">${formatTime(result.testTime)}</div>
  316. </div>
  317. </div>
  318. `).join('');
  319. container.innerHTML = html;
  320. // 更新分页
  321. updatePagination('test-results-pagination', pagination, loadTestResults);
  322. }
  323. // 加载通知记录
  324. async function loadNotifications(page = 1) {
  325. try {
  326. showLoading();
  327. const params = new URLSearchParams({
  328. page: page,
  329. limit: 20
  330. });
  331. const response = await fetch(`${API_BASE}/notifications?${params}`);
  332. const data = await response.json();
  333. if (data.success) {
  334. updateNotificationsList(data.data);
  335. currentNotificationsPage = page;
  336. }
  337. hideLoading();
  338. } catch (error) {
  339. console.error('加载通知记录失败:', error);
  340. hideLoading();
  341. showError('加载通知记录失败: ' + error.message);
  342. }
  343. }
  344. // 更新通知列表
  345. function updateNotificationsList(data) {
  346. const container = document.getElementById('notifications-list');
  347. const { notifications, pagination } = data;
  348. if (notifications.length === 0) {
  349. container.innerHTML = '<div class="text-center text-muted">暂无通知记录</div>';
  350. return;
  351. }
  352. const html = notifications.map(notification => `
  353. <div class="notification-item ${notification.isSent ? 'notification-sent' : 'notification-failed'}">
  354. <div class="result-header">
  355. <div class="result-node">${notification.type}</div>
  356. <div class="result-time">${formatTime(notification.createdAt)}</div>
  357. </div>
  358. <div class="result-details">
  359. <div class="result-detail">
  360. <i class="bi ${notification.isSent ? 'bi-check-circle text-success' : 'bi-x-circle text-danger'}"></i>
  361. 状态: ${notification.isSent ? '已发送' : '发送失败'}
  362. </div>
  363. <div class="result-detail">
  364. <i class="bi bi-chat"></i>
  365. 内容: ${notification.message.substring(0, 100)}${notification.message.length > 100 ? '...' : ''}
  366. </div>
  367. ${notification.node ? `
  368. <div class="result-detail">
  369. <i class="bi bi-hdd-network"></i>
  370. 节点: ${notification.node.name}
  371. </div>
  372. ` : ''}
  373. </div>
  374. </div>
  375. `).join('');
  376. container.innerHTML = html;
  377. // 更新分页
  378. updatePagination('notifications-pagination', pagination, loadNotifications);
  379. }
  380. // 加载设置页面
  381. async function loadSettings() {
  382. try {
  383. showLoading();
  384. // 加载系统状态
  385. const statusResponse = await fetch(`${API_BASE}/status`);
  386. const statusData = await statusResponse.json();
  387. if (statusData.success) {
  388. updateSystemStatus(statusData.data);
  389. }
  390. // 加载订阅状态
  391. const subscriptionResponse = await fetch(`${API_BASE}/subscription/status`);
  392. const subscriptionData = await subscriptionResponse.json();
  393. if (subscriptionData.success) {
  394. updateSubscriptionStatus(subscriptionData.data);
  395. }
  396. hideLoading();
  397. } catch (error) {
  398. console.error('加载设置失败:', error);
  399. hideLoading();
  400. showError('加载设置失败: ' + error.message);
  401. }
  402. }
  403. // 更新系统状态
  404. function updateSystemStatus(status) {
  405. const container = document.getElementById('system-status');
  406. const html = `
  407. <div class="row">
  408. <div class="col-md-6">
  409. <h6>调度器状态</h6>
  410. <div class="mb-2">
  411. <span class="badge ${status.isRunning ? 'bg-success' : 'bg-danger'}">
  412. ${status.isRunning ? '运行中' : '已停止'}
  413. </span>
  414. </div>
  415. <div class="mb-2">
  416. <small class="text-muted">下次测速: ${status.nextTestTime ? formatTime(status.nextTestTime) : '未设置'}</small>
  417. </div>
  418. <div class="mb-2">
  419. <small class="text-muted">测速间隔: ${status.testInterval ? Math.round(status.testInterval / 60000) + '分钟' : '未设置'}</small>
  420. </div>
  421. </div>
  422. <div class="col-md-6">
  423. <h6>系统信息</h6>
  424. <div class="mb-2">
  425. <small class="text-muted">运行时间: ${formatUptime(status.uptime)}</small>
  426. </div>
  427. <div class="mb-2">
  428. <small class="text-muted">总测速次数: ${status.totalTests || 0}</small>
  429. </div>
  430. </div>
  431. </div>
  432. `;
  433. container.innerHTML = html;
  434. }
  435. // 更新订阅状态
  436. function updateSubscriptionStatus(status) {
  437. const container = document.getElementById('subscription-status');
  438. const html = `
  439. <div class="mb-2">
  440. <strong>订阅地址:</strong> ${status.subscriptionUrl || '未配置'}
  441. </div>
  442. <div class="mb-2">
  443. <strong>更新间隔:</strong> ${status.updateInterval ? Math.round(status.updateInterval / 60000) + '分钟' : '未设置'}
  444. </div>
  445. <div class="mb-2">
  446. <strong>自动更新:</strong>
  447. <span class="badge ${status.autoUpdateEnabled ? 'bg-success' : 'bg-secondary'}">
  448. ${status.autoUpdateEnabled ? '已启用' : '已禁用'}
  449. </span>
  450. </div>
  451. ${status.lastUpdate ? `
  452. <div class="mb-2">
  453. <strong>最后更新:</strong> ${formatTime(status.lastUpdate)}
  454. </div>
  455. ` : ''}
  456. `;
  457. container.innerHTML = html;
  458. }
  459. // 开始测速
  460. async function startSpeedTest() {
  461. try {
  462. showLoading();
  463. const response = await fetch(`${API_BASE}/test/manual`, {
  464. method: 'POST',
  465. headers: {
  466. 'Content-Type': 'application/json'
  467. },
  468. body: JSON.stringify({})
  469. });
  470. const data = await response.json();
  471. if (data.success) {
  472. const retestedInfo = data.data.retestedNodes > 0 ? `,其中 ${data.data.retestedNodes} 个高延迟节点已重测` : '';
  473. showSuccess(`测速已开始,共测试 ${data.data.testedNodes} 个节点${retestedInfo}`);
  474. // 刷新当前页面数据
  475. if (currentPage === 'dashboard') {
  476. await loadDashboard();
  477. } else if (currentPage === 'speed-test') {
  478. await loadTestResults();
  479. }
  480. } else {
  481. showError('测速失败: ' + data.error);
  482. }
  483. hideLoading();
  484. } catch (error) {
  485. console.error('测速失败:', error);
  486. hideLoading();
  487. showError('测速失败: ' + error.message);
  488. }
  489. }
  490. // 测试通知
  491. async function testNotification() {
  492. try {
  493. showLoading();
  494. const response = await fetch(`${API_BASE}/notifications/test`, {
  495. method: 'POST'
  496. });
  497. const data = await response.json();
  498. if (data.success) {
  499. showSuccess('通知测试成功');
  500. } else {
  501. showError('通知测试失败: ' + data.error);
  502. }
  503. hideLoading();
  504. } catch (error) {
  505. console.error('通知测试失败:', error);
  506. hideLoading();
  507. showError('通知测试失败: ' + error.message);
  508. }
  509. }
  510. // 刷新统计
  511. async function refreshStats() {
  512. await loadDashboard();
  513. showSuccess('统计信息已刷新');
  514. }
  515. // 显示系统状态
  516. async function showSystemStatus() {
  517. await showPage('settings');
  518. }
  519. // 搜索节点
  520. function searchNodes() {
  521. loadNodes();
  522. }
  523. // 搜索结果
  524. // 搜索防抖函数
  525. let searchTimeout;
  526. function searchResults() {
  527. loadTestResults(1);
  528. }
  529. // 实时搜索功能
  530. function setupRealTimeSearch() {
  531. const nodeFilter = document.getElementById('result-node-filter');
  532. if (nodeFilter) {
  533. nodeFilter.addEventListener('input', function() {
  534. clearTimeout(searchTimeout);
  535. searchTimeout = setTimeout(() => {
  536. loadTestResults(1);
  537. }, 500); // 500ms 防抖延迟
  538. });
  539. }
  540. }
  541. // 导入节点
  542. function importNodes() {
  543. const modal = new bootstrap.Modal(document.getElementById('importModal'));
  544. modal.show();
  545. }
  546. // 确认导入
  547. async function confirmImport() {
  548. try {
  549. const configPath = document.getElementById('config-path').value;
  550. const configUrl = document.getElementById('config-url').value;
  551. if (!configPath && !configUrl) {
  552. showError('请提供配置文件路径或URL');
  553. return;
  554. }
  555. showLoading();
  556. const response = await fetch(`${API_BASE}/import/clash`, {
  557. method: 'POST',
  558. headers: {
  559. 'Content-Type': 'application/json'
  560. },
  561. body: JSON.stringify({
  562. configPath: configPath || undefined,
  563. configUrl: configUrl || undefined
  564. })
  565. });
  566. const data = await response.json();
  567. if (data.success) {
  568. showSuccess(`成功导入 ${data.data.imported} 个节点`);
  569. bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
  570. if (currentPage === 'nodes') {
  571. await loadNodes();
  572. }
  573. } else {
  574. showError('导入失败: ' + data.error);
  575. }
  576. hideLoading();
  577. } catch (error) {
  578. console.error('导入失败:', error);
  579. hideLoading();
  580. showError('导入失败: ' + error.message);
  581. }
  582. }
  583. // 更新订阅
  584. async function updateSubscription() {
  585. try {
  586. showLoading();
  587. const response = await fetch(`${API_BASE}/subscription/update`, {
  588. method: 'POST'
  589. });
  590. const data = await response.json();
  591. if (data.success) {
  592. showSuccess('订阅更新成功');
  593. await loadSettings();
  594. } else {
  595. showError('订阅更新失败: ' + data.error);
  596. }
  597. hideLoading();
  598. } catch (error) {
  599. console.error('订阅更新失败:', error);
  600. hideLoading();
  601. showError('订阅更新失败: ' + error.message);
  602. }
  603. }
  604. // 查看节点详情
  605. async function viewNodeDetail(nodeId) {
  606. try {
  607. const response = await fetch(`${API_BASE}/nodes/${nodeId}`);
  608. const data = await response.json();
  609. if (data.success) {
  610. const node = data.data;
  611. const modal = new bootstrap.Modal(document.getElementById('nodeDetailModal'));
  612. document.getElementById('node-detail-content').innerHTML = `
  613. <div class="row">
  614. <div class="col-md-6">
  615. <h6>基本信息</h6>
  616. <table class="table table-sm">
  617. <tr><td>名称:</td><td>${node.name}</td></tr>
  618. <tr><td>类型:</td><td>${node.type}</td></tr>
  619. <tr><td>服务器:</td><td>${node.server}</td></tr>
  620. <tr><td>端口:</td><td>${node.port}</td></tr>
  621. <tr><td>状态:</td><td><span class="badge ${node.status === 'online' ? 'bg-success' : 'bg-danger'}">${node.status === 'online' ? '在线' : '离线'}</span></td></tr>
  622. </table>
  623. </div>
  624. <div class="col-md-6">
  625. <h6>最近测速结果</h6>
  626. ${node.testResults && node.testResults.length > 0 ? `
  627. <div class="result-item ${node.testResults[0].isSuccess ? 'result-success' : 'result-failure'}">
  628. <div class="result-header">
  629. <div class="result-time">${formatTime(node.testResults[0].testTime)}</div>
  630. </div>
  631. <div class="result-details">
  632. <div class="result-detail">
  633. <i class="bi ${node.testResults[0].isSuccess ? 'bi-check-circle text-success' : 'bi-x-circle text-danger'}"></i>
  634. 状态: ${node.testResults[0].isSuccess ? '成功' : '失败'}
  635. </div>
  636. ${node.testResults[0].isSuccess ? `
  637. <div class="result-detail">
  638. <i class="bi bi-speedometer2"></i>
  639. 延迟: ${node.testResults[0].latency}ms
  640. </div>
  641. ` : `
  642. <div class="result-detail">
  643. <i class="bi bi-exclamation-triangle"></i>
  644. 错误: ${node.testResults[0].error || '未知错误'}
  645. </div>
  646. `}
  647. </div>
  648. </div>
  649. ` : '<div class="text-muted">暂无测速结果</div>'}
  650. </div>
  651. </div>
  652. `;
  653. modal.show();
  654. }
  655. } catch (error) {
  656. console.error('获取节点详情失败:', error);
  657. showError('获取节点详情失败: ' + error.message);
  658. }
  659. }
  660. // 测试单个节点
  661. async function testSingleNode(nodeId) {
  662. try {
  663. showLoading();
  664. const response = await fetch(`${API_BASE}/test/manual`, {
  665. method: 'POST',
  666. headers: {
  667. 'Content-Type': 'application/json'
  668. },
  669. body: JSON.stringify({ nodeIds: [nodeId] })
  670. });
  671. const data = await response.json();
  672. if (data.success) {
  673. showSuccess('节点测速已开始');
  674. // 刷新当前页面数据
  675. if (currentPage === 'nodes') {
  676. await loadNodes();
  677. } else if (currentPage === 'speed-test') {
  678. await loadTestResults();
  679. }
  680. } else {
  681. showError('节点测速失败: ' + data.error);
  682. }
  683. hideLoading();
  684. } catch (error) {
  685. console.error('节点测速失败:', error);
  686. hideLoading();
  687. showError('节点测速失败: ' + error.message);
  688. }
  689. }
  690. // 更新分页
  691. function updatePagination(containerId, pagination, loadFunction) {
  692. const container = document.getElementById(containerId);
  693. if (pagination.pages <= 1) {
  694. container.innerHTML = '';
  695. return;
  696. }
  697. // 根据容器ID确定函数名
  698. let functionName = 'loadTestResults';
  699. if (containerId === 'notifications-pagination') {
  700. functionName = 'loadNotifications';
  701. }
  702. let html = '<ul class="pagination">';
  703. // 上一页
  704. if (pagination.page > 1) {
  705. html += `<li class="page-item"><a class="page-link" href="#" onclick="event.preventDefault(); ${functionName}(${pagination.page - 1})">上一页</a></li>`;
  706. }
  707. // 页码
  708. const startPage = Math.max(1, pagination.page - 2);
  709. const endPage = Math.min(pagination.pages, pagination.page + 2);
  710. for (let i = startPage; i <= endPage; i++) {
  711. html += `<li class="page-item ${i === pagination.page ? 'active' : ''}"><a class="page-link" href="#" onclick="event.preventDefault(); ${functionName}(${i})">${i}</a></li>`;
  712. }
  713. // 下一页
  714. if (pagination.page < pagination.pages) {
  715. html += `<li class="page-item"><a class="page-link" href="#" onclick="event.preventDefault(); ${functionName}(${pagination.page + 1})">下一页</a></li>`;
  716. }
  717. html += '</ul>';
  718. container.innerHTML = html;
  719. }
  720. // 工具函数
  721. function formatTime(timeString) {
  722. const date = new Date(timeString);
  723. return date.toLocaleString('zh-CN');
  724. }
  725. function formatSpeed(speed) {
  726. if (!speed) return 'N/A';
  727. if (speed < 1024) return speed + ' B/s';
  728. if (speed < 1024 * 1024) return (speed / 1024).toFixed(1) + ' KB/s';
  729. if (speed < 1024 * 1024 * 1024) return (speed / (1024 * 1024)).toFixed(1) + ' MB/s';
  730. return (speed / (1024 * 1024 * 1024)).toFixed(1) + ' GB/s';
  731. }
  732. function formatUptime(seconds) {
  733. if (!seconds) return 'N/A';
  734. const hours = Math.floor(seconds / 3600);
  735. const minutes = Math.floor((seconds % 3600) / 60);
  736. return `${hours}小时${minutes}分钟`;
  737. }
  738. function showLoading() {
  739. document.getElementById('loading-overlay').style.display = 'flex';
  740. }
  741. function hideLoading() {
  742. document.getElementById('loading-overlay').style.display = 'none';
  743. }
  744. function showSuccess(message) {
  745. // 创建成功提示
  746. const toast = document.createElement('div');
  747. toast.className = 'alert alert-success alert-dismissible fade show position-fixed';
  748. toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
  749. toast.innerHTML = `
  750. ${message}
  751. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  752. `;
  753. document.body.appendChild(toast);
  754. // 3秒后自动移除
  755. setTimeout(() => {
  756. if (toast.parentNode) {
  757. toast.parentNode.removeChild(toast);
  758. }
  759. }, 3000);
  760. }
  761. function showError(message) {
  762. // 创建错误提示
  763. const toast = document.createElement('div');
  764. toast.className = 'alert alert-danger alert-dismissible fade show position-fixed';
  765. toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
  766. toast.innerHTML = `
  767. ${message}
  768. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  769. `;
  770. document.body.appendChild(toast);
  771. // 5秒后自动移除
  772. setTimeout(() => {
  773. if (toast.parentNode) {
  774. toast.parentNode.removeChild(toast);
  775. }
  776. }, 5000);
  777. }