148 lines
5.4 KiB
Python
148 lines
5.4 KiB
Python
"""HTTP view of the stage. The page polls /api/state."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse
|
|
|
|
from simulator.artnet import ArtNetNode
|
|
from simulator.decode import view_stage
|
|
from simulator.stage import Stage, apply_show, load_stage, set_heading
|
|
|
|
STATIC = Path(__file__).resolve().parent / "static"
|
|
|
|
CONTENT_TYPES = {
|
|
".html": "text/html; charset=utf-8",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".css": "text/css; charset=utf-8",
|
|
}
|
|
|
|
|
|
class Simulator:
|
|
def __init__(self, stage: Stage, node: ArtNetNode, show: Path | None = None):
|
|
self.stage = stage
|
|
self.node = node
|
|
self.show = show
|
|
|
|
def state(self) -> dict:
|
|
stats = self.node.stats()
|
|
stats["fixtures"] = view_stage(self.stage, self.node.snapshot())
|
|
return stats
|
|
|
|
def stage_dir(self) -> Path | None:
|
|
return self.stage.path.parent if self.stage.path else None
|
|
|
|
def stages(self) -> dict:
|
|
"""The stage maps next to the current one, for the page's drop-down."""
|
|
folder = self.stage_dir()
|
|
files = sorted(path.name for path in folder.glob("*.json")) if folder else []
|
|
current = self.stage.path.name if self.stage.path else None
|
|
return {"current": current, "stages": files}
|
|
|
|
def switch(self, name: str) -> Stage:
|
|
"""Load another stage map from the same folder, with the same show."""
|
|
folder = self.stage_dir()
|
|
if folder is None or name not in self.stages()["stages"]:
|
|
raise KeyError(name)
|
|
stage = load_stage(folder / name)
|
|
if self.show is not None:
|
|
apply_show(stage, self.show)
|
|
self.stage = stage
|
|
return stage
|
|
|
|
|
|
def make_handler(sim: Simulator):
|
|
class Handler(BaseHTTPRequestHandler):
|
|
simulator = sim
|
|
|
|
def log_message(self, fmt: str, *args) -> None:
|
|
return
|
|
|
|
def do_POST(self) -> None:
|
|
path = urlparse(self.path).path
|
|
if path == "/api/stage":
|
|
self._switch_stage()
|
|
return
|
|
if path != "/api/heading":
|
|
self.send_error(404)
|
|
return
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
if length <= 0 or length > 4096:
|
|
self._json({"error": "bad heading"}, 400)
|
|
return
|
|
try:
|
|
payload = json.loads(self.rfile.read(length))
|
|
fixture = set_heading(
|
|
self.simulator.stage,
|
|
str(payload["id"]),
|
|
direction=payload.get("direction"),
|
|
zero=payload.get("zero"),
|
|
)
|
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
|
self._json({"error": "bad heading"}, 400)
|
|
return
|
|
self._json({"id": fixture.id, "direction": fixture.direction, "zero": fixture.zero})
|
|
|
|
def do_GET(self) -> None:
|
|
path = urlparse(self.path).path
|
|
if path == "/api/state":
|
|
self._json(self.simulator.state())
|
|
return
|
|
if path == "/api/stage":
|
|
self._json(self.simulator.stage.to_json())
|
|
return
|
|
if path == "/api/stages":
|
|
self._json(self.simulator.stages())
|
|
return
|
|
if path in ("/", "/index.html"):
|
|
self._file(STATIC / "index.html")
|
|
return
|
|
if path.startswith("/static/"):
|
|
target = (STATIC / path.removeprefix("/static/")).resolve()
|
|
if STATIC.resolve() in target.parents or target == STATIC.resolve():
|
|
self._file(target)
|
|
return
|
|
self.send_error(404)
|
|
|
|
def _switch_stage(self) -> None:
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
if length <= 0 or length > 4096:
|
|
self._json({"error": "bad stage"}, 400)
|
|
return
|
|
try:
|
|
name = str(json.loads(self.rfile.read(length))["file"])
|
|
stage = self.simulator.switch(name)
|
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
|
self._json({"error": "bad stage"}, 400)
|
|
return
|
|
self._json(stage.to_json())
|
|
|
|
def _json(self, payload: dict, status: int = 200) -> None:
|
|
body = json.dumps(payload).encode()
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def _file(self, path: Path) -> None:
|
|
if not path.is_file():
|
|
self.send_error(404)
|
|
return
|
|
body = path.read_bytes()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", CONTENT_TYPES.get(path.suffix, "application/octet-stream"))
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
return Handler
|
|
|
|
|
|
def make_server(sim: Simulator, host: str, port: int) -> ThreadingHTTPServer:
|
|
return ThreadingHTTPServer((host, port), make_handler(sim))
|