diff --git a/app/app.py b/app/app.py index d2f1571..47da364 100644 --- a/app/app.py +++ b/app/app.py @@ -2,6 +2,7 @@ import asyncio import hmac +import ipaddress import json import io import os @@ -12,6 +13,7 @@ import socket import threading import time import zipfile +from collections import deque from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -129,6 +131,24 @@ def _read_meminfo(): return info +def _public_ip(): + """The address players connect to: PUBLIC_IP if set, else the source address of the default route + (gsm runs on the host network). None behind NAT; the UI then falls back to the page's hostname.""" + if os.environ.get("PUBLIC_IP"): + return os.environ["PUBLIC_IP"] + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("1.1.1.1", 80)) # UDP: picks a route, sends nothing + ip = s.getsockname()[0] + return ip if ipaddress.ip_address(ip).is_global else None + except OSError: + return None + + +PUBLIC_IP = _public_ip() +NET_HISTORY = 100 # samples (one per 3 s) kept for the VPS network graphs + + def _read_net(): rx = tx = 0 for line in Path("/proc/net/dev").read_text().splitlines()[2:]: @@ -323,6 +343,7 @@ def stats_loop(): prev_cpu = _read_cpu() prev_net = _read_net() prev_t = time.time() + net_history = deque(maxlen=NET_HISTORY) pool = ThreadPoolExecutor(max_workers=8) while True: time.sleep(3) @@ -336,6 +357,7 @@ def stats_loop(): rx, tx = _read_net() now = time.time() dt = now - prev_t + net_history.append([round((rx - prev_net[0]) / dt), round((tx - prev_net[1]) / dt)]) host = { "cpu_percent": round(cpu_pct, 1), "cpu_count": os.cpu_count(), @@ -347,6 +369,8 @@ def stats_loop(): "disk_used": du.used, "net_rx_rate": (rx - prev_net[0]) / dt, "net_tx_rate": (tx - prev_net[1]) / dt, + "net_history": list(net_history), # [[rx, tx] bytes/s], oldest first + "public_ip": PUBLIC_IP, } prev_net, prev_t = (rx, tx), now diff --git a/app/static/app.js b/app/static/app.js index 425b93d..c743eb6 100644 --- a/app/static/app.js +++ b/app/static/app.js @@ -89,7 +89,28 @@ function renderHost() { setBar('#b-swap', h.swap_total ? (100 * h.swap_used) / h.swap_total : 0); $('#m-disk').textContent = `${fmtBytes(h.disk_used)} / ${fmtBytes(h.disk_total)}`; setBar('#b-disk', (100 * h.disk_used) / h.disk_total); - $('#m-net').textContent = `Network: ↓ ${fmtRate(h.net_rx_rate)} ↑ ${fmtRate(h.net_tx_rate)}`; + $('#m-rx').textContent = fmtRate(h.net_rx_rate); + $('#m-tx').textContent = fmtRate(h.net_tx_rate); + const hist = h.net_history || []; + drawGraph('#g-rx', hist.map((x) => x[0])); + drawGraph('#g-tx', hist.map((x) => x[1])); +} + +// Area graph of the last NET_HISTORY samples (app.py), right-aligned so it fills in from the right after a +// restart. Each graph scales to its own peak, shown in the tooltip. +const GRAPH_POINTS = 100; +function drawGraph(id, vals) { + const svg = $(id); + const peak = Math.max(1, ...vals); + const step = 100 / (GRAPH_POINTS - 1); + const x0 = 100 - (vals.length - 1) * step; + const pts = vals.map((v, i) => `${(x0 + i * step).toFixed(2)},${(24 - (22 * v) / peak).toFixed(2)}`); + const line = pts.length > 1 ? `M${pts.join('L')}` : ''; + svg.querySelector('.line').setAttribute('d', line); + svg.querySelector('.area').setAttribute('d', line && `${line}L100,24L${x0.toFixed(2)},24Z`); + let title = svg.querySelector('title'); + if (!title) title = svg.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'title')); + title.textContent = `Peak ${fmtRate(peak)} in the last ${(GRAPH_POINTS * 3) / 60} minutes`; } function fmtDuration(sec) { @@ -149,11 +170,27 @@ function timeAgo(iso) { return `on ${t.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}`; } +// The server address on each card copies itself when clicked. Cards re-render every poll, so the +// "Copied!" state is kept here rather than on the element. +let copied = { addr: null, text: '' }; +let copiedTimer = null; +const copyAddr = (addr) => ``; + +async function copyToClipboard(addr) { + let text = 'Copied!'; + try { await navigator.clipboard.writeText(addr); } catch { text = 'Copy failed'; } + copied = { addr, text }; + renderServers(); + clearTimeout(copiedTimer); + copiedTimer = setTimeout(() => { copied = { addr: null, text: '' }; renderServers(); }, 1500); +} + const STATE_LABEL = { online: 'Online', starting: 'Starting…', exited: 'Stopped', created: 'Stopped', restarting: 'Restarting…' }; function renderServers() { $('#empty-msg').classList.toggle('hidden', servers.length > 0); - const host = location.hostname; + const host = stats.host.public_ip || location.hostname; $('#server-list').innerHTML = servers.map((s) => { const st = stats.servers[s.id]; const running = s.state === 'online' || s.state === 'starting'; @@ -167,7 +204,7 @@ function renderServers() {
${esc(s.server_name)}${isBusy ? 'Working…' : s.busy ? esc(s.busy) : STATE_LABEL[s.state] || esc(s.state)}
-
${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world ${esc(s.world)}`} · connect to ${esc(host)}:${s.port}
+
${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world ${esc(s.world)}`} · connect to ${copyAddr(`${host}:${s.port}`)}
${running ? playersLine(st) : s.last_online ? `
Last online ${esc(timeAgo(s.last_online))}
` : ''}
@@ -190,6 +227,8 @@ function renderServers() { } $('#server-list').addEventListener('click', async (e) => { + const addr = e.target.closest('.copy-addr'); + if (addr) return copyToClipboard(addr.dataset.addr); const btn = e.target.closest('button[data-act]'); if (!btn) return; const card = btn.closest('.server'); diff --git a/app/static/index.html b/app/static/index.html index d596d27..4624786 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -42,8 +42,13 @@
Memory–
Swap–
Disk–
+
+
Download–
+ +
Upload–
+ +
-

Servers

diff --git a/app/static/style.css b/app/static/style.css index c275284..da0a4dc 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -80,7 +80,15 @@ a { color: var(--accent); } .meter-label span:last-child { color: var(--muted); font-variant-numeric: tabular-nums; } .bar { height: 8px; background: var(--bar); border-radius: 4px; overflow: hidden; } .bar > div { height: 100%; width: 0; background: var(--ok); transition: width .5s, background .5s; } -.net { margin: 12px 0 0; font-size: 13px; color: var(--muted); } +.net-meter { grid-column: 1 / -1; } +.graph { display: block; width: 100%; height: 24px; background: var(--bar); border-radius: 4px; } +.graph .line { fill: none; stroke-width: 1.5; vector-effect: non-scaling-stroke; } +.graph .area { stroke: none; opacity: .25; } +.graph.rx .line { stroke: var(--ok); } +.graph.rx .area { fill: var(--ok); } +.graph.tx .line { stroke: #79c0ff; } +.graph.tx .area { fill: #79c0ff; } +.graph-gap { margin-top: 8px; } .section-title { margin: 24px 0 12px; } .empty { color: var(--muted); text-align: center; padding: 24px; } @@ -94,6 +102,18 @@ a { color: var(--accent); } .server-top { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: flex-start; } .server-name { font-weight: 600; font-size: 16px; } .server-meta { color: var(--muted); font-size: 13px; } +.copy-addr { + font: inherit; font-weight: 600; color: var(--text); background: none; border: 0; padding: 0; border-radius: 0; + text-decoration: underline; text-underline-offset: 2px; cursor: pointer; position: relative; +} +.copy-addr::after { + content: attr(data-tip); position: absolute; left: 50%; bottom: calc(100% + 6px); transform: translateX(-50%); + background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 6px; + padding: 3px 8px; font-size: 12px; font-weight: normal; white-space: nowrap; pointer-events: none; + opacity: 0; transition: opacity .15s; +} +.copy-addr:hover::after, .copy-addr:focus-visible::after, .copy-addr[data-tip="Copied!"]::after, +.copy-addr[data-tip="Copy failed"]::after { opacity: 1; } .badge { display: inline-block; font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid currentColor; margin-left: 6px; vertical-align: 2px; } .badge.online { color: var(--ok); } .badge.starting { color: var(--warn); }