593 lines
24 KiB
Python
593 lines
24 KiB
Python
"""Static server plus local map editing and read-only site export API.
|
||
|
||
python server/serve.py [port] # read-only, default 8080
|
||
python server/serve.py [port] --editable # trusted local editing
|
||
|
||
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 re
|
||
import socket
|
||
import socketserver
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import uuid
|
||
import zipfile
|
||
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"
|
||
MARKER_DIR = WEB / "data" / "markers"
|
||
MARKER_EDIT_DIR = WEB / "data" / "marker-edits"
|
||
EXPORT_DIR = ROOT / "exports"
|
||
EXPORT_ZIP = EXPORT_DIR / "tarkov-map-static.zip"
|
||
CONFIG_LOCK = threading.Lock()
|
||
|
||
|
||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||
extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map,
|
||
".webp": "image/webp"}
|
||
editable = False
|
||
|
||
# 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 send_export(self, include_body: bool) -> None:
|
||
if not self.editable:
|
||
self.send_json(403, {"error": "This server is read-only"})
|
||
return
|
||
if not EXPORT_ZIP.exists():
|
||
self.send_json(404, {"error": "No static export has been created yet"})
|
||
return
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "application/zip")
|
||
self.send_header(
|
||
"Content-Disposition", f'attachment; filename="{EXPORT_ZIP.name}"'
|
||
)
|
||
self.send_header("Content-Length", str(EXPORT_ZIP.stat().st_size))
|
||
self.send_header("Cache-Control", "no-store")
|
||
self.end_headers()
|
||
if include_body:
|
||
with EXPORT_ZIP.open("rb") as source:
|
||
self.copyfile(source, self.wfile)
|
||
|
||
def do_GET(self) -> None: # noqa: N802 - stdlib handler API
|
||
path = urlsplit(self.path).path
|
||
if path == "/data/capabilities.json":
|
||
self.send_json(200, {
|
||
"mapEditing": self.editable,
|
||
"markerEditing": self.editable,
|
||
"markerPersistence": "server" if self.editable else "none",
|
||
"exporting": self.editable,
|
||
})
|
||
return
|
||
if path == "/api/export/download":
|
||
self.send_export(include_body=True)
|
||
return
|
||
super().do_GET()
|
||
|
||
def do_HEAD(self) -> None: # noqa: N802 - stdlib handler API
|
||
if urlsplit(self.path).path == "/api/export/download":
|
||
self.send_export(include_body=False)
|
||
return
|
||
super().do_HEAD()
|
||
|
||
def do_POST(self) -> None: # noqa: N802 - stdlib handler API
|
||
if not self.editable:
|
||
self.send_json(403, {"error": "This server is read-only"})
|
||
return
|
||
|
||
path = urlsplit(self.path).path
|
||
if path not in {"/api/placement", "/api/trim", "/api/marker", "/api/export"}:
|
||
self.send_json(404, {"error": "unknown API endpoint"})
|
||
return
|
||
|
||
if path == "/api/export":
|
||
try:
|
||
result = export_static_site()
|
||
except PlacementError as exc:
|
||
self.send_json(exc.status, {"error": str(exc)})
|
||
return
|
||
self.send_json(200, result)
|
||
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["mapId"] if path == "/api/marker" else 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")
|
||
elif path == "/api/trim":
|
||
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")
|
||
else:
|
||
marker_id = payload.get("id")
|
||
action = payload.get("action", "save")
|
||
if action not in {"save", "delete"}:
|
||
raise ValueError("marker action must be save or delete")
|
||
if marker_id is not None and (
|
||
not isinstance(marker_id, str) or not 1 <= len(marker_id) <= 120
|
||
):
|
||
raise ValueError("marker id must be a string no longer than 120 characters")
|
||
if action == "delete":
|
||
if marker_id is None:
|
||
raise ValueError("deleting a marker requires its id")
|
||
else:
|
||
x, y = float(payload["x"]), float(payload["y"])
|
||
if not all(math.isfinite(v) and 0 <= v <= 1 for v in (x, y)):
|
||
raise ValueError("marker x and y must be finite numbers from 0 to 1")
|
||
label = payload["label"]
|
||
if not isinstance(label, str) or not label.strip() or len(label.strip()) > 160:
|
||
raise ValueError("marker label must contain 1 to 160 characters")
|
||
label = label.strip()
|
||
category = payload["category"]
|
||
if not isinstance(category, str) or not re.fullmatch(r"[a-z0-9-]{1,40}", category):
|
||
raise ValueError("marker category must use lowercase letters, numbers or hyphens")
|
||
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)
|
||
elif path == "/api/trim":
|
||
result = save_trim(map_id, points, transparency)
|
||
elif action == "delete":
|
||
result = delete_marker(marker_id, map_id)
|
||
else:
|
||
result = save_marker(marker_id, map_id, x, y, label, category)
|
||
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=31536000, 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 export_static_site() -> dict:
|
||
"""Create an atomic, read-only ZIP containing only the deployable web root."""
|
||
required = [
|
||
WEB / "index.html",
|
||
WEB / "app.js",
|
||
WEB / "style.css",
|
||
WEB / "data" / "world.json",
|
||
WEB / "data" / "capabilities.json",
|
||
WEB / "tiles",
|
||
]
|
||
missing = [str(path.relative_to(ROOT)) for path in required if not path.exists()]
|
||
if missing:
|
||
raise PlacementError(
|
||
"static export is incomplete; missing " + ", ".join(missing), 409
|
||
)
|
||
|
||
stored_suffixes = {
|
||
".webp", ".png", ".jpg", ".jpeg", ".gif", ".ico",
|
||
".woff", ".woff2", ".zip",
|
||
}
|
||
excluded_prefixes = ("data/marker-defaults/",)
|
||
with CONFIG_LOCK:
|
||
EXPORT_DIR.mkdir(parents=True, exist_ok=True)
|
||
temporary = EXPORT_DIR / f".{EXPORT_ZIP.name}.{os.getpid()}.tmp"
|
||
file_count = 0
|
||
source_bytes = 0
|
||
try:
|
||
with zipfile.ZipFile(temporary, "w", allowZip64=True) as archive:
|
||
for path in sorted(item for item in WEB.rglob("*") if item.is_file()):
|
||
relative = path.relative_to(WEB).as_posix()
|
||
if relative.startswith(excluded_prefixes):
|
||
continue
|
||
compression = (
|
||
zipfile.ZIP_STORED
|
||
if path.suffix.lower() in stored_suffixes
|
||
else zipfile.ZIP_DEFLATED
|
||
)
|
||
archive.write(path, relative, compress_type=compression)
|
||
file_count += 1
|
||
source_bytes += path.stat().st_size
|
||
manifest = {
|
||
"format": 1,
|
||
"readOnly": True,
|
||
"fileCount": file_count,
|
||
"sourceBytes": source_bytes,
|
||
}
|
||
archive.writestr(
|
||
"export-manifest.json",
|
||
json.dumps(manifest, indent=2) + "\n",
|
||
compress_type=zipfile.ZIP_DEFLATED,
|
||
)
|
||
temporary.replace(EXPORT_ZIP)
|
||
except (OSError, zipfile.BadZipFile) as exc:
|
||
temporary.unlink(missing_ok=True)
|
||
raise PlacementError(f"static export failed: {exc}") from exc
|
||
|
||
return {
|
||
"ok": True,
|
||
"fileName": EXPORT_ZIP.name,
|
||
"download": "/api/export/download",
|
||
"fileCount": file_count + 1,
|
||
"sourceBytes": source_bytes,
|
||
"zipBytes": EXPORT_ZIP.stat().st_size,
|
||
}
|
||
|
||
|
||
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 _marker_file(directory: Path, map_id: str) -> Path:
|
||
if not re.fullmatch(r"[a-z0-9-]+", map_id):
|
||
raise PlacementError("map id contains unsupported filename characters", 400)
|
||
return directory / f"{map_id}.json"
|
||
|
||
|
||
def _write_marker_edits(map_id: str, raw: dict) -> None:
|
||
MARKER_EDIT_DIR.mkdir(parents=True, exist_ok=True)
|
||
destination = _marker_file(MARKER_EDIT_DIR, map_id)
|
||
temporary = destination.with_name(f"{destination.name}.{os.getpid()}.tmp")
|
||
temporary.write_text(
|
||
json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||
)
|
||
temporary.replace(destination)
|
||
|
||
|
||
def save_marker(
|
||
marker_id: str | None,
|
||
map_id: str,
|
||
x: float,
|
||
y: float,
|
||
label: str,
|
||
category: str,
|
||
) -> dict:
|
||
"""Persist a user marker or an override without touching PSD extraction output."""
|
||
with CONFIG_LOCK:
|
||
maps = json.loads(CONFIG.read_text(encoding="utf-8")).get("maps", [])
|
||
if not any(m.get("id") == map_id and not m.get("base") for m in maps):
|
||
raise PlacementError(f"unknown map id: {map_id}", 404)
|
||
marker_path = _marker_file(MARKER_DIR, map_id)
|
||
edit_path = _marker_file(MARKER_EDIT_DIR, map_id)
|
||
if not marker_path.exists():
|
||
raise PlacementError(
|
||
f"web/data/markers/{map_id}.json is missing; extract markers first", 409
|
||
)
|
||
|
||
extracted = json.loads(marker_path.read_text(encoding="utf-8")).get("markers", [])
|
||
originals = {item.get("id"): item for item in extracted if item.get("id")}
|
||
if edit_path.exists():
|
||
edits = json.loads(edit_path.read_text(encoding="utf-8"))
|
||
else:
|
||
edits = {"version": 2, "overrides": {}, "added": [], "deleted": []}
|
||
edits["version"] = 2
|
||
overrides = edits.setdefault("overrides", {})
|
||
added = edits.setdefault("added", [])
|
||
deleted = edits.setdefault("deleted", [])
|
||
|
||
values = {
|
||
"mapId": map_id,
|
||
"x": round(x, 6),
|
||
"y": round(y, 6),
|
||
"label": label,
|
||
"category": category,
|
||
}
|
||
if marker_id is None:
|
||
marker_id = f"user-{uuid.uuid4().hex}"
|
||
record = {"id": marker_id, **values, "source": "User marker"}
|
||
added.append(record)
|
||
else:
|
||
if marker_id in deleted:
|
||
deleted.remove(marker_id)
|
||
added_record = next((item for item in added if item.get("id") == marker_id), None)
|
||
if added_record is not None:
|
||
added_record.update(values)
|
||
record = dict(added_record)
|
||
else:
|
||
original = originals.get(marker_id)
|
||
if original is None:
|
||
raise PlacementError(f"unknown marker id: {marker_id}", 404)
|
||
if original.get("mapId") != map_id:
|
||
raise PlacementError("an extracted marker cannot be moved to another map", 400)
|
||
comparable = {
|
||
**original,
|
||
"x": round(float(original.get("x", 0)), 6),
|
||
"y": round(float(original.get("y", 0)), 6),
|
||
}
|
||
override = {
|
||
key: value for key, value in values.items()
|
||
if value != comparable.get(key)
|
||
}
|
||
if override:
|
||
overrides[marker_id] = override
|
||
else:
|
||
overrides.pop(marker_id, None)
|
||
record = {**original, **override}
|
||
|
||
_write_marker_edits(map_id, edits)
|
||
return {"ok": True, "marker": record}
|
||
|
||
|
||
def delete_marker(marker_id: str, map_id: str) -> dict:
|
||
"""Hide an extracted marker or remove a user marker without touching defaults."""
|
||
with CONFIG_LOCK:
|
||
maps = json.loads(CONFIG.read_text(encoding="utf-8")).get("maps", [])
|
||
if not any(m.get("id") == map_id and not m.get("base") for m in maps):
|
||
raise PlacementError(f"unknown map id: {map_id}", 404)
|
||
marker_path = _marker_file(MARKER_DIR, map_id)
|
||
edit_path = _marker_file(MARKER_EDIT_DIR, map_id)
|
||
if not marker_path.exists():
|
||
raise PlacementError(
|
||
f"web/data/markers/{map_id}.json is missing; extract markers first", 409
|
||
)
|
||
|
||
extracted = json.loads(marker_path.read_text(encoding="utf-8")).get("markers", [])
|
||
originals = {item.get("id"): item for item in extracted if item.get("id")}
|
||
edits = json.loads(edit_path.read_text(encoding="utf-8")) if edit_path.exists() \
|
||
else {"version": 2, "overrides": {}, "added": [], "deleted": []}
|
||
edits["version"] = 2
|
||
overrides = edits.setdefault("overrides", {})
|
||
added = edits.setdefault("added", [])
|
||
deleted = edits.setdefault("deleted", [])
|
||
|
||
added_record = next((item for item in added if item.get("id") == marker_id), None)
|
||
if added_record is not None:
|
||
edits["added"] = [item for item in added if item.get("id") != marker_id]
|
||
else:
|
||
original = originals.get(marker_id)
|
||
if original is None:
|
||
raise PlacementError(f"unknown marker id: {marker_id}", 404)
|
||
if original.get("mapId") != map_id:
|
||
raise PlacementError("an extracted marker cannot be deleted from another map", 400)
|
||
if marker_id not in deleted:
|
||
deleted.append(marker_id)
|
||
deleted.sort()
|
||
overrides.pop(marker_id, None)
|
||
_write_marker_edits(map_id, edits)
|
||
return {"ok": True, "deletedId": marker_id, "mapId": map_id}
|
||
|
||
|
||
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")
|
||
|
||
args = sys.argv[1:]
|
||
Handler.editable = "--editable" in args
|
||
positional = [arg for arg in args if not arg.startswith("--")]
|
||
port = int(positional[0]) if positional 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" mode {'editable' if Handler.editable else 'read-only'}")
|
||
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()
|