load_mod_ui_pedalboard.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/env python3
  2. """Load the selected mod-ui pedalboard through its active session WebSocket."""
  3. import argparse
  4. import base64
  5. import hashlib
  6. import json
  7. import os
  8. import socket
  9. import struct
  10. import sys
  11. import time
  12. from pathlib import Path
  13. from urllib.error import URLError
  14. from urllib.parse import urlencode
  15. from urllib.request import urlopen
  16. from urllib.request import Request
  17. def encode_control_frame(opcode, payload=b""):
  18. payload = payload if isinstance(payload, bytes) else payload.encode("utf-8")
  19. mask = os.urandom(4)
  20. size = len(payload)
  21. if size < 126:
  22. header = bytes((0x80 | opcode, 0x80 | size))
  23. elif size < 65536:
  24. header = bytes((0x80 | opcode, 0x80 | 126)) + struct.pack("!H", size)
  25. else:
  26. header = bytes((0x80 | opcode, 0x80 | 127)) + struct.pack("!Q", size)
  27. masked = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
  28. return header + mask + masked
  29. def request_load_through_ui(host, port, bundle, timeout):
  30. """Open the normal pedalboard page and load through its browser-owned session."""
  31. websocket_path = "/websocket"
  32. with socket.create_connection((host, port), timeout=timeout) as connection:
  33. connection.settimeout(timeout)
  34. key = base64.b64encode(os.urandom(16)).decode("ascii")
  35. request = (
  36. f"GET {websocket_path} HTTP/1.1\r\n"
  37. f"Host: {host}:{port}\r\n"
  38. "Upgrade: websocket\r\n"
  39. "Connection: Upgrade\r\n"
  40. f"Origin: http://{host}:{port}\r\n"
  41. f"Sec-WebSocket-Key: {key}\r\n"
  42. "Sec-WebSocket-Version: 13\r\n\r\n"
  43. )
  44. connection.sendall(request.encode("ascii"))
  45. response = bytearray()
  46. while not response.endswith(b"\r\n\r\n"):
  47. chunk = connection.recv(1)
  48. if not chunk:
  49. raise RuntimeError("mod-ui closed the WebSocket handshake")
  50. response.extend(chunk)
  51. if b" 101 " not in response.split(b"\r\n", 1)[0]:
  52. raise RuntimeError("mod-ui rejected the WebSocket handshake")
  53. expected = base64.b64encode(
  54. hashlib.sha1(
  55. (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii")
  56. ).digest()
  57. )
  58. headers = response.decode("latin-1").split("\r\n")
  59. accept_header = next(
  60. (
  61. value.strip()
  62. for line in headers
  63. if line.casefold().startswith("sec-websocket-accept:")
  64. for value in (line.split(":", 1)[1],)
  65. ),
  66. None,
  67. )
  68. if accept_header != expected.decode("ascii"):
  69. raise RuntimeError("mod-ui returned an invalid WebSocket accept key")
  70. # Register as the browser's active session and wait for its initial state.
  71. receive_initial_state(connection)
  72. acknowledged = False
  73. def load_bundle_through_page():
  74. nonlocal acknowledged
  75. body = urlencode({"bundlepath": str(bundle)}).encode()
  76. request = Request(
  77. f"http://{host}:{port}/pedalboard/load_bundle/",
  78. data=body,
  79. method="POST",
  80. )
  81. with urlopen(request, timeout=timeout) as response:
  82. data = response.read().decode("utf-8", errors="replace")
  83. if not json.loads(data).get("ok"):
  84. raise RuntimeError(f"mod-ui rejected bundle load: {data}")
  85. acknowledged = True
  86. from urllib.parse import quote
  87. page_url = (
  88. f"http://{host}:{port}/pedalboard.html?v=rigforge&bundlepath="
  89. f"{quote(str(bundle), safe='')}"
  90. )
  91. with urlopen(page_url, timeout=timeout) as page:
  92. html = page.read().decode("utf-8", errors="replace")
  93. if "fakeLoadFromServerData" not in html:
  94. raise RuntimeError("mod-ui pedalboard page did not contain its board data")
  95. try:
  96. wait_for_message_prefix(connection, "loading_end ", timeout=timeout)
  97. except TimeoutError:
  98. if acknowledged:
  99. raise
  100. # The server has accepted this socket but no browser has answered its
  101. # initial data_ready barrier. Defer the real page load until the UI
  102. # acknowledges the empty-board reset below.
  103. reset_request = Request(f"http://{host}:{port}/reset")
  104. with urlopen(reset_request, timeout=timeout) as response:
  105. if not json.loads(response.read().decode("utf-8", errors="replace")):
  106. raise RuntimeError("mod-ui refused to reset the current pedalboard")
  107. deadline = time.monotonic() + timeout
  108. message = None
  109. while time.monotonic() < deadline:
  110. opcode, payload = receive_frame(connection)
  111. if opcode == 0x8:
  112. raise RuntimeError("mod-ui closed its WebSocket during pedalboard load")
  113. if opcode == 0x9:
  114. connection.sendall(encode_control_frame(0xA, payload))
  115. continue
  116. if opcode != 0x1:
  117. continue
  118. incoming = payload.decode("utf-8", errors="replace")
  119. if incoming == "ping":
  120. connection.sendall(encode_control_frame(0x1, "pong"))
  121. elif incoming.startswith("data_ready "):
  122. connection.sendall(encode_control_frame(0x1, incoming))
  123. if not acknowledged:
  124. load_bundle_through_page()
  125. elif incoming.startswith("loading_end "):
  126. message = incoming
  127. break
  128. if message is None:
  129. raise TimeoutError("mod-ui did not finish loading the pedalboard")
  130. return message
  131. def receive_frame(connection):
  132. header = receive_exact(connection, 2)
  133. first, second = header
  134. opcode = first & 0x0F
  135. size = second & 0x7F
  136. if size == 126:
  137. size = struct.unpack("!H", receive_exact(connection, 2))[0]
  138. elif size == 127:
  139. size = struct.unpack("!Q", receive_exact(connection, 8))[0]
  140. mask = receive_exact(connection, 4) if second & 0x80 else b""
  141. payload = receive_exact(connection, size)
  142. if mask:
  143. payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
  144. return opcode, payload
  145. def receive_exact(connection, size):
  146. payload = bytearray()
  147. while len(payload) < size:
  148. chunk = connection.recv(size - len(payload))
  149. if not chunk:
  150. raise RuntimeError("mod-ui closed its WebSocket")
  151. payload.extend(chunk)
  152. return bytes(payload)
  153. def receive_initial_state(connection):
  154. while True:
  155. opcode, payload = receive_frame(connection)
  156. if opcode == 0x8:
  157. raise RuntimeError("mod-ui closed WebSocket before initial state")
  158. if opcode == 0x9:
  159. connection.sendall(encode_control_frame(0xA, payload))
  160. continue
  161. if opcode == 0x1:
  162. message = payload.decode("utf-8", errors="replace")
  163. if message.startswith("loading_end "):
  164. return
  165. def wait_for_message_prefix(connection, prefix, timeout=None):
  166. deadline = time.monotonic() + timeout if timeout is not None else None
  167. while True:
  168. if deadline is not None:
  169. remaining = deadline - time.monotonic()
  170. if remaining <= 0:
  171. raise TimeoutError(f"timed out waiting for mod-ui message {prefix!r}")
  172. connection.settimeout(remaining)
  173. opcode, payload = receive_frame(connection)
  174. if opcode == 0x8:
  175. raise RuntimeError("mod-ui closed WebSocket during pedalboard load")
  176. if opcode == 0x9:
  177. connection.sendall(encode_control_frame(0xA, payload))
  178. continue
  179. if opcode == 0x1:
  180. message = payload.decode("utf-8", errors="replace")
  181. if message.startswith(prefix):
  182. return message
  183. def wait_http(host, port, timeout):
  184. deadline = time.monotonic() + timeout
  185. while time.monotonic() < deadline:
  186. try:
  187. with urlopen(f"http://{host}:{port}/ping/", timeout=1) as response:
  188. if 200 <= response.status < 400:
  189. return
  190. except (OSError, TimeoutError, URLError):
  191. time.sleep(0.2)
  192. raise TimeoutError(f"mod-ui HTTP endpoint did not become ready at {host}:{port}")
  193. def main(argv=None):
  194. parser = argparse.ArgumentParser(description=__doc__)
  195. parser.add_argument("bundle", type=Path)
  196. parser.add_argument("--host", default="127.0.0.1")
  197. parser.add_argument("--port", type=int, default=8888)
  198. parser.add_argument("--timeout", type=float, default=20)
  199. args = parser.parse_args(argv)
  200. bundle = args.bundle.resolve()
  201. if not bundle.is_dir():
  202. parser.error(f"pedalboard bundle directory does not exist: {bundle}")
  203. try:
  204. wait_http(args.host, args.port, args.timeout)
  205. message = request_load_through_ui(
  206. args.host, args.port, bundle, args.timeout
  207. )
  208. print(f"mod-ui session accepted pedalboard load: {message}")
  209. except (OSError, RuntimeError, TimeoutError, ValueError) as error:
  210. print(f"ERROR: {error}", file=sys.stderr)
  211. return 1
  212. return 0
  213. if __name__ == "__main__":
  214. raise SystemExit(main())