const $ = (s) => document.querySelector(s); async function api(path, opts = {}) { const res = await fetch(path, opts); if (res.status === 401 && !path.endsWith('/login')) { showLogin(); throw new Error('Not logged in'); } const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.detail || `Request failed (${res.status})`); return data; } const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); function fmtBytes(b) { if (!b) return '0 B'; const u = ['B', 'KB', 'MB', 'GB', 'TB']; const i = Math.min(u.length - 1, Math.floor(Math.log(b) / Math.log(1024))); return `${(b / 1024 ** i).toFixed(i >= 3 ? 1 : 0)} ${u[i]}`; } const fmtRate = (b) => `${fmtBytes(b)}/s`; function setBar(id, pct) { const el = $(id); el.style.width = `${Math.min(100, pct)}%`; el.style.background = pct > 90 ? 'var(--bad)' : pct > 70 ? 'var(--warn)' : 'var(--ok)'; } // ---------- auth ---------- function showLogin() { stopPolling(); $('#app-view').classList.add('hidden'); $('#login-view').classList.remove('hidden'); $('#login-password').focus(); } function showApp() { $('#login-view').classList.add('hidden'); $('#app-view').classList.remove('hidden'); startPolling(); } $('#login-form').addEventListener('submit', async (e) => { e.preventDefault(); $('#login-error').textContent = ''; try { await api('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: $('#login-password').value }), }); $('#login-password').value = ''; showApp(); } catch (err) { $('#login-error').textContent = err.message; } }); $('#logout-btn').addEventListener('click', async () => { await api('/api/logout', { method: 'POST' }); showLogin(); }); // ---------- dashboard ---------- let servers = []; let stats = { host: {}, servers: {} }; let pollTimer = null; const busy = new Set(); // server ids with an action in progress function startPolling() { if (pollTimer) return; refresh(); pollTimer = setInterval(refresh, 3000); } function stopPolling() { clearInterval(pollTimer); pollTimer = null; } async function refresh() { try { [servers, stats] = await Promise.all([api('/api/servers'), api('/api/stats')]); renderHost(); renderServers(); if ($('#manage-dialog').open) renderPlayers(); if (view === 'backups') loadBackups(); } catch (e) { /* shown on next successful poll */ } } function renderHost() { const h = stats.host; if (!h.mem_total) return; $('#m-cpu').textContent = `${h.cpu_percent}% of ${h.cpu_count} cores`; setBar('#b-cpu', h.cpu_percent); $('#m-mem').textContent = `${fmtBytes(h.mem_used)} / ${fmtBytes(h.mem_total)}`; setBar('#b-mem', (100 * h.mem_used) / h.mem_total); $('#m-swap').textContent = h.swap_total ? `${fmtBytes(h.swap_used)} / ${fmtBytes(h.swap_total)}` : 'none'; 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-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 = `${id === '#g-rx' ? 'Download' : 'Upload'}: peak ${fmtRate(peak)} in the last ${(GRAPH_POINTS * 3) / 60} minutes`; } function fmtDuration(sec) { const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60); if (h) return `${h}h ${m}m`; return m ? `${m}m ${Math.floor(sec % 60)}s` : `${Math.floor(sec)}s`; } function playersLine(st) { if (!st || !st.players) return ''; const n = st.players.length; const stop = st.auto_stop_in != null ? ` · auto stop in ${Math.ceil(st.auto_stop_in / 60)} min` : ''; return `
` : '');
// "just now", "5 mins ago", "3 hours ago", "2 days ago", "3 weeks ago"; a date after about a month.
function timeAgo(iso) {
const t = new Date(iso);
const sec = (Date.now() - t) / 1000;
const ago = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'} ago`;
if (sec < 60) return 'just now';
if (sec < 3600) return ago(Math.floor(sec / 60), 'min');
if (sec < 86400) return ago(Math.floor(sec / 3600), 'hour');
if (sec < 7 * 86400) return ago(Math.floor(sec / 86400), 'day');
if (sec < 30 * 86400) return ago(Math.floor(sec / (7 * 86400)), 'week');
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 = 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';
const badgeCls = s.state === 'online' ? 'online' : running || s.state === 'restarting' ? 'starting' : 'stopped';
const isBusy = busy.has(s.id);
const memPct = st && stats.host.mem_total ? (100 * st.mem_used) / stats.host.mem_total : 0;
return `
Loading…
'; $('#manage-dialog').showModal(); try { const { fields, values, backups, mods, auto_stop } = await api(`/api/servers/${s.id}/settings`); $('#autostop-enabled').checked = auto_stop.enabled; $('#autostop-minutes').value = auto_stop.minutes; $('#mods-section').classList.toggle('hidden', !mods); if (mods) $('#mods-summary').textContent = s.summary || ''; $('#world-section').classList.toggle('hidden', !backups); $('#world-download').href = `/api/servers/${s.id}/world.zip`; $('#settings-form').classList.toggle('hidden', !fields.length); $('#settings-fields').innerHTML = fields.map((f) => ` `).join(''); $('#settings-restart-note').classList.toggle('hidden', !['online', 'starting'].includes(s.state)); } catch (err) { $('#settings-fields').innerHTML = ''; $('#settings-error').textContent = err.message; } } function renderPlayers() { const s = servers.find((x) => x.id === managed?.id) || managed; const st = stats.servers[s.id]; const list = st?.players; let html; if (!['online', 'starting'].includes(s.state)) html = 'The server is not running.'; else if (!st?.ready) html = 'Waiting for the server to come online…'; else if (!list) html = 'Couldn\'t get the player list from the server.'; else if (!list.length) html = 'No players connected.'; if (html) { $('#players-body').innerHTML = `${html}
`; } else { $('#players-body').innerHTML = `| Player | IP address | Connected | Ping |
|---|---|---|---|
| ${esc(p.name)} | ${esc(p.ip || '–')} | ${fmtDuration(p.connected_for)} | ${p.ping == null ? '–' : `${p.ping} ms`} |
| Created | Session notes | Size | |
|---|---|---|---|
| ${b.created ? esc(new Date(b.created).toLocaleString()) : ''} | ${esc(sessionNotes(b))} | ${fmtBytes(b.size)} | Download |
No backups yet. See About Backups for when they are made.
'; } $('#about-backups-btn').addEventListener('click', () => $('#about-backups').showModal()); $('#about-backups-close').addEventListener('click', () => $('#about-backups').close()); // ---------- logs ---------- let logSource = null; const MAX_LOG_LINES = 3000; // Colour each line by the most severe level it mentions. function logLevel(line) { if (/\b(ERROR|FATAL|CRITICAL|Exception|FAIL(ED)?)\b/i.test(line)) return 'error'; if (/\b(WARN(ING)?)\b/i.test(line)) return 'warn'; if (/\bDEBUG\b/.test(line)) return 'debug'; if (/\bINFO\b/.test(line)) return 'info'; return ''; } function appendLogLines(lines) { const body = $('#logs-body'); const atBottom = body.scrollTop + body.clientHeight >= body.scrollHeight - 30; const frag = document.createDocumentFragment(); for (const line of lines) { const div = document.createElement('div'); div.textContent = line || '\u00a0'; const lvl = logLevel(line); if (lvl) div.className = `log-${lvl}`; frag.append(div); } body.append(frag); while (body.childElementCount > MAX_LOG_LINES) body.firstElementChild.remove(); if (atBottom) body.scrollTop = body.scrollHeight; } function setLogStatus(text, live) { $('#logs-status').textContent = text; $('#logs-status').classList.toggle('live', !!live); } function openLogs(s) { $('#logs-title').textContent = `Logs: ${s.server_name}`; $('#logs-body').replaceChildren(); setLogStatus('Connecting…'); $('#logs-dialog').showModal(); connectLogs(s); } function connectLogs(s) { if (logSource) logSource.close(); const es = new EventSource(`/api/servers/${s.id}/logs/stream?tail=500`); logSource = es; let first = true; es.onopen = () => setLogStatus('Live', true); es.onmessage = (e) => { if (first) { $('#logs-body').replaceChildren(); first = false; } // fresh tail on (re)connect appendLogLines(JSON.parse(e.data)); }; es.addEventListener('end', () => { es.close(); setLogStatus('Server stopped. No new output.'); }); es.onerror = () => { es.close(); setLogStatus('Disconnected. Reconnecting…'); setTimeout(() => { if (logSource === es && $('#logs-dialog').open) connectLogs(s); }, 3000); }; } $('#logs-close').addEventListener('click', () => $('#logs-dialog').close()); $('#logs-dialog').addEventListener('close', () => { if (logSource) logSource.close(); logSource = null; }); // ---------- wizard ---------- const wiz = { step: 1, game: null }; const form = $('#wizard-form'); $('#new-server-btn').addEventListener('click', async () => { form.reset(); wiz.step = 1; wiz.game = null; $('#upload-fields').classList.add('hidden'); $('#wiz-error').textContent = ''; const games = await api('/api/games'); wiz.games = Object.fromEntries(games.map((g) => [g.id, g])); $('#game-list').innerHTML = games.map((g) => ` `).join(''); showStep(); $('#wizard').showModal(); }); $('#game-list').addEventListener('click', (e) => { const b = e.target.closest('.game-option'); if (!b) return; wiz.game = b.dataset.game; document.querySelectorAll('.game-option').forEach((x) => x.classList.toggle('selected', x === b)); goNext(); }); function showStep() { document.querySelectorAll('.wiz-step').forEach((el) => el.classList.toggle('hidden', +el.dataset.step !== wiz.step)); $('#wiz-back').classList.toggle('hidden', wiz.step === 1); $('#wiz-next').classList.toggle('hidden', wiz.step !== 2); $('#wiz-create').classList.toggle('hidden', wiz.step !== 3); $('#wiz-error').textContent = ''; } async function goNext() { if (wiz.step === 1) { if (!wiz.game) return; const { port } = await api(`/api/suggest-port?game=${wiz.game}`); form.port.value = port; setupGameFields(); wiz.step = 2; } else if (wiz.step === 2) { const err = validateStep2(); if (err) { $('#wiz-error').textContent = err; return; } renderReview(); wiz.step = 3; } showStep(); } // Show only the selected game's fields; hidden ones are disabled so they don't block validation. function setupGameFields() { const g = wiz.game; $('#wiz-game-title').textContent = `${wiz.games[g].name} server`; document.querySelectorAll('.game-fields').forEach((el) => { const on = el.dataset.game === g; el.classList.toggle('hidden', !on); el.querySelectorAll('input, select').forEach((i) => { i.disabled = !on; }); }); const pw = form.password; if (g === 'valheim') { pw.required = true; pw.minLength = 5; $('#password-help').textContent = '(at least 5 characters, not part of the server name)'; } else { pw.required = false; pw.removeAttribute('minlength'); $('#password-help').textContent = '(optional; leave empty for an open server)'; updateMemoryHelp(); renderPresetMods(); } } // One recommended-mod checkbox (wizard and mod manager): name, note, and when it was last updated. function presetLabel(p, inputAttrs) { const updated = p.updated ? `Updated ${timeAgo(new Date(p.updated * 1000).toISOString())}` : ''; return ``; } // Build 42 mod checklist from /api/games; all ticked by default. function renderPresetMods() { const presets = wiz.games.zomboid.mod_presets || []; $('#preset-mods').innerHTML = presets.map((m) => presetLabel(m, `name="preset_mods" value="${esc(m.key)}" checked`)).join(''); updatePresetVisibility(); } function updatePresetVisibility() { const b42 = form.branch.value === wiz.games.zomboid.preset_branch; $('#preset-mods-fieldset').classList.toggle('hidden', !b42); $('#preset-mods-b41').classList.toggle('hidden', b42); form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.disabled = !b42; }); } const checkedPresets = () => [...form.querySelectorAll('input[name="preset_mods"]:checked:not(:disabled)')]; $('#preset-all').addEventListener('click', () => form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.checked = true; })); $('#preset-none').addEventListener('click', () => form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.checked = false; })); function updateMemoryHelp() { const free = wiz.games?.zomboid?.free_memory_mb; if (free == null) return; const need = (+form.memory_mb.value || 0) + 768; const el = $('#memory-help'); el.textContent = `Needs about ${need} MB free to start; ${free} MB is free right now.` + (need > free ? ' The server won\'t start until other servers free up memory or you lower this.' : ''); el.classList.toggle('error', need > free); } function validateStep2() { const fields = [...form.querySelectorAll('.wiz-step[data-step="2"] input, .wiz-step[data-step="2"] select')] .filter((i) => !i.disabled && i.type !== 'radio' && i.type !== 'file'); for (const input of fields) { if (!input.checkValidity()) { input.reportValidity(); return `Please fix the ${input.name.replace('_', ' ')}.`; } } if (wiz.game === 'valheim') { if (form.server_name.value.includes(form.password.value)) return 'The password cannot appear in the server name.'; if (form.world_source.value === 'upload' && !form.world_files.files.length) { return 'Choose your world files to upload.'; } } return ''; } function renderReview() { const common = [ ['Game', wiz.games[wiz.game].name], ['Server name', form.server_name.value], ['Password', form.password.value || '(none)'], ['Port', `${form.port.value} (and ${+form.port.value + 1}), UDP`], ]; const upload = form.world_source.value === 'upload'; const rows = wiz.game === 'valheim' ? [...common, ['World', form.world_name.value], ['World source', upload ? `Upload: ${[...form.world_files.files].map((f) => f.name).join(', ')}` : 'New world'], ] : [...common, ['Admin password', form.admin_password.value], ['Game version', form.branch.selectedOptions[0].textContent], ['Memory', `${form.memory_mb.value} MB`], ['Max players', form.max_players.value], ['Mods', checkedPresets().map((i) => i.closest('label').querySelector('.preset-name').textContent).join(', ') || 'None'], ]; $('#review').innerHTML = rows.map(([k, v]) => `