(() => { "use strict"; const root = document.querySelector(".traffic-monitor"); if (!root) return; const endpoint = root.dataset.endpoint; const nodeStrip = document.getElementById("traffic-nodes"); const canvas = document.getElementById("traffic-chart"); const empty = document.getElementById("traffic-empty"); const tooltip = document.getElementById("traffic-tooltip"); const ctx = canvas.getContext("2d"); const state = { minutes: 60, nodes: [], selectedId: null, points: [] }; let loading = false; const formatRate = (bytesPerSecond) => { const bits = Number(bytesPerSecond || 0) * 8; if (bits >= 1e9) return `${(bits / 1e9).toFixed(2)} Gbps`; if (bits >= 1e6) return `${(bits / 1e6).toFixed(2)} Mbps`; if (bits >= 1e3) return `${(bits / 1e3).toFixed(1)} Kbps`; return `${Math.round(bits)} bps`; }; const formatBytes = (bytes) => { let value = Number(bytes || 0); const units = ["B", "KB", "MB", "GB", "TB"]; let unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; } return `${value.toFixed(unit === 0 ? 0 : value >= 100 ? 0 : value >= 10 ? 1 : 2)} ${units[unit]}`; }; const formatTime = (value, includeDate = false) => { if (!value) return "尚未上报"; return new Intl.DateTimeFormat("zh-CN", { month: includeDate ? "2-digit" : undefined, day: includeDate ? "2-digit" : undefined, hour: "2-digit", minute: "2-digit", second: includeDate ? undefined : "2-digit", hour12: false, }).format(new Date(value)); }; const selectedNode = () => state.nodes.find((node) => node.id === state.selectedId) || state.nodes[0]; function renderNodes() { if (!state.nodes.length) { nodeStrip.innerHTML = '
尚未配置可用节点
'; return; } nodeStrip.innerHTML = state.nodes.map((node) => ` `).join(""); nodeStrip.querySelectorAll("[data-node-id]").forEach((button) => { button.addEventListener("click", () => { state.selectedId = Number(button.dataset.nodeId); render(); }); }); } function renderSummary(node) { const set = (id, value) => { document.getElementById(id).textContent = value; }; if (!node) { ["current-download", "current-upload", "total-traffic", "active-subscriptions"].forEach((id) => set(id, "--")); set("chart-title", "请选择节点"); return; } set("current-download", formatRate(node.current_download_bytes_per_second)); set("current-upload", formatRate(node.current_upload_bytes_per_second)); set("total-traffic", formatBytes(node.total_upload_bytes + node.total_download_bytes)); set("total-breakdown", `上传 ${formatBytes(node.total_upload_bytes)} · 下载 ${formatBytes(node.total_download_bytes)}`); set("active-subscriptions", `${node.active_subscriptions} 个`); set("last-seen", node.last_seen_at ? `最后上报 ${formatTime(node.last_seen_at)}` : "等待节点上报"); set("chart-title", `${node.name} · ${node.region}`); } function escapeHtml(value) { return String(value ?? "").replace(/[&<>'"]/g, (char) => ({ "&": "&", "<": "<", ">": ">", "'": "'", '"': """, })[char]); } function drawChart(node) { const samples = node?.samples || []; empty.hidden = samples.length > 0; tooltip.hidden = true; const rect = canvas.getBoundingClientRect(); const dpr = Math.max(1, window.devicePixelRatio || 1); canvas.width = Math.round(rect.width * dpr); canvas.height = Math.round(rect.height * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, rect.width, rect.height); state.points = []; if (!samples.length || rect.width < 120 || rect.height < 100) return; const pad = { top: 18, right: 18, bottom: 30, left: 67 }; const width = rect.width - pad.left - pad.right; const height = rect.height - pad.top - pad.bottom; const start = Date.now() - state.minutes * 60 * 1000; const end = Date.now(); const maxBps = Math.max(1, ...samples.flatMap((sample) => [sample.upload_bytes_per_second, sample.download_bytes_per_second])); const topBps = maxBps * 1.15; const xFor = (at) => pad.left + Math.max(0, Math.min(1, (new Date(at).getTime() - start) / (end - start))) * width; const yFor = (value) => pad.top + height - (Number(value || 0) / topBps) * height; ctx.font = "12px system-ui, sans-serif"; ctx.lineWidth = 1; for (let row = 0; row <= 4; row += 1) { const y = pad.top + (height * row / 4); ctx.strokeStyle = "#e6eef5"; ctx.beginPath(); ctx.moveTo(pad.left, y); ctx.lineTo(rect.width - pad.right, y); ctx.stroke(); ctx.fillStyle = "#8294a7"; ctx.textAlign = "right"; ctx.fillText(formatRate(topBps * (1 - row / 4)), pad.left - 10, y + 4); } for (let col = 0; col <= 4; col += 1) { const x = pad.left + width * col / 4; ctx.fillStyle = "#8294a7"; ctx.textAlign = col === 0 ? "left" : col === 4 ? "right" : "center"; ctx.fillText(formatTime(start + (end - start) * col / 4, state.minutes >= 1440), x, rect.height - 7); } const drawSeries = (field, color, fillColor) => { const gradient = ctx.createLinearGradient(0, pad.top, 0, pad.top + height); gradient.addColorStop(0, fillColor); gradient.addColorStop(1, "rgba(255,255,255,0)"); ctx.beginPath(); samples.forEach((sample, index) => { const x = xFor(sample.at); const y = yFor(sample[field]); index ? ctx.lineTo(x, y) : ctx.moveTo(x, y); }); const last = samples[samples.length - 1]; const first = samples[0]; ctx.lineTo(xFor(last.at), pad.top + height); ctx.lineTo(xFor(first.at), pad.top + height); ctx.closePath(); ctx.fillStyle = gradient; ctx.fill(); ctx.beginPath(); samples.forEach((sample, index) => { const x = xFor(sample.at); const y = yFor(sample[field]); index ? ctx.lineTo(x, y) : ctx.moveTo(x, y); }); ctx.strokeStyle = color; ctx.lineWidth = 2.5; ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.stroke(); }; drawSeries("download_bytes_per_second", "#1478e6", "rgba(20,120,230,.16)"); drawSeries("upload_bytes_per_second", "#09b7dc", "rgba(9,183,220,.09)"); state.points = samples.map((sample) => ({ x: xFor(sample.at), sample })); } function render() { if (!state.selectedId && state.nodes.length) state.selectedId = state.nodes[0].id; if (state.selectedId && !state.nodes.some((node) => node.id === state.selectedId)) state.selectedId = state.nodes[0]?.id || null; renderNodes(); const node = selectedNode(); renderSummary(node); drawChart(node); } async function refresh() { if (loading) return; loading = true; const live = document.getElementById("traffic-live"); try { const response = await fetch(`${endpoint}?minutes=${state.minutes}`, { credentials: "same-origin", cache: "no-store" }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); state.nodes = data.nodes || []; live.classList.remove("is-error"); live.querySelector("span").textContent = "监控数据连接正常"; document.getElementById("traffic-updated").textContent = `刷新于 ${formatTime(data.generated_at)}`; render(); } catch (error) { live.classList.add("is-error"); live.querySelector("span").textContent = "监控数据暂时中断"; } finally { loading = false; } } document.querySelectorAll("[data-minutes]").forEach((button) => { button.addEventListener("click", () => { document.querySelectorAll("[data-minutes]").forEach((item) => item.classList.remove("is-active")); button.classList.add("is-active"); state.minutes = Number(button.dataset.minutes); refresh(); }); }); canvas.addEventListener("mousemove", (event) => { if (!state.points.length) return; const rect = canvas.getBoundingClientRect(); const mouseX = event.clientX - rect.left; const point = state.points.reduce((best, candidate) => Math.abs(candidate.x - mouseX) < Math.abs(best.x - mouseX) ? candidate : best); if (Math.abs(point.x - mouseX) > 36) { tooltip.hidden = true; return; } tooltip.innerHTML = `${formatTime(point.sample.at, true)}下载 ${formatRate(point.sample.download_bytes_per_second)}上传 ${formatRate(point.sample.upload_bytes_per_second)}`; tooltip.hidden = false; tooltip.style.left = `${Math.min(rect.width - 175, Math.max(4, point.x + 10))}px`; tooltip.style.top = "18px"; }); canvas.addEventListener("mouseleave", () => { tooltip.hidden = true; }); window.addEventListener("resize", () => drawChart(selectedNode())); refresh(); window.setInterval(refresh, 5000); })();