load_mod_ui_pedalboard.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. from urllib.parse import quote
  73. page_url = (
  74. f"http://{host}:{port}/pedalboard.html?v=rigforge&bundlepath="
  75. f"{quote(str(bundle), safe='')}"
  76. )
  77. with urlopen(page_url, timeout=timeout) as page:
  78. html = page.read().decode("utf-8", errors="replace")
  79. if "fakeLoadFromServerData" not in html:
  80. raise RuntimeError("mod-ui pedalboard page did not contain its board data")
  81. wait_for_message_prefix(connection, "loading_end ")
  82. reset_request = Request(f"http://{host}:{port}/reset")
  83. with urlopen(reset_request, timeout=timeout) as response:
  84. if not json.loads(response.read().decode("utf-8", errors="replace")):
  85. raise RuntimeError("mod-ui refused to reset the current pedalboard")
  86. # Match the active browser's acknowledgement that its reset is complete.
  87. # Desktop.loadPedalboard uses POST after reset. The HTTP response only
  88. # confirms Host.load(), while browser host.js must consume loading_start
  89. # and then its own data_ready round trip before drawing cables.
  90. body = urlencode({"bundlepath": str(bundle)}).encode()
  91. request = Request(
  92. f"http://{host}:{port}/pedalboard/load_bundle/",
  93. data=body,
  94. method="POST",
  95. )
  96. with urlopen(request, timeout=timeout) as response:
  97. data = response.read().decode("utf-8", errors="replace")
  98. if not json.loads(data).get("ok"):
  99. raise RuntimeError(f"mod-ui rejected bundle load: {data}")
  100. connection.sendall(encode_control_frame(0x1, "data_ready 1"))
  101. message = wait_for_message_prefix(connection, "loading_end ")
  102. return message
  103. def receive_frame(connection):
  104. header = receive_exact(connection, 2)
  105. first, second = header
  106. opcode = first & 0x0F
  107. size = second & 0x7F
  108. if size == 126:
  109. size = struct.unpack("!H", receive_exact(connection, 2))[0]
  110. elif size == 127:
  111. size = struct.unpack("!Q", receive_exact(connection, 8))[0]
  112. mask = receive_exact(connection, 4) if second & 0x80 else b""
  113. payload = receive_exact(connection, size)
  114. if mask:
  115. payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
  116. return opcode, payload
  117. def receive_exact(connection, size):
  118. payload = bytearray()
  119. while len(payload) < size:
  120. chunk = connection.recv(size - len(payload))
  121. if not chunk:
  122. raise RuntimeError("mod-ui closed its WebSocket")
  123. payload.extend(chunk)
  124. return bytes(payload)
  125. def receive_initial_state(connection):
  126. while True:
  127. opcode, payload = receive_frame(connection)
  128. if opcode == 0x8:
  129. raise RuntimeError("mod-ui closed WebSocket before initial state")
  130. if opcode == 0x9:
  131. connection.sendall(encode_control_frame(0xA, payload))
  132. continue
  133. if opcode == 0x1:
  134. message = payload.decode("utf-8", errors="replace")
  135. if message.startswith("loading_end "):
  136. return
  137. def wait_for_message_prefix(connection, prefix):
  138. while True:
  139. opcode, payload = receive_frame(connection)
  140. if opcode == 0x8:
  141. raise RuntimeError("mod-ui closed WebSocket during pedalboard load")
  142. if opcode == 0x9:
  143. connection.sendall(encode_control_frame(0xA, payload))
  144. continue
  145. if opcode == 0x1:
  146. message = payload.decode("utf-8", errors="replace")
  147. if message.startswith(prefix):
  148. return message
  149. def wait_http(host, port, timeout):
  150. deadline = time.monotonic() + timeout
  151. while time.monotonic() < deadline:
  152. try:
  153. with urlopen(f"http://{host}:{port}/ping/", timeout=1) as response:
  154. if 200 <= response.status < 400:
  155. return
  156. except (OSError, TimeoutError, URLError):
  157. time.sleep(0.2)
  158. raise TimeoutError(f"mod-ui HTTP endpoint did not become ready at {host}:{port}")
  159. def main(argv=None):
  160. parser = argparse.ArgumentParser(description=__doc__)
  161. parser.add_argument("bundle", type=Path)
  162. parser.add_argument("--host", default="127.0.0.1")
  163. parser.add_argument("--port", type=int, default=8888)
  164. parser.add_argument("--timeout", type=float, default=20)
  165. args = parser.parse_args(argv)
  166. bundle = args.bundle.resolve()
  167. if not bundle.is_dir():
  168. parser.error(f"pedalboard bundle directory does not exist: {bundle}")
  169. try:
  170. wait_http(args.host, args.port, args.timeout)
  171. message = request_load_through_ui(
  172. args.host, args.port, bundle, args.timeout
  173. )
  174. print(f"mod-ui session accepted pedalboard load: {message}")
  175. except (OSError, RuntimeError, TimeoutError, ValueError) as error:
  176. print(f"ERROR: {error}", file=sys.stderr)
  177. return 1
  178. return 0
  179. if __name__ == "__main__":
  180. raise SystemExit(main())