"""Local editor: load the SMC-PAD preset, edit it, save it back.""" from __future__ import annotations import json import mimetypes import threading import traceback from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import urlparse from padcontroller.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour from padcontroller.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global STATIC_DIR = Path(__file__).parent / "static" # The image MidiSuite uploads for its factory reset, and its global block. FACTORY_IMAGE = Path(__file__).parent / "factory.bin" FACTORY_GLOBAL = bytes.fromhex("780032040000020001010000") class ApiError(Exception): def __init__(self, message: str, status: int = 400): super().__init__(message) self.status = status class Editor: def __init__(self): self.lock = threading.Lock() def status(self) -> dict: port = connected() return {"connected": port is not None, "port": port} def load(self) -> dict: with self.lock: try: with Link() as link: document = unpack(read_image(link)) document["global"] = unpack_global(read_global(link)) return document except PadError as exc: raise ApiError(str(exc), 503) from exc def save(self, document: dict) -> dict: try: desired = pack(document) block = document.get("global") settings = pack_global(block) if isinstance(block, dict) else None except PresetError as exc: raise ApiError(str(exc)) from exc with self.lock: try: written = save_image(desired, settings=settings) except PadError as exc: raise ApiError(str(exc), 503) from exc if written: message = f"Saved on the pad. {written} bytes written." else: message = "Saved on the pad." return {"ok": True, "message": message, "bytes": written} def colour(self, body: dict) -> dict: try: preset = int(body["preset"]) index = int(body["index"]) rgb = body["rgb"] if not isinstance(rgb, list) or len(rgb) != 3: raise PresetError("a pad colour needs red, green, and blue") except (KeyError, TypeError, ValueError) as exc: raise ApiError("colour needs a preset, a pad, and an rgb colour") from exc with self.lock: try: offset = write_colour(preset, index, rgb) except PresetError as exc: raise ApiError(str(exc)) from exc except PadError as exc: raise ApiError(str(exc), 503) from exc return {"ok": True, "offset": offset} def bank(self, body: dict) -> dict: bank = body.get("bank") if isinstance(bank, bool) or bank not in (0, 1): raise ApiError("bank must be 0 or 1") with self.lock: try: set_bank(bank) except PadError as exc: raise ApiError(str(exc), 503) from exc return {"ok": True, "bank": bank} def imported(self, raw: bytes) -> dict: try: return unpack(raw) except PresetError as exc: raise ApiError(str(exc)) from exc def factory(self) -> dict: document = unpack(FACTORY_IMAGE.read_bytes()) document["global"] = unpack_global(FACTORY_GLOBAL) return document def exported(self, document: dict) -> bytes: try: return pack(document) except PresetError as exc: raise ApiError(str(exc)) from exc def make_server(host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer: editor = Editor() handler = type("BoundHandler", (Handler,), {"editor": editor}) server = ThreadingHTTPServer((host, port), handler) server.editor = editor # type: ignore[attr-defined] return server class Handler(BaseHTTPRequestHandler): editor: Editor def log_message(self, fmt: str, *args) -> None: return def _json(self, status: int, body: dict) -> None: raw = json.dumps(body).encode() self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(raw))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(raw) def _bytes(self, raw: bytes, content_type: str, filename: str | None = None) -> None: self.send_response(200) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(raw))) self.send_header("Cache-Control", "no-store") if filename: self.send_header("Content-Disposition", f'attachment; filename="{filename}"') self.end_headers() self.wfile.write(raw) def _read(self) -> bytes: n = int(self.headers.get("Content-Length") or 0) return self.rfile.read(n) if n > 0 else b"" def _json_body(self) -> dict: raw = self._read() if not raw: return {} try: body = json.loads(raw.decode("utf-8")) except json.JSONDecodeError as exc: raise ApiError(f"invalid JSON: {exc}") from exc if not isinstance(body, dict): raise ApiError("expected a JSON object") return body def _static(self, rel: str) -> None: rel = rel.lstrip("/") or "index.html" path = (STATIC_DIR / rel).resolve() if STATIC_DIR.resolve() not in path.parents or not path.is_file(): self.send_error(404) return ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream" if ctype.startswith("text/") or ctype.endswith(("javascript", "json")): ctype = f"{ctype}; charset=utf-8" self._bytes(path.read_bytes(), ctype) def _dispatch(self, method: str) -> None: url = urlparse(self.path) editor = self.editor try: if not url.path.startswith("/api/"): if method != "GET": self.send_error(405) return if url.path == "/favicon.ico": self.send_response(204) self.send_header("Content-Length", "0") self.end_headers() return self._static(url.path) return route = (method, url.path) if route == ("GET", "/api/status"): self._json(200, editor.status()) elif route == ("POST", "/api/load"): self._json(200, editor.load()) elif route == ("POST", "/api/save"): self._json(200, editor.save(self._json_body())) elif route == ("POST", "/api/colour"): self._json(200, editor.colour(self._json_body())) elif route == ("POST", "/api/bank"): self._json(200, editor.bank(self._json_body())) elif route == ("POST", "/api/import"): raw = self._read() if len(raw) != IMAGE_LEN: raise ApiError(f"preset file is {len(raw)} bytes, expected {IMAGE_LEN}") self._json(200, editor.imported(raw)) elif route == ("POST", "/api/factory"): self._json(200, editor.factory()) elif route == ("POST", "/api/export"): self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin") else: self._json(404, {"error": f"no route {method} {url.path}"}) except ApiError as exc: self._json(exc.status, {"error": str(exc)}) except Exception as exc: # noqa: BLE001 — surface anything else to the UI traceback.print_exc() self._json(500, {"error": f"{type(exc).__name__}: {exc}"}) def do_GET(self) -> None: # noqa: N802 self._dispatch("GET") def do_POST(self) -> None: # noqa: N802 self._dispatch("POST")