app.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. showSuccess(`测速已开始,共测试 ${data.data.testedNodes} 个节点`);
  473. // 刷新当前页面数据
  474. if (currentPage === 'dashboard') {
  475. await loadDashboard();
  476. } else if (currentPage === 'speed-test') {
  477. await loadTestResults();
  478. }
  479. } else {
  480. showError('测速失败: ' + data.error);
  481. }
  482. hideLoading();
  483. } catch (error) {
  484. console.error('测速失败:', error);
  485. hideLoading();
  486. showError('测速失败: ' + error.message);
  487. }
  488. }
  489. // 测试通知
  490. async function testNotification() {
  491. try {
  492. showLoading();
  493. const response = await fetch(`${API_BASE}/notifications/test`, {
  494. method: 'POST'
  495. });
  496. const data = await response.json();
  497. if (data.success) {
  498. showSuccess('通知测试成功');
  499. } else {
  500. showError('通知测试失败: ' + data.error);
  501. }
  502. hideLoading();
  503. } catch (error) {
  504. console.error('通知测试失败:', error);
  505. hideLoading();
  506. showError('通知测试失败: ' + error.message);
  507. }
  508. }
  509. // 刷新统计
  510. async function refreshStats() {
  511. await loadDashboard();
  512. showSuccess('统计信息已刷新');
  513. }
  514. // 显示系统状态
  515. async function showSystemStatus() {
  516. await showPage('settings');
  517. }
  518. // 搜索节点
  519. function searchNodes() {
  520. loadNodes();
  521. }
  522. // 搜索结果
  523. // 搜索防抖函数
  524. let searchTimeout;
  525. function searchResults() {
  526. loadTestResults(1);
  527. }
  528. // 实时搜索功能
  529. function setupRealTimeSearch() {
  530. const nodeFilter = document.getElementById('result-node-filter');
  531. if (nodeFilter) {
  532. nodeFilter.addEventListener('input', function() {
  533. clearTimeout(searchTimeout);
  534. searchTimeout = setTimeout(() => {
  535. loadTestResults(1);
  536. }, 500); // 500ms 防抖延迟
  537. });
  538. }
  539. }
  540. // 导入节点
  541. function importNodes() {
  542. const modal = new bootstrap.Modal(document.getElementById('importModal'));
  543. modal.show();
  544. }
  545. // 确认导入
  546. async function confirmImport() {
  547. try {
  548. const configPath = document.getElementById('config-path').value;
  549. const configUrl = document.getElementById('config-url').value;
  550. if (!configPath && !configUrl) {
  551. showError('请提供配置文件路径或URL');
  552. return;
  553. }
  554. showLoading();
  555. const response = await fetch(`${API_BASE}/import/clash`, {
  556. method: 'POST',
  557. headers: {
  558. 'Content-Type': 'application/json'
  559. },
  560. body: JSON.stringify({
  561. configPath: configPath || undefined,
  562. configUrl: configUrl || undefined
  563. })
  564. });
  565. const data = await response.json();
  566. if (data.success) {
  567. showSuccess(`成功导入 ${data.data.imported} 个节点`);
  568. bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
  569. if (currentPage === 'nodes') {
  570. await loadNodes();
  571. }
  572. } else {
  573. showError('导入失败: ' + data.error);
  574. }
  575. hideLoading();
  576. } catch (error) {
  577. console.error('导入失败:', error);
  578. hideLoading();
  579. showError('导入失败: ' + error.message);
  580. }
  581. }
  582. // 更新订阅
  583. async function updateSubscription() {
  584. try {
  585. showLoading();
  586. const response = await fetch(`${API_BASE}/subscription/update`, {
  587. method: 'POST'
  588. });
  589. const data = await response.json();
  590. if (data.success) {
  591. showSuccess('订阅更新成功');
  592. await loadSettings();
  593. } else {
  594. showError('订阅更新失败: ' + data.error);
  595. }
  596. hideLoading();
  597. } catch (error) {
  598. console.error('订阅更新失败:', error);
  599. hideLoading();
  600. showError('订阅更新失败: ' + error.message);
  601. }
  602. }
  603. // 查看节点详情
  604. async function viewNodeDetail(nodeId) {
  605. try {
  606. const response = await fetch(`${API_BASE}/nodes/${nodeId}`);
  607. const data = await response.json();
  608. if (data.success) {
  609. const node = data.data;
  610. const modal = new bootstrap.Modal(document.getElementById('nodeDetailModal'));
  611. document.getElementById('node-detail-content').innerHTML = `
  612. <div class="row">
  613. <div class="col-md-6">
  614. <h6>基本信息</h6>
  615. <table class="table table-sm">
  616. <tr><td>名称:</td><td>${node.name}</td></tr>
  617. <tr><td>类型:</td><td>${node.type}</td></tr>
  618. <tr><td>服务器:</td><td>${node.server}</td></tr>
  619. <tr><td>端口:</td><td>${node.port}</td></tr>
  620. <tr><td>状态:</td><td><span class="badge ${node.status === 'online' ? 'bg-success' : 'bg-danger'}">${node.status === 'online' ? '在线' : '离线'}</span></td></tr>
  621. </table>
  622. </div>
  623. <div class="col-md-6">
  624. <h6>最近测速结果</h6>
  625. ${node.testResults && node.testResults.length > 0 ? `
  626. <div class="result-item ${node.testResults[0].isSuccess ? 'result-success' : 'result-failure'}">
  627. <div class="result-header">
  628. <div class="result-time">${formatTime(node.testResults[0].testTime)}</div>
  629. </div>
  630. <div class="result-details">
  631. <div class="result-detail">
  632. <i class="bi ${node.testResults[0].isSuccess ? 'bi-check-circle text-success' : 'bi-x-circle text-danger'}"></i>
  633. 状态: ${node.testResults[0].isSuccess ? '成功' : '失败'}
  634. </div>
  635. ${node.testResults[0].isSuccess ? `
  636. <div class="result-detail">
  637. <i class="bi bi-speedometer2"></i>
  638. 延迟: ${node.testResults[0].latency}ms
  639. </div>
  640. ` : `
  641. <div class="result-detail">
  642. <i class="bi bi-exclamation-triangle"></i>
  643. 错误: ${node.testResults[0].error || '未知错误'}
  644. </div>
  645. `}
  646. </div>
  647. </div>
  648. ` : '<div class="text-muted">暂无测速结果</div>'}
  649. </div>
  650. </div>
  651. `;
  652. modal.show();
  653. }
  654. } catch (error) {
  655. console.error('获取节点详情失败:', error);
  656. showError('获取节点详情失败: ' + error.message);
  657. }
  658. }
  659. // 测试单个节点
  660. async function testSingleNode(nodeId) {
  661. try {
  662. showLoading();
  663. const response = await fetch(`${API_BASE}/test/manual`, {
  664. method: 'POST',
  665. headers: {
  666. 'Content-Type': 'application/json'
  667. },
  668. body: JSON.stringify({ nodeIds: [nodeId] })
  669. });
  670. const data = await response.json();
  671. if (data.success) {
  672. showSuccess('节点测速已开始');
  673. // 刷新当前页面数据
  674. if (currentPage === 'nodes') {
  675. await loadNodes();
  676. } else if (currentPage === 'speed-test') {
  677. await loadTestResults();
  678. }
  679. } else {
  680. showError('节点测速失败: ' + data.error);
  681. }
  682. hideLoading();
  683. } catch (error) {
  684. console.error('节点测速失败:', error);
  685. hideLoading();
  686. showError('节点测速失败: ' + error.message);
  687. }
  688. }
  689. // 更新分页
  690. function updatePagination(containerId, pagination, loadFunction) {
  691. const container = document.getElementById(containerId);
  692. if (pagination.pages <= 1) {
  693. container.innerHTML = '';
  694. return;
  695. }
  696. let html = '<ul class="pagination">';
  697. // 上一页
  698. if (pagination.page > 1) {
  699. html += `<li class="page-item"><a class="page-link" href="#" onclick="loadFunction(${pagination.page - 1})">上一页</a></li>`;
  700. }
  701. // 页码
  702. const startPage = Math.max(1, pagination.page - 2);
  703. const endPage = Math.min(pagination.pages, pagination.page + 2);
  704. for (let i = startPage; i <= endPage; i++) {
  705. html += `<li class="page-item ${i === pagination.page ? 'active' : ''}"><a class="page-link" href="#" onclick="loadFunction(${i})">${i}</a></li>`;
  706. }
  707. // 下一页
  708. if (pagination.page < pagination.pages) {
  709. html += `<li class="page-item"><a class="page-link" href="#" onclick="loadFunction(${pagination.page + 1})">下一页</a></li>`;
  710. }
  711. html += '</ul>';
  712. container.innerHTML = html;
  713. }
  714. // 工具函数
  715. function formatTime(timeString) {
  716. const date = new Date(timeString);
  717. return date.toLocaleString('zh-CN');
  718. }
  719. function formatSpeed(speed) {
  720. if (!speed) return 'N/A';
  721. if (speed < 1024) return speed + ' B/s';
  722. if (speed < 1024 * 1024) return (speed / 1024).toFixed(1) + ' KB/s';
  723. if (speed < 1024 * 1024 * 1024) return (speed / (1024 * 1024)).toFixed(1) + ' MB/s';
  724. return (speed / (1024 * 1024 * 1024)).toFixed(1) + ' GB/s';
  725. }
  726. function formatUptime(seconds) {
  727. if (!seconds) return 'N/A';
  728. const hours = Math.floor(seconds / 3600);
  729. const minutes = Math.floor((seconds % 3600) / 60);
  730. return `${hours}小时${minutes}分钟`;
  731. }
  732. function showLoading() {
  733. document.getElementById('loading-overlay').style.display = 'flex';
  734. }
  735. function hideLoading() {
  736. document.getElementById('loading-overlay').style.display = 'none';
  737. }
  738. function showSuccess(message) {
  739. // 创建成功提示
  740. const toast = document.createElement('div');
  741. toast.className = 'alert alert-success alert-dismissible fade show position-fixed';
  742. toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
  743. toast.innerHTML = `
  744. ${message}
  745. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  746. `;
  747. document.body.appendChild(toast);
  748. // 3秒后自动移除
  749. setTimeout(() => {
  750. if (toast.parentNode) {
  751. toast.parentNode.removeChild(toast);
  752. }
  753. }, 3000);
  754. }
  755. function showError(message) {
  756. // 创建错误提示
  757. const toast = document.createElement('div');
  758. toast.className = 'alert alert-danger alert-dismissible fade show position-fixed';
  759. toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
  760. toast.innerHTML = `
  761. ${message}
  762. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  763. `;
  764. document.body.appendChild(toast);
  765. // 5秒后自动移除
  766. setTimeout(() => {
  767. if (toast.parentNode) {
  768. toast.parentNode.removeChild(toast);
  769. }
  770. }, 5000);
  771. }