The server kept streaming (and holding the one-test lock) after the browser stopped reading, so the next test got a 409. The server now ends the stream at the chosen duration, the browser reads to the end, and a new test ends any earlier stream instead of being refused. Errors show in the cell. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
810 lines
35 KiB
JavaScript
810 lines
35 KiB
JavaScript
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();
|
||
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;
|
||
}
|
||
}
|
||
|
||
// 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 = '';
|
||
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`);
|
||
$('#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';
|
||
});
|
||
|
||
$('#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;
|
||
if (!sn) return b.type === 'manual' && 'session' in b ? 'Server was stopped' : '–';
|
||
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 } = 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()) : ''}</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();
|
||
});
|