commit cb9a6d1970429c243d98ecace974bea46ac6aa25 Author: neil Date: Fri Oct 16 19:54:56 2026 -0700 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) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..087f725 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +cj +__pycache__/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4639025 --- /dev/null +++ b/CLAUDE.md @@ -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/`: + +- `-poster.jpg`: Steam `library_600x900.jpg` (served as 300x450), shown on server cards +- `-header.jpg`: Steam `header.jpg` (460x215), shown in the game picker + +`` 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//`. + 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=; game= + 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@ ./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 bash -c '"$STEAMCMDDIR/steamcmd.sh" +force_install_dir "$STEAMAPPDIR" +login anonymous +workshop_download_item 108600 +quit' +docker exec 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..baeea1a --- /dev/null +++ b/README.md @@ -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://`) 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@ ./deploy.sh +``` + +This copies the code to `/opt/gsm/src` on the server and runs `install.sh` from there. diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000..50f5857 --- /dev/null +++ b/app/Dockerfile @@ -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"] diff --git a/app/app.py b/app/app.py new file mode 100644 index 0000000..d2f1571 --- /dev/null +++ b/app/app.py @@ -0,0 +1,1299 @@ +"""Game server manager: a small password-protected web UI for running game servers in Docker.""" + +import asyncio +import hmac +import json +import io +import os +import re +import secrets +import shutil +import socket +import threading +import time +import zipfile +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import docker +from starlette.concurrency import run_in_threadpool +from docker.errors import NotFound +from fastapi import Depends, FastAPI, File, Form, HTTPException, Request, UploadFile +from fastapi.responses import FileResponse, StreamingResponse +from fastapi.staticfiles import StaticFiles +from starlette.middleware.sessions import SessionMiddleware + +import players as pl +from backups import Backups +import zomboid + +ADMIN_PASSWORD = os.environ["ADMIN_PASSWORD"] +SECRET_KEY = os.environ.get("SECRET_KEY") or secrets.token_hex(32) +DATA_DIR = Path(os.environ.get("DATA_DIR", "/srv/gameservers")) +STATIC_DIR = Path(__file__).parent / "static" +LABEL = "gsm.managed" + +# Each game type describes how to build its container. Add new games here. +GAMES = { + "valheim": { + "name": "Valheim", + "image": "lloesche/valheim-server", + "default_port": 2456, + "ports_needed": 2, # game port and game port + 1, both UDP + "ready_marker": "Game server connected", + "query_ports": [1], # Steam server query (A2S) port, as an offset from the game port + "backups": True, + # Settings that can be changed later from the server's Manage dialog. + "settings": [ + {"key": "password", "label": "Server password", "type": "text", "minlength": 5, + "help": "At least 5 characters, and not part of the server name."}, + {"key": "port", "label": "Port", "type": "number", "min": 1024, "max": 65534, + "help": "UDP. This port and the next one are used."}, + ], + }, + "zomboid": { + "name": "Project Zomboid", + "image": zomboid.IMAGE, + "default_port": 16261, + "ports_needed": 2, # PORT and UDPPORT (port + 1), both UDP + "ready": "health", # the image's healthcheck turns healthy once the server has started + "query_ports": [0, 1], + "mods": True, + "backups": True, + "settings": [ + {"key": "password", "label": "Server password", "type": "text", "required": False, + "help": "Leave empty for no password."}, + {"key": "port", "label": "Port", "type": "number", "min": 1024, "max": 65534, + "help": "UDP. This port and the next one are used."}, + {"key": "memory_mb", "label": "Memory (MB)", "type": "number", "min": 1024, "max": 65536, + "help": "Java heap for the server. Build 42 with mods wants 4096 or more."}, + {"key": "max_players", "label": "Max players", "type": "number", "min": 1, "max": 100}, + ], + }, +} + +backups = Backups(DATA_DIR) +client = docker.from_env() +app = FastAPI() +app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, max_age=60 * 60 * 24 * 30, same_site="strict", https_only=True) + + +# ---------- auth ---------- + +def require_auth(request: Request): + if not request.session.get("auth"): + raise HTTPException(401, "Not logged in") + + +@app.post("/api/login") +async def login(request: Request): + body = await request.json() + if not hmac.compare_digest(str(body.get("password", "")).encode(), ADMIN_PASSWORD.encode()): + time.sleep(1) # slow down guessing + raise HTTPException(401, "Wrong password") + request.session["auth"] = True + return {"ok": True} + + +@app.post("/api/logout") +def logout(request: Request): + request.session.clear() + return {"ok": True} + + +@app.get("/api/me") +def me(request: Request): + return {"authenticated": bool(request.session.get("auth"))} + + +# ---------- stats collection (background thread) ---------- + +stats_lock = threading.Lock() +host_stats: dict = {} +server_stats: dict = {} # container id -> stats +ready_cache: dict = {} # container id -> started_at when ready marker was seen + + +def _read_cpu(): + parts = Path("/proc/stat").read_text().splitlines()[0].split()[1:] + vals = list(map(int, parts)) + idle = vals[3] + vals[4] + return sum(vals), idle + + +def _read_meminfo(): + info = {} + for line in Path("/proc/meminfo").read_text().splitlines(): + k, v = line.split(":", 1) + info[k] = int(v.split()[0]) * 1024 + return info + + +def _read_net(): + rx = tx = 0 + for line in Path("/proc/net/dev").read_text().splitlines()[2:]: + iface, data = line.split(":", 1) + iface = iface.strip() + if iface == "lo" or iface.startswith(("veth", "docker", "br-")): + continue + f = data.split() + rx += int(f[0]) + tx += int(f[8]) + return rx, tx + + +def _container_stats(c, prev_net): + s = c.stats(stream=False) + cpu = s.get("cpu_stats", {}) + pre = s.get("precpu_stats", {}) + cpu_delta = cpu.get("cpu_usage", {}).get("total_usage", 0) - pre.get("cpu_usage", {}).get("total_usage", 0) + sys_delta = cpu.get("system_cpu_usage", 0) - pre.get("system_cpu_usage", 0) + ncpu = cpu.get("online_cpus") or os.cpu_count() or 1 + cpu_pct = (cpu_delta / sys_delta) * ncpu * 100 if sys_delta > 0 else 0.0 + mem = s.get("memory_stats", {}) + mem_used = mem.get("usage", 0) - mem.get("stats", {}).get("inactive_file", 0) + nets = s.get("networks", {}) or {} + rx = sum(n.get("rx_bytes", 0) for n in nets.values()) + tx = sum(n.get("tx_bytes", 0) for n in nets.values()) + now = time.time() + rx_rate = tx_rate = 0.0 + if prev_net: + dt = now - prev_net["t"] + if dt > 0: + rx_rate = max(0, rx - prev_net["rx"]) / dt + tx_rate = max(0, tx - prev_net["tx"]) / dt + return { + "cpu_percent": round(cpu_pct, 1), + "mem_used": max(0, mem_used), + "net_rx_rate": rx_rate, + "net_tx_rate": tx_rate, + "_net": {"t": now, "rx": rx, "tx": tx}, + } + + +def _check_ready(c): + game = GAMES.get(c.labels.get("gsm.game", "")) + if not game: + return True + if game.get("ready") == "health": + return c.attrs.get("State", {}).get("Health", {}).get("Status") == "healthy" + started = c.attrs.get("State", {}).get("StartedAt") + if ready_cache.get(c.id) == started: + return True + # Read the log from the start until the marker shows up. A tail isn't enough: on a server that has + # been up for a while the marker has scrolled far back, and the cache is empty after a redeploy. + marker = game["ready_marker"].encode() + tail = b"" + try: + for chunk in c.logs(stream=True, follow=False): + if marker in tail + chunk: + ready_cache[c.id] = started + return True + tail = chunk[-len(marker):] + except Exception: + pass + return False + + +vh_sessions: dict = {} # container id -> players.ValheimSessions +ping_cache: dict = {} # ip -> ms or None +idle_since: dict = {} # container name -> when the server was last seen with nobody online +AUTO_STOP_DEFAULT_MIN = 15 +NEW_SERVER_AUTO_STOP = {"auto_stop": True, "auto_stop_minutes": AUTO_STOP_DEFAULT_MIN} # on for new servers + + +def _query_players(c): + """A2S players and (for Valheim) log sessions for a running server. Runs in the stats pool.""" + game = GAMES.get(c.labels.get("gsm.game"), {}) + port = int(c.labels.get("gsm.port", 0)) + a2s = None + for off in game.get("query_ports", []): + a2s = pl.a2s_players(port + off) + if a2s is not None: + break + sessions = None + if c.labels.get("gsm.game") == "valheim": + sessions = vh_sessions.setdefault(c.id, pl.ValheimSessions()).update(c) + return a2s, sessions + + +def _auto_stop_check(c, st, now): + """Stop a server that has had nobody online for its auto stop timeout.""" + cfg = _load_cfg(c.name) + minutes = cfg.get("auto_stop_minutes", AUTO_STOP_DEFAULT_MIN) + if not cfg.get("auto_stop") or not st.get("ready") or st.get("players") is None or busy_ops.get(c.name): + idle_since.pop(c.name, None) + return + if st["players"]: + idle_since.pop(c.name, None) + return + stop_at = idle_since.setdefault(c.name, now) + minutes * 60 + st["auto_stop_in"] = max(0, round(stop_at - now)) + if now >= stop_at: + busy_ops[c.name] = "Auto-stopping (no players)…" + threading.Thread(target=_auto_stop, args=(c.name, minutes), daemon=True).start() + + +def _auto_stop(cname, minutes): + try: + print(f"auto stop: {cname} had no players for {minutes} min, stopping", flush=True) + client.containers.get(cname).stop(timeout=120) # saves the world + except Exception as e: + print("auto stop failed:", e, flush=True) + finally: + busy_ops.pop(cname, None) + idle_since.pop(cname, None) + + +def ping_loop(): + """Ping connected players every few seconds; the stats loop reads the latest results.""" + pool = ThreadPoolExecutor(max_workers=8) + while True: + time.sleep(5) + with stats_lock: + ips = {p["ip"] for st in server_stats.values() for p in st.get("players") or [] if p.get("ip")} + results = dict(zip(ips, pool.map(pl.ping_ms, ips))) + ping_cache.clear() + ping_cache.update(results) + + +# ---------- automatic backups ---------- +# A run of a server (one StartedAt) becomes eligible once a player is seen online. The backup is +# taken when that run ends: the server stopped (by hand or auto stop), restarted or was recreated. +# The eligible run is kept in a file so a manager restart doesn't forget it. + +def _pending_path(cname): + return DATA_DIR / cname / "backup_pending" + + +def _read_pending(cname): + """{"started": StartedAt of the eligible run, "peak": most players seen online at once}, or None.""" + try: + text = _pending_path(cname).read_text().strip() + except OSError: + return None + try: + return json.loads(text) + except ValueError: # older marker: just the StartedAt + return {"started": text, "peak": 1} if text else None + + +def _write_pending(cname, pending): + _pending_path(cname).write_text(json.dumps(pending)) + + +def _session_notes(c, pending): + """Length and peak player count of the run that `pending` describes, for a backup's notes.""" + state = c.attrs.get("State", {}) + start = _parse_time(pending["started"]) + end = _parse_time(state["FinishedAt"]) if state.get("FinishedAt") else 0 + if (c.status == "running" and pending["started"] == state.get("StartedAt")) or end < start: + end = time.time() # still running (a download mid-session) + return {"length": round(end - start), "peak": pending.get("peak", 0)} + + +def _auto_backup_check(new_stats): + for c in client.containers.list(all=True, filters={"label": LABEL}): + if not GAMES.get(c.labels.get("gsm.game"), {}).get("backups") or busy_ops.get(c.name): + continue + started = c.attrs.get("State", {}).get("StartedAt") + running = c.status == "running" + pending = _read_pending(c.name) + if pending and (not running or pending["started"] != started): + _pending_path(c.name).unlink(missing_ok=True) + busy_ops[c.name] = "Backing up world…" + threading.Thread(target=_auto_backup, args=(c, _session_notes(c, pending)), daemon=True).start() + continue + online = len((new_stats.get(c.id) or {}).get("players") or []) + if running and online and (not pending or online > pending.get("peak", 0)): + _write_pending(c.name, {"started": started, "peak": online}) + + +def _auto_backup(c, session): + try: + b = _make_backup(c, "auto", session) + print(f"auto backup: {c.name} -> {b['id']}", flush=True) + except Exception as e: + print("auto backup failed:", c.name, getattr(e, "detail", e), flush=True) + finally: + busy_ops.pop(c.name, None) + + +def stats_loop(): + prev_cpu = _read_cpu() + prev_net = _read_net() + prev_t = time.time() + pool = ThreadPoolExecutor(max_workers=8) + while True: + time.sleep(3) + try: + total, idle = _read_cpu() + dt_total = total - prev_cpu[0] + cpu_pct = 100 * (1 - (idle - prev_cpu[1]) / dt_total) if dt_total else 0 + prev_cpu = (total, idle) + m = _read_meminfo() + du = shutil.disk_usage(DATA_DIR) + rx, tx = _read_net() + now = time.time() + dt = now - prev_t + host = { + "cpu_percent": round(cpu_pct, 1), + "cpu_count": os.cpu_count(), + "mem_total": m["MemTotal"], + "mem_used": m["MemTotal"] - m["MemAvailable"], + "swap_total": m.get("SwapTotal", 0), + "swap_used": m.get("SwapTotal", 0) - m.get("SwapFree", 0), + "disk_total": du.total, + "disk_used": du.used, + "net_rx_rate": (rx - prev_net[0]) / dt, + "net_tx_rate": (tx - prev_net[1]) / dt, + } + prev_net, prev_t = (rx, tx), now + + containers = client.containers.list(filters={"label": LABEL}) + futures = {c.id: pool.submit(_container_stats, c, server_stats.get(c.id, {}).get("_net")) for c in containers} + ready = {c.id: _check_ready(c) for c in containers} + pfutures = {c.id: pool.submit(_query_players, c) for c in containers if ready[c.id]} + new_stats = {} + for c in containers: + try: + st = futures[c.id].result(timeout=10) + st["ready"] = ready[c.id] + st["players"] = None + if c.id in pfutures: + a2s, sessions = pfutures[c.id].result(timeout=10) + st["players"] = pl.combine(a2s, pl.udp_flows(int(c.labels.get("gsm.port", 0))), sessions, now) + for p in st["players"] or []: + p["ping"] = ping_cache.get(p["ip"]) + p["connected_for"] = round(now - p.pop("since")) + _auto_stop_check(c, st, now) + new_stats[c.id] = st + except Exception as e: + print("stats error for", c.name, e, flush=True) + for cid in [k for k in vh_sessions if k not in ready]: + del vh_sessions[cid] + _auto_backup_check(new_stats) + with stats_lock: + host_stats.clear() + host_stats.update(host) + server_stats.clear() + server_stats.update(new_stats) + except Exception as e: # keep the loop alive no matter what + print("stats error:", e, flush=True) + + +threading.Thread(target=stats_loop, daemon=True).start() +threading.Thread(target=ping_loop, daemon=True).start() + + +@app.get("/api/stats", dependencies=[Depends(require_auth)]) +def get_stats(): + with stats_lock: + return { + "host": dict(host_stats), + "servers": {k: {kk: vv for kk, vv in v.items() if not kk.startswith("_")} for k, v in server_stats.items()}, + } + + +# ---------- servers ---------- + +def _server_info(c): + l = c.labels + port = int(l.get("gsm.port", 0)) + state = c.status # running, exited, restarting, created... + with stats_lock: + st = server_stats.get(c.id) + if state == "running": + state = "online" if st and st.get("ready") else "starting" + return { + "id": c.id, + "short_id": c.short_id, + "container": c.name, + "game": l.get("gsm.game"), + "game_name": GAMES.get(l.get("gsm.game"), {}).get("name", l.get("gsm.game")), + "server_name": l.get("gsm.server_name"), + "world": l.get("gsm.world"), + "port": port, + "state": state, + "created": l.get("gsm.created"), + "summary": _summary(c), + "busy": busy_ops.get(c.name), + "last_online": _last_online(c) if c.status != "running" else None, + } + + +# When a stopped server last ran. Docker keeps this as the container's FinishedAt, but recreating the +# container (saving settings) loses it, so the old value is kept in a file for the new container. + +def _last_online_path(cname): + return DATA_DIR / cname / "last_online" + + +def _last_online(c): + finished = c.attrs.get("State", {}).get("FinishedAt", "") + if finished and not finished.startswith("0001-"): + return finished + try: + return _last_online_path(c.name).read_text().strip() or None + except OSError: + return None + + +def _remember_last_online(c): + c.reload() + if last := _last_online(c): + _last_online_path(c.name).write_text(last) + + +def _summary(c): + if c.labels.get("gsm.game") == "zomboid": + cfg = _load_cfg(c.name) + n = len(cfg.get("mods", [])) + text = f"{zomboid.BRANCHES.get(cfg.get('branch'), '')} · {n} mod{'s' if n != 1 else ''}" + return text + (" · changes pending restart" if cfg.get("dirty") else "") + return None + + +# Long-running operations per container name, e.g. "Restarting in 60s…", shown on the server card. +busy_ops: dict = {} + + +def _cfg_path(cname): + return DATA_DIR / cname / "gsm.json" + + +def _load_cfg(cname): + try: + return json.loads(_cfg_path(cname).read_text()) + except (OSError, ValueError): + return {} + + +def _save_cfg(cname, cfg): + p = _cfg_path(cname) + tmp = p.with_suffix(".tmp") + tmp.write_text(json.dumps(cfg, indent=2)) + tmp.replace(p) + + +def _require_memory(needed_mb, what): + """Refuse to start something that doesn't fit in free RAM, so it can't make running servers swap.""" + avail = _read_meminfo()["MemAvailable"] // (1024 * 1024) + if avail < needed_mb: + raise HTTPException(400, f"Not enough free memory to start {what}: it needs about {needed_mb} MB " + f"and {avail} MB is free. Stop another server or lower its memory setting.") + + +def _require_no_players(c, what): + """Refuse actions that would kick players (stop, restart, delete, settings changes) while anyone is on.""" + with stats_lock: + online = len((server_stats.get(c.id) or {}).get("players") or []) + if online: + raise HTTPException(409, f"{online} player{'s are' if online != 1 else ' is'} connected. " + f"{what} is disabled until everyone has left.") + + +def _get(cid): + try: + c = client.containers.get(cid) + except NotFound: + raise HTTPException(404, "Server not found") + if c.labels.get(LABEL) != "true": + raise HTTPException(404, "Server not found") + return c + + +@app.get("/api/games", dependencies=[Depends(require_auth)]) +def list_games(): + avail = _read_meminfo()["MemAvailable"] // (1024 * 1024) + return [{"id": k, "name": v["name"], "default_port": v["default_port"], "ports_needed": v["ports_needed"], + "free_memory_mb": avail, + **({"mod_presets": zomboid.presets_with_updates(), "preset_branch": zomboid.PRESET_BRANCH} if k == "zomboid" else {})} + for k, v in GAMES.items()] + + +@app.get("/api/servers", dependencies=[Depends(require_auth)]) +def list_servers(): + cs = client.containers.list(all=True, filters={"label": LABEL}) + return sorted((_server_info(c) for c in cs), key=lambda s: s.get("created") or "") + + +def _used_ports(): + used = set() + for c in client.containers.list(all=True, filters={"label": LABEL}): + p = int(c.labels.get("gsm.port", 0)) + n = GAMES.get(c.labels.get("gsm.game"), {}).get("ports_needed", 1) + used.update(range(p, p + n)) + return used + + +def _udp_port_free(port): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.bind(("0.0.0.0", port)) + return True + except OSError: + return False + finally: + s.close() + + +@app.get("/api/suggest-port", dependencies=[Depends(require_auth)]) +def suggest_port(game: str = "valheim"): + g = GAMES[game] + used = _used_ports() + port = g["default_port"] + while any(p in used or not _udp_port_free(p) for p in range(port, port + g["ports_needed"])): + port += g["ports_needed"] + return {"port": port} + + +WORLD_RE = re.compile(r"^[A-Za-z0-9_]{1,40}$") +MAX_UPLOAD = 1024 * 1024 * 1024 # 1 GB total + + +def _read_world_upload(uploads): + """Collect Valheim world files from uploaded files and/or zips. + + Returns ("folder", {filename: bytes}) for the current format (a world folder holding + _main.N.db2/.fwl2/...) or ("legacy", {".db": bytes, ".fwl": bytes}) for the classic pair. + """ + found = {} # basename -> bytes + total = 0 + for up in uploads: + if not up.filename: + continue + data = up.file.read() + total += len(data) + if total > MAX_UPLOAD: + raise HTTPException(400, "Upload is too large (max 1 GB)") + name = os.path.basename(up.filename.replace("\\", "/")) + if name.lower().endswith(".zip"): + try: + with zipfile.ZipFile(io.BytesIO(data)) as z: + for info in z.infolist(): + if info.is_dir() or info.file_size > MAX_UPLOAD: + continue + base = os.path.basename(info.filename) + if base and not base.startswith("."): + found[base] = z.read(info) + except zipfile.BadZipFile: + raise HTTPException(400, f"{name} is not a valid zip file") + else: + found[name] = data + + # Current-format worlds are a folder holding a save set _main.N.{db2,fwl2,ok,chunks} plus *.chunk files. + # Valheim deletes an incomplete save set as an "orphan" and silently generates a fresh world, + # so refuse uploads that are missing any part of it. + saves = sorted({int(m.group(1)) for n in found if (m := re.fullmatch(r"_main\.(\d+)\.db2", n))}) + if saves or any(n.endswith(".fwl2") for n in found): + if not saves: + raise HTTPException(400, "The upload has a .fwl2 file but no matching .db2 world file.") + n = saves[-1] # newest save in the folder + missing = [f"_main.{n}.{ext}" for ext in ("db2", "fwl2", "ok", "chunks") if f"_main.{n}.{ext}" not in found] + if missing: + raise HTTPException(400, f"The world upload is incomplete: missing {', '.join(missing)}. Valheim discards " + "incomplete worlds and starts a new one. Upload every file in the world folder, " + "or zip the whole folder and upload the zip.") + chunk_files = {k: v for k, v in found.items() if k.endswith(".chunk")} + # An empty index is ~10 bytes; a bigger one lists chunk files that must be present. + if len(found[f"_main.{n}.chunks"]) > 16 and not chunk_files: + raise HTTPException(400, "The world upload is missing its .chunk files (where buildings and terrain " + "are stored). Upload every file in the world folder, or zip the whole folder.") + folder = {k: v for k, v in found.items() if k.startswith(f"_main.{n}.")} + folder.update(chunk_files) + return "folder", folder + db = [n for n in found if n.lower().endswith(".db")] + fwl = [n for n in found if n.lower().endswith(".fwl")] + if len(db) == 1 and len(fwl) == 1: + return "legacy", {".db": found[db[0]], ".fwl": found[fwl[0]]} + if len(db) > 1 or len(fwl) > 1: + raise HTTPException(400, "Found more than one world in the upload; upload one world at a time") + raise HTTPException(400, "Couldn't find a world in the upload. Upload every file in your world folder, " + "a zip of that folder, or a classic .db + .fwl pair") + + +def _validate_password(password, server_name): + if len(password) < 5: + raise HTTPException(400, "Password must be at least 5 characters") + if password in server_name: + raise HTTPException(400, "Valheim does not allow the password to appear in the server name") + + +def _validate_port(g, port, own=None): + """Check that port..port+n is free. `own` is the container being edited, whose ports don't count.""" + if not (1024 <= port <= 65535 - g["ports_needed"]): + raise HTTPException(400, "Port must be between 1024 and 65534") + needed = range(port, port + g["ports_needed"]) + own_ports = set() + if own is not None: + p = int(own.labels.get("gsm.port", 0)) + own_ports = set(range(p, p + g["ports_needed"])) + used = _used_ports() - own_ports + if any(p in used for p in needed): + raise HTTPException(400, f"Port {port} or {port + 1} is already used by another server") + if not all(p in own_ports or _udp_port_free(p) for p in needed): + raise HTTPException(400, f"Port {port} or {port + 1} is already in use on the VPS") + + +def _ensure_image(image): + """containers.create doesn't pull, so fetch the image first if this VPS doesn't have it yet.""" + try: + client.images.get(image) + except docker.errors.ImageNotFound: + client.images.pull(image) + + +def _run_valheim(cname, server_name, world_name, password, port, created, start=True): + base = DATA_DIR / cname + _ensure_image(GAMES["valheim"]["image"]) + c = client.containers.create( + GAMES["valheim"]["image"], + name=cname, + detach=True, + environment={ + "SERVER_NAME": server_name, + "WORLD_NAME": world_name, + "SERVER_PASS": password, + "SERVER_PORT": str(port), + "SERVER_PUBLIC": "true", + "TZ": "UTC", + }, + ports={f"{p}/udp": p for p in range(port, port + 2)}, + volumes={ + str(base / "config"): {"bind": "/config", "mode": "rw"}, + str(base / "server"): {"bind": "/opt/valheim", "mode": "rw"}, + }, + labels={ + LABEL: "true", + "gsm.game": "valheim", + "gsm.server_name": server_name, + "gsm.world": world_name, + "gsm.port": str(port), + "gsm.created": created, + }, + restart_policy={"Name": "unless-stopped"}, + cap_add=["SYS_NICE"], + ) + if start: + c.start() + c.reload() + return c + + +def _env(c): + return dict(e.split("=", 1) for e in c.attrs["Config"]["Env"] if "=" in e) + + +def _validate_zomboid(cfg, own=None): + if not 1024 <= cfg["memory_mb"] <= 65536: + raise HTTPException(400, "Memory must be between 1024 and 65536 MB") + if not 1 <= cfg["max_players"] <= 100: + raise HTTPException(400, "Max players must be between 1 and 100") + if len(cfg.get("password", "")) > 60 or any(ch in cfg.get("password", "") for ch in "\r\n"): + raise HTTPException(400, "Password is too long or has line breaks") + _validate_port(GAMES["zomboid"], cfg["port"], own=own) + + +def _run_zomboid(cname, cfg, start=True): + base = DATA_DIR / cname + for sub in ("data", "game"): + (base / sub).mkdir(parents=True, exist_ok=True) + os.chown(base / sub, 1000, 1000) # the image runs as uid 1000 + _ensure_image(zomboid.IMAGE) + c = client.containers.create( + zomboid.IMAGE, + name=cname, + detach=True, + environment=zomboid.container_env(cfg), + ports={f"{p}/udp": p for p in (cfg["port"], cfg["port"] + 1)}, + volumes={ + str(base / "data"): {"bind": "/home/steam/Zomboid", "mode": "rw"}, + str(base / "game"): {"bind": "/home/steam/pz-dedicated", "mode": "rw"}, + }, + labels={ + LABEL: "true", + "gsm.game": "zomboid", + "gsm.server_name": cfg["server_name"], + "gsm.world": "", + "gsm.port": str(cfg["port"]), + "gsm.created": cfg["created"], + }, + # unless-stopped also brings it back after the image's own restart for mod updates (exit code 0) + restart_policy={"Name": "unless-stopped"}, + log_config={"type": "json-file", "config": {"max-size": "50m", "max-file": "3"}}, + stop_signal="SIGTERM", + ) + cfg["dirty"] = False + _save_cfg(cname, cfg) + if start: + c.start() + c.reload() + return c + + +def _create_zomboid(server_name, password, port, admin_password, memory_mb, max_players, branch, preset_mods): + if branch not in zomboid.BRANCHES: + raise HTTPException(400, "Unknown game version") + if preset_mods and branch != zomboid.PRESET_BRANCH: + raise HTTPException(400, "The mod presets are for Build 42 only") + try: + workshop_ids, mods = zomboid.preset_selection(preset_mods) + except ValueError as e: + raise HTTPException(400, str(e)) + if len(admin_password) < 5: + raise HTTPException(400, "Admin password must be at least 5 characters") + cfg = { + "server_name": server_name, "password": password, "admin_password": admin_password, + "port": port, "memory_mb": memory_mb, "max_players": max_players, "branch": branch, + "workshop_ids": workshop_ids, "mods": mods, "auto_update": True, **NEW_SERVER_AUTO_STOP, + "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + _validate_zomboid(cfg) + _require_memory(memory_mb + zomboid.MEMORY_OVERHEAD_MB, "this server") + slug = re.sub(r"[^a-z0-9]+", "-", server_name.lower()).strip("-")[:30] or "server" + cname = f"gsm-zomboid-{slug}-{secrets.token_hex(2)}" + (DATA_DIR / cname).mkdir(parents=True) + try: + c = _run_zomboid(cname, cfg) + except Exception as e: + shutil.rmtree(DATA_DIR / cname, ignore_errors=True) + raise HTTPException(500, f"Failed to start container: {e}") + return _server_info(c) + + +def _recreate_zomboid(c, start): + """Apply the stored config: Docker can't change env or ports in place, so replace the container.""" + cfg = _load_cfg(c.name) + name = c.name + if c.status in ("running", "restarting"): + c.stop(timeout=120) # the server saves the world on SIGTERM + _remember_last_online(c) + c.remove() + return _run_zomboid(name, cfg, start=start) + + +@app.post("/api/servers", dependencies=[Depends(require_auth)]) +async def create_server( + game: str = Form(...), + server_name: str = Form(...), + password: str = Form(""), + port: int = Form(...), + world_name: str = Form(""), + world_source: str = Form("new"), + world_files: list[UploadFile] | None = File(None), + admin_password: str = Form(""), + memory_mb: int = Form(4096), + max_players: int = Form(8), + branch: str = Form("public"), + preset_mods: list[str] = Form([]), +): + if game not in GAMES: + raise HTTPException(400, "Unknown game") + g = GAMES[game] + server_name = server_name.strip() + if not server_name or len(server_name) > 60: + raise HTTPException(400, "Server name is required (max 60 characters)") + if game == "zomboid": + # in a thread: the first create pulls the image, which shouldn't freeze the rest of the site + return await run_in_threadpool(_create_zomboid, server_name, password, port, admin_password, memory_mb, max_players, branch, preset_mods) + if not WORLD_RE.match(world_name): + raise HTTPException(400, "World name may only contain letters, numbers and underscores") + _validate_password(password, server_name) + _validate_port(g, port) + world = None + if world_source == "upload": + world = _read_world_upload(world_files or []) + + slug = re.sub(r"[^a-z0-9]+", "-", world_name.lower()).strip("-") or "world" + cname = f"gsm-{game}-{slug}-{secrets.token_hex(2)}" + base = DATA_DIR / cname + config_dir = base / "config" + worlds_dir = config_dir / "worlds_local" + worlds_dir.mkdir(parents=True, exist_ok=True) + (base / "server").mkdir(parents=True, exist_ok=True) + _save_cfg(cname, dict(NEW_SERVER_AUTO_STOP)) + + if world: + kind, files = world + if kind == "folder": + (worlds_dir / world_name).mkdir() + for fname, data in files.items(): + (worlds_dir / world_name / fname).write_bytes(data) + else: + for ext, data in files.items(): + (worlds_dir / f"{world_name}{ext}").write_bytes(data) + + try: + c = await run_in_threadpool(_run_valheim, cname, server_name, world_name, password, port, + time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) + except Exception as e: + shutil.rmtree(base, ignore_errors=True) + raise HTTPException(500, f"Failed to start container: {e}") + return _server_info(c) + + +@app.post("/api/servers/{cid}/{action}", dependencies=[Depends(require_auth)]) +def server_action(cid: str, action: str): + c = _get(cid) + if busy_ops.get(c.name): + raise HTTPException(409, f"Busy: {busy_ops[c.name]}") + if action in ("stop", "restart"): + _require_no_players(c, action.capitalize()) + if c.labels.get("gsm.game") == "zomboid" and action in ("start", "restart"): + cfg = _load_cfg(c.name) + if action == "start": + _require_memory(cfg["memory_mb"] + zomboid.MEMORY_OVERHEAD_MB, "this server") + if cfg.get("dirty"): # saved changes waiting for a restart + return _server_info(_recreate_zomboid(c, start=True)) + if action == "start": + c.start() + elif action == "stop": + c.stop(timeout=120) # give Valheim time to save the world + elif action == "restart": + c.restart(timeout=120) + else: + raise HTTPException(400, "Unknown action") + c.reload() + return _server_info(c) + + +@app.delete("/api/servers/{cid}", dependencies=[Depends(require_auth)]) +def delete_server(cid: str, delete_data: bool = False): + c = _get(cid) + name = c.name + if busy_ops.get(name): + raise HTTPException(409, f"Busy: {busy_ops[name]}") + _require_no_players(c, "Delete") + busy_ops[name] = "Deleting…" # keeps the stats loop from backing up while files are removed + try: + if c.status == "running": + c.stop(timeout=120) + pending = _read_pending(name) + if pending: # players were on since the last backup: keep this world + _pending_path(name).unlink(missing_ok=True) + c.reload() # for the stop time in the session notes + try: + _make_backup(c, "auto", _session_notes(c, pending)) + except Exception as e: + print("backup before delete failed:", name, getattr(e, "detail", e), flush=True) + c.remove() + finally: + busy_ops.pop(name, None) + if delete_data: + shutil.rmtree(DATA_DIR / name, ignore_errors=True) + return {"ok": True} + + +@app.get("/api/servers/{cid}/logs", dependencies=[Depends(require_auth)]) +def server_logs(cid: str, tail: int = 200): + c = _get(cid) + return {"logs": c.logs(tail=min(tail, 2000), timestamps=False).decode(errors="replace")} + + +@app.get("/api/servers/{cid}/logs/stream", dependencies=[Depends(require_auth)]) +async def stream_logs(cid: str, request: Request, tail: int = 500): + """Server-sent events: the last `tail` lines, then new lines as the container writes them.""" + c = _get(cid) + loop = asyncio.get_running_loop() + queue: asyncio.Queue = asyncio.Queue() + stream = c.logs(stream=True, follow=True, tail=min(tail, 2000)) + + def reader(): + # Docker's log stream is blocking, so read it in a thread and hand chunks to the event loop. + try: + for chunk in stream: + loop.call_soon_threadsafe(queue.put_nowait, chunk) + except Exception: + pass + loop.call_soon_threadsafe(queue.put_nowait, None) + + threading.Thread(target=reader, daemon=True).start() + + async def events(): + buf = b"" + try: + while True: + try: + chunk = await asyncio.wait_for(queue.get(), timeout=15) + except asyncio.TimeoutError: + if await request.is_disconnected(): + break + yield ": keepalive\n\n" + continue + if chunk is None: # container stopped or was removed + yield "event: end\ndata: {}\n\n" + break + buf += chunk + *lines, buf = buf.split(b"\n") + if lines: + text = [l.decode(errors="replace").rstrip("\r") for l in lines] + yield f"data: {json.dumps(text)}\n\n" + finally: + stream.close() # unblocks the reader thread + + return StreamingResponse(events(), media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) + + +# ---------- frontend ---------- + +app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") + + +@app.get("/") +def index(): + return FileResponse(STATIC_DIR / "index.html") + + +@app.get("/api/servers/{cid}/settings", dependencies=[Depends(require_auth)]) +def get_settings(cid: str): + c = _get(cid) + game = c.labels.get("gsm.game") + env = _env(c) + if game == "valheim": + values = {"password": env.get("SERVER_PASS", ""), "port": int(c.labels.get("gsm.port", 0))} + elif game == "zomboid": + cfg = _load_cfg(c.name) + values = {k: cfg.get(k) for k in ("password", "port", "memory_mb", "max_players")} + else: + values = {} + g = GAMES.get(game, {}) + cfg = _load_cfg(c.name) + return {"fields": g.get("settings", []), "values": values, "backups": g.get("backups", False), + "mods": g.get("mods", False), + "auto_stop": {"enabled": bool(cfg.get("auto_stop")), + "minutes": cfg.get("auto_stop_minutes", AUTO_STOP_DEFAULT_MIN)}} + + +@app.put("/api/servers/{cid}/autostop", dependencies=[Depends(require_auth)]) +async def update_auto_stop(cid: str, request: Request): + """Saved in gsm.json and read by the stats loop, so no restart is needed.""" + c = _get(cid) + body = await request.json() + try: + minutes = int(body.get("minutes")) + except (TypeError, ValueError): + raise HTTPException(400, "Timeout must be a number of minutes") + if not 5 <= minutes <= 1440: + raise HTTPException(400, "Timeout must be between 5 and 1440 minutes") + cfg = _load_cfg(c.name) + cfg.update(auto_stop=bool(body.get("enabled")), auto_stop_minutes=minutes) + _save_cfg(c.name, cfg) + idle_since.pop(c.name, None) # start the countdown over with the new setting + return {"enabled": cfg["auto_stop"], "minutes": minutes} + + +@app.put("/api/servers/{cid}/settings", dependencies=[Depends(require_auth)]) +async def update_settings(cid: str, request: Request): + c = _get(cid) + body = await request.json() + if busy_ops.get(c.name): + raise HTTPException(409, f"Busy: {busy_ops[c.name]}") + _require_no_players(c, "Saving settings") # saving recreates the container + if c.labels.get("gsm.game") == "zomboid": + return _update_zomboid_settings(c, body) + if c.labels.get("gsm.game") != "valheim": + raise HTTPException(400, "This game has no editable settings") + l = c.labels + try: + port = int(body.get("port")) + except (TypeError, ValueError): + raise HTTPException(400, "Port must be a number") + password = str(body.get("password", "")) + _validate_password(password, l["gsm.server_name"]) + _validate_port(GAMES["valheim"], port, own=c) + + # Docker can't change published ports in place, so recreate the container. + # World data lives in the bind-mounted folders, so nothing is lost. + was_running = c.status in ("running", "restarting") + if was_running: + c.stop(timeout=120) # saves the world + _remember_last_online(c) + c.remove() + c = _run_valheim(c.name, l["gsm.server_name"], l["gsm.world"], password, port, l["gsm.created"], start=was_running) + return _server_info(c) + + +def _backup_files(c): + """[(path, name in zip)] of the world/save files for a server; raises 404 if nothing is saved yet.""" + game = c.labels.get("gsm.game") + if game == "valheim": + world = c.labels["gsm.world"] + worlds_dir = DATA_DIR / c.name / "config" / "worlds_local" + # Current format is a folder per world; older worlds are a .db + .fwl pair. + files = [p for p in (worlds_dir / world).rglob("*") if p.is_file()] if (worlds_dir / world).is_dir() else [] + files += [p for p in worlds_dir.glob(f"{world}.*") if p.is_file()] + if not any(p.suffix in (".db2", ".db") for p in files): + raise HTTPException(404, "This world hasn't been saved yet. Valheim saves about every 30 minutes " + "and when the server stops. Try again after that.") + return [(p, p.relative_to(worlds_dir).as_posix()) for p in files] + if game == "zomboid": + data = DATA_DIR / c.name / "data" + n = zomboid.SERVERNAME + files = [p for p in (data / "Saves" / "Multiplayer" / n).rglob("*") if p.is_file()] + if not files: + raise HTTPException(404, "This server hasn't saved a world yet. Start it once and try again.") + files += [p for p in (data / "db").glob(f"{n}.db") if p.is_file()] + files += [p for p in (data / "Server").glob(f"{n}*") if p.is_file()] # ini, sandbox vars, spawn regions + return [(p, p.relative_to(data).as_posix()) for p in files] + raise HTTPException(400, "Backups are not supported for this game") + + +def _make_backup(c, kind, session=None): + l = c.labels + game = l.get("gsm.game") + return backups.create(game, kind, c.name, _backup_files(c), { + "game_name": GAMES.get(game, {}).get("name", game), "server_name": l.get("gsm.server_name"), + "world": l.get("gsm.world") or None, "session": session, + }) + + +@app.get("/api/servers/{cid}/world.zip", dependencies=[Depends(require_auth)]) +def download_world(cid: str): + """Download the saved world. Each download is also kept as a manual backup.""" + c = _get(cid) + if busy_ops.get(c.name): + raise HTTPException(409, f"Busy: {busy_ops[c.name]}") + session = None + if c.status == "running": + with stats_lock: + online = len((server_stats.get(c.id) or {}).get("players") or []) + pending = _read_pending(c.name) + if not pending or pending["started"] != c.attrs["State"]["StartedAt"]: + pending = {"started": c.attrs["State"]["StartedAt"], "peak": 0} + session = {**_session_notes(c, pending), "running": True} + session["peak"] = max(session["peak"], online) + b = _make_backup(c, "manual", session) + label = re.sub(r"[^A-Za-z0-9_-]+", "", b["game_name"]) + "_" + re.sub(r"[^A-Za-z0-9_-]+", "_", b["world"] or b["server_name"]) + filename = f"{label}_{time.strftime('%Y-%m-%d', time.gmtime())}.zip" + return FileResponse(backups.path(*b["id"].split("/")), media_type="application/zip", filename=filename) + + +@app.get("/api/backups", dependencies=[Depends(require_auth)]) +def list_backups(): + games = [{"id": k, "name": g["name"]} for k, g in GAMES.items() if g.get("backups")] + return {"games": games, "backups": backups.list(), "keep": 5} + + +@app.get("/api/backups/{game}/{kind}/{name}", dependencies=[Depends(require_auth)]) +def download_backup(game: str, kind: str, name: str): + p = backups.path(game, kind, name) + if not p: + raise HTTPException(404, "Backup not found") + return FileResponse(p, media_type="application/zip", filename=name) + + +# ---------- Project Zomboid: settings and mods ---------- + +def _update_zomboid_settings(c, body): + cfg = _load_cfg(c.name) + old_mem = cfg["memory_mb"] + try: + cfg.update(password=str(body.get("password") or ""), port=int(body["port"]), + memory_mb=int(body["memory_mb"]), max_players=int(body["max_players"])) + except (KeyError, TypeError, ValueError): + raise HTTPException(400, "Port, memory and max players must be numbers") + _validate_zomboid(cfg, own=c) + running = c.status in ("running", "restarting") + if running and cfg["memory_mb"] > old_mem: + _require_memory(cfg["memory_mb"] - old_mem, "this server with more memory") + _save_cfg(c.name, cfg) + return _server_info(_recreate_zomboid(c, start=running)) + + +def _zomboid(cid): + c = _get(cid) + if c.labels.get("gsm.game") != "zomboid": + raise HTTPException(400, "Mods are only supported for Project Zomboid") + return c + + +def _mods_cache_path(cname): + return DATA_DIR / cname / "mods_cache.json" + + +def _refresh_mod_info(cname, download_ids): + """Background: download new workshop items into the running server, then read its mod info.""" + try: + c = client.containers.get(cname) + if download_ids: + busy_ops[cname] = f"Downloading {len(download_ids)} workshop item(s)…" + res = c.exec_run(zomboid.download_command(download_ids)) + if res.exit_code != 0: + print("steamcmd failed:", res.output[-2000:].decode(errors="replace"), flush=True) + busy_ops[cname] = "Reading mod info…" + res = c.exec_run(["list-mods"], demux=True) + out, err = res.output + if res.exit_code != 0: + raise RuntimeError((err or out or b"").decode(errors="replace").strip()[-500:] or "list-mods failed") + info = zomboid.parse_list_mods(out) + info["fetched"] = time.time() + info["error"] = None + except Exception as e: + info = {**_read_mods_cache(cname), "error": str(e)} + finally: + busy_ops.pop(cname, None) + _mods_cache_path(cname).write_text(json.dumps(info)) + + +def _read_mods_cache(cname): + try: + return json.loads(_mods_cache_path(cname).read_text()) + except (OSError, ValueError): + return {} + + +@app.get("/api/servers/{cid}/mods", dependencies=[Depends(require_auth)]) +def get_mods(cid: str): + c = _zomboid(cid) + cfg = _load_cfg(c.name) + cache = _read_mods_cache(c.name) + started = c.attrs.get("State", {}).get("StartedAt", "") + try: + logs = c.logs(since=_parse_time(started), tail=5000).decode(errors="replace") if started else "" + except Exception: + logs = "" + return { + "workshop_ids": cfg.get("workshop_ids", []), + "mods": cfg.get("mods", []), + "auto_update": cfg.get("auto_update", True), + "dirty": cfg.get("dirty", False), + "branch": cfg.get("branch"), + "running": c.status == "running", + "ready": _check_ready(c) if c.status == "running" else False, + "busy": busy_ops.get(c.name), + "fetch_pending": c.name in fetch_pending, + "info": cache, + "issues": zomboid.parse_issues(logs), + } + + +def _parse_time(iso): + from datetime import datetime + return int(datetime.fromisoformat(iso[:26].rstrip("Z") + "+00:00").timestamp()) + + +@app.post("/api/workshop/lookup", dependencies=[Depends(require_auth)]) +async def workshop_lookup(request: Request): + body = await request.json() + try: + return await asyncio.to_thread(zomboid.lookup, str(body.get("text", ""))) + except ValueError as e: + raise HTTPException(400, str(e)) + except Exception as e: + raise HTTPException(502, f"Steam Workshop lookup failed: {e}") + + +# Servers started by "Start server and fetch mod info", waiting to come online. Not a busy_op, so +# Stop stays available; stopping the server cancels the fetch. +fetch_pending: dict = {} # container name -> time requested +FETCH_WAIT_S = 2 * 60 * 60 # a first start with a big mod list downloads gigabytes + + +def _start_fetch(cname): + cfg = _load_cfg(cname) + downloaded = {i["id"] for i in _read_mods_cache(cname).get("items", []) if i.get("downloaded")} + new_ids = [i for i in cfg.get("workshop_ids", []) if i not in downloaded] + busy_ops[cname] = "Starting…" + threading.Thread(target=_refresh_mod_info, args=(cname, new_ids), daemon=True).start() + + +def _fetch_when_ready(cname): + """Background: wait for a server we just started to come online, then fetch its mod info.""" + error = None + try: + deadline = time.time() + FETCH_WAIT_S + while time.time() < deadline: + time.sleep(5) + if busy_ops.get(cname): + continue # e.g. still being recreated + try: + c = client.containers.get(cname) + except NotFound: + error = "The server was removed before it came online." + return + if c.status not in ("running", "restarting"): + error = "The server stopped before it came online, so mod info wasn't fetched." + return + if c.status == "running" and _check_ready(c): + _start_fetch(cname) + return + error = "The server didn't come online within 2 hours, so mod info wasn't fetched." + except Exception as e: + error = str(e) + finally: + fetch_pending.pop(cname, None) + if error: + print("fetch after start:", cname, error, flush=True) + _mods_cache_path(cname).write_text(json.dumps({**_read_mods_cache(cname), "error": error})) + + +@app.post("/api/servers/{cid}/mods/refresh", dependencies=[Depends(require_auth)]) +def refresh_mods(cid: str, start: bool = False): + c = _zomboid(cid) + if busy_ops.get(c.name): + raise HTTPException(409, f"Busy: {busy_ops[c.name]}") + if fetch_pending.get(c.name): + raise HTTPException(409, "Already waiting for the server to come online to fetch mod info.") + if c.status == "running" and _check_ready(c): + _start_fetch(c.name) + return {"ok": True} + if not start: + raise HTTPException(400, "Start the server (and wait until it's online) to download mods and read their info.") + if c.status != "running": + server_action(c.id, "start") # memory check, and applies saved changes by recreating the container + fetch_pending[c.name] = time.time() + threading.Thread(target=_fetch_when_ready, args=(c.name,), daemon=True).start() + return {"ok": True, "started": True} + + +@app.put("/api/servers/{cid}/mods", dependencies=[Depends(require_auth)]) +async def save_mods(cid: str, request: Request): + c = _zomboid(cid) + if busy_ops.get(c.name): + raise HTTPException(409, f"Busy: {busy_ops[c.name]}") + body = await request.json() + ids = [str(i) for i in body.get("workshop_ids", [])] + mods = [str(m).strip().lstrip("\\") for m in body.get("mods", [])] + if not all(re.fullmatch(r"\d{6,12}", i) for i in ids): + raise HTTPException(400, "Workshop IDs must be numbers") + bad = [m for m in mods if not zomboid.MOD_ID_RE.match(m)] + if bad: + raise HTTPException(400, f"Invalid mod ID: {bad[0]!r}") + cfg = _load_cfg(c.name) + cfg.update(workshop_ids=list(dict.fromkeys(ids)), mods=list(dict.fromkeys(mods)), + auto_update=bool(body.get("auto_update", True)), dirty=True) + _save_cfg(c.name, cfg) + if body.get("apply") == "now": + busy_ops[c.name] = "Applying mod changes…" + threading.Thread(target=_apply_now, args=(c.name,), daemon=True).start() + return get_mods(c.id) + + +def _console(c, *args): + return c.exec_run(["console", *args]).exit_code == 0 + + +def _apply_now(cname): + """Warn players, then restart with the new mod list. With nobody online, restart at once.""" + try: + c = client.containers.get(cname) + if c.status == "running" and _check_ready(c): + _console(c, "players") + time.sleep(3) + players = zomboid.player_count(c.logs(tail=200).decode(errors="replace")) + if players: + _console(c, "servermsg", "Server restarting in 60 seconds to apply mod changes.") + for left in range(60, 0, -1): + busy_ops[cname] = f"Restarting in {left}s ({players} online)…" + if left == 10: + _console(c, "servermsg", "Server restarting in 10 seconds.") + time.sleep(1) + busy_ops[cname] = "Restarting with new mods…" + c.reload() + _recreate_zomboid(c, start=c.status in ("running", "restarting")) + except Exception as e: + print("apply mods failed:", e, flush=True) + finally: + busy_ops.pop(cname, None) diff --git a/app/backups.py b/app/backups.py new file mode 100644 index 0000000..c72bc04 --- /dev/null +++ b/app/backups.py @@ -0,0 +1,68 @@ +"""World backups, stored as zips under DATA_DIR/backups///. + +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 diff --git a/app/players.py b/app/players.py new file mode 100644 index 0000000..471850f --- /dev/null +++ b/app/players.py @@ -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(" 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 diff --git a/app/requirements.txt b/app/requirements.txt new file mode 100644 index 0000000..1227289 --- /dev/null +++ b/app/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.115.* +uvicorn==0.32.* +docker==7.1.* +python-multipart==0.0.* +itsdangerous==2.2.* diff --git a/app/static/app.js b/app/static/app.js new file mode 100644 index 0000000..425b93d --- /dev/null +++ b/app/static/app.js @@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 ? ` · auto stop in ${Math.ceil(st.auto_stop_in / 60)} min` : ''; + return `
${n} player${n === 1 ? '' : 's'}${stop}
`; +} + +// 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 ``; + return ``; +} + +// 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/ (-poster.jpg 300x450, -header.jpg 460x215). +const GAME_ART = new Set(['valheim', 'zomboid']); +const artImg = (game, kind, cls) => (GAME_ART.has(game) + ? `` : ''); + +// "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 ` +
+ ${artImg(s.game, 'poster', 'server-art')} +
+
+
+
${esc(s.server_name)}${isBusy ? 'Working…' : s.busy ? esc(s.busy) : STATE_LABEL[s.state] || esc(s.state)}
+
${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world ${esc(s.world)}`} · connect to ${esc(host)}:${s.port}
+ ${running ? playersLine(st) : s.last_online ? `
Last online ${esc(timeAgo(s.last_online))}
` : ''} +
+
+ ${running + ? `${guardedButton('restart', 'Restart', st, isBusy)} + ${guardedButton('stop', 'Stop', st, isBusy)}` + : ``} + +
+
+ ${running && st ? ` +
+
CPU${st.cpu_percent}%
+
Memory${fmtBytes(st.mem_used)}
+
Network↓ ${fmtRate(st.net_rx_rate)} ↑ ${fmtRate(st.net_tx_rate)}
+
` : ''} +
+
`; + }).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 = '

Loading…

'; + $('#manage-dialog').showModal(); + try { + const { fields, values, backups, mods, auto_stop } = await api(`/api/servers/${s.id}/settings`); + $('#autostop-enabled').checked = auto_stop.enabled; + $('#autostop-minutes').value = auto_stop.minutes; + $('#mods-section').classList.toggle('hidden', !mods); + if (mods) $('#mods-summary').textContent = s.summary || ''; + $('#world-section').classList.toggle('hidden', !backups); + $('#world-download').href = `/api/servers/${s.id}/world.zip`; + $('#settings-form').classList.toggle('hidden', !fields.length); + $('#settings-fields').innerHTML = fields.map((f) => ` + `).join(''); + $('#settings-restart-note').classList.toggle('hidden', !['online', 'starting'].includes(s.state)); + } catch (err) { $('#settings-fields').innerHTML = ''; $('#settings-error').textContent = err.message; } +} + +function renderPlayers() { + const s = servers.find((x) => x.id === managed?.id) || managed; + const st = stats.servers[s.id]; + const list = st?.players; + let html; + if (!['online', 'starting'].includes(s.state)) html = 'The server is not running.'; + else if (!st?.ready) html = 'Waiting for the server to come online…'; + else if (!list) html = 'Couldn\'t get the player list from the server.'; + else if (!list.length) html = 'No players connected.'; + if (html) { + $('#players-body').innerHTML = `

${html}

`; + } else { + $('#players-body').innerHTML = ` + + ${list.map((p) => ` + ${p.ping == null ? '–' : `${p.ping} ms`}`).join('')} +
PlayerIP addressConnectedPing
${esc(p.name)}${esc(p.ip || '–')}${fmtDuration(p.connected_for)}
`; + } + 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 `
+

${esc(b0.game_name || b0.game)} - ${esc(b0.server_name || b0.container)}${b0.world ? ` world ${esc(b0.world)}` : ''}

+ ${BACKUP_KINDS.map(([kind, label]) => { + const rows = list.filter((b) => b.type === kind); + if (!rows.length) return ''; + return `
+

${label} ${rows.length} of ${keep} kept

+ + + ${rows.map((b) => ` + + + + + `).join('')} +
CreatedSession notesSize
${b.created ? esc(new Date(b.created).toLocaleString()) : ''}${esc(sessionNotes(b))}${fmtBytes(b.size)}Download
+
`; + }).join('')} +
`; + }).join('') : '

No backups yet. See About Backups for when they are made.

'; +} + +$('#about-backups-btn').addEventListener('click', () => $('#about-backups').showModal()); +$('#about-backups-close').addEventListener('click', () => $('#about-backups').close()); + +// ---------- logs ---------- + +let logSource = null; +const MAX_LOG_LINES = 3000; + +// Colour each line by the most severe level it mentions. +function logLevel(line) { + if (/\b(ERROR|FATAL|CRITICAL|Exception|FAIL(ED)?)\b/i.test(line)) return 'error'; + if (/\b(WARN(ING)?)\b/i.test(line)) return 'warn'; + if (/\bDEBUG\b/.test(line)) return 'debug'; + if (/\bINFO\b/.test(line)) return 'info'; + return ''; +} + +function appendLogLines(lines) { + const body = $('#logs-body'); + const atBottom = body.scrollTop + body.clientHeight >= body.scrollHeight - 30; + const frag = document.createDocumentFragment(); + for (const line of lines) { + const div = document.createElement('div'); + div.textContent = line || '\u00a0'; + const lvl = logLevel(line); + if (lvl) div.className = `log-${lvl}`; + frag.append(div); + } + body.append(frag); + while (body.childElementCount > MAX_LOG_LINES) body.firstElementChild.remove(); + if (atBottom) body.scrollTop = body.scrollHeight; +} + +function setLogStatus(text, live) { + $('#logs-status').textContent = text; + $('#logs-status').classList.toggle('live', !!live); +} + +function openLogs(s) { + $('#logs-title').textContent = `Logs: ${s.server_name}`; + $('#logs-body').replaceChildren(); + setLogStatus('Connecting…'); + $('#logs-dialog').showModal(); + connectLogs(s); +} + +function connectLogs(s) { + if (logSource) logSource.close(); + const es = new EventSource(`/api/servers/${s.id}/logs/stream?tail=500`); + logSource = es; + let first = true; + es.onopen = () => setLogStatus('Live', true); + es.onmessage = (e) => { + if (first) { $('#logs-body').replaceChildren(); first = false; } // fresh tail on (re)connect + appendLogLines(JSON.parse(e.data)); + }; + es.addEventListener('end', () => { es.close(); setLogStatus('Server stopped. No new output.'); }); + es.onerror = () => { + es.close(); + setLogStatus('Disconnected. Reconnecting…'); + setTimeout(() => { if (logSource === es && $('#logs-dialog').open) connectLogs(s); }, 3000); + }; +} +$('#logs-close').addEventListener('click', () => $('#logs-dialog').close()); +$('#logs-dialog').addEventListener('close', () => { if (logSource) logSource.close(); logSource = null; }); + +// ---------- wizard ---------- + +const wiz = { step: 1, game: null }; +const form = $('#wizard-form'); + +$('#new-server-btn').addEventListener('click', async () => { + form.reset(); + wiz.step = 1; wiz.game = null; + $('#upload-fields').classList.add('hidden'); + $('#wiz-error').textContent = ''; + const games = await api('/api/games'); + wiz.games = Object.fromEntries(games.map((g) => [g.id, g])); + $('#game-list').innerHTML = games.map((g) => ` + `).join(''); + showStep(); + $('#wizard').showModal(); +}); + +$('#game-list').addEventListener('click', (e) => { + const b = e.target.closest('.game-option'); + if (!b) return; + wiz.game = b.dataset.game; + document.querySelectorAll('.game-option').forEach((x) => x.classList.toggle('selected', x === b)); + goNext(); +}); + +function showStep() { + document.querySelectorAll('.wiz-step').forEach((el) => el.classList.toggle('hidden', +el.dataset.step !== wiz.step)); + $('#wiz-back').classList.toggle('hidden', wiz.step === 1); + $('#wiz-next').classList.toggle('hidden', wiz.step !== 2); + $('#wiz-create').classList.toggle('hidden', wiz.step !== 3); + $('#wiz-error').textContent = ''; +} + +async function goNext() { + if (wiz.step === 1) { + if (!wiz.game) return; + const { port } = await api(`/api/suggest-port?game=${wiz.game}`); + form.port.value = port; + setupGameFields(); + wiz.step = 2; + } else if (wiz.step === 2) { + const err = validateStep2(); + if (err) { $('#wiz-error').textContent = err; return; } + renderReview(); + wiz.step = 3; + } + showStep(); +} + +// Show only the selected game's fields; hidden ones are disabled so they don't block validation. +function setupGameFields() { + const g = wiz.game; + $('#wiz-game-title').textContent = `${wiz.games[g].name} server`; + document.querySelectorAll('.game-fields').forEach((el) => { + const on = el.dataset.game === g; + el.classList.toggle('hidden', !on); + el.querySelectorAll('input, select').forEach((i) => { i.disabled = !on; }); + }); + const pw = form.password; + if (g === 'valheim') { + pw.required = true; pw.minLength = 5; + $('#password-help').textContent = '(at least 5 characters, not part of the server name)'; + } else { + pw.required = false; pw.removeAttribute('minlength'); + $('#password-help').textContent = '(optional; leave empty for an open server)'; + updateMemoryHelp(); + renderPresetMods(); + } +} + +// One recommended-mod checkbox (wizard and mod manager): name, note, and when it was last updated. +function presetLabel(p, inputAttrs) { + const updated = p.updated ? `Updated ${timeAgo(new Date(p.updated * 1000).toISOString())}` : ''; + return ``; +} + +// Build 42 mod checklist from /api/games; all ticked by default. +function renderPresetMods() { + const presets = wiz.games.zomboid.mod_presets || []; + $('#preset-mods').innerHTML = presets.map((m) => presetLabel(m, `name="preset_mods" value="${esc(m.key)}" checked`)).join(''); + updatePresetVisibility(); +} + +function updatePresetVisibility() { + const b42 = form.branch.value === wiz.games.zomboid.preset_branch; + $('#preset-mods-fieldset').classList.toggle('hidden', !b42); + $('#preset-mods-b41').classList.toggle('hidden', b42); + form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.disabled = !b42; }); +} + +const checkedPresets = () => [...form.querySelectorAll('input[name="preset_mods"]:checked:not(:disabled)')]; +$('#preset-all').addEventListener('click', () => form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.checked = true; })); +$('#preset-none').addEventListener('click', () => form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.checked = false; })); + +function updateMemoryHelp() { + const free = wiz.games?.zomboid?.free_memory_mb; + if (free == null) return; + const need = (+form.memory_mb.value || 0) + 768; + const el = $('#memory-help'); + el.textContent = `Needs about ${need} MB free to start; ${free} MB is free right now.` + + (need > free ? ' The server won\'t start until other servers free up memory or you lower this.' : ''); + el.classList.toggle('error', need > free); +} + +function validateStep2() { + const fields = [...form.querySelectorAll('.wiz-step[data-step="2"] input, .wiz-step[data-step="2"] select')] + .filter((i) => !i.disabled && i.type !== 'radio' && i.type !== 'file'); + for (const input of fields) { + if (!input.checkValidity()) { + input.reportValidity(); + return `Please fix the ${input.name.replace('_', ' ')}.`; + } + } + if (wiz.game === 'valheim') { + if (form.server_name.value.includes(form.password.value)) return 'The password cannot appear in the server name.'; + if (form.world_source.value === 'upload' && !form.world_files.files.length) { + return 'Choose your world files to upload.'; + } + } + return ''; +} + +function renderReview() { + const common = [ + ['Game', wiz.games[wiz.game].name], + ['Server name', form.server_name.value], + ['Password', form.password.value || '(none)'], + ['Port', `${form.port.value} (and ${+form.port.value + 1}), UDP`], + ]; + const upload = form.world_source.value === 'upload'; + const rows = wiz.game === 'valheim' ? [...common, + ['World', form.world_name.value], + ['World source', upload ? `Upload: ${[...form.world_files.files].map((f) => f.name).join(', ')}` : 'New world'], + ] : [...common, + ['Admin password', form.admin_password.value], + ['Game version', form.branch.selectedOptions[0].textContent], + ['Memory', `${form.memory_mb.value} MB`], + ['Max players', form.max_players.value], + ['Mods', checkedPresets().map((i) => i.closest('label').querySelector('.preset-name').textContent).join(', ') || 'None'], + ]; + $('#review').innerHTML = rows.map(([k, v]) => `
${esc(k)}
${esc(v)}
`).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(); +}); diff --git a/app/static/art/valheim-header.jpg b/app/static/art/valheim-header.jpg new file mode 100644 index 0000000..ee51d83 Binary files /dev/null and b/app/static/art/valheim-header.jpg differ diff --git a/app/static/art/valheim-poster.jpg b/app/static/art/valheim-poster.jpg new file mode 100644 index 0000000..1124621 Binary files /dev/null and b/app/static/art/valheim-poster.jpg differ diff --git a/app/static/art/zomboid-header.jpg b/app/static/art/zomboid-header.jpg new file mode 100644 index 0000000..238fb2e Binary files /dev/null and b/app/static/art/zomboid-header.jpg differ diff --git a/app/static/art/zomboid-poster.jpg b/app/static/art/zomboid-poster.jpg new file mode 100644 index 0000000..39564ad Binary files /dev/null and b/app/static/art/zomboid-poster.jpg differ diff --git a/app/static/index.html b/app/static/index.html new file mode 100644 index 0000000..d596d27 --- /dev/null +++ b/app/static/index.html @@ -0,0 +1,301 @@ + + + + + +Game Servers + + + + + + + + + + + + +

About Backups

+

What is backed up

+
    +
  • Valheim: the world folder (.db2, .fwl2, .ok, .chunks and .chunk files), or the .db + .fwl pair for older worlds.
  • +
  • Project Zomboid: the world save, the player database and the server's settings files.
  • +
+

Automatic backups

+
    +
  • A server run becomes eligible for a backup once at least one player connects.
  • +
  • If the server starts and nobody connects, no backup is made.
  • +
  • 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.
  • +
  • Backups are taken after the server has stopped, so they hold the world as it was saved on shutdown.
  • +
+

Manual backups

+
    +
  • Made every time you use Download in a server's Manage panel: the zip you download is also saved here.
  • +
  • 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.
  • +
+

Retention

+
    +
  • The newest 5 automatic and newest 5 manual backups are kept for each server. Older ones are + deleted when a new backup is made.
  • +
  • Backups are stored on the VPS in /srv/gameservers/backups/<game>/<auto|manual>/, + outside the server's own folder, so they are kept even if the server and its world files are deleted.
  • +
+
+ + + +
+
+

New game server

+

Choose a game

+
+
+ + + + + +

+
+ + + + + +
+
+
+ + + +
+

Manage

+ +
+ +
+

Players

+
+
+ +
+

Server Auto Stop

+ + +

+

+
+
+ +
+

Settings

+
+ +

+
+
+ + + + + +
+

Logs

+
Live, color-coded output from the game server.
+
+ +
+

Delete server

+ +
+
+
+ + + +
+

Mods

+ +
+ +
+ + +
+ +
+ Import from another server's config + +
+
+
+ +
+
+

Workshop items

+
+
+
+

Enabled mods & load order

+ +
+

Mods load top to bottom. Auto-sort puts each mod after the ones it requires.

+
    +
    +
    + + + + +
    + + + +
    +

    Logs

    + +
    +
    
    +
    + + + + + diff --git a/app/static/mods.js b/app/static/mods.js new file mode 100644 index 0000000..fd8fb77 --- /dev/null +++ b/app/static/mods.js @@ -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 = '

    No workshop items yet. Paste a link above to add one.

    '; + 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 ? `map: ${esc(m.maps.join(', '))}` : '', + m.error ? `can't load` : '', + m.require.length ? `needs ${m.require.length}` : '', + ].join(''); + return ``; + }).join(''); + } else if (info?.downloaded) { + modsHtml = '

    No mods found in this item.

    '; + } else { + modsHtml = `

    Mod IDs show up once the server has downloaded this item: + click Fetch mod info while the server is online, or restart it.

    `; + } + const warn = t.zomboid === false || info?.available === false + ? 'not available / not a Project Zomboid item' : ''; + return `
    +
    + ${t.preview ? `` : ''} +
    + ${esc(title)} +
    ${esc(id)}${size ? ` · ${fmtBytes(size)}` : ''}${info?.downloaded ? ' · downloaded' : ''} ${warn}
    +
    + +
    + ${modsHtml} +
    `; + }).join(''); +} + +function renderOrder() { + const known = knownMods(); + if (!mm.mods.length) { + $('#mods-order').innerHTML = '

    No mods enabled. Tick mods on the left to enable them.

    '; + return; + } + $('#mods-order').innerHTML = mm.mods.map((id, i) => { + const m = known[id]; + return `
  1. + ${esc(m?.name || id)} ${esc(id)} + + + + + +
  2. `; + }).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) => `
  3. + ${esc(i.text).replace(/\n/g, '
    ')}
    ${i.source ? ` (${i.source})` : ''} +
  4. `).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) => `
    ${esc(m.text)}${m.action === 'enable-all' + ? '
    ' : ''}
    `).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 }]); } +}); diff --git a/app/static/style.css b/app/static/style.css new file mode 100644 index 0000000..c275284 --- /dev/null +++ b/app/static/style.css @@ -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; } diff --git a/app/zomboid.py b/app/zomboid.py new file mode 100644 index 0000000..a0c910f --- /dev/null +++ b/app/zomboid.py @@ -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_ 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"(? ./deploy.sh +# Copies the code to /opt/gsm/src on the server and runs install.sh there. SITE= is passed on if set. +set -euo pipefail +[ -n "${HOST:-}" ] || { echo "usage: HOST=root@ $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" diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..8e13d7d --- /dev/null +++ b/install.sh @@ -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 | 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=" +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