summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMaxim Devaev <[email protected]>2022-07-19 16:42:46 +0300
committerMaxim Devaev <[email protected]>2022-07-19 16:42:46 +0300
commitadf4be9bf7c3b04fde04a6f3e516e48c5ea1a1e6 (patch)
treed36c60db2a833436937243240cbd6331e987a42a
parentb16359c53e5dd62839a9af0fa14bdb9c5f350c75 (diff)
common event parsing
-rw-r--r--kvmd/apps/vnc/server.py14
-rw-r--r--kvmd/clients/kvmd.py30
-rw-r--r--kvmd/htserver.py12
3 files changed, 24 insertions, 32 deletions
diff --git a/kvmd/apps/vnc/server.py b/kvmd/apps/vnc/server.py
index 49d0c81f..64113c11 100644
--- a/kvmd/apps/vnc/server.py
+++ b/kvmd/apps/vnc/server.py
@@ -164,16 +164,16 @@ class _Client(RfbClient): # pylint: disable=too-many-instance-attributes
async with self.__kvmd_session.ws() as self.__kvmd_ws:
logger.info("[kvmd] %s: Connected to KVMD websocket", self._remote)
self.__stage3_ws_connected.set_passed()
- async for event in self.__kvmd_ws.communicate():
- await self.__process_ws_event(event)
+ async for (event_type, event) in self.__kvmd_ws.communicate():
+ await self.__process_ws_event(event_type, event)
raise RfbError("KVMD closed the websocket (the server may have been stopped)")
finally:
self.__kvmd_ws = None
- async def __process_ws_event(self, event: Dict) -> None:
- if event["event_type"] == "info_meta_state":
+ async def __process_ws_event(self, event_type: str, event: Dict) -> None:
+ if event_type == "info_meta_state":
try:
- host = event["event"]["server"]["host"]
+ host = event["server"]["host"]
except Exception:
host = None
else:
@@ -184,10 +184,10 @@ class _Client(RfbClient): # pylint: disable=too-many-instance-attributes
await self._send_rename(name)
self.__shared_params.name = name
- elif event["event_type"] == "hid_state":
+ elif event_type == "hid_state":
async with self.__lock:
if self._encodings.has_leds_state:
- await self._send_leds_state(**event["event"]["keyboard"]["leds"])
+ await self._send_leds_state(**event["keyboard"]["leds"])
# =====
diff --git a/kvmd/clients/kvmd.py b/kvmd/clients/kvmd.py
index b4585bcc..6a15937b 100644
--- a/kvmd/clients/kvmd.py
+++ b/kvmd/clients/kvmd.py
@@ -22,7 +22,6 @@
import asyncio
import contextlib
-import json
import types
from typing import Tuple
@@ -37,6 +36,7 @@ import aiohttp
from .. import aiotools
from .. import htclient
+from .. import htserver
# =====
@@ -132,10 +132,10 @@ class KvmdClientWs:
def __init__(self, ws: aiohttp.ClientWebSocketResponse) -> None:
self.__ws = ws
- self.__writer_queue: "asyncio.Queue[Dict]" = asyncio.Queue()
+ self.__writer_queue: "asyncio.Queue[Tuple[str, Dict]]" = asyncio.Queue()
self.__communicated = False
- async def communicate(self) -> AsyncGenerator[Dict, None]:
+ async def communicate(self) -> AsyncGenerator[Tuple[str, Dict], None]:
assert not self.__communicated
self.__communicated = True
receive_task: Optional[asyncio.Task] = None
@@ -152,7 +152,7 @@ class KvmdClientWs:
if receive_task in done:
msg = receive_task.result()
if msg.type == aiohttp.WSMsgType.TEXT:
- yield json.loads(msg.data)
+ yield htserver.parse_ws_event(msg.data)
elif msg.type == aiohttp.WSMsgType.CLOSE:
await self.__ws.close()
elif msg.type == aiohttp.WSMsgType.CLOSED:
@@ -162,7 +162,7 @@ class KvmdClientWs:
receive_task = None
if writer_task in done:
- await self.__ws.send_str(json.dumps(writer_task.result()))
+ await htserver.send_ws_event(self.__ws, *writer_task.result())
writer_task = None
finally:
if receive_task:
@@ -176,28 +176,16 @@ class KvmdClientWs:
self.__communicated = False
async def send_key_event(self, key: str, state: bool) -> None:
- await self.__writer_queue.put({
- "event_type": "key",
- "event": {"key": key, "state": state},
- })
+ await self.__writer_queue.put(("key", {"key": key, "state": state}))
async def send_mouse_button_event(self, button: str, state: bool) -> None:
- await self.__writer_queue.put({
- "event_type": "mouse_button",
- "event": {"button": button, "state": state},
- })
+ await self.__writer_queue.put(("mouse_button", {"button": button, "state": state}))
async def send_mouse_move_event(self, to_x: int, to_y: int) -> None:
- await self.__writer_queue.put({
- "event_type": "mouse_move",
- "event": {"to": {"x": to_x, "y": to_y}},
- })
+ await self.__writer_queue.put(("mouse_move", {"to": {"x": to_x, "y": to_y}}))
async def send_mouse_wheel_event(self, delta_x: int, delta_y: int) -> None:
- await self.__writer_queue.put({
- "event_type": "mouse_wheel",
- "event": {"delta": {"x": delta_x, "y": delta_y}},
- })
+ await self.__writer_queue.put(("mouse_wheel", {"delta": {"x": delta_x, "y": delta_y}}))
class KvmdClientSession:
diff --git a/kvmd/htserver.py b/kvmd/htserver.py
index 94d2c3ee..3a523b00 100644
--- a/kvmd/htserver.py
+++ b/kvmd/htserver.py
@@ -208,6 +208,13 @@ async def stream_json_exception(response: StreamResponse, err: Exception) -> Non
}, False)
+async def send_ws_event(wsr: WebSocketResponse, event_type: str, event: Optional[Dict]) -> None:
+ await wsr.send_str(json.dumps({
+ "event_type": event_type,
+ "event": event,
+ }))
+
+
def parse_ws_event(msg: str) -> Tuple[str, Dict]:
data = json.loads(msg)
if not isinstance(data, dict):
@@ -246,10 +253,7 @@ class WsSession:
return f"WsSession(id={id(self)}, {self.kwargs})"
async def send_event(self, event_type: str, event: Optional[Dict]) -> None:
- await self.wsr.send_str(json.dumps({
- "event_type": event_type,
- "event": event,
- }))
+ await send_ws_event(self.wsr, event_type, event)
class HttpServer: