game-servers/app/static/app.js
neil 51db28f3d5
Rollback: restore a server's world from any of its backups, with a Current marker
Manage gets a Backup section (between World and Logs) listing the server's automatic and manual
backups. Rolling back is only allowed while the server is stopped and nothing else, such as an
automatic backup, is running on it; the server claims the busy flag atomically so the two can't race.
A run players were on is backed up first. The new world is extracted to a staging folder and checked
before the old one is deleted.

The backup that holds the world as it is now is marked Current (its button is disabled, and the
Backups page tags it). It's tracked in backups/<game>/<container>.current: set by automatic backups
and rollbacks, none while players have been on, newest automatic backup when there's no record.
Rolling back to an automatic backup can keep the Current backup as a manual one (or make one if
nothing is current), warning when that pushes out the oldest of 5 manual backups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:53:25 -08:00

982 lines
44 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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();
applyBandwidthGuard();
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`;
}
// More/Less on the resources card; remembered per browser.
function setResourcesOpen(open) {
$('#resources-more').classList.toggle('hidden', !open);
$('#resources-toggle').textContent = open ? 'Less ▴' : 'More ▾';
$('#resources-toggle').setAttribute('aria-expanded', open);
try { localStorage.setItem('resources-open', open ? '1' : ''); } catch { /* private mode */ }
}
try { setResourcesOpen(!!localStorage.getItem('resources-open')); } catch { /* private mode */ }
$('#resources-toggle').addEventListener('click', () => setResourcesOpen($('#resources-more').classList.contains('hidden')));
// Bandwidth test: download random bytes from the VPS for the chosen number of seconds (1-60) and report
// the fastest half second, i.e. the VPS's upload as seen by this browser. app.py refuses it while
// players are connected.
const BW_MAX_S = 60;
const fmtMbps = (bytesPerSec) => `${((bytesPerSec * 8) / 1e6).toFixed(bytesPerSec < 125000 ? 2 : 0)} Mbit/s`;
let bwRunning = false;
function bwSeconds() {
const n = Math.round(+$('#bw-seconds').value);
return Number.isFinite(n) ? Math.min(BW_MAX_S, Math.max(1, n)) : 5;
}
try { const saved = localStorage.getItem('bw-seconds'); if (saved) $('#bw-seconds').value = saved; } catch { /* private mode */ }
$('#bw-seconds').addEventListener('change', () => {
$('#bw-seconds').value = bwSeconds();
try { localStorage.setItem('bw-seconds', bwSeconds()); } catch { /* private mode */ }
});
function applyBandwidthGuard() {
const online = Object.values(stats.servers).reduce((n, st) => n + (st.players?.length || 0), 0);
const why = online ? `${online} player${online === 1 ? ' is' : 's are'} connected. The test uses all of the VPS's `
+ 'bandwidth and would lag them, so it\'s disabled until everyone has left.' : '';
$('#bw-btn').disabled = bwRunning || !!why;
$('#bw-seconds').disabled = bwRunning;
$('#bw-tip').title = why;
}
$('#bw-btn').addEventListener('click', async () => {
const seconds = bwSeconds();
$('#bw-seconds').value = seconds;
bwRunning = true;
applyBandwidthGuard();
$('#bw-btn').textContent = 'Testing…';
const out = $('#bw-result');
const detail = $('#bw-detail');
detail.textContent = '';
detail.classList.remove('error');
out.title = '';
const ctrl = new AbortController();
const failsafe = setTimeout(() => ctrl.abort(), (seconds + 15) * 1000); // the server ends the stream itself
let total = 0;
let peak = 0;
let elapsed = 0;
const samples = []; // [time, total bytes]
try {
const res = await fetch(`/api/bandwidth-test?seconds=${seconds}`, { signal: ctrl.signal, cache: 'no-store' });
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).detail || `Request failed (${res.status})`);
const reader = res.body.getReader();
const start = performance.now();
samples.push([start, 0]);
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.length;
const now = performance.now();
elapsed = (now - start) / 1000;
samples.push([now, total]);
while (samples.length > 2 && now - samples[1][0] >= 500) samples.shift(); // keep a 0.5 s window
const [t0, b0] = samples[0];
if (now - t0 >= 500) peak = Math.max(peak, ((total - b0) * 1000) / (now - t0));
out.textContent = `Testing… ${fmtMbps(total / elapsed)}`;
}
} catch (err) {
if (err.name !== 'AbortError' || !peak) {
out.textContent = 'Test failed';
detail.textContent = err.name === 'AbortError' ? 'The VPS stopped responding.' : err.message;
detail.classList.add('error');
}
}
clearTimeout(failsafe);
if (peak) {
out.textContent = `Peak ${fmtMbps(peak)}`;
detail.textContent = `Average ${fmtMbps(total / elapsed)} · ${fmtBytes(total)} in ${elapsed.toFixed(1)} s`;
out.title = `Fastest half second (${fmtRate(peak)}) of a download from the VPS. Limited by your own connection too.`;
}
bwRunning = false;
$('#bw-btn').textContent = 'Test bandwidth';
applyBandwidthGuard();
});
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 ? ` <span class="muted">· auto stop in ${Math.ceil(st.auto_stop_in / 60)} min</span>` : '';
return `<div class="server-players${n ? '' : ' none'}">${n} player${n === 1 ? '' : 's'}${stop}</div>`;
}
// Actions that kick players (stop, restart, delete, saving settings) are blocked while anyone is
// online; the server refuses them too. Disabled buttons don't get hover events in every browser,
// so the tooltip sits on a wrapper.
function playersBlockReason(st, what) {
const n = st?.players?.length || 0;
return n ? `${n} player${n === 1 ? ' is' : 's are'} connected. ${what} is disabled until everyone has left, so nobody gets kicked mid-game.` : '';
}
function guardedButton(act, label, st, isBusy) {
const why = playersBlockReason(st, label);
if (!why) return `<button class="small" data-act="${act}" ${isBusy ? 'disabled' : ''}>${label}</button>`;
return `<span class="tip" title="${esc(why)}"><button class="small" data-act="${act}" disabled>${label}</button></span>`;
}
// Same guard for the manage dialog's buttons; re-applied on every poll while it is open.
function applyManageGuard() {
const st = stats.servers[managed?.id];
for (const [id, what] of [['settings-save', 'Saving settings'], ['manage-delete', 'Delete']]) {
const btn = $(`#${id}`);
if (btn.textContent.endsWith('…')) continue; // mid-request
const why = playersBlockReason(st, what);
btn.disabled = !!why;
$(`#${id}-tip`).title = why;
}
const why = rollbackBlockReason();
for (const btn of document.querySelectorAll('#rollback-list .rollback-btn')) {
btn.disabled = rollingBack || !!why;
btn.parentElement.title = rollingBack ? '' : why;
}
if ($('#rollback-dialog').open && !rollingBack) {
$('#rollback-confirm').disabled = !!why;
$('#rollback-blocked').textContent = why;
$('#rollback-blocked').classList.toggle('hidden', !why);
}
// An automatic backup (or another job) just finished: show the new list.
const s = servers.find((x) => x.id === managed?.id);
const busyNow = !!(s?.busy || busy.has(managed?.id));
// Players joining (the world moves past every backup) changes which backup is current too.
const pendingNow = !!s?.backup_pending;
if (((managedWasBusy && !busyNow) || pendingNow !== managedWasPending) && !rollingBack
&& !$('#rollback-section').classList.contains('hidden')) loadRollbackList();
managedWasBusy = busyNow;
managedWasPending = pendingNow;
}
// Official Steam library art, stored in static/art/ (<game>-poster.jpg 300x450, <game>-header.jpg 460x215).
const GAME_ART = new Set(['valheim', 'zomboid']);
const artImg = (game, kind, cls) => (GAME_ART.has(game)
? `<img class="${cls}" src="/static/art/${game}-${kind}.jpg" alt="" loading="lazy">` : '');
// "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) => `<button type="button" class="copy-addr" data-addr="${esc(addr)}" data-tip="${
copied.addr === addr ? esc(copied.text) : 'Click to copy'}">${esc(addr)}</button>`;
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 `
<div class="card server" data-id="${esc(s.id)}">
${artImg(s.game, 'poster', 'server-art')}
<div class="server-body">
<div class="server-top">
<div>
<div class="server-name">${esc(s.server_name)}<span class="badge ${badgeCls}">${isBusy ? 'Working…' : s.busy ? esc(s.busy) : STATE_LABEL[s.state] || esc(s.state)}</span></div>
<div class="server-meta">${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world <b>${esc(s.world)}</b>`} · connect to ${copyAddr(`${host}:${s.port}`)}</div>
${running ? playersLine(st) : s.last_online ? `<div class="server-last-online" title="${esc(new Date(s.last_online).toLocaleString())}">Last online ${esc(timeAgo(s.last_online))}</div>` : ''}
</div>
<div class="server-actions">
${running
? `${guardedButton('restart', 'Restart', st, isBusy)}
${guardedButton('stop', 'Stop', st, isBusy)}`
: `<button class="small" data-act="start" ${isBusy ? 'disabled' : ''}>Start</button>`}
<button class="small primary manage-btn" data-act="manage" ${isBusy ? 'disabled' : ''}>Manage</button>
</div>
</div>
${running && st ? `
<div class="server-stats">
<div><div class="meter-label"><span>CPU</span><span class="stat-val">${st.cpu_percent}%</span></div><div class="bar"><div style="width:${Math.min(100, st.cpu_percent / (stats.host.cpu_count || 1))}%"></div></div></div>
<div><div class="meter-label"><span>Memory</span><span class="stat-val">${fmtBytes(st.mem_used)}</span></div><div class="bar"><div style="width:${memPct}%"></div></div></div>
<div><div class="meter-label"><span>Network</span><span class="stat-val">↓ ${fmtRate(st.net_rx_rate)} ↑ ${fmtRate(st.net_tx_rate)}</span></div></div>
</div>` : ''}
</div>
</div>`;
}).join('');
}
$('#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');
const id = card.dataset.id;
const s = servers.find((x) => x.id === id);
const act = btn.dataset.act;
if (act === 'manage') return openManage(s);
const path = `/api/servers/${id}/${act}`;
const method = 'POST';
busy.add(id);
renderServers();
try { await api(path, { method }); } catch (err) { alert(err.message); }
busy.delete(id);
refresh();
});
// ---------- manage ----------
let managed = null; // server open in the manage dialog
async function openManage(s) {
managed = s;
$('#manage-title').textContent = s.server_name;
$('#manage-sub').textContent = `${s.game_name} · ${s.summary || `world ${s.world}`}`;
$('#settings-error').textContent = '';
$('#delete-data').checked = false;
$('#autostop-error').textContent = '';
$('#rollback-section').classList.add('hidden');
$('#rollback-list').innerHTML = '';
$('#rollback-messages').innerHTML = '';
renderPlayers();
$('#settings-fields').innerHTML = '<p class="muted small">Loading…</p>';
$('#manage-dialog').showModal();
try {
const { fields, values, backups, mods, auto_stop } = await api(`/api/servers/${s.id}/settings`);
$('#rollback-section').classList.toggle('hidden', !backups);
if (backups) loadRollbackList();
$('#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) => `
<label>${esc(f.label)}
<input name="${esc(f.key)}" type="${f.type === 'number' ? 'number' : 'text'}" ${f.required === false ? '' : 'required'} value="${esc(values[f.key] ?? '')}"
${f.minlength ? `minlength="${f.minlength}"` : ''} ${f.min != null ? `min="${f.min}"` : ''} ${f.max != null ? `max="${f.max}"` : ''}>
${f.help ? `<span class="muted field-help">${esc(f.help)}</span>` : ''}
</label>`).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 = `<p class="muted small" style="margin:0">${html}</p>`;
} else {
$('#players-body').innerHTML = `<table class="players-table">
<tr><th>Player</th><th>IP address</th><th>Connected</th><th>Ping</th></tr>
${list.map((p) => `<tr><td>${esc(p.name)}</td><td>${esc(p.ip || '–')}</td><td>${fmtDuration(p.connected_for)}</td>
<td${p.ping == null ? ' class="muted" title="This player\'s network doesn\'t answer ping"' : ''}>${p.ping == null ? '–' : `${p.ping} ms`}</td></tr>`).join('')}
</table>`;
}
applyManageGuard();
$('#autostop-status').textContent = st?.auto_stop_in != null
? `Nobody is online. Stopping in ${Math.ceil(st.auto_stop_in / 60)} min unless someone joins.` : '';
}
$('#autostop-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = $('#autostop-save');
btn.disabled = true; btn.textContent = 'Saving…';
$('#autostop-error').textContent = '';
try {
await api(`/api/servers/${managed.id}/autostop`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: $('#autostop-enabled').checked, minutes: +$('#autostop-minutes').value }),
});
btn.textContent = 'Saved';
setTimeout(() => { btn.textContent = 'Save'; }, 1500);
} catch (err) { $('#autostop-error').textContent = err.message; btn.textContent = 'Save'; }
btn.disabled = false;
refresh();
});
$('#manage-close').addEventListener('click', () => $('#manage-dialog').close());
$('#world-download').addEventListener('click', async (e) => {
e.preventDefault();
const a = e.currentTarget;
if (a.dataset.busy) return;
a.dataset.busy = '1'; a.textContent = 'Preparing…';
try {
const res = await fetch(a.href);
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).detail || `Download failed (${res.status})`);
const name = /filename="?([^"]+)"?/.exec(res.headers.get('Content-Disposition') || '')?.[1] || 'world.zip';
const url = URL.createObjectURL(await res.blob());
const tmp = Object.assign(document.createElement('a'), { href: url, download: name });
document.body.append(tmp); tmp.click(); tmp.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
} catch (err) { alert(err.message); }
delete a.dataset.busy; a.textContent = 'Download';
});
// ---------- rollback (manage dialog) ----------
let serverBackups = { auto: [], manual: [], keep: 5 }; // the managed server's backups, newest first
let managedWasBusy = false;
let managedWasPending = false;
let currentBackupId = null; // the backup holding the managed server's world as it is now
let rollbackTarget = null;
let rollingBack = false;
// Rolling back is only allowed while the server is stopped and nothing else (an automatic backup,
// a start, a delete...) is running on it; the server checks this too.
function rollbackBlockReason() {
const s = servers.find((x) => x.id === managed?.id) || managed;
if (!s) return '';
if (s.busy) return `Rolling back is disabled while this runs: ${s.busy}`;
if (busy.has(s.id)) return 'Rolling back is disabled while another action on this server finishes.';
if (!['exited', 'created'].includes(s.state)) return 'Stop the server before rolling back.';
return '';
}
const fmtWhen = (iso) => (iso ? new Date(iso).toLocaleString() : 'unknown time');
async function loadRollbackList() {
const s = managed;
let data;
try { data = await api('/api/backups'); } catch (err) {
$('#rollback-list').innerHTML = `<p class="error">${esc(err.message)}</p>`;
return;
}
if (managed !== s) return;
const mine = data.backups.filter((b) => b.container === s.container);
serverBackups = { auto: mine.filter((b) => b.type === 'auto'), manual: mine.filter((b) => b.type === 'manual'), keep: data.keep };
currentBackupId = data.current?.[s.container] || null;
if (!mine.length) {
$('#rollback-list').innerHTML = '<p class="muted small" style="margin:0">This server has no backups yet. See <b>About Backups</b> on the Backups page for when they are made.</p>';
return;
}
$('#rollback-list').innerHTML = BACKUP_KINDS.map(([kind, label]) => {
const rows = serverBackups[kind];
if (!rows.length) return '';
return `<div class="backup-kind">
<h4>${label} <span class="muted small">${rows.length} of ${data.keep} kept</span></h4>
<table class="backups-table">
<tr><th>Created</th><th>Session notes</th><th></th></tr>
${rows.map((b) => `<tr>
<td>${esc(fmtWhen(b.created))}</td>
<td class="muted">${esc(sessionNotes(b))}</td>
<td class="row-end">${b.id === currentBackupId
? '<span class="tip" title="The server\'s world is this backup, so rolling back to it would change nothing."><button class="small" disabled>Current</button></span>'
: `<span class="tip"><button class="small rollback-btn" data-id="${esc(b.id)}">Roll back</button></span>`}</td>
</tr>`).join('')}
</table>
</div>`;
}).join('');
applyManageGuard();
}
$('#rollback-list').addEventListener('click', (e) => {
const btn = e.target.closest('.rollback-btn');
if (!btn) return;
const b = [...serverBackups.auto, ...serverBackups.manual].find((x) => x.id === btn.dataset.id);
if (b) openRollback(b);
});
function openRollback(b) {
rollbackTarget = b;
const s = servers.find((x) => x.id === managed.id) || managed;
const backupPending = !!s.backup_pending; // players were on since the last automatic backup
const kindLabel = b.type === 'auto' ? 'automatic' : 'manual';
$('#rollback-title').textContent = `Roll back ${s.server_name}?`;
$('#rollback-what').innerHTML = `The current world is replaced with the ${kindLabel} backup from <b>${esc(fmtWhen(b.created))}</b>`
+ ` <span class="muted">(${esc(sessionNotes(b))})</span>.`;
// Auto: offer to keep the world being rolled back from as a manual backup. That's the current
// backup if it's automatic, the backup of the run players were just on, or a fresh manual backup
// when no backup holds it. A manual current backup is kept already.
const cur = [...serverBackups.auto, ...serverBackups.manual].find((x) => x.id === currentBackupId);
const alreadyKept = b.type === 'auto' && !backupPending && cur?.type === 'manual';
const canPromote = b.type === 'auto' && !alreadyKept;
$('#rollback-promote').classList.toggle('hidden', !canPromote);
const keptNote = $('#rollback-kept-note');
keptNote.classList.toggle('hidden', !alreadyKept);
if (alreadyKept) {
keptNote.textContent = `The world you're rolling back from is already kept as the manual backup from ${fmtWhen(cur.created)}.`;
}
if (canPromote) {
$('#rollback-promote-check').checked = true;
const keep = ', so you can return to the point you rolled back from without newer automatic backups pushing it out.';
$('#rollback-promote-help').textContent = backupPending
? `Players were on since the last automatic backup, so the current world is backed up first and that backup is moved to the manual backups${keep}`
: cur
? `The current world's backup (automatic, from ${fmtWhen(cur.created)}) is moved to the manual backups${keep}`
: `No backup holds the current world, so a manual backup of it is made${keep}`;
const manual = serverBackups.manual;
const full = manual.length >= serverBackups.keep;
$('#rollback-promote-full').classList.toggle('hidden', !full);
if (full) {
$('#rollback-promote-full').textContent = `There are already ${manual.length} manual backups, so this pushes the`
+ ` oldest one (from ${fmtWhen(manual[manual.length - 1].created)}) out of the list.`;
}
}
$('#rollback-running').textContent = 'The server stays stopped; start it when you\'re ready. '
+ (backupPending && !canPromote ? 'Players were on since the last automatic backup, so the current world is backed up automatically first.' : '');
$('#rollback-confirm').textContent = 'Roll back';
$('#rollback-error').textContent = '';
applyManageGuard(); // sets the confirm button and the reason it's disabled, if any
$('#rollback-dialog').showModal();
}
$('#rollback-cancel').addEventListener('click', () => { if (!rollingBack) $('#rollback-dialog').close(); });
$('#rollback-dialog').addEventListener('cancel', (e) => { if (rollingBack) e.preventDefault(); });
$('#rollback-confirm').addEventListener('click', async () => {
const b = rollbackTarget;
const promote = !$('#rollback-promote').classList.contains('hidden') && $('#rollback-promote-check').checked;
const btn = $('#rollback-confirm');
btn.disabled = true; btn.textContent = 'Rolling back…';
$('#rollback-cancel').disabled = true;
$('#rollback-error').textContent = '';
$('#rollback-blocked').classList.add('hidden');
rollingBack = true;
const id = managed.id;
busy.add(id); renderServers(); applyManageGuard();
try {
const res = await api(`/api/servers/${id}/rollback`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: b.id, promote }),
});
managed = res.server; // a Project Zomboid server with pending changes is recreated, so its id can change
$('#rollback-dialog').close();
let msg = `Rolled back to the ${b.type === 'auto' ? 'automatic' : 'manual'} backup from ${fmtWhen(b.created)}.`;
if (res.promoted) msg += ` The world you rolled back from (backup from ${fmtWhen(res.promoted.created)}) is now a manual backup.`;
$('#rollback-messages').innerHTML = `<div class="msg msg-success">${esc(msg)}</div>`;
} catch (err) {
$('#rollback-error').textContent = err.message;
btn.textContent = 'Roll back';
btn.disabled = false;
} finally {
busy.delete(id);
rollingBack = false;
$('#rollback-cancel').disabled = false;
loadRollbackList();
refresh();
}
});
$('#manage-logs').addEventListener('click', () => openLogs(managed));
$('#open-mods').addEventListener('click', () => openMods(managed));
$('#settings-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = $('#settings-save');
const body = {};
for (const input of $('#settings-fields').querySelectorAll('input')) {
body[input.name] = input.type === 'number' ? +input.value : input.value;
}
btn.disabled = true; btn.textContent = 'Saving…';
$('#settings-error').textContent = '';
busy.add(managed.id); renderServers();
try {
const updated = await api(`/api/servers/${managed.id}/settings`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
busy.delete(managed.id);
managed = updated; // the container is recreated, so its id changes
$('#manage-dialog').close();
} catch (err) {
busy.delete(managed.id);
$('#settings-error').textContent = err.message;
} finally {
btn.disabled = false; btn.textContent = 'Save settings';
applyManageGuard();
refresh();
}
});
$('#manage-delete').addEventListener('click', async () => {
const s = managed;
const wipe = $('#delete-data').checked;
const msg = wipe
? `Delete "${s.server_name}" AND its world files? This cannot be undone.`
: `Delete "${s.server_name}"? The world files are kept on the VPS.`;
if (!confirm(msg)) return;
const btn = $('#manage-delete');
btn.disabled = true; btn.textContent = 'Deleting…';
busy.add(s.id); renderServers();
try {
await api(`/api/servers/${s.id}?delete_data=${wipe}`, { method: 'DELETE' });
$('#manage-dialog').close();
} catch (err) { alert(err.message); }
busy.delete(s.id);
btn.disabled = false; btn.textContent = 'Delete server';
applyManageGuard();
refresh();
});
// ---------- navigation ----------
let view = 'servers';
function showView() {
view = location.hash === '#backups' ? 'backups' : 'servers';
for (const v of ['servers', 'backups']) $(`#view-${v}`).classList.toggle('hidden', v !== view);
document.querySelectorAll('.tabs a').forEach((a) => a.classList.toggle('active', a.dataset.view === view));
$('#new-server-btn').classList.toggle('hidden', view !== 'servers');
if (view === 'backups') loadBackups();
}
window.addEventListener('hashchange', showView);
showView();
// ---------- backups ----------
const BACKUP_KINDS = [['auto', 'Automatic'], ['manual', 'Manual']];
function sessionNotes(b) {
const sn = b.session;
const promoted = b.promoted ? 'Kept from a rollback' : '';
if (!sn) return promoted || (b.type === 'manual' && 'session' in b ? 'Server was stopped' : '–');
if (promoted) return `${promoted} · ${fmtDuration(sn.length)} session · peak ${sn.peak} player${sn.peak === 1 ? '' : 's'}`;
const peak = `peak ${sn.peak} player${sn.peak === 1 ? '' : 's'}`;
return sn.running ? `${fmtDuration(sn.length)} into a running session · ${peak}` : `${fmtDuration(sn.length)} session · ${peak}`;
}
async function loadBackups() {
let data;
try { data = await api('/api/backups'); } catch (e) { return; }
const { backups, keep, current } = data;
// One card per server, ordered by its newest backup (the list arrives newest first).
const byServer = new Map();
for (const b of backups) {
if (!byServer.has(b.container)) byServer.set(b.container, []);
byServer.get(b.container).push(b);
}
$('#backup-list').innerHTML = byServer.size ? [...byServer.values()].map((list) => {
const b0 = list[0];
return `<div class="card backup-game">
<h3>${esc(b0.game_name || b0.game)} - ${esc(b0.server_name || b0.container)}${b0.world ? ` <span class="muted small">world ${esc(b0.world)}</span>` : ''}</h3>
${BACKUP_KINDS.map(([kind, label]) => {
const rows = list.filter((b) => b.type === kind);
if (!rows.length) return '';
return `<div class="backup-kind">
<h4>${label} <span class="muted small">${rows.length} of ${keep} kept</span></h4>
<table class="backups-table">
<tr><th>Created</th><th>Session notes</th><th>Size</th><th></th></tr>
${rows.map((b) => `<tr>
<td>${b.created ? esc(new Date(b.created).toLocaleString()) : ''}${current?.[b.container] === b.id
? ' <span class="current-tag" title="Holds the server\'s world as it is now">Current</span>' : ''}</td>
<td class="muted">${esc(sessionNotes(b))}</td>
<td>${fmtBytes(b.size)}</td>
<td class="row-end"><a class="button ghost small" href="/api/backups/${b.id.split('/').map(encodeURIComponent).join('/')}" download>Download</a></td>
</tr>`).join('')}
</table>
</div>`;
}).join('')}
</div>`;
}).join('') : '<p class="empty">No backups yet. See <b>About Backups</b> for when they are made.</p>';
}
$('#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) => `
<button type="button" class="game-option" data-game="${esc(g.id)}">
${artImg(g.id, 'header', 'game-option-art')}
<span class="game-option-text"><b>${esc(g.name)}</b><span class="muted small">default port ${g.default_port}</span></span>
</button>`).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 `<label class="radio preset-mod"><input type="checkbox" ${inputAttrs}>
<span><span class="preset-name">${esc(p.name)}</span>${p.note ? ` <span class="muted small">${esc(p.note)}</span>` : ''}
${(p.includes || []).map((d) => `<span class="preset-include muted">+ ${esc(d)}</span>`).join('')}
${updated ? `<span class="preset-meta muted">${esc(updated)}</span>` : ''}</span></label>`;
}
// 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]) => `<dt>${esc(k)}</dt><dd>${esc(v)}</dd>`).join('');
}
form.addEventListener('input', (e) => { if (e.target.name === 'memory_mb') updateMemoryHelp(); });
form.addEventListener('change', (e) => {
if (e.target.name === 'branch') updatePresetVisibility();
if (e.target.name === 'world_source') {
$('#upload-fields').classList.toggle('hidden', form.world_source.value !== 'upload');
}
// Pre-fill the world name from an uploaded file name.
if (e.target.name === 'world_files' && !form.world_name.value) {
const f = [...e.target.files].find((x) => /\.(zip|db|fwl)$/i.test(x.name) && !x.name.startsWith('_main.'));
if (f) form.world_name.value = f.name.replace(/\.(zip|db|fwl)$/i, '').replace(/[^A-Za-z0-9_]/g, '');
}
});
$('#wiz-next').addEventListener('click', goNext);
$('#wiz-back').addEventListener('click', () => { wiz.step -= 1; showStep(); });
$('#wiz-cancel').addEventListener('click', () => $('#wizard').close());
$('#wiz-create').addEventListener('click', async () => {
const btn = $('#wiz-create');
btn.disabled = true; btn.textContent = 'Creating…';
const fd = new FormData();
fd.append('game', wiz.game);
for (const k of ['server_name', 'password', 'port']) fd.append(k, form[k].value);
if (wiz.game === 'valheim') {
fd.append('world_name', form.world_name.value);
fd.append('world_source', form.world_source.value);
if (form.world_source.value === 'upload') {
for (const f of form.world_files.files) fd.append('world_files', f);
}
} else {
for (const k of ['admin_password', 'branch', 'memory_mb', 'max_players']) fd.append(k, form[k].value);
for (const i of checkedPresets()) fd.append('preset_mods', i.value);
}
try {
await api('/api/servers', { method: 'POST', body: fd });
$('#wizard').close();
refresh();
} catch (err) {
$('#wiz-error').textContent = err.message;
} finally {
btn.disabled = false; btn.textContent = 'Create server';
}
});
// ---------- boot ----------
api('/api/me').then((r) => (r.authenticated ? showApp() : showLogin())).catch(showLogin);
// Enter in the wizard should advance, not close the dialog.
form.addEventListener('submit', (e) => {
e.preventDefault();
if (wiz.step === 2) goNext();
else if (wiz.step === 3) $('#wiz-create').click();
});