summaryrefslogtreecommitdiff
path: root/kvmd/htserver.py
diff options
context:
space:
mode:
authorMaxim Devaev <[email protected]>2022-04-12 06:26:38 +0300
committerMaxim Devaev <[email protected]>2022-04-12 06:31:22 +0300
commit1e5c8535f6a30629381b08ccfae1fc4668955ba8 (patch)
tree0892ce9341d0810bad4381809c3ceb3d07942892 /kvmd/htserver.py
parent80b5546d21cb5c67aeb4f28f339fa4a029bc88c2 (diff)
refactoring
Diffstat (limited to 'kvmd/htserver.py')
-rw-r--r--kvmd/htserver.py20
1 files changed, 19 insertions, 1 deletions
diff --git a/kvmd/htserver.py b/kvmd/htserver.py
index 34b38846..00fe24ea 100644
--- a/kvmd/htserver.py
+++ b/kvmd/htserver.py
@@ -38,6 +38,7 @@ from aiohttp.web import Request
from aiohttp.web import Response
from aiohttp.web import StreamResponse
from aiohttp.web import WebSocketResponse
+from aiohttp.web import WSMsgType
from aiohttp.web import Application
from aiohttp.web import run_app
from aiohttp.web import normalize_path_middleware
@@ -220,7 +221,7 @@ async def broadcast_ws_event(wss: List[WebSocketResponse], event_type: str, even
], return_exceptions=True)
-def parse_ws_event(msg: str) -> Tuple[str, Dict]:
+def _parse_ws_event(msg: str) -> Tuple[str, Dict]:
data = json.loads(msg)
if not isinstance(data, dict):
raise RuntimeError("Top-level event structure is not a dict")
@@ -233,6 +234,23 @@ def parse_ws_event(msg: str) -> Tuple[str, Dict]:
return (event_type, event)
+async def process_ws_messages(ws: WebSocketResponse, handlers: Dict[str, Callable]) -> None:
+ logger = get_logger(1)
+ async for msg in ws:
+ if msg.type != WSMsgType.TEXT:
+ break
+ try:
+ (event_type, event) = _parse_ws_event(msg.data)
+ except Exception as err:
+ logger.error("Can't parse JSON event from websocket: %r", err)
+ else:
+ handler = handlers.get(event_type)
+ if handler:
+ await handler(ws, event)
+ else:
+ logger.error("Unknown websocket event: %r", msg.data)
+
+
# =====
_REQUEST_AUTH_INFO = "_kvmd_auth_info"