pyh0n/pyhon/connection/handler.py

132 lines
4.6 KiB
Python
Raw Normal View History

2023-04-10 00:20:28 +05:30
import json
2023-04-09 21:43:50 +05:30
from contextlib import asynccontextmanager
import aiohttp
from pyhon import const
from pyhon.connection.auth import HonAuth, _LOGGER
from pyhon.connection.device import HonDevice
from pyhon.exceptions import HonAuthenticationError
2023-04-09 21:43:50 +05:30
class HonBaseConnectionHandler:
_HEADERS = {"user-agent": const.USER_AGENT, "Content-Type": "application/json"}
2023-04-10 10:04:19 +05:30
def __init__(self, session=None):
2023-04-12 05:39:41 +05:30
self._create_session = session is None
2023-04-10 10:04:19 +05:30
self._session = session
2023-04-09 21:43:50 +05:30
self._auth = None
async def __aenter__(self):
2023-04-10 00:20:28 +05:30
return await self.create()
2023-04-09 21:43:50 +05:30
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
async def create(self):
2023-04-12 05:39:41 +05:30
if self._create_session:
self._session = aiohttp.ClientSession()
2023-04-10 00:20:28 +05:30
return self
2023-04-09 21:43:50 +05:30
@asynccontextmanager
2023-04-10 10:04:19 +05:30
async def _intercept(self, method, *args, loop=0, **kwargs):
2023-04-10 03:17:33 +05:30
raise NotImplementedError
2023-04-09 21:43:50 +05:30
2023-04-10 10:04:19 +05:30
@asynccontextmanager
async def get(self, *args, **kwargs):
async with self._intercept(self._session.get, *args, **kwargs) as response:
yield response
2023-04-09 21:43:50 +05:30
@asynccontextmanager
async def post(self, *args, **kwargs):
2023-04-10 10:04:19 +05:30
async with self._intercept(self._session.post, *args, **kwargs) as response:
yield response
2023-04-09 21:43:50 +05:30
async def close(self):
2023-04-12 05:39:41 +05:30
if self._create_session:
await self._session.close()
2023-04-09 21:43:50 +05:30
class HonConnectionHandler(HonBaseConnectionHandler):
2023-04-10 10:04:19 +05:30
def __init__(self, email, password, session=None):
super().__init__(session=session)
2023-04-09 21:43:50 +05:30
self._device = HonDevice()
self._email = email
self._password = password
if not self._email:
raise HonAuthenticationError("An email address must be specified")
2023-04-09 21:43:50 +05:30
if not self._password:
raise HonAuthenticationError("A password address must be specified")
2023-04-09 21:43:50 +05:30
@property
def device(self):
return self._device
async def create(self):
await super().create()
self._auth = HonAuth(self._session, self._email, self._password, self._device)
2023-04-10 00:20:28 +05:30
return self
2023-04-09 21:43:50 +05:30
async def _check_headers(self, headers):
2023-04-12 22:44:14 +05:30
if not (self._auth.cognito_token and self._auth.id_token):
await self._auth.authenticate()
headers["cognito-token"] = self._auth.cognito_token
headers["id-token"] = self._auth.id_token
return self._HEADERS | headers
2023-04-09 21:43:50 +05:30
@asynccontextmanager
2023-04-09 22:13:57 +05:30
async def _intercept(self, method, *args, loop=0, **kwargs):
2023-04-09 21:43:50 +05:30
kwargs["headers"] = await self._check_headers(kwargs.get("headers", {}))
2023-04-09 22:13:57 +05:30
async with method(*args, **kwargs) as response:
2023-04-11 20:39:02 +05:30
if response.status in [401, 403] and loop == 0:
2023-04-09 22:13:57 +05:30
_LOGGER.info("Try refreshing token...")
await self._auth.refresh()
2023-04-12 01:44:36 +05:30
async with self._intercept(
method, *args, loop=loop + 1, **kwargs
) as result:
2023-04-11 20:39:02 +05:30
yield result
elif response.status in [401, 403] and loop == 1:
2023-04-10 00:25:36 +05:30
_LOGGER.warning(
"%s - Error %s - %s",
response.request_info.url,
response.status,
await response.text(),
)
2023-04-09 21:43:50 +05:30
await self.create()
2023-04-12 01:44:36 +05:30
async with self._intercept(
method, *args, loop=loop + 1, **kwargs
) as result:
2023-04-11 20:39:02 +05:30
yield result
2023-04-09 21:43:50 +05:30
elif loop >= 2:
2023-04-10 00:25:36 +05:30
_LOGGER.error(
"%s - Error %s - %s",
response.request_info.url,
response.status,
await response.text(),
)
raise HonAuthenticationError("Login failure")
2023-04-09 21:43:50 +05:30
else:
2023-04-10 00:20:28 +05:30
try:
await response.json()
yield response
except json.JSONDecodeError:
2023-04-10 00:25:36 +05:30
_LOGGER.warning(
"%s - JsonDecodeError %s - %s",
response.request_info.url,
response.status,
await response.text(),
)
2023-04-10 00:20:28 +05:30
yield {}
2023-04-09 21:43:50 +05:30
class HonAnonymousConnectionHandler(HonBaseConnectionHandler):
_HEADERS = HonBaseConnectionHandler._HEADERS | {"x-api-key": const.API_KEY}
@asynccontextmanager
2023-04-10 10:04:19 +05:30
async def _intercept(self, method, *args, loop=0, **kwargs):
kwargs["headers"] = kwargs.pop("headers", {}) | self._HEADERS
async with method(*args, **kwargs) as response:
if response.status == 403:
_LOGGER.error("Can't authenticate anymore")
2023-04-09 21:43:50 +05:30
yield response