#!/usr/bin/env python3 """Load the selected mod-ui pedalboard through its active session WebSocket.""" import argparse import base64 import hashlib import json import os import socket import struct import sys import time from pathlib import Path from urllib.error import URLError from urllib.parse import urlencode from urllib.request import urlopen from urllib.request import Request def encode_control_frame(opcode, payload=b""): payload = payload if isinstance(payload, bytes) else payload.encode("utf-8") mask = os.urandom(4) size = len(payload) if size < 126: header = bytes((0x80 | opcode, 0x80 | size)) elif size < 65536: header = bytes((0x80 | opcode, 0x80 | 126)) + struct.pack("!H", size) else: header = bytes((0x80 | opcode, 0x80 | 127)) + struct.pack("!Q", size) masked = bytes(value ^ mask[index % 4] for index, value in enumerate(payload)) return header + mask + masked def request_load_through_ui(host, port, bundle, timeout): """Open the normal pedalboard page and load through its browser-owned session.""" websocket_path = "/websocket" with socket.create_connection((host, port), timeout=timeout) as connection: connection.settimeout(timeout) key = base64.b64encode(os.urandom(16)).decode("ascii") request = ( f"GET {websocket_path} HTTP/1.1\r\n" f"Host: {host}:{port}\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" f"Origin: http://{host}:{port}\r\n" f"Sec-WebSocket-Key: {key}\r\n" "Sec-WebSocket-Version: 13\r\n\r\n" ) connection.sendall(request.encode("ascii")) response = bytearray() while not response.endswith(b"\r\n\r\n"): chunk = connection.recv(1) if not chunk: raise RuntimeError("mod-ui closed the WebSocket handshake") response.extend(chunk) if b" 101 " not in response.split(b"\r\n", 1)[0]: raise RuntimeError("mod-ui rejected the WebSocket handshake") expected = base64.b64encode( hashlib.sha1( (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii") ).digest() ) headers = response.decode("latin-1").split("\r\n") accept_header = next( ( value.strip() for line in headers if line.casefold().startswith("sec-websocket-accept:") for value in (line.split(":", 1)[1],) ), None, ) if accept_header != expected.decode("ascii"): raise RuntimeError("mod-ui returned an invalid WebSocket accept key") # Register as the browser's active session and wait for its initial state. receive_initial_state(connection) acknowledged = False def load_bundle_through_page(): nonlocal acknowledged body = urlencode({"bundlepath": str(bundle)}).encode() request = Request( f"http://{host}:{port}/pedalboard/load_bundle/", data=body, method="POST", ) with urlopen(request, timeout=timeout) as response: data = response.read().decode("utf-8", errors="replace") if not json.loads(data).get("ok"): raise RuntimeError(f"mod-ui rejected bundle load: {data}") acknowledged = True from urllib.parse import quote page_url = ( f"http://{host}:{port}/pedalboard.html?v=rigforge&bundlepath=" f"{quote(str(bundle), safe='')}" ) with urlopen(page_url, timeout=timeout) as page: html = page.read().decode("utf-8", errors="replace") if "fakeLoadFromServerData" not in html: raise RuntimeError("mod-ui pedalboard page did not contain its board data") try: wait_for_message_prefix(connection, "loading_end ", timeout=timeout) except TimeoutError: if acknowledged: raise # The server has accepted this socket but no browser has answered its # initial data_ready barrier. Defer the real page load until the UI # acknowledges the empty-board reset below. reset_request = Request(f"http://{host}:{port}/reset") with urlopen(reset_request, timeout=timeout) as response: if not json.loads(response.read().decode("utf-8", errors="replace")): raise RuntimeError("mod-ui refused to reset the current pedalboard") deadline = time.monotonic() + timeout message = None while time.monotonic() < deadline: opcode, payload = receive_frame(connection) if opcode == 0x8: raise RuntimeError("mod-ui closed its WebSocket during pedalboard load") if opcode == 0x9: connection.sendall(encode_control_frame(0xA, payload)) continue if opcode != 0x1: continue incoming = payload.decode("utf-8", errors="replace") if incoming == "ping": connection.sendall(encode_control_frame(0x1, "pong")) elif incoming.startswith("data_ready "): connection.sendall(encode_control_frame(0x1, incoming)) if not acknowledged: load_bundle_through_page() elif incoming.startswith("loading_end "): message = incoming break if message is None: raise TimeoutError("mod-ui did not finish loading the pedalboard") return message def receive_frame(connection): header = receive_exact(connection, 2) first, second = header opcode = first & 0x0F size = second & 0x7F if size == 126: size = struct.unpack("!H", receive_exact(connection, 2))[0] elif size == 127: size = struct.unpack("!Q", receive_exact(connection, 8))[0] mask = receive_exact(connection, 4) if second & 0x80 else b"" payload = receive_exact(connection, size) if mask: payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload)) return opcode, payload def receive_exact(connection, size): payload = bytearray() while len(payload) < size: chunk = connection.recv(size - len(payload)) if not chunk: raise RuntimeError("mod-ui closed its WebSocket") payload.extend(chunk) return bytes(payload) def receive_initial_state(connection): while True: opcode, payload = receive_frame(connection) if opcode == 0x8: raise RuntimeError("mod-ui closed WebSocket before initial state") if opcode == 0x9: connection.sendall(encode_control_frame(0xA, payload)) continue if opcode == 0x1: message = payload.decode("utf-8", errors="replace") if message.startswith("loading_end "): return def wait_for_message_prefix(connection, prefix, timeout=None): deadline = time.monotonic() + timeout if timeout is not None else None while True: if deadline is not None: remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError(f"timed out waiting for mod-ui message {prefix!r}") connection.settimeout(remaining) opcode, payload = receive_frame(connection) if opcode == 0x8: raise RuntimeError("mod-ui closed WebSocket during pedalboard load") if opcode == 0x9: connection.sendall(encode_control_frame(0xA, payload)) continue if opcode == 0x1: message = payload.decode("utf-8", errors="replace") if message.startswith(prefix): return message def wait_http(host, port, timeout): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: with urlopen(f"http://{host}:{port}/ping/", timeout=1) as response: if 200 <= response.status < 400: return except (OSError, TimeoutError, URLError): time.sleep(0.2) raise TimeoutError(f"mod-ui HTTP endpoint did not become ready at {host}:{port}") def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("bundle", type=Path) parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=8888) parser.add_argument("--timeout", type=float, default=20) args = parser.parse_args(argv) bundle = args.bundle.resolve() if not bundle.is_dir(): parser.error(f"pedalboard bundle directory does not exist: {bundle}") try: wait_http(args.host, args.port, args.timeout) message = request_load_through_ui( args.host, args.port, bundle, args.timeout ) print(f"mod-ui session accepted pedalboard load: {message}") except (OSError, RuntimeError, TimeoutError, ValueError) as error: print(f"ERROR: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())