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