| 1 |
from typing import Any, Optional, Union |
| 2 |
|
| 3 |
import aiohttp |
| 4 |
import asyncio |
| 5 |
import logging |
| 6 |
|
| 7 |
from . import error |
| 8 |
|
| 9 |
DEFAULT_TIMEOUT = aiohttp.ClientTimeout(total=None, sock_connect=5, sock_read=5) |
| 10 |
DEFAULT_PORT = 80 |
| 11 |
|
| 12 |
logger = logging.getLogger(__name__) |
| 13 |
|
| 14 |
|
| 15 |
class ApiHost: |
| 16 |
def __init__( |
| 17 |
self, |
| 18 |
host: str, |
| 19 |
port: int, |
| 20 |
timeout: int, |
| 21 |
session: Any, |
| 22 |
loop: Any, |
| 23 |
logger: logging.Logger = logger, |
| 24 |
**auth, |
| 25 |
): |
| 26 |
self._host = host |
| 27 |
self._port = port |
| 28 |
self._username = auth.get("username") |
| 29 |
self._password = auth.get("password") |
| 30 |
|
| 31 |
self._logger = logger |
| 32 |
|
| 33 |
self._timeout = timeout if timeout else DEFAULT_TIMEOUT |
| 34 |
|
| 35 |
self._session = session |
| 36 |
|
| 37 |
auth = None |
| 38 |
|
| 39 |
if any(data is not None for data in [self._username, self._password]): |
| 40 |
auth = aiohttp.BasicAuth(login=self._username, password=self._password) |
| 41 |
|
| 42 |
if not self._session: |
| 43 |
self._session = aiohttp.ClientSession(loop=loop, timeout=timeout, auth=auth) |
| 44 |
|
| 45 |
|
| 46 |
self._loop = loop |
| 47 |
|
| 48 |
async def async_request( |
| 49 |
self, |
| 50 |
path: str, |
| 51 |
async_method: Any, |
| 52 |
data: Union[dict, str, None] = None, |
| 53 |
allow_ota_check_response: bool = False, |
| 54 |
) -> Optional[dict]: |
| 55 |
|
| 56 |
client_timeout = self._timeout |
| 57 |
url = self.api_path(path) |
| 58 |
try: |
| 59 |
if data is not None: |
| 60 |
response = await async_method(url, timeout=client_timeout, data=data) |
| 61 |
else: |
| 62 |
response = await async_method(url, timeout=client_timeout) |
| 63 |
|
| 64 |
accepted_statuses = (200, 202, 204) if allow_ota_check_response else (200,) |
| 65 |
if response.status not in accepted_statuses: |
| 66 |
if response.status == 401: |
| 67 |
raise error.UnauthorizedRequest( |
| 68 |
f"Request to {url} failed with HTTP {response.status}, UNAUTHORISED" |
| 69 |
) |
| 70 |
raise error.HttpError( |
| 71 |
f"Request to {url} failed with HTTP {response.status}" |
| 72 |
) |
| 73 |
|
| 74 |
if response.content_type != "application/json": |
| 75 |
return None |
| 76 |
|
| 77 |
return await response.json() |
| 78 |
|
| 79 |
except asyncio.TimeoutError as ex: |
| 80 |
raise error.TimeoutError( |
| 81 |
f"Failed to connect to {self.host}:{self.port} within {client_timeout}s: ({ex})" |
| 82 |
) from ex |
| 83 |
|
| 84 |
except aiohttp.ClientConnectionError as ex: |
| 85 |
raise error.ConnectionError( |
| 86 |
f"Failed to connect to {self.host}:{self.port}: {ex}" |
| 87 |
) from ex |
| 88 |
|
| 89 |
except aiohttp.ClientError as ex: |
| 90 |
raise error.ClientError(f"API request {url} failed: {ex}") from ex |
| 91 |
|
| 92 |
except UnicodeDecodeError as ex: |
| 93 |
raise error.ConnectionError( |
| 94 |
f"Invalid response encoding from {url}: {ex}" |
| 95 |
) from ex |
| 96 |
|
| 97 |
async def async_api_get(self, path: str) -> Optional[dict]: |
| 98 |
try: |
| 99 |
return await self.async_request(path, self._session.get) |
| 100 |
except Exception as ex: |
| 101 |
logger.debug(f"EXCEPTION DURING API CALL: {ex}") |
| 102 |
raise ex |
| 103 |
|
| 104 |
async def async_api_get_ota(self, path: str) -> Optional[dict]: |
| 105 |
try: |
| 106 |
return await self.async_request( |
| 107 |
path, self._session.get, allow_ota_check_response=True |
| 108 |
) |
| 109 |
except Exception as ex: |
| 110 |
logger.debug(f"EXCEPTION DURING API CALL: {ex}") |
| 111 |
raise ex |
| 112 |
|
| 113 |
async def async_api_post( |
| 114 |
self, path: str, data: Union[dict, str, None] |
| 115 |
) -> Optional[dict]: |
| 116 |
return await self.async_request(path, self._session.post, data) |
| 117 |
|
| 118 |
def api_path(self, path: str) -> str: |
| 119 |
host = self._host |
| 120 |
port = self._port |
| 121 |
|
| 122 |
|
| 123 |
return f"http://{host}:{port}/{path[1:]}" |
| 124 |
|
| 125 |
@property |
| 126 |
def logger(self) -> Any: |
| 127 |
return self._logger |
| 128 |
|
| 129 |
@property |
| 130 |
def host(self) -> str: |
| 131 |
return self._host |
| 132 |
|
| 133 |
@property |
| 134 |
def port(self) -> int: |
| 135 |
return self._port |