"""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