diff options
author | Devaev Maxim <[email protected]> | 2020-05-28 11:03:49 +0300 |
---|---|---|
committer | Devaev Maxim <[email protected]> | 2020-05-28 11:03:49 +0300 |
commit | 1c93f6a562d1c2106d148cebb128397989fb84fd (patch) | |
tree | 8065e45b9a07004b5823d8f57a3272796aeb2704 /kvmd | |
parent | fbdfb009a1f752236eeacc8c2528167a64d5d3a8 (diff) |
refactoring
Diffstat (limited to 'kvmd')
-rw-r--r-- | kvmd/__init__.py | 5 | ||||
-rw-r--r-- | kvmd/aiotools.py | 16 | ||||
-rw-r--r-- | kvmd/apps/ipmi/__init__.py | 4 | ||||
-rw-r--r-- | kvmd/apps/kvmd/streamer.py | 7 | ||||
-rw-r--r-- | kvmd/apps/vnc/__init__.py | 4 | ||||
-rw-r--r-- | kvmd/clients/kvmd.py | 13 | ||||
-rw-r--r-- | kvmd/clients/streamer.py | 6 | ||||
-rw-r--r-- | kvmd/htclient.py | 43 | ||||
-rw-r--r-- | kvmd/plugins/auth/http.py | 7 |
9 files changed, 63 insertions, 42 deletions
diff --git a/kvmd/__init__.py b/kvmd/__init__.py index 4ff56339..6ecb95d5 100644 --- a/kvmd/__init__.py +++ b/kvmd/__init__.py @@ -21,8 +21,3 @@ __version__ = "1.63" - - -# ===== -def make_user_agent(app: str) -> str: - return f"{app}/{__version__}" diff --git a/kvmd/aiotools.py b/kvmd/aiotools.py index 6f76423e..15aa5b9c 100644 --- a/kvmd/aiotools.py +++ b/kvmd/aiotools.py @@ -39,8 +39,6 @@ from typing import TypeVar from typing import Optional from typing import Any -import aiohttp - import aiofiles import aiofiles.base @@ -96,20 +94,6 @@ async def wait_first(*aws: Awaitable) -> Tuple[Set[asyncio.Future], Set[asyncio. # ===== -def raise_not_200(response: aiohttp.ClientResponse) -> None: - if response.status != 200: - assert response.reason is not None - response.release() - raise aiohttp.ClientResponseError( - response.request_info, - response.history, - status=response.status, - message=response.reason, - headers=response.headers, - ) - - -# ===== async def afile_write_now(afile: aiofiles.base.AiofilesContextManager, data: bytes) -> None: await afile.write(data) await afile.flush() diff --git a/kvmd/apps/ipmi/__init__.py b/kvmd/apps/ipmi/__init__.py index 54e15513..52145337 100644 --- a/kvmd/apps/ipmi/__init__.py +++ b/kvmd/apps/ipmi/__init__.py @@ -25,7 +25,7 @@ from typing import Optional from ...clients.kvmd import KvmdClient -from ... import make_user_agent +from ... import htclient from .. import init @@ -45,7 +45,7 @@ def main(argv: Optional[List[str]]=None) -> None: IpmiServer( auth_manager=IpmiAuthManager(**config.auth._unpack()), kvmd=KvmdClient( - user_agent=make_user_agent("KVMD-IPMI"), + user_agent=htclient.make_user_agent("KVMD-IPMI"), **config.kvmd._unpack(), ), **config.server._unpack(), diff --git a/kvmd/apps/kvmd/streamer.py b/kvmd/apps/kvmd/streamer.py index cc8b9d29..357a46bb 100644 --- a/kvmd/apps/kvmd/streamer.py +++ b/kvmd/apps/kvmd/streamer.py @@ -36,10 +36,9 @@ import aiohttp from ...logging import get_logger from ... import aiotools +from ... import htclient from ... import gpio -from ... import make_user_agent - # ===== class Streamer: # pylint: disable=too-many-instance-attributes @@ -182,7 +181,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes session = self.__ensure_http_session() try: async with session.get(self.__make_url("state")) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) state = (await response.json())["result"] except (aiohttp.ClientConnectionError, aiohttp.ServerConnectionError): pass @@ -245,7 +244,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes def __ensure_http_session(self) -> aiohttp.ClientSession: if not self.__http_session: kwargs: Dict = { - "headers": {"User-Agent": make_user_agent("KVMD")}, + "headers": {"User-Agent": htclient.make_user_agent("KVMD")}, "timeout": aiohttp.ClientTimeout(total=self.__timeout), } if self.__unix_path: diff --git a/kvmd/apps/vnc/__init__.py b/kvmd/apps/vnc/__init__.py index a88a3966..aaf67740 100644 --- a/kvmd/apps/vnc/__init__.py +++ b/kvmd/apps/vnc/__init__.py @@ -26,7 +26,7 @@ from typing import Optional from ...clients.kvmd import KvmdClient from ...clients.streamer import StreamerClient -from ... import make_user_agent +from ... import htclient from .. import init @@ -42,7 +42,7 @@ def main(argv: Optional[List[str]]=None) -> None: argv=argv, )[2].vnc - user_agent = make_user_agent("KVMD-VNC") + user_agent = htclient.make_user_agent("KVMD-VNC") # pylint: disable=protected-access VncServer( diff --git a/kvmd/clients/kvmd.py b/kvmd/clients/kvmd.py index 70fa7661..e514fb16 100644 --- a/kvmd/clients/kvmd.py +++ b/kvmd/clients/kvmd.py @@ -37,6 +37,7 @@ from typing import Optional import aiohttp from .. import aiotools +from .. import htclient # ===== @@ -56,7 +57,7 @@ class _AuthApiPart(_BaseApiPart): session = self._ensure_http_session() try: async with session.get(self._make_url("auth/check")) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) return True except aiohttp.ClientResponseError as err: if err.status in [401, 403]: @@ -71,14 +72,14 @@ class _StreamerApiPart(_BaseApiPart): url=self._make_url("streamer/set_params"), params={"quality": quality, "desired_fps": desired_fps}, ) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) 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: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) result = (await response.json())["result"] return (result["keymaps"]["default"], set(result["keymaps"]["available"])) @@ -89,14 +90,14 @@ class _HidApiPart(_BaseApiPart): params={"limit": limit, "keymap": keymap_name}, data=text, ) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) class _AtxApiPart(_BaseApiPart): async def get_state(self) -> Dict: session = self._ensure_http_session() async with session.get(self._make_url("atx")) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) return (await response.json())["result"] async def switch_power(self, action: str) -> bool: @@ -106,7 +107,7 @@ class _AtxApiPart(_BaseApiPart): url=self._make_url("atx/power"), params={"action": action}, ) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) return True except aiohttp.ClientResponseError as err: if err.status == 409: diff --git a/kvmd/clients/streamer.py b/kvmd/clients/streamer.py index 7a56556b..493ac080 100644 --- a/kvmd/clients/streamer.py +++ b/kvmd/clients/streamer.py @@ -26,7 +26,7 @@ from typing import AsyncGenerator import aiohttp -from .. import aiotools +from .. import htclient # ===== @@ -59,7 +59,7 @@ class StreamerClient: url=self.__make_url("stream"), params={"extra_headers": "1"}, ) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) reader = aiohttp.MultipartReader.from_response(response) while True: @@ -87,7 +87,7 @@ class StreamerClient: # async def get_snapshot(self) -> Tuple[bool, bytes]: # async with self.__make_http_session(infinite=False) as session: # async with session.get(self.__make_url("snapshot")) as response: -# aiotools.raise_not_200(response) +# htclient.raise_not_200(response) # return ( # (response.headers["X-UStreamer-Online"] == "true"), # bytes(await response.read()), diff --git a/kvmd/htclient.py b/kvmd/htclient.py new file mode 100644 index 00000000..654b603c --- /dev/null +++ b/kvmd/htclient.py @@ -0,0 +1,43 @@ +# ========================================================================== # +# # +# KVMD - The main Pi-KVM daemon. # +# # +# Copyright (C) 2018 Maxim Devaev <[email protected]> # +# # +# This program is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# This program is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see <https://www.gnu.org/licenses/>. # +# # +# ========================================================================== # + + +import aiohttp + +from . import __version__ + + +# ===== +def make_user_agent(app: str) -> str: + return f"{app}/{__version__}" + + +def raise_not_200(response: aiohttp.ClientResponse) -> None: + if response.status != 200: + assert response.reason is not None + response.release() + raise aiohttp.ClientResponseError( + response.request_info, + response.history, + status=response.status, + message=response.reason, + headers=response.headers, + ) diff --git a/kvmd/plugins/auth/http.py b/kvmd/plugins/auth/http.py index c87d624a..4e826726 100644 --- a/kvmd/plugins/auth/http.py +++ b/kvmd/plugins/auth/http.py @@ -33,8 +33,7 @@ from ...validators.basic import valid_float_f01 from ...logging import get_logger -from ... import make_user_agent -from ... import aiotools +from ... import htclient from . import BaseAuthService @@ -86,11 +85,11 @@ class Plugin(BaseAuthService): "secret": self.__secret, }, headers={ - "User-Agent": make_user_agent("KVMD"), + "User-Agent": htclient.make_user_agent("KVMD"), "X-KVMD-User": user, }, ) as response: - aiotools.raise_not_200(response) + htclient.raise_not_200(response) return True except Exception: get_logger().exception("Failed HTTP auth request for user %r", user) |