Files
TarkovMaps/server/serve.py
T

305 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Static server plus local placement/trim editing API, reachable 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
path = urlsplit(self.path).path
if path not in {"/api/placement", "/api/trim"}:
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"]
if not isinstance(map_id, str) or not map_id or map_id == "overall":
raise ValueError("id must name a detail map")
if path == "/api/placement":
cx, cy = float(payload["cx"]), float(payload["cy"])
width, height = float(payload["w"]), float(payload["h"])
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")
else:
points = normalize_trim_points(payload["points"])
transparency = float(payload["outsideTransparency"])
if not math.isfinite(transparency) or not 0 <= transparency <= 1:
raise ValueError("outsideTransparency must be between 0 and 1")
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
self.send_json(400, {"error": str(exc)})
return
try:
if path == "/api/placement":
result = save_placement(map_id, cx, cy, width, height)
else:
result = save_trim(map_id, points, transparency)
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 or "/tiles-trimmed/" 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 normalize_trim_points(value) -> list[list[float]]:
if not isinstance(value, list) or len(value) > 500:
raise ValueError("points must be a list containing at most 500 vertices")
if value and len(value) < 3:
raise ValueError("a trim polygon needs at least three points, or none to clear it")
points = []
for point in value:
if not isinstance(point, list) or len(point) != 2:
raise ValueError("each trim point must be [x, y]")
x, y = float(point[0]), float(point[1])
if not math.isfinite(x) or not math.isfinite(y) or not 0 <= x <= 1 or not 0 <= y <= 1:
raise ValueError("trim point coordinates must be finite values from 0 to 1")
points.append([round(x, 6), round(y, 6)])
return points
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 _write_world(raw: dict) -> None:
path = WEB / "data" / "world.json"
temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
temporary.write_text(
json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
temporary.replace(path)
def save_trim(map_id: str, points: list[list[float]], transparency: float) -> dict:
"""Persist a polygon and build a separate, permanently masked raster copy."""
with CONFIG_LOCK:
original_config = CONFIG.read_text(encoding="utf-8")
raw = json.loads(original_config)
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"
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 a trim",
409,
)
trim = {
"points": points,
"outsideTransparency": round(transparency, 3),
}
if points:
selected["trim"] = trim
else:
selected.pop("trim", None)
trim = None
try:
_write_config(raw)
proc = subprocess.run(
[sys.executable, str(BUILD_TOOL), map_id, "--tiles-only", "--trim-only"],
cwd=ROOT,
capture_output=True,
text=True,
timeout=300,
check=False,
)
except (OSError, subprocess.TimeoutExpired) as exc:
CONFIG.write_text(original_config, encoding="utf-8")
raise PlacementError(
f"permanent trim could not be built; maps.json was restored: {exc}"
) from exc
if proc.returncode:
CONFIG.write_text(original_config, encoding="utf-8")
raise PlacementError(
"permanent trim build 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, "trim": trim, "map": entry}
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()