"""Static server for web/, reachable from other devices on the LAN. python server/serve.py [port] # default 8080 Deliberately dependency-free. Tiles are immutable once built, so they get a long cache lifetime while the app shell stays uncached -- that is the whole difference between a snappy second visit and re-downloading every tile. For heavier use put Caddy or nginx in front of web/ instead; nothing here is special. """ from __future__ import annotations import functools import http.server import json import math import os import socket import socketserver import subprocess import sys import threading from pathlib import Path from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parent.parent WEB = ROOT / "web" CONFIG = ROOT / "maps.json" BUILD_TOOL = ROOT / "tools" / "build.py" CONFIG_LOCK = threading.Lock() class Handler(http.server.SimpleHTTPRequestHandler): extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map, ".webp": "image/webp"} # SimpleHTTPRequestHandler defaults to HTTP/1.0, which closes the socket # after every response -- one TCP handshake per tile. A map view pulls ~30 # tiles, so over WiFi that is ~30 extra round trips. HTTP/1.1 keeps the # connection open. Safe here because every response carries Content-Length. protocol_version = "HTTP/1.1" timeout = 10 # don't let idle keep-alive sockets pin threads forever def send_json(self, status: int, payload: dict) -> None: body = json.dumps(payload, ensure_ascii=False).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def do_POST(self) -> None: # noqa: N802 - stdlib handler API if urlsplit(self.path).path != "/api/placement": self.send_json(404, {"error": "unknown API endpoint"}) return try: length = int(self.headers.get("Content-Length", "0")) if not 0 < length <= 16_384: raise ValueError("request body must be between 1 and 16384 bytes") payload = json.loads(self.rfile.read(length)) map_id = payload["id"] cx, cy = float(payload["cx"]), float(payload["cy"]) width, height = float(payload["w"]), float(payload["h"]) if not isinstance(map_id, str) or not map_id or map_id == "overall": raise ValueError("id must name a detail map") if not all(math.isfinite(v) for v in (cx, cy, width, height)): raise ValueError("cx, cy, w and h must be finite numbers") if width <= 0 or height <= 0: raise ValueError("w and h must be greater than zero") except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: self.send_json(400, {"error": str(exc)}) return try: result = save_placement(map_id, cx, cy, width, height) except PlacementError as exc: self.send_json(exc.status, {"error": str(exc)}) return self.send_json(200, result) def end_headers(self): if "/tiles/" in self.path: self.send_header("Cache-Control", "public, max-age=604800, immutable") else: self.send_header("Cache-Control", "no-cache") super().end_headers() def log_message(self, fmt, *args): pass # one line per tile is unreadable class PlacementError(Exception): def __init__(self, message: str, status: int = 500): super().__init__(message) self.status = status def _write_config(raw: dict) -> None: temporary = CONFIG.with_name(f"{CONFIG.name}.{os.getpid()}.tmp") temporary.write_text( json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) temporary.replace(CONFIG) def save_placement(map_id: str, cx: float, cy: float, width: float, height: float) -> dict: """Persist one map's center and dimensions, then rebuild its tile pyramid.""" with CONFIG_LOCK: original = CONFIG.read_text(encoding="utf-8") raw = json.loads(original) selected = next((m for m in raw["maps"] if m["id"] == map_id), None) if selected is None: raise PlacementError(f"unknown map id: {map_id}", 404) world_path = WEB / "data" / "world.json" if world_path.exists(): world = json.loads(world_path.read_text(encoding="utf-8")) max_x = world["worldSize"][0] / world["overallScale"] max_y = world["worldSize"][1] / world["overallScale"] if not 0 <= cx <= max_x or not 0 <= cy <= max_y: raise PlacementError( f"center must remain inside the rotated overall map " f"(x 0–{max_x:.0f}, y 0–{max_y:.0f})", 400, ) if width > max_x * 2 or height > max_y * 2: raise PlacementError( f"map dimensions are too large (maximum {max_x * 2:.0f} × {max_y * 2:.0f})", 400, ) base = ROOT / "build" / map_id / "base.png" if not base.exists(): raise PlacementError( f"{base.relative_to(ROOT)} is missing; export the map before saving placement", 409, ) selected["place"]["cx"] = round(cx, 2) selected["place"]["cy"] = round(cy, 2) selected["place"]["w"] = round(width, 2) selected["place"]["h"] = round(height, 2) _write_config(raw) try: proc = subprocess.run( [sys.executable, str(BUILD_TOOL), map_id, "--tiles-only"], cwd=ROOT, capture_output=True, text=True, timeout=300, check=False, ) except (OSError, subprocess.TimeoutExpired) as exc: CONFIG.write_text(original, encoding="utf-8") raise PlacementError(f"tile rebuild could not finish; maps.json was restored: {exc}") \ from exc if proc.returncode: CONFIG.write_text(original, encoding="utf-8") raise PlacementError( "tile rebuild failed; maps.json was restored\n" + (proc.stderr or proc.stdout)[-2000:] ) manifest = json.loads(world_path.read_text(encoding="utf-8")) entry = next(m for m in manifest["maps"] if m["id"] == map_id) return { "ok": True, "id": map_id, "cx": selected["place"]["cx"], "cy": selected["place"]["cy"], "w": selected["place"]["w"], "h": selected["place"]["h"], "map": entry, } class Server(socketserver.ThreadingTCPServer): allow_reuse_address = True daemon_threads = True def lan_ip() -> str: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("10.255.255.255", 1)) # no packets sent; just picks the route return s.getsockname()[0] except OSError: return "127.0.0.1" finally: s.close() def main() -> None: if not (WEB / "data" / "world.json").exists(): print("warning: web/data/world.json missing -- run tools/build.py first\n") port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080 handler = functools.partial(Handler, directory=str(WEB)) with Server(("0.0.0.0", port), handler) as httpd: print(f"serving {WEB}") print(f" local http://localhost:{port}/") print(f" LAN http://{lan_ip()}:{port}/") print("\nCtrl+C to stop") try: httpd.serve_forever() except KeyboardInterrupt: print("\nstopped") if __name__ == "__main__": main()