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

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
cj
__pycache__/

48
CLAUDE.md Normal file
View file

@ -0,0 +1,48 @@
# Game server manager
## Game art
Server cards show a portrait poster and the new-server game picker shows a wide banner. Both are official
Steam library art, saved into the app (not hotlinked, so the page doesn't depend on Steam and viewers'
browsers don't contact Valve).
Files live in `app/static/art/`:
- `<game>-poster.jpg`: Steam `library_600x900.jpg` (served as 300x450), shown on server cards
- `<game>-header.jpg`: Steam `header.jpg` (460x215), shown in the game picker
`<game>` is the game's key in `GAMES` in `app/app.py` (`valheim`, `zomboid`).
To add art for a new game:
1. Find its Steam app ID: the number in its store URL, `store.steampowered.com/app/<id>/`.
Use the game's app ID, not the dedicated server's (Project Zomboid is 108600, its server is 380870).
2. Download both images:
```sh
id=<steam app id>; game=<GAMES key>
curl -fo app/static/art/$game-poster.jpg https://cdn.cloudflare.steamstatic.com/steam/apps/$id/library_600x900.jpg
curl -fo app/static/art/$game-header.jpg https://cdn.cloudflare.steamstatic.com/steam/apps/$id/header.jpg
```
`library_600x900_2x.jpg` is a sharper poster if ever needed (about 2-4x the size).
3. Add the key to `GAME_ART` in `app/static/app.js`. Games not listed there simply show no image.
4. Deploy with `HOST=root@<server> ./deploy.sh` (the Dockerfile copies all of `static/`).
Current art: Valheim (892970), Project Zomboid (108600). Steam swaps library art for major updates
(Valheim's poster is the "Bog Witch" update art as of 2026-10), so re-download if it looks dated.
## Project Zomboid mod presets
The new-server wizard's Build 42 mod checklist comes from `PRESET_MODS` in `app/zomboid.py`. Each entry
lists its Workshop items and Mod IDs, including required dependencies, in load order.
Don't trust Mod IDs from guides or Workshop descriptions (several don't list them, and B41/B42 versions
differ). Verify by downloading into a running PZ container and reading `list-mods`:
```sh
docker exec <pz container> bash -c '"$STEAMCMDDIR/steamcmd.sh" +force_install_dir "$STEAMAPPDIR" +login anonymous +workshop_download_item 108600 <id> +quit'
docker exec <pz container> list-mods # JSON: each item's mod ids, "require" lists and errors
```
Required Workshop items for a mod are listed under "Required items" on its Workshop page. Last verified
on build 42.21.0, 2026-10-16. Rain Wash (B41 only), "Occupation Based Starting Gear" and "Vehicle Edge
Slide Fix" (no matching Workshop item found) were left out at the user's request.

88
README.md Normal file
View file

@ -0,0 +1,88 @@
# Game server manager
A small web app for running dedicated game servers on your own Linux server or VPS. You can create,
start, stop and configure servers from a browser, see who's playing, stop idle servers automatically and
keep world backups.
Supported games: **Valheim** and **Project Zomboid** (Build 42, with a Workshop mod picker).
## Install
On your server, as root (or with sudo), run:
```sh
curl -fsSL https://git.neilbantoc.dev/pub/game-servers/raw/branch/main/install.sh | sudo bash
```
When it finishes, it prints the web address (`https://<your server's IP>`) and the login password.
The installer:
- checks the machine first (Linux, root, free ports 443 and 8080, RAM, disk space) and stops with a clear
message if something is wrong;
- installs `curl`, `tar`, `iproute2` and Docker if they're missing (Docker via
[get.docker.com](https://get.docker.com));
- runs the manager in a Docker container named `gsm`, with [Caddy](https://caddyserver.com) in front of it
(container `caddy`) for HTTPS. Caddy gets a free Let's Encrypt certificate for your server's IP
address, so you don't need a domain name;
- keeps its files in `/opt/gsm` and game data in `/srv/gameservers`.
### Options
Set these before `bash`, after `sudo`:
```sh
curl -fsSL https://git.neilbantoc.dev/pub/game-servers/raw/branch/main/install.sh | sudo SITE=games.example.com ADMIN_PASSWORD=hunter22 bash
```
| Variable | Meaning |
| --- | --- |
| `SITE` | Address for the web UI: a domain pointing at the server, or its public IP. Default: the server's public IPv4 |
| `ADMIN_PASSWORD` | Web UI password, set on first install. Default: random, printed at the end |
| `GSM_REF` | Branch or tag to install. Default: `main` |
| `SKIP_DOCKER_INSTALL=1` | Stop with an error if Docker is missing instead of installing it |
### Requirements
- A Linux server with a public IPv4 address. It must be x86_64, because the game images are built for it.
- Enough RAM for the games you want: about 1.5 GB per Valheim server, 3 GB or more per Project Zomboid
server.
- Inbound ports open in your provider's firewall:
- TCP 443 for the web UI, and 80 if it's free (redirects to https);
- UDP for each game server: two ports each, from 2456 for Valheim and from 16261 for Project Zomboid.
The installer opens the web ports in `ufw` if it's active. Docker opens the game ports itself.
## Update
Run the install command again. It downloads the latest version and restarts the manager. Your password,
settings, game servers and worlds are kept. Running game servers keep running.
## Change the password
Edit `ADMIN_PASSWORD` in `/opt/gsm/.env`, then run the install command again.
## Uninstall
```sh
docker rm -f gsm caddy
docker rm -f $(docker ps -aq --filter label=gsm.managed=true) # the game servers
rm -rf /opt/gsm
rm -rf /srv/gameservers # worlds and backups: only if you're sure
```
## Security notes
The manager controls Docker on the host (it mounts `/var/run/docker.sock`), which amounts to root access.
Anyone with the web password can create and delete game servers and their worlds, so use a strong
password.
## Development
`app/` is the FastAPI backend and a plain JavaScript frontend (`app/static/`). To deploy a local checkout,
including uncommitted changes, to a server you can SSH into as root:
```sh
HOST=root@<server> ./deploy.sh
```
This copies the code to `/opt/gsm/src` on the server and runs `install.sh` from there.

8
app/Dockerfile Normal file
View file

@ -0,0 +1,8 @@
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN apt-get update && apt-get install -y --no-install-recommends iputils-ping && rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py zomboid.py players.py backups.py ./
COPY static ./static
CMD ["uvicorn", "app:app", "--host", "127.0.0.1", "--port", "8080", "--proxy-headers"]

1299
app/app.py Normal file

File diff suppressed because it is too large Load diff

68
app/backups.py Normal file
View file

@ -0,0 +1,68 @@
"""World backups, stored as zips under DATA_DIR/backups/<game>/<auto|manual>/.
Each zip has a .json sidecar with what the list page shows. Backups live outside the server's own
folder so they survive deleting a server together with its files.
"""
import json
import os
import re
import tempfile
import time
import zipfile
from pathlib import Path
KINDS = ("auto", "manual")
KEEP = 5 # newest backups kept per server and kind
NAME_RE = re.compile(r"^[a-z0-9-]+__\d{8}-\d{6}\.zip$")
class Backups:
def __init__(self, data_dir):
self.root = Path(data_dir) / "backups"
def create(self, game, kind, cname, files, meta):
"""Zip `files` ([(path, name in zip)]) as a new backup and prune old ones. Returns its metadata."""
assert kind in KINDS
folder = self.root / game / kind
folder.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
zpath = folder / f"{cname}__{stamp}.zip"
fd, tmp = tempfile.mkstemp(suffix=".tmp", dir=folder)
try:
with os.fdopen(fd, "wb") as f, zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as z:
for path, arcname in files:
z.write(path, arcname)
os.replace(tmp, zpath) # never list a half-written zip
except BaseException:
os.unlink(tmp)
raise
meta = {**meta, "game": game, "type": kind, "container": cname,
"created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "size": zpath.stat().st_size}
zpath.with_suffix(".json").write_text(json.dumps(meta))
self._prune(folder, cname)
return {**meta, "id": f"{game}/{kind}/{zpath.name}"}
def _prune(self, folder, cname):
zips = sorted(folder.glob(f"{cname}__*.zip"), reverse=True) # names sort by time
for old in zips[KEEP:]:
old.unlink(missing_ok=True)
old.with_suffix(".json").unlink(missing_ok=True)
def list(self):
out = []
for zpath in self.root.glob("*/*/*.zip"):
game, kind = zpath.parent.parent.name, zpath.parent.name
try:
meta = json.loads(zpath.with_suffix(".json").read_text())
except (OSError, ValueError):
meta = {"container": zpath.name.split("__")[0], "size": zpath.stat().st_size}
out.append({**meta, "game": game, "type": kind, "id": f"{game}/{kind}/{zpath.name}"})
return sorted(out, key=lambda b: b["id"].rsplit("__", 1)[-1], reverse=True)
def path(self, game, kind, name):
"""The zip for a backup id, or None if the id isn't a valid existing backup."""
if kind not in KINDS or not re.fullmatch(r"[a-z0-9]+", game) or not NAME_RE.match(name):
return None
p = self.root / game / kind / name
return p if p.is_file() else None

176
app/players.py Normal file
View file

@ -0,0 +1,176 @@
"""Who is connected to a game server: count, names, IP addresses, connection time and ping.
- Count and connection time come from the Steam server query (A2S) on the server's query port,
which is what the game itself reports to the server browser.
- IP addresses come from the host's conntrack table (gsm uses the host network, so it sees the NAT
entries Docker makes for each client's UDP flow to the game port).
- Names: Valheim leaves A2S names empty, so they are read from its "Got character ZDOID" log lines.
- Ping is a plain ICMP echo. Many home routers don't answer it, so it is often unknown.
"""
import calendar
import re
import socket
import struct
import subprocess
import time
from pathlib import Path
A2S_HEADER = b"\xff\xff\xff\xff"
def _a2s(sock, addr, request):
sock.sendto(request, addr)
data = sock.recv(4096)
if data[4:5] == b"A": # challenge: repeat the request with the number the server sent
if request[4:5] == b"U":
request = request[:5] + data[5:9]
else:
request = request + data[5:9]
sock.sendto(request, addr)
data = sock.recv(4096)
return data
def a2s_players(port, host="127.0.0.1", timeout=1.5):
"""[{name, duration}] from A2S_PLAYER, or None if the server doesn't answer."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(timeout)
try:
data = _a2s(s, (host, port), A2S_HEADER + b"U" + A2S_HEADER)
except OSError:
return None
finally:
s.close()
if data[:5] != A2S_HEADER + b"D":
return None
players, pos = [], 6
try:
for _ in range(data[5]):
end = data.index(b"\x00", pos + 1)
name = data[pos + 1:end].decode(errors="replace")
_score, duration = struct.unpack_from("<lf", data, end + 1)
players.append({"name": name, "duration": max(0.0, duration)})
pos = end + 9
except (ValueError, struct.error):
pass # truncated reply: keep the players read so far
return players
# ---------- IP addresses from conntrack ----------
CONNTRACK = Path("/proc/net/nf_conntrack")
_CT_RE = re.compile(r"\budp\s+\d+\s+(\d+)\s+src=(\S+) dst=\S+ sport=(\d+) dport=(\d+)")
_first_seen: dict = {} # (ip, sport, dport) -> time gsm first saw the flow
def udp_flows(port):
"""Live client flows to a UDP port, oldest first: [{ip, since}]."""
try:
text = CONNTRACK.read_text()
except OSError:
return []
now = time.time()
seen, flows = set(), []
for m in _CT_RE.finditer(text):
left, ip, sport, dport = int(m.group(1)), m.group(2), m.group(3), int(m.group(4))
key = (ip, sport, dport)
seen.add(key)
# Game clients send packets constantly, so their entry's timeout stays near the 120 s maximum.
# A flow that has gone quiet for over 30 s belongs to someone who already left.
if dport != port or left < 90 or ip.startswith("127."):
continue
flows.append({"ip": ip, "since": _first_seen.setdefault(key, now)})
for key in [k for k in _first_seen if k not in seen]:
del _first_seen[key]
return sorted(flows, key=lambda f: f["since"])
# ---------- Valheim player names from the log ----------
_VH_CONNECT = re.compile(r"Got connection SteamID (\d+)")
_VH_CLOSE = re.compile(r"Closing socket (\d+)")
_VH_CHARACTER = re.compile(r"Got character ZDOID from (.+?) : (-?\d+):(\d+)")
def _docker_ts(line):
"""(sortable timestamp string, unix time) from a `docker logs --timestamps` line."""
ts = line.split(" ", 1)[0]
sec, _, frac = ts.rstrip("Z").partition(".")
return f"{sec}.{frac.ljust(9, '0')}", calendar.timegm(time.strptime(sec, "%Y-%m-%dT%H:%M:%S"))
class ValheimSessions:
"""Follows a Valheim container's log to know who is connected and their character names."""
def __init__(self):
self.started = None
self.last_ts = ""
self.sessions = [] # [{steam_id, since, name}] in join order
def update(self, c):
started = c.attrs.get("State", {}).get("StartedAt")
if started != self.started: # new container or restarted: read its log from the start
self.started, self.last_ts, self.sessions = started, "", []
since = calendar.timegm(time.strptime(self.last_ts[:19], "%Y-%m-%dT%H:%M:%S")) if self.last_ts else None
raw = c.logs(timestamps=True, since=since) if since else c.logs(timestamps=True)
for line in raw.decode(errors="replace").splitlines():
try:
key, t = _docker_ts(line)
except ValueError:
continue
if key <= self.last_ts:
continue # `since` has 1 s granularity, so skip lines already handled
self.last_ts = key
if m := _VH_CONNECT.search(line):
self.sessions = [s for s in self.sessions if s["steam_id"] != m.group(1)]
self.sessions.append({"steam_id": m.group(1), "since": t, "name": None})
elif m := _VH_CLOSE.search(line):
self.sessions = [s for s in self.sessions if s["steam_id"] != m.group(1)]
elif (m := _VH_CHARACTER.search(line)) and (m.group(2), m.group(3)) != ("0", "0"):
# Logged when a character spawns (0:0 is a death). The first spawn after joining names
# the newest unnamed session; later ones are respawns.
if not any(s["name"] == m.group(1) for s in self.sessions):
for s in reversed(self.sessions):
if s["name"] is None:
s["name"] = m.group(1)
break
return self.sessions
# ---------- ping ----------
def ping_ms(ip, timeout=1):
"""Round trip time in ms, or None when the host doesn't answer ICMP echo."""
try:
out = subprocess.run(["ping", "-n", "-c", "1", "-W", str(timeout), ip],
capture_output=True, text=True, timeout=timeout + 2).stdout
except (OSError, subprocess.TimeoutExpired):
return None
m = re.search(r"time[=<]([\d.]+) ?ms", out)
return round(float(m.group(1))) if m else None
def combine(a2s, flows, sessions, now):
"""Merge the sources into [{name, ip, since}], longest connected first.
A2S is the source of truth for who is online. IPs and log names don't carry a player ID that
A2S shares, so they are matched up by join order, which is exact for one player and almost
always right for more.
"""
if a2s is None:
if sessions is None:
return None
a2s = [{"name": "", "duration": now - s["since"]} for s in sessions]
players = sorted(a2s, key=lambda p: -p["duration"])
flows = flows[-len(players):] if players else [] # the newest flows, in case a stale one lingers
named = [s["name"] for s in sessions] if sessions and len(sessions) == len(players) else []
out = []
for i, p in enumerate(players):
name = p["name"] or (named[i] if i < len(named) else None)
out.append({
"name": name or f"Player {i + 1}",
"ip": flows[i]["ip"] if len(flows) == len(players) else None,
"since": now - p["duration"],
})
return out

5
app/requirements.txt Normal file
View file

@ -0,0 +1,5 @@
fastapi==0.115.*
uvicorn==0.32.*
docker==7.1.*
python-multipart==0.0.*
itsdangerous==2.2.*

681
app/static/app.js Normal file
View file

@ -0,0 +1,681 @@
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();
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-net').textContent = `Network: ↓ ${fmtRate(h.net_rx_rate)} ↑ ${fmtRate(h.net_tx_rate)}`;
}
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' })}`;
}
const STATE_LABEL = { online: 'Online', starting: 'Starting…', exited: 'Stopped', created: 'Stopped', restarting: 'Restarting…' };
function renderServers() {
$('#empty-msg').classList.toggle('hidden', servers.length > 0);
const host = location.hostname;
$('#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 <b>${esc(host)}:${s.port}</b></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 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();
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

301
app/static/index.html Normal file
View file

@ -0,0 +1,301 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Servers</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<!-- Login -->
<section id="login-view" class="hidden">
<form id="login-form" class="card login-card">
<h1>Game Servers</h1>
<input type="password" id="login-password" placeholder="Password" autocomplete="current-password" autofocus required>
<button type="submit" class="primary">Log in</button>
<p class="error" id="login-error"></p>
</form>
</section>
<!-- Dashboard -->
<section id="app-view" class="hidden">
<header>
<div class="brand">
<h1>Game Servers</h1>
<nav class="tabs">
<a href="#servers" data-view="servers">Servers</a>
<a href="#backups" data-view="backups">Backups</a>
</nav>
</div>
<div class="header-actions">
<button class="primary" id="new-server-btn">+ New game server</button>
<button class="ghost" id="logout-btn">Log out</button>
</div>
</header>
<div id="view-servers">
<div class="card" id="resources">
<h2>VPS resources</h2>
<div class="meters">
<div class="meter"><div class="meter-label"><span>CPU</span><span id="m-cpu">–</span></div><div class="bar"><div id="b-cpu"></div></div></div>
<div class="meter"><div class="meter-label"><span>Memory</span><span id="m-mem">–</span></div><div class="bar"><div id="b-mem"></div></div></div>
<div class="meter"><div class="meter-label"><span>Swap</span><span id="m-swap">–</span></div><div class="bar"><div id="b-swap"></div></div></div>
<div class="meter"><div class="meter-label"><span>Disk</span><span id="m-disk">–</span></div><div class="bar"><div id="b-disk"></div></div></div>
</div>
<p class="net" id="m-net"></p>
</div>
<h2 class="section-title">Servers</h2>
<div id="server-list"></div>
<p class="empty hidden" id="empty-msg">No servers yet. Click <b>+ New game server</b> to create one.</p>
</div>
<div id="view-backups" class="hidden">
<div class="row-between section-title">
<h2 style="margin:0">Backups</h2>
<button class="ghost" id="about-backups-btn">About Backups</button>
</div>
<div id="backup-list"></div>
</div>
</section>
<!-- About backups -->
<dialog id="about-backups">
<div class="logs-head"><h2 style="margin:0">About Backups</h2><button class="ghost" id="about-backups-close">Close</button></div>
<h3>What is backed up</h3>
<ul class="about-list">
<li><b>Valheim:</b> the world folder (<code>.db2</code>, <code>.fwl2</code>, <code>.ok</code>, <code>.chunks</code> and <code>.chunk</code> files), or the <code>.db</code> + <code>.fwl</code> pair for older worlds.</li>
<li><b>Project Zomboid:</b> the world save, the player database and the server's settings files.</li>
</ul>
<h3>Automatic backups</h3>
<ul class="about-list">
<li>A server run becomes eligible for a backup once <b>at least one player connects</b>.</li>
<li>If the server starts and nobody connects, no backup is made.</li>
<li>The backup is taken when that run ends: the server is stopped by hand or by auto stop, restarted,
or recreated after a settings change. Deleting a server also backs up an eligible run first.</li>
<li>Backups are taken after the server has stopped, so they hold the world as it was saved on shutdown.</li>
</ul>
<h3>Manual backups</h3>
<ul class="about-list">
<li>Made every time you use <b>Download</b> in a server's Manage panel: the zip you download is also saved here.</li>
<li>While the server is running this is its last autosave (Valheim saves about every 30 minutes). Stop the
server first for an up-to-the-minute copy.</li>
</ul>
<h3>Retention</h3>
<ul class="about-list">
<li>The newest <b>5 automatic</b> and newest <b>5 manual</b> backups are kept for each server. Older ones are
deleted when a new backup is made.</li>
<li>Backups are stored on the VPS in <code>/srv/gameservers/backups/&lt;game&gt;/&lt;auto|manual&gt;/</code>,
outside the server's own folder, so they are kept even if the server and its world files are deleted.</li>
</ul>
</dialog>
<!-- Wizard -->
<dialog id="wizard">
<form id="wizard-form" method="dialog">
<div class="wiz-step" data-step="1">
<h2>New game server</h2>
<p class="muted">Choose a game</p>
<div id="game-list" class="game-list"></div>
</div>
<div class="wiz-step hidden" data-step="2">
<h2 id="wiz-game-title">New server</h2>
<label>Server name <span class="muted">(shown in the server browser)</span>
<input name="server_name" required maxlength="60">
</label>
<label>Password <span class="muted" id="password-help"></span>
<input name="password">
</label>
<label>Port <span class="muted">(UDP; this port and the next one are used)</span>
<input name="port" type="number" min="1024" max="65534" required>
</label>
<div class="game-fields" data-game="valheim">
<label>World name <span class="muted">(letters, numbers, underscores)</span>
<input name="world_name" required pattern="[A-Za-z0-9_]{1,40}">
</label>
<fieldset>
<legend>World</legend>
<label class="radio"><input type="radio" name="world_source" value="new" checked> Create a new world</label>
<label class="radio"><input type="radio" name="world_source" value="upload"> Upload an existing world</label>
<div id="upload-fields" class="hidden">
<p class="muted small">Easiest: <b>zip your whole world folder</b> and upload the zip. Or select
<b>every file</b> inside the folder: the <code>_main.N.db2</code>, <code>.fwl2</code>, <code>.ok</code> and
<code>.chunks</code> files <i>and</i> all the <code>.chunk</code> files. Valheim throws away an incomplete
world and starts a new one. Older worlds saved as a <code>.db</code> + <code>.fwl</code> pair also work.
On Windows, worlds are in <code>%USERPROFILE%\AppData\LocalLow\IronGate\Valheim\worlds_local</code>.</p>
<label>World files <input type="file" name="world_files" multiple></label>
</div>
</fieldset>
</div>
<div class="game-fields" data-game="zomboid">
<label>Admin password <span class="muted">(for the in-game <code>admin</code> account; at least 5 characters)</span>
<input name="admin_password" required minlength="5">
</label>
<label>Game version
<select name="branch">
<option value="public">Build 42 (current stable)</option>
<option value="legacy41">Build 41 (legacy)</option>
</select>
</label>
<label>Memory (MB) <span class="muted">(Java heap; Build 42 with mods wants 4096 or more)</span>
<input name="memory_mb" type="number" min="1024" max="65536" step="256" value="4096" required>
<span class="field-help" id="memory-help"></span>
</label>
<label>Max players
<input name="max_players" type="number" min="1" max="100" value="8" required>
</label>
<fieldset id="preset-mods-fieldset">
<legend>Mods <span class="muted small">(Build 42)</span></legend>
<div class="row-between small"><span class="muted">Players get these from the Workshop when they join.</span>
<span><button type="button" class="ghost small" id="preset-all">All</button> <button type="button" class="ghost small" id="preset-none">None</button></span></div>
<div id="preset-mods" class="preset-mods"></div>
</fieldset>
<p class="muted small hidden" id="preset-mods-b41">The mod checklist is for Build 42. Add Build 41 mods after creating the server.</p>
<p class="muted small">Add or change mods later from <b>Manage → Mods</b>. The first start
downloads the game (about 7 GB) plus any mods and can take 10+ minutes.</p>
</div>
</div>
<div class="wiz-step hidden" data-step="3">
<h2>Review</h2>
<dl id="review"></dl>
<p class="muted small">The first start downloads the Valheim server (about 1 GB), so it can take a few minutes to come online.</p>
</div>
<p class="error" id="wiz-error"></p>
<div class="wiz-actions">
<button type="button" class="ghost" id="wiz-cancel">Cancel</button>
<span class="spacer"></span>
<button type="button" class="ghost hidden" id="wiz-back">Back</button>
<button type="button" class="primary hidden" id="wiz-next">Next</button>
<button type="button" class="primary hidden" id="wiz-create">Create server</button>
</div>
</form>
</dialog>
<!-- Manage (contents depend on the server's game type) -->
<dialog id="manage-dialog">
<div class="logs-head">
<div><h2 id="manage-title" style="margin:0">Manage</h2><div class="muted small" id="manage-sub"></div></div>
<button class="ghost" id="manage-close">Close</button>
</div>
<div class="manage-section">
<h3>Players</h3>
<div id="players-body"></div>
</div>
<form class="manage-section" id="autostop-form">
<h3>Server Auto Stop</h3>
<label class="radio"><input type="checkbox" id="autostop-enabled"> Auto stop server when no players are connected</label>
<label>Auto stop timeout (mins)
<input type="number" id="autostop-minutes" min="5" max="1440" step="5" value="15" required>
</label>
<p class="muted small" id="autostop-status"></p>
<p class="error" id="autostop-error"></p>
<div class="row-end"><button type="submit" class="primary" id="autostop-save">Save</button></div>
</form>
<form id="settings-form" class="manage-section">
<h3>Settings</h3>
<div id="settings-fields"></div>
<p class="muted small hidden" id="settings-restart-note">Saving restarts the server, which disconnects anyone playing.</p>
<p class="error" id="settings-error"></p>
<div class="row-end"><span class="tip" id="settings-save-tip"><button type="submit" class="primary" id="settings-save">Save settings</button></span></div>
</form>
<div class="manage-section hidden" id="mods-section">
<h3>Mods</h3>
<div class="row-between"><span class="muted small" id="mods-summary"></span><button class="ghost" id="open-mods">Manage mods</button></div>
</div>
<div class="manage-section hidden" id="world-section">
<h3>World</h3>
<div class="row-between">
<span class="muted small">Download the saved world as a zip; a copy is also kept in <b>Backups</b>. While the server
is running this is the last autosave; stop the server first for an up-to-the-minute copy.</span>
<a class="button ghost" id="world-download" download>Download</a>
</div>
</div>
<div class="manage-section">
<h3>Logs</h3>
<div class="row-between"><span class="muted small">Live, color-coded output from the game server.</span><button class="ghost" id="manage-logs">View logs</button></div>
</div>
<div class="manage-section danger-zone">
<h3>Delete server</h3>
<label class="radio"><input type="checkbox" id="delete-data"> Also delete the world files (cannot be undone)</label>
<div class="row-end"><span class="tip" id="manage-delete-tip"><button class="danger" id="manage-delete">Delete server</button></span></div>
</div>
</dialog>
<!-- Mod manager (Project Zomboid) -->
<dialog id="mods-dialog" class="wide">
<div class="logs-head">
<div><h2 id="mods-title" style="margin:0">Mods</h2><span class="muted small" id="mods-status"></span></div>
<button class="ghost" id="mods-close">Close</button>
</div>
<div class="mods-add">
<input id="mods-add-input" placeholder="Paste a Steam Workshop link or ID, or a collection link">
<button class="primary" id="mods-add-btn">Add</button>
</div>
<details class="mods-presets hidden" id="mods-presets" open>
<summary class="small"><b>Recommended mods</b> <span class="muted">(Build 42; ticking adds the Workshop items and enables their mods)</span></summary>
<div class="row-between small presets-bar"><span class="muted" id="mods-presets-count"></span>
<button type="button" class="ghost small" id="mods-presets-all">Add all</button></div>
<div id="mods-presets-list" class="preset-mods"></div>
</details>
<details class="mods-import">
<summary class="muted small">Import from another server's config</summary>
<textarea id="mods-import-text" rows="3" placeholder="WorkshopItems=2169435993;2392709985&#10;Mods=\ModOptions;\tsarslib"></textarea>
<div class="row-end"><button class="ghost small" id="mods-import-btn">Import</button></div>
</details>
<div id="mods-messages" class="msgs"></div>
<div class="mods-grid">
<div>
<h3>Workshop items <span class="muted small" id="items-count"></span></h3>
<div id="mods-items" class="mods-list"></div>
</div>
<div>
<div class="row-between"><h3>Enabled mods &amp; load order</h3>
<span><button class="ghost small" id="mods-enable-all" title="Enable every mod in the downloaded workshop items, then auto-sort">Enable all</button>
<button class="ghost small" id="mods-sort">Auto-sort</button></span></div>
<p class="muted small">Mods load top to bottom. Auto-sort puts each mod after the ones it requires.</p>
<ol id="mods-order" class="mods-list mods-order"></ol>
</div>
</div>
<div id="mods-issues-section" class="hidden">
<h3>Issues</h3>
<ul id="mods-issues" class="mods-issues"></ul>
</div>
<div class="mods-footer">
<label class="radio"><input type="checkbox" id="mods-auto-update"> Auto-update mods (checks every 15 min; warns players 5 min before restarting)</label>
<span class="spacer"></span>
<button class="ghost" id="mods-fetch" title="Download new items into the running server and read their mod IDs">Fetch mod info</button>
<button class="ghost" id="mods-save">Save for next restart</button>
<button class="primary" id="mods-apply">Save &amp; restart now</button>
</div>
</dialog>
<!-- Logs -->
<dialog id="logs-dialog" class="wide">
<div class="logs-head">
<div><h2 id="logs-title" style="margin:0">Logs</h2><span class="logs-status" id="logs-status"></span></div>
<button class="ghost" id="logs-close">Close</button>
</div>
<pre id="logs-body"></pre>
</dialog>
<script src="/static/app.js"></script>
<script src="/static/mods.js"></script>
</body>
</html>

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 }]); }
});

204
app/static/style.css Normal file
View file

@ -0,0 +1,204 @@
:root {
--bg: #0f1216;
--card: #181d23;
--border: #2a313a;
--text: #e6e9ed;
--muted: #8b95a1;
--accent: #e0a040;
--accent-text: #1a1206;
--ok: #4cc38a;
--warn: #e0a040;
--bad: #e5534b;
--bar: #262d36;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
}
section { max-width: 960px; margin: 0 auto; padding: 16px; }
h1 { font-size: 22px; margin: 0; }
h2 { font-size: 17px; margin: 0 0 12px; }
.hidden { display: none !important; }
.muted { color: var(--muted); font-weight: normal; }
.small { font-size: 13px; }
.error { color: var(--bad); min-height: 1em; margin: 8px 0 0; }
code { font-size: 12px; word-break: break-all; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px; }
button, a.button {
font: inherit; border-radius: 8px; padding: 8px 14px; cursor: pointer;
border: 1px solid var(--border); background: transparent; color: var(--text);
}
a.button { text-decoration: none; white-space: nowrap; display: inline-block; }
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 600; }
button.danger { color: var(--bad); }
button:disabled { opacity: .5; cursor: default; }
button.small { padding: 4px 10px; font-size: 13px; }
input:not([type=radio]):not([type=checkbox]):not([type=file]), select, textarea {
width: 100%; font: inherit; padding: 9px 11px; margin-top: 4px;
background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 8px;
}
input[type=file] { display: block; margin-top: 4px; max-width: 100%; color: var(--muted); }
label { display: block; margin-bottom: 14px; font-weight: 500; }
label.radio { display: flex; gap: 8px; align-items: center; font-weight: normal; margin-bottom: 8px; }
fieldset { border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin: 0; }
legend { padding: 0 6px; color: var(--muted); }
/* login */
#login-view { min-height: 100vh; display: flex; align-items: center; justify-content: center; }
.login-card { width: 100%; max-width: 340px; display: flex; flex-direction: column; gap: 12px; }
/* header */
header { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
.header-actions { display: flex; gap: 8px; }
.brand { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; }
.tabs { display: flex; gap: 4px; }
.tabs a { color: var(--muted); text-decoration: none; padding: 6px 12px; border-radius: 8px; font-weight: 500; }
.tabs a:hover { color: var(--text); }
.tabs a.active { color: var(--text); background: var(--card); box-shadow: 0 0 0 1px var(--border) inset; }
/* backups */
#backup-list { display: grid; gap: 12px; }
.backup-game h3 { font-size: 16px; margin: 0 0 4px; }
.backup-kind { margin-top: 12px; }
.backup-kind h4 { font-size: 14px; margin: 0 0 6px; }
.backups-table { width: 100%; border-collapse: collapse; font-size: 13px; font-variant-numeric: tabular-nums; }
.backups-table th { text-align: left; color: var(--muted); font-weight: normal; padding: 0 8px 6px 0; }
.backups-table td { padding: 6px 8px 6px 0; border-top: 1px solid var(--border); vertical-align: middle; }
.backups-table a.button.small { padding: 4px 10px; font-size: 13px; }
#about-backups h3 { font-size: 15px; margin: 16px 0 6px; }
.about-list { margin: 0; padding-left: 20px; font-size: 14px; }
.about-list li { margin: 4px 0; }
a { color: var(--accent); }
/* resources */
.meters { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 14px; }
.meter-label { display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 4px; }
.meter-label span:last-child { color: var(--muted); font-variant-numeric: tabular-nums; }
.bar { height: 8px; background: var(--bar); border-radius: 4px; overflow: hidden; }
.bar > div { height: 100%; width: 0; background: var(--ok); transition: width .5s, background .5s; }
.net { margin: 12px 0 0; font-size: 13px; color: var(--muted); }
.section-title { margin: 24px 0 12px; }
.empty { color: var(--muted); text-align: center; padding: 24px; }
/* server cards */
#server-list { display: grid; gap: 12px; }
.server { display: flex; gap: 14px; align-items: flex-start; }
.server-body { display: grid; gap: 12px; flex: 1; min-width: 0; }
.server-art { width: 72px; aspect-ratio: 2 / 3; object-fit: cover; border-radius: 6px; flex: none; background: var(--bar); }
@media (max-width: 520px) { .server-art { width: 52px; } }
.server-top { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: flex-start; }
.server-name { font-weight: 600; font-size: 16px; }
.server-meta { color: var(--muted); font-size: 13px; }
.badge { display: inline-block; font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid currentColor; margin-left: 6px; vertical-align: 2px; }
.badge.online { color: var(--ok); }
.badge.starting { color: var(--warn); }
.badge.stopped { color: var(--muted); }
.server-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; font-size: 13px; }
.server-stats .stat-val { color: var(--muted); font-variant-numeric: tabular-nums; }
.server-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.tip { display: inline-flex; }
.tip button:disabled { pointer-events: none; }
.server-players { font-size: 13px; color: var(--ok); margin-top: 2px; }
.server-players.none { color: var(--muted); }
.server-last-online { font-size: 13px; color: var(--muted); margin-top: 2px; }
.players-table { width: 100%; border-collapse: collapse; font-size: 13px; font-variant-numeric: tabular-nums; }
.players-table th { text-align: left; color: var(--muted); font-weight: normal; padding: 0 8px 6px 0; }
.players-table td { padding: 6px 8px 6px 0; border-top: 1px solid var(--border); }
.players-table td:first-child { word-break: break-all; }
/* dialogs */
dialog {
background: var(--card); color: var(--text); border: 1px solid var(--border); border-radius: 12px;
padding: 20px; width: min(520px, calc(100vw - 32px)); max-height: calc(100vh - 32px);
}
dialog.wide { width: 95vw; max-width: 95vw; }
#mods-dialog.wide { width: min(1200px, 95vw); }
dialog::backdrop { background: rgba(0,0,0,.6); }
.wiz-actions { display: flex; gap: 8px; margin-top: 16px; }
.spacer { flex: 1; }
.game-list { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.game-option { text-align: left; padding: 0; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; }
.game-option:hover { border-color: var(--muted); }
.game-option-art { width: 100%; aspect-ratio: 460 / 215; object-fit: cover; display: block; background: var(--bar); }
.game-option-text { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; }
.game-option.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
.preset-mods { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0 12px; margin-top: 10px; }
.preset-mods label.radio { margin-bottom: 6px; align-items: flex-start; }
.preset-mods input { margin-top: 4px; }
.preset-meta { display: block; font-size: 12px; }
.preset-include { display: block; font-size: 12px; }
.presets-bar { margin-top: 8px; }
#review { display: grid; grid-template-columns: auto 1fr; gap: 6px 16px; margin: 0; }
#review dt { color: var(--muted); }
#review dd { margin: 0; word-break: break-all; }
.logs-head { display: flex; justify-content: space-between; align-items: center; }
#logs-body {
background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 10px;
font-size: 12px; height: 75vh; overflow: auto; margin-top: 12px; white-space: pre-wrap; word-break: break-all;
}
/* manage dialog */
.manage-section { border-top: 1px solid var(--border); margin-top: 16px; padding-top: 14px; }
.manage-section h3 { font-size: 15px; margin: 0 0 10px; }
.row-end { display: flex; justify-content: flex-end; }
.row-between { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.danger-zone h3 { color: var(--bad); }
.field-help { display: block; font-size: 12px; margin-top: 4px; }
.server-actions .manage-btn { margin-left: 6px; }
/* log viewer */
.logs-status { font-size: 12px; color: var(--muted); }
.logs-status.live { color: var(--ok); }
.logs-status.live::before { content: "● "; }
#logs-body { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.4; }
.log-error { color: #ff7b72; }
.log-warn { color: #e3b341; }
.log-info { color: #79c0ff; }
.log-debug { color: var(--muted); }
/* mod manager */
.mods-add { display: flex; gap: 8px; margin-top: 14px; }
.mods-add input { margin-top: 0 !important; }
.mods-import { margin-top: 8px; }
.mods-presets { margin-top: 10px; border: 1px solid var(--border); border-radius: 8px; padding: 8px 12px; }
.mods-presets summary { cursor: pointer; }
.mods-import textarea { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; margin: 6px 0; }
.mods-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 8px; }
@media (max-width: 760px) { .mods-grid { grid-template-columns: 1fr; } }
.mods-grid h3, #mods-issues-section h3 { font-size: 15px; margin: 8px 0; }
.mods-list { max-height: 45vh; overflow: auto; border: 1px solid var(--border); border-radius: 8px; padding: 8px; margin: 0; }
.mod-item { border-bottom: 1px solid var(--border); padding: 8px 0; }
.mod-item:last-child { border-bottom: 0; }
.mod-item-head { display: flex; gap: 10px; align-items: center; margin-bottom: 6px; }
.mod-item-head img { width: 48px; height: 48px; object-fit: cover; border-radius: 6px; flex: none; }
.mod-item-title { flex: 1; min-width: 0; }
.mod-item-title a { color: var(--text); font-weight: 600; text-decoration: none; }
.mod-item-title a:hover { text-decoration: underline; }
.mod-row { margin: 4px 0 4px 6px; align-items: flex-start; }
.mod-row code, .mods-order code { color: var(--muted); }
.tag { display: inline-block; font-size: 11px; padding: 0 6px; border: 1px solid var(--border); border-radius: 999px; color: var(--muted); margin-left: 4px; }
.tag-bad { color: var(--bad); border-color: var(--bad); }
.mods-order { padding-left: 32px; }
.mods-order li { padding: 4px 0; border-bottom: 1px solid var(--border); }
.mods-order li:last-child { border-bottom: 0; }
.mods-order li { display: list-item; }
.mods-order li > .order-name { display: inline-block; max-width: calc(100% - 110px); word-break: break-all; }
.order-btns { float: right; display: inline-flex; gap: 4px; }
.mods-issues { margin: 0; padding-left: 20px; font-size: 13px; max-height: 25vh; overflow: auto; }
.mods-issues li { margin: 4px 0; }
.issue-error { color: var(--bad); }
.issue-warning { color: var(--warn); }
.msgs { display: grid; gap: 6px; margin-top: 8px; }
.msg { font-size: 13px; white-space: pre-line; border-left: 3px solid currentColor; padding: 6px 10px; border-radius: 4px; background: var(--bg); }
.msg-info { color: #79c0ff; }
.msg-success { color: var(--ok); }
.msg-warning { color: var(--warn); }
.msg-error { color: var(--bad); }
.msg-actions { margin-top: 6px; }
.mods-footer { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 14px; border-top: 1px solid var(--border); padding-top: 12px; }
.mods-footer label { margin: 0; font-size: 13px; }

238
app/zomboid.py Normal file
View file

@ -0,0 +1,238 @@
"""Project Zomboid support: container settings, Steam Workshop lookups and mod info.
Uses the ghcr.io/gameserver-images/project-zomboid image, which is configured entirely through
environment variables (INI_<Key> for pzserver.ini, WORKSHOP_IDS, MEMORY, ...). It downloads workshop
items itself, adds mod maps to Map= and logs "Warning:"/"Error:" lines about mod problems.
"""
import json
import re
import time
import urllib.parse
import urllib.request
IMAGE = "ghcr.io/gameserver-images/project-zomboid:1"
WORKSHOP_APP_ID = 108600 # Project Zomboid's Steam app (the dedicated server is 380870)
BRANCHES = {"public": "Build 42", "legacy41": "Build 41"}
SERVERNAME = "pzserver"
MEMORY_OVERHEAD_MB = 768 # JVM and native memory on top of the Java heap
MOD_ID_RE = re.compile(r"^[^;\\\r\n]{1,100}$")
STEAM_API = "https://api.steampowered.com/ISteamRemoteStorage"
# Mods offered as checkboxes when creating a Build 42 server. Workshop and mod IDs were checked with
# `list-mods` on build 42.21.0 (2026-10-16). Each entry carries its required items, in load order;
# "main" names the entry's own items (the rest are dependencies) for its "last updated" date;
# "includes" names those dependencies for the checklist.
PRESET_MODS = [
{"key": "common_sense", "name": "Common Sense", "note": "B42.20+ update",
"items": ["3750253491"], "mods": ["VB_CommonSense"]},
{"key": "better_sorting", "name": "Better Sorting",
"items": ["2313387159"], "mods": ["BetterSortCC"]},
{"key": "proximity_inventory", "name": "Proximity Inventory",
"items": ["2847184718"], "mods": ["ProximityInventory"]},
{"key": "has_been_read", "name": "Has Been Read",
"items": ["2544353492"], "mods": ["P4HasBeenRead"]},
{"key": "skill_recovery_journal", "name": "Skill Recovery Journal",
"includes": ["errorMagnifier", "Mod Update and Alert System"],
"items": ["3077900375", "2896041179", "2503622437"], "main": ["2503622437"],
"mods": ["ChuckleberryFinnAlertSystem", "errorMagnifier", "SkillRecoveryJournal"]},
{"key": "clean_ui", "name": "CleanUI + Clean HotBar", "includes": ["NeatUI Framework"],
"items": ["3508537032", "3437629766", "3461263912"], "main": ["3437629766", "3461263912"], "mods": ["NeatUI_Framework", "CleanUI", "CleanHotBar"]},
{"key": "better_auto_mechanics", "name": "Better Auto Mechanics",
"items": ["3635856965"], "mods": ["better-auto-mechanics"]},
{"key": "combat_text", "name": "Combat Text",
"items": ["2286124931"], "mods": ["CombatText"]},
{"key": "kill_count", "name": "KillCount",
"items": ["2553809727"], "mods": ["KillCount"]},
{"key": "map_legend_ui", "name": "Map Legend UI",
"items": ["2710167561"], "mods": ["MapLegendUI"]},
]
PRESET_BRANCH = "public" # the preset is Build 42 only
def preset_selection(keys):
"""(workshop_ids, mods) for the chosen preset keys, without duplicates, in load order."""
chosen = [m for m in PRESET_MODS if m["key"] in set(keys)]
if len(chosen) != len(set(keys)):
raise ValueError("Unknown mod in the selection")
items = list(dict.fromkeys(i for m in chosen for i in m["items"]))
mods = list(dict.fromkeys(i for m in chosen for i in m["mods"]))
return items, mods
_presets_cache = {"t": 0, "data": None}
def presets_with_updates():
"""PRESET_MODS plus "updated" (unix time of the newest main item's last Workshop update).
Looked up on Steam at most once an hour; without Steam the list is returned without dates.
"""
if _presets_cache["data"] and time.time() - _presets_cache["t"] < 3600:
return _presets_cache["data"]
try:
details = workshop_details([i for m in PRESET_MODS for i in m["items"]])
except Exception:
return PRESET_MODS
data = []
for m in PRESET_MODS:
times = [details.get(i, {}).get("updated") for i in m.get("main", m["items"])]
data.append({**m, "updated": max((t for t in times if t), default=None)})
_presets_cache.update(t=time.time(), data=data)
return data
def container_env(cfg):
"""Environment for the image from a server's stored config."""
mods = cfg.get("mods", [])
if cfg.get("branch", "public") != "legacy41":
mods = ["\\" + m for m in mods] # Build 42 writes mod IDs with a backslash in front
return {
"SERVERNAME": SERVERNAME,
"GAME_BRANCH": cfg.get("branch", "public"),
"ADMINPASSWORD": cfg["admin_password"],
"INI_PublicName": cfg["server_name"],
"INI_Public": "true",
"INI_Password": cfg.get("password", ""),
"INI_MaxPlayers": str(cfg.get("max_players", 8)),
"INI_BackupsOnVersionChange": "true",
"PORT": str(cfg["port"]),
"UDPPORT": str(cfg["port"] + 1),
"MEMORY": f"{cfg['memory_mb']}m",
# Always set, even when empty: the image keeps a removed variable's last value in the ini.
"WORKSHOP_IDS": ";".join(cfg.get("workshop_ids", [])),
"INI_Mods": ";".join(mods),
"MOD_UPDATE_CHECK": "15m" if cfg.get("auto_update", True) else "",
"TZ": "UTC",
}
# ---------- Steam Workshop ----------
def parse_workshop_ids(text):
"""Workshop IDs from links (…?id=123) and bare numbers, in order, without duplicates."""
ids = re.findall(r"(?<!\d)(\d{6,12})(?!\d)", text or "")
return list(dict.fromkeys(ids))
def _steam_post(method, params):
data = urllib.parse.urlencode(params).encode()
with urllib.request.urlopen(f"{STEAM_API}/{method}/v1/", data=data, timeout=20) as r:
return json.load(r)["response"]
def collection_children(ids):
"""{collection id: [child ids]} for the IDs that are collections."""
if not ids:
return {}
params = {"collectioncount": len(ids), **{f"publishedfileids[{i}]": x for i, x in enumerate(ids)}}
out = {}
for d in _steam_post("GetCollectionDetails", params).get("collectiondetails", []):
children = [c["publishedfileid"] for c in d.get("children", []) if c.get("filetype") == 0]
if d.get("result") == 1 and children:
out[d["publishedfileid"]] = children
return out
def workshop_details(ids):
"""{id: {...}} with title, preview image, size and update time of workshop items."""
out = {}
for start in range(0, len(ids), 100):
batch = ids[start:start + 100]
params = {"itemcount": len(batch), **{f"publishedfileids[{i}]": x for i, x in enumerate(batch)}}
for d in _steam_post("GetPublishedFileDetails", params).get("publishedfiledetails", []):
ok = d.get("result") == 1
out[d["publishedfileid"]] = {
"id": d["publishedfileid"],
"available": ok,
"title": d.get("title") if ok else None,
"preview": d.get("preview_url") if ok else None,
"size": int(d.get("file_size") or 0) if ok else 0,
"updated": d.get("time_updated") if ok else None,
"zomboid": ok and d.get("consumer_app_id") == WORKSHOP_APP_ID,
}
return out
def lookup(text):
"""Resolve pasted links/IDs: collections are expanded into their items."""
ids = parse_workshop_ids(text)
if not ids:
raise ValueError("No workshop IDs found. Paste a Steam Workshop link or the number from it.")
collections = collection_children(ids)
items = []
for i in ids:
items.extend(collections.get(i, [i]))
items = list(dict.fromkeys(items))
details = workshop_details(items)
coll_titles = workshop_details(list(collections)) if collections else {}
return {
"items": [details.get(i, {"id": i, "available": False, "zomboid": False}) for i in items],
"collections": [{"id": c, "title": coll_titles.get(c, {}).get("title"), "count": len(ch)}
for c, ch in collections.items()],
}
# ---------- mod info from the running container ----------
def download_command(ids):
"""Shell command that downloads workshop items into the server's game volume while it runs."""
items = " ".join(f"+workshop_download_item {WORKSHOP_APP_ID} {int(i)}" for i in ids)
return ["bash", "-c", f'"$STEAMCMDDIR/steamcmd.sh" +force_install_dir "$STEAMAPPDIR" '
f'+login anonymous {items} +quit']
def parse_list_mods(raw):
"""Keep what the mod manager needs from `list-mods` output (format 2)."""
data = json.loads(raw)
items = []
for it in data.get("items", []):
items.append({
"id": it["id"],
"title": it.get("title"),
"available": it.get("available", True),
"downloaded": it.get("downloaded", False),
"size": it.get("size"),
"updated": it.get("updated"),
"mods": [{
"id": m.get("id"),
"name": m.get("name"),
"require": m.get("require", []),
"loadAfter": m.get("loadModAfter", []),
"loadBefore": m.get("loadModBefore", []),
"incompatible": m.get("incompatible", []),
"maps": m.get("maps", []),
"error": m.get("error"),
"hasSandbox": bool(m.get("sandbox")),
} for m in it.get("mods", []) if m.get("id")],
})
return {"gameVersion": data.get("gameVersion"), "items": items, "serverMap": data.get("server", {}).get("map", [])}
def parse_issues(log_text, limit=40):
"""The image's "Warning: ..." and "Error: ..." lines (with their indented continuation lines)."""
issues = []
current = None
for line in log_text.splitlines():
m = re.match(r"^(Warning|Error): (.*)", line)
if m:
current = {"level": m.group(1).lower(), "text": m.group(2)}
issues.append(current)
elif current and line.startswith((" ", "\t")) and line.strip():
current["text"] += "\n" + line.strip()
else:
current = None
# Repeated starts log the same warnings again; keep the latest of each.
seen, unique = set(), []
for i in reversed(issues):
if i["text"] not in seen:
seen.add(i["text"])
unique.append(i)
return list(reversed(unique))[-limit:]
def player_count(log_text):
"""Players online from the latest reply to the `players` console command, or None."""
found = re.findall(r"Players connected \((\d+)\)", log_text)
return int(found[-1]) if found else None

10
caddy/Caddyfile Normal file
View file

@ -0,0 +1,10 @@
# HTTPS for the bare IP via Let's Encrypt short-lived IP certificates.
# install.sh fills in the site address below (the server's public IP, or SITE).
__SITE__ {
tls {
issuer acme {
profile shortlived
}
}
reverse_proxy 127.0.0.1:8080
}

10
deploy.sh Executable file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Deploy this checkout (including uncommitted changes) to a server over SSH:
# HOST=root@<server> ./deploy.sh
# Copies the code to /opt/gsm/src on the server and runs install.sh there. SITE=<ip or domain> is passed on if set.
set -euo pipefail
[ -n "${HOST:-}" ] || { echo "usage: HOST=root@<server> $0" >&2; exit 1; }
cd "$(dirname "$0")"
tar -czf - --exclude=__pycache__ app caddy install.sh |
ssh "$HOST" 'rm -rf /opt/gsm/src && mkdir -p /opt/gsm/src && tar -xzf - -C /opt/gsm/src'
ssh "$HOST" "${SITE:+SITE=$(printf %q "$SITE") }GSM_SRC=/opt/gsm/src bash /opt/gsm/src/install.sh"

173
install.sh Executable file
View file

@ -0,0 +1,173 @@
#!/usr/bin/env bash
# Install or update the game server manager on this machine.
#
# curl -fsSL https://git.neilbantoc.dev/pub/game-servers/raw/branch/main/install.sh | sudo bash
#
# Settings (environment variables, all optional):
# SITE address to serve the web UI on: a domain pointing here, or this machine's public IP.
# Default: the existing install's address, otherwise this machine's public IPv4.
# ADMIN_PASSWORD web UI password, used on first install only. Default: a random one, printed at the end.
# GSM_REPO repository to install from (default below); GSM_REF the branch or tag (default main).
# GSM_SRC install from this local checkout instead of downloading (deploy.sh uses this).
# SKIP_DOCKER_INSTALL=1 fail instead of installing Docker when it's missing.
set -euo pipefail
GSM_REPO=${GSM_REPO:-https://git.neilbantoc.dev/pub/game-servers}
GSM_REF=${GSM_REF:-main}
DIR=/opt/gsm
DATA=/srv/gameservers
say() { printf '\033[1m==> %s\033[0m\n' "$*"; }
warn() { printf '\033[33mwarning:\033[0m %s\n' "$*" >&2; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }
random() { local s; s=$(head -c 4096 /dev/urandom | LC_ALL=C tr -dc "$1"); printf %s "${s:0:$2}"; }
# ---------- preflight ----------
say "Checking this machine"
[ "$(uname -s)" = Linux ] || die "this installer only supports Linux"
[ "$(id -u)" -eq 0 ] || die "run as root, e.g. curl -fsSL <url> | sudo bash"
case "$(uname -m)" in
x86_64|amd64) ;;
*) warn "this is a $(uname -m) machine. The manager will run, but the game server images are built for x86_64, so games may not start." ;;
esac
mem_mb=$(awk '/^MemTotal:/ {print int($2 / 1024)}' /proc/meminfo)
[ "$mem_mb" -ge 3500 ] || warn "only ${mem_mb} MB of RAM. One Valheim server needs about 1.5 GB and Project Zomboid needs 3 GB or more."
mkdir -p "$DATA"
disk_gb=$(df -Pk "$DATA" | awk 'NR == 2 {print int($4 / 1048576)}')
[ "$disk_gb" -ge 10 ] || warn "only ${disk_gb} GB free in $DATA. Each game server needs a few GB, plus room for backups."
pkg_install() {
if have apt-get; then DEBIAN_FRONTEND=noninteractive apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "$@" >/dev/null
elif have dnf; then dnf install -y -q "$@"
elif have yum; then yum install -y -q "$@"
else die "please install: $*"
fi
}
missing=()
have curl || missing+=(curl)
have tar || missing+=(tar)
have ss || missing+=(iproute2)
if [ ${#missing[@]} -gt 0 ]; then
say "Installing ${missing[*]}"
pkg_install "${missing[@]}"
fi
# Docker
if ! have docker; then
[ "${SKIP_DOCKER_INSTALL:-}" = 1 ] && die "Docker is not installed (see https://docs.docker.com/engine/install/)"
say "Installing Docker (get.docker.com)"
curl -fsSL https://get.docker.com | sh >/dev/null
fi
if ! docker info >/dev/null 2>&1; then
have systemctl && systemctl enable --now docker >/dev/null 2>&1 || true
docker info >/dev/null 2>&1 || die "Docker is installed but not running (try: systemctl start docker)"
fi
# Containers named gsm and caddy are ours if they run the gsm image / mount our Caddyfile.
exists() { docker inspect "$1" >/dev/null 2>&1; }
ours_gsm() { [ "$(docker inspect -f '{{.Config.Image}}' gsm 2>/dev/null)" = gsm ]; }
ours_caddy() { docker inspect -f '{{range .Mounts}}{{.Source}} {{end}}' caddy 2>/dev/null | grep -q "$DIR/Caddyfile"; }
exists gsm && ! ours_gsm && die "a container named 'gsm' already exists and isn't this app. Rename or remove it first."
exists caddy && ! ours_caddy && die "a container named 'caddy' already exists and isn't this app's. Rename or remove it first."
port_used() { ss -tlnH "sport = :$1" | grep -q .; }
if port_used 443 && ! ours_caddy; then
die "port 443 is in use by another program ($(ss -tlnpH 'sport = :443' | grep -o 'users:(("[^"]*' | cut -d'"' -f2 | head -1)). The manager needs it for HTTPS."
fi
if port_used 8080 && ! ours_gsm; then
die "port 8080 is in use by another program. The manager listens on 127.0.0.1:8080."
fi
# Without port 80 Caddy can still get certificates (TLS-ALPN challenge on 443), it just can't redirect http:// to https://.
redirects=1
if { port_used 80 && ! ours_caddy; } || grep -q disable_redirects "$DIR/Caddyfile" 2>/dev/null; then
redirects=0
warn "port 80 is used by another program, so http:// addresses won't redirect to https://"
fi
# Address to serve on
is_private() { [[ $1 =~ ^(10|127)\. || $1 =~ ^192\.168\. || $1 =~ ^172\.(1[6-9]|2[0-9]|3[01])\. || $1 =~ ^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\. || $1 =~ ^169\.254\. ]]; }
if [ -z "${SITE:-}" ] && [ -f "$DIR/Caddyfile" ]; then
SITE=$(grep -m1 -E '^[^[:space:]{}#][^[:space:]]* \{$' "$DIR/Caddyfile" | cut -d' ' -f1 || true)
fi
if [ -z "${SITE:-}" ]; then
SITE=$(ip -4 route get 1.1.1.1 2>/dev/null | grep -o 'src [0-9.]*' | cut -d' ' -f2 || true)
if [ -z "$SITE" ] || is_private "$SITE"; then
for url in https://api.ipify.org https://ipv4.icanhazip.com https://checkip.amazonaws.com; do
SITE=$(curl -4 -fsS --max-time 10 "$url" 2>/dev/null | tr -d '[:space:]' || true)
[[ $SITE =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] && break
done
fi
[[ $SITE =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "couldn't find this machine's public IPv4 address. Set it yourself: SITE=<ip or domain>"
fi
[[ $SITE =~ ^[A-Za-z0-9.-]+$ ]] || die "SITE must be a domain name or IPv4 address, got '$SITE'"
if have ufw && ufw status 2>/dev/null | grep -q '^Status: active'; then
say "Opening the HTTPS port in ufw"
ufw allow 443/tcp >/dev/null
[ $redirects = 1 ] && ufw allow 80/tcp >/dev/null
fi
# ---------- install ----------
mkdir -p "$DIR"
if [ -n "${GSM_SRC:-}" ]; then
src=$GSM_SRC
else
say "Downloading $GSM_REPO ($GSM_REF)"
src=$(mktemp -d)
trap 'rm -rf "$src"' EXIT
curl -fsSL "$GSM_REPO/archive/$GSM_REF.tar.gz" | tar -xz -C "$src" --strip-components=1
fi
[ -f "$src/app/Dockerfile" ] && [ -f "$src/caddy/Caddyfile" ] || die "$src doesn't look like a game-servers checkout"
rm -rf "$DIR/app.new"
cp -r "$src/app" "$DIR/app.new"
rm -rf "$DIR/app"
mv "$DIR/app.new" "$DIR/app"
first_install=0
if [ ! -f "$DIR/.env" ]; then
first_install=1
password=${ADMIN_PASSWORD:-$(random a-zA-Z0-9 16)}
umask 077
printf 'ADMIN_PASSWORD=%s\nSECRET_KEY=%s\n' "$password" "$(random a-f0-9 64)" > "$DIR/.env"
umask 022
fi
say "Building and starting the manager"
docker build -q -t gsm "$DIR/app" >/dev/null
docker rm -f gsm >/dev/null 2>&1 || true
docker run -d --name gsm --restart unless-stopped --network host \
--env-file "$DIR/.env" \
-v /var/run/docker.sock:/var/run/docker.sock \
-v "$DATA:$DATA" \
gsm >/dev/null
say "Starting Caddy (HTTPS) for $SITE"
{ [ $redirects = 0 ] && printf '{\n\tauto_https disable_redirects\n}\n\n'
sed "s/__SITE__/$SITE/" "$src/caddy/Caddyfile"; } > "$DIR/Caddyfile.new"
cat "$DIR/Caddyfile.new" > "$DIR/Caddyfile" # in place: Caddy bind-mounts this file
rm "$DIR/Caddyfile.new"
if exists caddy; then
docker start caddy >/dev/null
out=$(docker exec caddy caddy reload --config /etc/caddy/Caddyfile 2>&1) || { echo "$out" >&2; die "Caddy rejected the new config"; }
else
docker run -d --name caddy --restart unless-stopped --network host \
-v "$DIR/Caddyfile:/etc/caddy/Caddyfile:ro" \
-v caddy_data:/data -v caddy_config:/config \
caddy:2 >/dev/null
fi
echo
say "Game server manager is running at https://$SITE"
if [ $first_install = 1 ]; then
if [ -n "${ADMIN_PASSWORD:-}" ]; then echo "Log in with the ADMIN_PASSWORD you set."
else echo "Password: $password (saved in $DIR/.env; edit it there and re-run this script to change it)"
fi
echo "The HTTPS certificate can take a minute to arrive on first start."
echo "Players connect on UDP ports 2456+ (Valheim) and 16261+ (Project Zomboid): open them in your provider's firewall if it has one."
fi