Game server manager: web UI for Valheim and Project Zomboid servers

FastAPI + vanilla JS app run as a Docker container behind Caddy (HTTPS by
IP). install.sh installs or updates it on a server in one command, with
preflight checks and Docker setup; deploy.sh pushes a local checkout to a
server over SSH and runs install.sh there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
neil 2026-10-16 19:54:56 -07:00
commit cb9a6d1970
No known key found for this signature in database
20 changed files with 3801 additions and 0 deletions

490
app/static/mods.js Normal file
View file

@ -0,0 +1,490 @@
// Mod manager for Project Zomboid servers. Uses $, api, esc, fmtBytes and refresh from app.js.
const mm = {
server: null,
workshopIds: [], // workshop items to download, in order
mods: [], // enabled mod IDs, in load order
autoUpdate: true,
info: {}, // mod info read from the server by list-mods (cached on the VPS)
titles: {}, // workshop details from lookups, for items the server hasn't read yet
edited: false, // unsaved changes
timer: null,
};
async function openMods(s) {
Object.assign(mm, { server: s, edited: false }); // titles (with preview art) are kept between opens
$('#mods-title').textContent = `Mods: ${s.server_name}`;
showMsgs([]);
$('#mods-add-input').value = '';
$('#mods-dialog').showModal();
await loadMods(true);
loadPresets();
clearInterval(mm.timer);
mm.timer = setInterval(() => loadMods(false), 3000);
}
$('#mods-dialog').addEventListener('close', () => { clearInterval(mm.timer); refresh(); });
$('#mods-dialog').addEventListener('cancel', (e) => {
if (mm.edited && !confirm('Discard unsaved mod changes?')) e.preventDefault();
});
$('#mods-close').addEventListener('click', () => {
if (mm.edited && !confirm('Discard unsaved mod changes?')) return;
$('#mods-dialog').close();
});
async function loadMods(full) {
let d;
try { d = await api(`/api/servers/${mm.server.id}/mods`); } catch (err) {
// While a restart recreates the container, its old id is briefly gone.
if (err.message !== 'Server not found') showMsgs([{ level: 'error', text: err.message }]);
return;
}
mm.state = d;
mm.info = d.info || {};
// Don't overwrite edits the user hasn't saved yet.
if (full || !mm.edited) {
mm.workshopIds = [...d.workshop_ids];
mm.mods = [...d.mods];
mm.autoUpdate = d.auto_update;
$('#mods-auto-update').checked = d.auto_update;
}
// Steam details carry the preview art, which the server's own mod info doesn't have, so look up
// every item we don't have them for yet, downloaded or not.
const missingTitles = mm.workshopIds.filter((id) => !mm.titles[id]);
if (full && missingTitles.length) lookupTitles(missingTitles);
renderMods();
}
async function lookupTitles(ids) {
try {
const r = await api('/api/workshop/lookup', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: ids.join(' ') }),
});
for (const it of r.items) mm.titles[it.id] = it;
renderMods();
} catch { /* titles are nice to have */ }
}
const itemInfo = (id) => (mm.info.items || []).find((i) => i.id === id);
// Every mod the server knows about, by mod ID.
function knownMods() {
const out = {};
for (const it of mm.info.items || []) for (const m of it.mods) out[m.id] = { ...m, item: it.id };
return out;
}
// ---------- rendering ----------
function renderMods() {
const d = mm.state || {};
const parts = [];
if (d.busy) parts.push(d.busy);
else if (d.fetch_pending) parts.push('Waiting for the server to come online; mod info is fetched then');
else if (!d.running) parts.push('Server stopped');
else if (!d.ready) parts.push('Server starting…');
else parts.push('Server online');
if (mm.edited) parts.push('unsaved changes');
else if (d.dirty) parts.push('saved, applies on next restart');
if (mm.info.fetched) parts.push(`mod info from ${new Date(mm.info.fetched * 1000).toLocaleString()}`);
if (mm.info.error) parts.push(`last fetch failed: ${mm.info.error}`);
$('#mods-status').textContent = parts.join(' · ');
const busy = !!d.busy;
// Stopped or still starting: one click (re)starts as needed and fetches once it's online; the VPS does the waiting.
const startFirst = !d.running && !d.fetch_pending;
const waitFirst = d.running && !d.ready && !d.fetch_pending;
$('#mods-fetch').textContent = startFirst ? 'Start server and fetch mod info' : waitFirst ? 'Fetch mod info when online' : 'Fetch mod info';
$('#mods-fetch').disabled = busy || d.fetch_pending;
$('#mods-save').disabled = busy || !mm.edited;
$('#mods-apply').disabled = busy || (!mm.edited && !d.dirty);
$('#mods-apply').textContent = d.running ? 'Save & restart now' : 'Save & apply';
renderPresets();
renderItems();
renderOrder();
renderIssues();
}
// ---------- recommended mods (same list as the new-server wizard) ----------
let presetInfo = null; // {mods, branch} from /api/games
async function loadPresets() {
if (presetInfo) return;
try {
const z = (await api('/api/games')).find((g) => g.id === 'zomboid');
presetInfo = { mods: z?.mod_presets || [], branch: z?.preset_branch };
renderMods();
} catch { /* the rest of the manager works without it */ }
}
const presetOn = (p) => p.items.every((i) => mm.workshopIds.includes(i)) && p.mods.every((m) => mm.mods.includes(m));
function renderPresets() {
const show = !!presetInfo?.mods.length && mm.state?.branch === presetInfo.branch;
$('#mods-presets').classList.toggle('hidden', !show);
if (!show) return;
const busy = !!mm.state?.busy;
const on = presetInfo.mods.filter(presetOn).length;
$('#mods-presets-count').textContent = `${on} of ${presetInfo.mods.length} added`;
$('#mods-presets-all').disabled = busy || on === presetInfo.mods.length;
$('#mods-presets-list').innerHTML = presetInfo.mods.map((p) => presetLabel(p,
`data-preset="${esc(p.key)}" ${presetOn(p) ? 'checked' : ''} ${busy ? 'disabled' : ''}`)).join('');
}
// Dependencies come first in each preset, so appending keeps a working load order.
function addPreset(p) {
const newItems = p.items.filter((i) => !mm.workshopIds.includes(i));
mm.workshopIds.push(...newItems);
mm.mods.push(...p.mods.filter((m) => !mm.mods.includes(m)));
return newItems;
}
$('#mods-presets-all').addEventListener('click', () => {
const newItems = presetInfo.mods.flatMap(addPreset);
if (newItems.length) lookupTitles(newItems);
changed();
});
$('#mods-presets-list').addEventListener('change', (e) => {
const p = presetInfo.mods.find((x) => x.key === e.target.dataset.preset);
if (!p) return;
if (e.target.checked) {
const newItems = addPreset(p);
if (newItems.length) lookupTitles(newItems);
} else {
// Keep anything another ticked preset still needs (shared dependencies).
const keep = presetInfo.mods.filter((x) => x !== p && presetOn(x));
const keepItems = new Set(keep.flatMap((x) => x.items));
const keepMods = new Set(keep.flatMap((x) => x.mods));
mm.workshopIds = mm.workshopIds.filter((i) => !p.items.includes(i) || keepItems.has(i));
mm.mods = mm.mods.filter((m) => !p.mods.includes(m) || keepMods.has(m));
}
changed();
});
function renderItems() {
$('#items-count').textContent = mm.workshopIds.length ? `(${mm.workshopIds.length})` : '';
if (!mm.workshopIds.length) {
$('#mods-items').innerHTML = '<p class="muted small">No workshop items yet. Paste a link above to add one.</p>';
return;
}
$('#mods-items').innerHTML = mm.workshopIds.map((id) => {
const info = itemInfo(id);
const t = mm.titles[id] || {};
const title = info?.title || t.title || `Workshop item ${id}`;
const size = info?.size || t.size;
const mods = info?.mods || [];
let modsHtml;
if (mods.length) {
modsHtml = mods.map((m) => {
const on = mm.mods.includes(m.id);
const badges = [
m.maps.length ? `<span class="tag">map: ${esc(m.maps.join(', '))}</span>` : '',
m.error ? `<span class="tag tag-bad" title="${esc(m.error)}">can't load</span>` : '',
m.require.length ? `<span class="tag" title="Requires ${esc(m.require.join(', '))}">needs ${m.require.length}</span>` : '',
].join('');
return `<label class="radio mod-row"><input type="checkbox" data-mod="${esc(m.id)}" ${on ? 'checked' : ''}>
<span><b>${esc(m.name || m.id)}</b> <code>${esc(m.id)}</code> ${badges}</span></label>`;
}).join('');
} else if (info?.downloaded) {
modsHtml = '<p class="muted small">No mods found in this item.</p>';
} else {
modsHtml = `<p class="muted small">Mod IDs show up once the server has downloaded this item:
click <b>Fetch mod info</b> while the server is online, or restart it.</p>`;
}
const warn = t.zomboid === false || info?.available === false
? '<span class="tag tag-bad">not available / not a Project Zomboid item</span>' : '';
return `<div class="mod-item">
<div class="mod-item-head">
${t.preview ? `<img src="${esc(t.preview)}" alt="" loading="lazy">` : ''}
<div class="mod-item-title">
<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${esc(id)}" target="_blank" rel="noopener">${esc(title)}</a>
<div class="muted small">${esc(id)}${size ? ` · ${fmtBytes(size)}` : ''}${info?.downloaded ? ' · downloaded' : ''} ${warn}</div>
</div>
<button class="ghost small danger" data-remove="${esc(id)}" title="Remove item">✕</button>
</div>
${modsHtml}
</div>`;
}).join('');
}
function renderOrder() {
const known = knownMods();
if (!mm.mods.length) {
$('#mods-order').innerHTML = '<p class="muted small">No mods enabled. Tick mods on the left to enable them.</p>';
return;
}
$('#mods-order').innerHTML = mm.mods.map((id, i) => {
const m = known[id];
return `<li data-idx="${i}">
<span class="order-name"><b>${esc(m?.name || id)}</b> <code>${esc(id)}</code></span>
<span class="order-btns">
<button class="ghost small" data-move="-1" ${i === 0 ? 'disabled' : ''} title="Move up">↑</button>
<button class="ghost small" data-move="1" ${i === mm.mods.length - 1 ? 'disabled' : ''} title="Move down">↓</button>
<button class="ghost small danger" data-disable title="Disable">✕</button>
</span>
</li>`;
}).join('');
}
// Problems we can see from the mod info, plus the image's own startup warnings.
function modProblems() {
const known = knownMods();
const haveInfo = (mm.info.items || []).length > 0;
const enabled = new Set(mm.mods);
const pos = Object.fromEntries(mm.mods.map((m, i) => [m, i]));
const out = [];
const conflicts = new Set();
for (const id of mm.mods) {
const m = known[id];
if (!m) {
if (haveInfo) out.push({ level: 'warning', text: `${id}: not found in any downloaded workshop item.` });
continue;
}
if (m.error) out.push({ level: 'error', text: `${m.name || id}: ${m.error}` });
for (const r of m.require) {
if (!enabled.has(r)) out.push({ level: 'warning', text: `${m.name || id} requires ${r}, which isn't enabled (the server loads it if it's downloaded).` });
else if (pos[r] > pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load after ${r}. Auto-sort fixes this.` });
}
for (const r of m.loadAfter) {
if (enabled.has(r) && pos[r] > pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load after ${r}. Auto-sort fixes this.` });
}
for (const r of m.loadBefore) {
if (enabled.has(r) && pos[r] < pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load before ${r}. Auto-sort fixes this.` });
}
for (const r of m.incompatible) {
// Either mod may declare the conflict; report each pair once.
const pair = [id, r].sort().join('\u0000');
if (enabled.has(r) && !conflicts.has(pair)) {
conflicts.add(pair);
out.push({ level: 'error', text: `${m.name || id} is incompatible with ${known[r]?.name || r}.` });
}
}
}
return out;
}
function renderIssues() {
const fromServer = (mm.state?.issues || []).map((i) => ({ ...i, source: 'server log' }));
const all = [...modProblems(), ...fromServer];
$('#mods-issues-section').classList.toggle('hidden', !all.length);
$('#mods-issues').innerHTML = all.map((i) => `<li class="issue-${i.level}">
<span>${esc(i.text).replace(/\n/g, '<br>')}</span>${i.source ? `<span class="muted small"> (${i.source})</span>` : ''}
</li>`).join('');
}
// ---------- editing ----------
function changed() { mm.edited = true; renderMods(); }
$('#mods-items').addEventListener('change', (e) => {
const id = e.target.dataset.mod;
if (!id) return;
if (e.target.checked) { if (!mm.mods.includes(id)) mm.mods.push(id); } else mm.mods = mm.mods.filter((m) => m !== id);
changed();
});
$('#mods-items').addEventListener('click', (e) => {
const id = e.target.closest('[data-remove]')?.dataset.remove;
if (!id) return;
const its = itemInfo(id)?.mods.map((m) => m.id) || [];
mm.workshopIds = mm.workshopIds.filter((x) => x !== id);
mm.mods = mm.mods.filter((m) => !its.includes(m));
changed();
});
$('#mods-order').addEventListener('click', (e) => {
const li = e.target.closest('li');
const btn = e.target.closest('button');
if (!li || !btn) return;
const i = +li.dataset.idx;
if (btn.dataset.move) {
const j = i + +btn.dataset.move;
[mm.mods[i], mm.mods[j]] = [mm.mods[j], mm.mods[i]];
} else if ('disable' in btn.dataset) {
mm.mods.splice(i, 1);
}
changed();
});
$('#mods-auto-update').addEventListener('change', (e) => { mm.autoUpdate = e.target.checked; changed(); });
// Topological sort: requirements and loadModAfter go first, loadModBefore after. Otherwise keeps the current order.
// ---------- messages ----------
// [{level: info|success|warning|error, text, action?}]; "enable-all" adds an Enable all button.
function showMsgs(list) {
$('#mods-messages').innerHTML = list.map((m) => `<div class="msg msg-${m.level}">${esc(m.text)}${m.action === 'enable-all'
? '<div class="msg-actions"><button class="ghost small" data-msg-action="enable-all">Enable all mods</button></div>' : ''}</div>`).join('');
}
$('#mods-messages').addEventListener('click', (e) => {
if (e.target.dataset.msgAction === 'enable-all') enableAll();
});
// Enable every loadable mod in the listed workshop items the server has read, then auto-sort.
function enableAll() {
let added = 0;
let broken = 0;
const unknown = [];
for (const id of mm.workshopIds) {
const info = itemInfo(id);
if (!info?.downloaded) { unknown.push(id); continue; }
for (const m of info.mods) {
if (m.error) { broken += 1; continue; }
if (!mm.mods.includes(m.id)) { mm.mods.push(m.id); added += 1; }
}
}
autoSort();
const msgs = [];
if (added) msgs.push({ level: 'success', text: `Enabled ${added} mod${added === 1 ? '' : 's'} and sorted the load order. Save to apply.` });
else msgs.push({ level: 'info', text: 'No more mods to enable from the downloaded items.' });
if (broken) msgs.push({ level: 'warning', text: `${broken} mod${broken === 1 ? '' : 's'} left off because the server reports they can't load.` });
if (unknown.length) {
msgs.push({ level: 'warning', text: `${unknown.length} workshop item${unknown.length === 1 ? ' hasn\'t' : 's haven\'t'} been downloaded yet, so `
+ 'their mods aren\'t known. Save, click Fetch mod info while the server is online, then Enable all again.' });
}
showMsgs(msgs);
changed();
}
$('#mods-enable-all').addEventListener('click', enableAll);
// Put each enabled mod after the ones it requires or asks to load after. Returns whether the order changed.
function autoSort() {
const known = knownMods();
const set = new Set(mm.mods);
const after = Object.fromEntries(mm.mods.map((m) => [m, new Set()])); // m loads after these
for (const id of mm.mods) {
const m = known[id];
if (!m) continue;
for (const r of [...m.require, ...m.loadAfter]) if (set.has(r) && r !== id) after[id].add(r);
for (const r of m.loadBefore) if (set.has(r) && r !== id) after[r].add(id);
}
const out = [];
const placed = new Set();
while (out.length < mm.mods.length) {
const next = mm.mods.find((m) => !placed.has(m) && [...after[m]].every((r) => placed.has(r)))
|| mm.mods.find((m) => !placed.has(m)); // a cycle: keep going in the current order
out.push(next); placed.add(next);
}
if (out.join() === mm.mods.join()) return false;
mm.mods = out;
return true;
}
$('#mods-sort').addEventListener('click', () => { if (autoSort()) changed(); });
async function addFromText(text) {
showMsgs([]);
const btn = $('#mods-add-btn');
btn.disabled = true; btn.textContent = 'Looking up…';
try {
const r = await api('/api/workshop/lookup', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }),
});
const skipped = [];
let added = 0;
for (const it of r.items) {
mm.titles[it.id] = it;
if (!it.available || !it.zomboid) { skipped.push(it); continue; }
if (!mm.workshopIds.includes(it.id)) { mm.workshopIds.push(it.id); added += 1; }
}
const msgs = [];
for (const c of r.collections) msgs.push({ level: 'info', text: `Collection "${c.title || c.id}" has ${c.count} items.` });
if (added) msgs.push({ level: 'success', text: `Added ${added} workshop item${added === 1 ? '' : 's'}.` });
else if (!skipped.length) msgs.push({ level: 'info', text: 'Already in the list.' });
if (skipped.length) {
msgs.push({ level: 'error', text: `Skipped items:\n${skipped.map((it) => ` - ${it.id}${it.title ? ` (${it.title})` : ''}`).join('\n')}`
+ '\n\nThese items are either unavailable or not a Project Zomboid item.' });
}
if (added && r.collections.length) {
msgs.push({ level: 'info', action: 'enable-all', text: 'Adding items doesn\'t enable their mods. To enable everything: '
+ 'click Save for next restart, then Fetch mod info while the server is online (it downloads the items and reads '
+ 'their mod IDs), then Enable all, then Save & restart now.' });
}
showMsgs(msgs);
if (added) changed();
return true;
} catch (err) {
showMsgs([{ level: 'error', text: err.message }]);
return false;
} finally {
btn.disabled = false; btn.textContent = 'Add';
}
}
$('#mods-add-btn').addEventListener('click', async () => {
const text = $('#mods-add-input').value.trim();
if (text && await addFromText(text)) $('#mods-add-input').value = '';
});
$('#mods-add-input').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); $('#mods-add-btn').click(); } });
// "WorkshopItems=1;2" and "Mods=\A;\B" lines from a pzserver.ini.
$('#mods-import-btn').addEventListener('click', async () => {
const text = $('#mods-import-text').value;
const items = /^\s*WorkshopItems\s*=(.*)$/mi.exec(text)?.[1] || '';
const mods = /^\s*Mods\s*=(.*)$/mi.exec(text)?.[1] || '';
if (!items.trim() && !mods.trim()) { showMsgs([{ level: 'error', text: 'Paste the WorkshopItems= and Mods= lines.' }]); return; }
for (const m of mods.split(';').map((x) => x.trim().replace(/^\\+/, '')).filter(Boolean)) {
if (!mm.mods.includes(m)) mm.mods.push(m);
}
if (items.trim()) await addFromText(items.replace(/;/g, ' '));
$('#mods-import-text').value = '';
changed();
});
// ---------- saving ----------
async function saveMods(apply) {
if (apply === 'now' && mm.state?.running && !confirm(
'Restart the server now with these mods? Players online get a 60-second warning first; with nobody online it restarts right away.')) return;
showMsgs([]);
try {
const d = await api(`/api/servers/${mm.server.id}/mods`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workshop_ids: mm.workshopIds, mods: mm.mods, auto_update: mm.autoUpdate, apply }),
});
mm.edited = false;
mm.state = d;
renderMods();
refresh();
if (apply === 'now') {
// The container is recreated, so its id changes; follow it by name.
watchForNewContainer();
}
} catch (err) { showMsgs([{ level: 'error', text: err.message }]); }
}
function watchForNewContainer() {
const name = mm.server.container;
const t = setInterval(async () => {
try {
const list = await api('/api/servers');
const s = list.find((x) => x.container === name);
if (s && s.id !== mm.server.id) { mm.server = s; clearInterval(t); }
if (!s || !$('#mods-dialog').open) clearInterval(t);
} catch { clearInterval(t); }
}, 2000);
}
$('#mods-save').addEventListener('click', () => saveMods('later'));
$('#mods-apply').addEventListener('click', () => saveMods('now'));
$('#mods-fetch').addEventListener('click', async () => {
if (mm.edited) { await saveMods('later'); if (mm.edited) return; }
showMsgs([]);
const start = !mm.state?.ready; // also waits for a server that is still starting
try {
await api(`/api/servers/${mm.server.id}/mods/refresh${start ? '?start=true' : ''}`, { method: 'POST' });
if (start) {
showMsgs([{ level: 'info', text: `${mm.state?.running ? 'Waiting for the server to come online.' : 'Starting the server.'} `
+ 'Mod info is fetched automatically once it\'s online. The first start with new mods downloads them first, which '
+ 'can take a while. You can close this window.' }]);
watchForNewContainer(); // starting with saved changes recreates the container under a new id
}
loadMods(false);
} catch (err) { showMsgs([{ level: 'error', text: err.message }]); }
});