diff options
author | Maxim Devaev <[email protected]> | 2024-10-22 00:51:03 +0300 |
---|---|---|
committer | Maxim Devaev <[email protected]> | 2024-10-22 05:39:18 +0300 |
commit | 0e4a70e7b9cdde53b1063686a896057d3c940e35 (patch) | |
tree | fd88a4f7a8c06341ff600dc27461437b90fb5bd3 /kvmd/clients/kvmd.py | |
parent | cda32a083faf3e7326cfe317336e473c905c6dfd (diff) |
refactoring
Diffstat (limited to 'kvmd/clients/kvmd.py')
-rw-r--r-- | kvmd/clients/kvmd.py | 121 |
1 files changed, 29 insertions, 92 deletions
diff --git a/kvmd/clients/kvmd.py b/kvmd/clients/kvmd.py index ddf0d024..a0412ce2 100644 --- a/kvmd/clients/kvmd.py +++ b/kvmd/clients/kvmd.py @@ -23,7 +23,6 @@ import asyncio import contextlib import struct -import types from typing import Callable from typing import AsyncGenerator @@ -34,22 +33,19 @@ from .. import aiotools from .. import htclient from .. import htserver +from . import BaseHttpClient +from . import BaseHttpClientSession + # ===== class _BaseApiPart: - def __init__( - self, - ensure_http_session: Callable[[], aiohttp.ClientSession], - make_url: Callable[[str], str], - ) -> None: - + def __init__(self, ensure_http_session: Callable[[], aiohttp.ClientSession]) -> None: self._ensure_http_session = ensure_http_session - self._make_url = make_url async def _set_params(self, handle: str, **params: (int | str | None)) -> None: session = self._ensure_http_session() async with session.post( - url=self._make_url(handle), + url=handle, params={ key: value for (key, value) in params.items() @@ -63,7 +59,7 @@ class _AuthApiPart(_BaseApiPart): async def check(self) -> bool: session = self._ensure_http_session() try: - async with session.get(self._make_url("auth/check")) as response: + async with session.get("/auth/check") as response: htclient.raise_not_200(response) return True except aiohttp.ClientResponseError as ex: @@ -75,13 +71,13 @@ class _AuthApiPart(_BaseApiPart): class _StreamerApiPart(_BaseApiPart): async def get_state(self) -> dict: session = self._ensure_http_session() - async with session.get(self._make_url("streamer")) as response: + async with session.get("/streamer") as response: htclient.raise_not_200(response) return (await response.json())["result"] async def set_params(self, quality: (int | None)=None, desired_fps: (int | None)=None) -> None: await self._set_params( - "streamer/set_params", + "/streamer/set_params", quality=quality, desired_fps=desired_fps, ) @@ -90,7 +86,7 @@ class _StreamerApiPart(_BaseApiPart): class _HidApiPart(_BaseApiPart): async def get_keymaps(self) -> tuple[str, set[str]]: session = self._ensure_http_session() - async with session.get(self._make_url("hid/keymaps")) as response: + async with session.get("/hid/keymaps") as response: htclient.raise_not_200(response) result = (await response.json())["result"] return (result["keymaps"]["default"], set(result["keymaps"]["available"])) @@ -98,7 +94,7 @@ class _HidApiPart(_BaseApiPart): async def print(self, text: str, limit: int, keymap_name: str) -> None: session = self._ensure_http_session() async with session.post( - url=self._make_url("hid/print"), + url="/hid/print", params={"limit": limit, "keymap": keymap_name}, data=text, ) as response: @@ -106,7 +102,7 @@ class _HidApiPart(_BaseApiPart): async def set_params(self, keyboard_output: (str | None)=None, mouse_output: (str | None)=None) -> None: await self._set_params( - "hid/set_params", + "/hid/set_params", keyboard_output=keyboard_output, mouse_output=mouse_output, ) @@ -115,7 +111,7 @@ class _HidApiPart(_BaseApiPart): class _AtxApiPart(_BaseApiPart): async def get_state(self) -> dict: session = self._ensure_http_session() - async with session.get(self._make_url("atx")) as response: + async with session.get("/atx") as response: htclient.raise_not_200(response) return (await response.json())["result"] @@ -123,7 +119,7 @@ class _AtxApiPart(_BaseApiPart): session = self._ensure_http_session() try: async with session.post( - url=self._make_url("atx/power"), + url="/atx/power", params={"action": action}, ) as response: htclient.raise_not_200(response) @@ -138,7 +134,6 @@ class _AtxApiPart(_BaseApiPart): class KvmdClientWs: def __init__(self, ws: aiohttp.ClientWebSocketResponse) -> None: self.__ws = ws - self.__writer_queue: "asyncio.Queue[tuple[str, dict] | bytes]" = asyncio.Queue() self.__communicated = False @@ -200,83 +195,25 @@ class KvmdClientWs: await self.__writer_queue.put(struct.pack(">bbbb", 5, 0, delta_x, delta_y)) -class KvmdClientSession: - def __init__( - self, - make_http_session: Callable[[], aiohttp.ClientSession], - make_url: Callable[[str], str], - ) -> None: - - self.__make_http_session = make_http_session - self.__make_url = make_url - - self.__http_session: (aiohttp.ClientSession | None) = None - - args = (self.__ensure_http_session, make_url) - - self.auth = _AuthApiPart(*args) - self.streamer = _StreamerApiPart(*args) - self.hid = _HidApiPart(*args) - self.atx = _AtxApiPart(*args) +class KvmdClientSession(BaseHttpClientSession): + def __init__(self, make_http_session: Callable[[], aiohttp.ClientSession]) -> None: + super().__init__(make_http_session) + self.auth = _AuthApiPart(self._ensure_http_session) + self.streamer = _StreamerApiPart(self._ensure_http_session) + self.hid = _HidApiPart(self._ensure_http_session) + self.atx = _AtxApiPart(self._ensure_http_session) @contextlib.asynccontextmanager async def ws(self) -> AsyncGenerator[KvmdClientWs, None]: - session = self.__ensure_http_session() - async with session.ws_connect(self.__make_url("ws"), params={"legacy": 0}) as ws: + session = self._ensure_http_session() + async with session.ws_connect("/ws", params={"legacy": "0"}) as ws: yield KvmdClientWs(ws) - def __ensure_http_session(self) -> aiohttp.ClientSession: - if not self.__http_session: - self.__http_session = self.__make_http_session() - return self.__http_session - - async def close(self) -> None: - if self.__http_session: - await self.__http_session.close() - self.__http_session = None - - async def __aenter__(self) -> "KvmdClientSession": - return self - - async def __aexit__( - self, - _exc_type: type[BaseException], - _exc: BaseException, - _tb: types.TracebackType, - ) -> None: - - await self.close() - - -class KvmdClient: - def __init__( - self, - unix_path: str, - timeout: float, - user_agent: str, - ) -> None: - - self.__unix_path = unix_path - self.__timeout = timeout - self.__user_agent = user_agent - - def make_session(self, user: str, passwd: str) -> KvmdClientSession: - return KvmdClientSession( - make_http_session=(lambda: self.__make_http_session(user, passwd)), - make_url=self.__make_url, - ) - - def __make_http_session(self, user: str, passwd: str) -> aiohttp.ClientSession: - return aiohttp.ClientSession( - headers={ - "X-KVMD-User": user, - "X-KVMD-Passwd": passwd, - "User-Agent": self.__user_agent, - }, - connector=aiohttp.UnixConnector(path=self.__unix_path), - timeout=aiohttp.ClientTimeout(total=self.__timeout), - ) - def __make_url(self, handle: str) -> str: - assert not handle.startswith("/"), handle - return f"http://localhost:0/{handle}" +class KvmdClient(BaseHttpClient): + def make_session(self, user: str="", passwd: str="") -> KvmdClientSession: + headers = { + "X-KVMD-User": user, + "X-KVMD-Passwd": passwd, + } + return KvmdClientSession(lambda: self._make_http_session(headers)) |