mod_ui_websocket.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. """Small synchronous WebSocket client for mod-ui's local control endpoint."""
  2. import base64
  3. import hashlib
  4. import os
  5. import socket
  6. import struct
  7. import uuid
  8. class ModUiWebSocketClient:
  9. def __init__(self, host, port, path="/websocket", timeout=5):
  10. self.host = host
  11. self.port = port
  12. self.path = path
  13. self.timeout = timeout
  14. self.connection = None
  15. self.buffer = bytearray()
  16. self.session_ready = False
  17. def connect(self):
  18. if self.connection is not None:
  19. return
  20. self.session_ready = False
  21. connection = socket.create_connection((self.host, self.port), timeout=self.timeout)
  22. connection.settimeout(self.timeout)
  23. key = base64.b64encode(os.urandom(16)).decode("ascii")
  24. request = (
  25. f"GET {self.path} HTTP/1.1\r\n"
  26. f"Host: {self.host}:{self.port}\r\n"
  27. "Upgrade: websocket\r\n"
  28. "Connection: Upgrade\r\n"
  29. f"Origin: http://{self.host}:{self.port}\r\n"
  30. f"Sec-WebSocket-Key: {key}\r\n"
  31. "Sec-WebSocket-Version: 13\r\n\r\n"
  32. )
  33. connection.sendall(request.encode("ascii"))
  34. response = bytearray()
  35. while not response.endswith(b"\r\n\r\n"):
  36. chunk = connection.recv(1)
  37. if not chunk:
  38. connection.close()
  39. raise RuntimeError("mod-ui closed the WebSocket handshake")
  40. response.extend(chunk)
  41. if len(response) > 16384:
  42. connection.close()
  43. raise RuntimeError("mod-ui WebSocket handshake headers are too large")
  44. lines = response.decode("latin-1").split("\r\n")
  45. if not lines or " 101 " not in f" {lines[0]} ":
  46. connection.close()
  47. raise RuntimeError(f"mod-ui rejected the WebSocket handshake: {lines[0] if lines else ''}")
  48. headers = {}
  49. for line in lines[1:]:
  50. if ":" in line:
  51. name, value = line.split(":", 1)
  52. headers[name.strip().casefold()] = value.strip()
  53. expected = base64.b64encode(
  54. hashlib.sha1(
  55. (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii")
  56. ).digest()
  57. ).decode("ascii")
  58. if headers.get("sec-websocket-accept") != expected:
  59. connection.close()
  60. raise RuntimeError("mod-ui returned an invalid WebSocket accept key")
  61. self.connection = connection
  62. def _send_frame(self, opcode, payload=b""):
  63. if self.connection is None:
  64. raise RuntimeError("mod-ui WebSocket is not connected")
  65. if isinstance(payload, str):
  66. payload = payload.encode("utf-8")
  67. mask = os.urandom(4)
  68. size = len(payload)
  69. if size < 126:
  70. header = bytes((0x80 | opcode, 0x80 | size))
  71. elif size < 65536:
  72. header = bytes((0x80 | opcode, 0x80 | 126)) + struct.pack("!H", size)
  73. else:
  74. header = bytes((0x80 | opcode, 0x80 | 127)) + struct.pack("!Q", size)
  75. masked = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
  76. self.connection.sendall(header + mask + masked)
  77. def send_text(self, text):
  78. self._send_frame(0x1, text)
  79. def _receive_exactly(self, size):
  80. while len(self.buffer) < size:
  81. chunk = self.connection.recv(max(4096, size - len(self.buffer)))
  82. if not chunk:
  83. raise RuntimeError("mod-ui closed the WebSocket connection")
  84. self.buffer.extend(chunk)
  85. result = bytes(self.buffer[:size])
  86. del self.buffer[:size]
  87. return result
  88. def receive_frame(self):
  89. first, second = self._receive_exactly(2)
  90. opcode = first & 0x0F
  91. masked = bool(second & 0x80)
  92. size = second & 0x7F
  93. if size == 126:
  94. size = struct.unpack("!H", self._receive_exactly(2))[0]
  95. elif size == 127:
  96. size = struct.unpack("!Q", self._receive_exactly(8))[0]
  97. mask = self._receive_exactly(4) if masked else b""
  98. payload = self._receive_exactly(size)
  99. if masked:
  100. payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
  101. return opcode, payload
  102. def process_control_message(self, message):
  103. if message == "ping":
  104. self.send_text("pong")
  105. elif message.startswith("data_ready "):
  106. self.send_text(message)
  107. elif message.startswith("rigforge_patch_set_ack "):
  108. return message
  109. return None
  110. def wait_for_loading_start(self):
  111. """Wait until backend starts loading a pedalboard on this session."""
  112. self.connect()
  113. while True:
  114. opcode, payload = self.receive_frame()
  115. if opcode == 0x8:
  116. self.close()
  117. raise RuntimeError("mod-ui closed the WebSocket while loading pedalboard")
  118. if opcode == 0x9:
  119. self._send_frame(0xA, payload)
  120. continue
  121. if opcode != 0x1:
  122. continue
  123. message = payload.decode("utf-8", errors="replace")
  124. if message == "ping":
  125. self.process_control_message(message)
  126. continue
  127. if message.startswith("loading_start "):
  128. # The browser sends loading_start when its initial state was
  129. # reported; reply to the corresponding data_ready before declaring
  130. # the UI session ready to accept pedalboard connections.
  131. continue
  132. if message.startswith("data_ready "):
  133. self.process_control_message(message)
  134. continue
  135. if message.startswith("loading_end "):
  136. self.session_ready = True
  137. return message
  138. def set_patch(self, instance, property_uri, value):
  139. self.connect()
  140. request_id = uuid.uuid4().hex
  141. self.send_text(
  142. f"rigforge_patch_set {request_id} {instance} {property_uri} p {value}"
  143. )
  144. while True:
  145. opcode, payload = self.receive_frame()
  146. if opcode == 0x8:
  147. raise RuntimeError("mod-ui closed the WebSocket while setting the NAM model")
  148. if opcode == 0x9:
  149. self._send_frame(0xA, payload)
  150. continue
  151. if opcode != 0x1:
  152. continue
  153. message = payload.decode("utf-8", errors="replace")
  154. if message == "ping" or message.startswith("data_ready "):
  155. self.process_control_message(message)
  156. continue
  157. if message.startswith(f"rigforge_patch_set_ack {request_id} "):
  158. status = message.rsplit(" ", 1)[-1]
  159. if status != "1":
  160. raise RuntimeError(f"mod-ui rejected NAM model update: {message}")
  161. return True
  162. def serve_once(self, timeout=1):
  163. if self.connection is None:
  164. self.connect()
  165. connection = self.connection
  166. connection.settimeout(timeout)
  167. try:
  168. opcode, payload = self.receive_frame()
  169. except socket.timeout:
  170. return
  171. finally:
  172. if self.connection is connection:
  173. connection.settimeout(self.timeout)
  174. if opcode == 0x8:
  175. connection, self.connection = self.connection, None
  176. self.buffer.clear()
  177. if connection is not None:
  178. connection.close()
  179. raise ConnectionError("mod-ui closed the session WebSocket")
  180. if opcode == 0x9:
  181. self._send_frame(0xA, payload)
  182. return None
  183. elif opcode == 0x1:
  184. message = payload.decode("utf-8", errors="replace")
  185. self.process_control_message(message)
  186. return message
  187. return None
  188. def close(self):
  189. connection, self.connection = self.connection, None
  190. self.buffer.clear()
  191. self.session_ready = False
  192. if connection is None:
  193. return
  194. try:
  195. try:
  196. self._send_close(connection)
  197. except OSError:
  198. pass
  199. finally:
  200. connection.close()
  201. @staticmethod
  202. def _send_close(connection):
  203. mask = os.urandom(4)
  204. payload = b""
  205. header = bytes((0x88, 0x80))
  206. connection.sendall(header + mask + payload)
  207. def __enter__(self):
  208. self.connect()
  209. return self
  210. def __exit__(self, _type, _value, _traceback):
  211. self.close()