|
| 1 | +"""Define a base client for interacting with Flo.""" |
| 2 | +import logging |
| 3 | +from datetime import datetime, timedelta |
| 4 | +from typing import Optional |
| 5 | +from urllib.parse import urlparse |
| 6 | + |
| 7 | +import boto3 |
| 8 | +from aiohttp import ClientSession, ClientTimeout |
| 9 | +from aiohttp.client_exceptions import ClientError |
| 10 | +from pycognito.aws_srp import AWSSRP |
| 11 | + |
| 12 | +from .const import API_BASE |
| 13 | +from .device import Device |
| 14 | +from .errors import RequestError |
| 15 | +from .home import Home |
| 16 | + |
| 17 | +_LOGGER = logging.getLogger(__name__) |
| 18 | + |
| 19 | +DEFAULT_HEADER_CONTENT_TYPE: str = "application/json" |
| 20 | +DEFAULT_HEADER_USER_AGENT: str = "phyn/18 CFNetwork/1331.0.7 Darwin/21.4.0" |
| 21 | +DEFAULT_HEADER_CONNECTION = "keep-alive" |
| 22 | +DEFAULT_HEADER_API_KEY = "E7nfOgW6VI64fYpifiZSr6Me5w1Upe155zbu4lq8" |
| 23 | +DEFAULT_HEADER_ACCEPT: str = "application/json" |
| 24 | +DEFAULT_HEADER_ACCEPT_ENCODING = "gzip, deflate, br" |
| 25 | + |
| 26 | +COGNITO_REGION = "us-east-1" |
| 27 | +COGNITO_POOL_ID = "us-east-1_UAv6IUsyh" |
| 28 | +COGNITO_CLIENT_ID = "5q2m8ti0urmepg4lup8q0ptldq" |
| 29 | + |
| 30 | +DEFAULT_TIMEOUT: int = 10 |
| 31 | + |
| 32 | + |
| 33 | +class API: |
| 34 | + """Define the API object.""" |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, username: str, password: str, *, session: Optional[ClientSession] = None |
| 38 | + ) -> None: |
| 39 | + """Initialize.""" |
| 40 | + self._username: str = username |
| 41 | + self._password: str = password |
| 42 | + self._session: ClientSession = session |
| 43 | + |
| 44 | + self._token: Optional[str] = None |
| 45 | + self._token_expiration: Optional[datetime] = None |
| 46 | + self._user_id: Optional[str] = None |
| 47 | + self._username: str = username |
| 48 | + |
| 49 | + self.home: Home = Home(self._request) |
| 50 | + self.device: Device = Device(self._request) |
| 51 | + |
| 52 | + async def _request(self, method: str, url: str, **kwargs) -> dict: |
| 53 | + """Make a request against the API.""" |
| 54 | + if self._token_expiration and datetime.now() >= self._token_expiration: |
| 55 | + _LOGGER.info("Requesting new access token to replace expired one") |
| 56 | + |
| 57 | + # Nullify the token so that the authentication request doesn't use it: |
| 58 | + self._token = None |
| 59 | + |
| 60 | + # Nullify the expiration so the authentication request doesn't get caught |
| 61 | + # here: |
| 62 | + self._token_expiration = None |
| 63 | + |
| 64 | + await self.async_authenticate() |
| 65 | + |
| 66 | + kwargs.setdefault("headers", {}) |
| 67 | + kwargs["headers"].update( |
| 68 | + { |
| 69 | + "Content-Type": DEFAULT_HEADER_CONTENT_TYPE, |
| 70 | + "User-Agent": DEFAULT_HEADER_USER_AGENT, |
| 71 | + "Connection": DEFAULT_HEADER_CONNECTION, |
| 72 | + "x-api-key": DEFAULT_HEADER_API_KEY, |
| 73 | + "Accept": DEFAULT_HEADER_ACCEPT, |
| 74 | + "Accept-Encoding": DEFAULT_HEADER_ACCEPT_ENCODING, |
| 75 | + } |
| 76 | + ) |
| 77 | + |
| 78 | + if self._token: |
| 79 | + kwargs["headers"]["Authorization"] = self._token |
| 80 | + |
| 81 | + use_running_session = self._session and not self._session.closed |
| 82 | + |
| 83 | + if use_running_session: |
| 84 | + session = self._session |
| 85 | + else: |
| 86 | + session = ClientSession(timeout=ClientTimeout(total=DEFAULT_TIMEOUT)) |
| 87 | + |
| 88 | + try: |
| 89 | + async with session.request(method, url, **kwargs) as resp: |
| 90 | + data: dict = await resp.json(content_type=None) |
| 91 | + resp.raise_for_status() |
| 92 | + return data |
| 93 | + except ClientError as err: |
| 94 | + raise RequestError(f"There was an error while requesting {url}") from err |
| 95 | + finally: |
| 96 | + if not use_running_session: |
| 97 | + await session.close() |
| 98 | + |
| 99 | + async def async_authenticate(self) -> None: |
| 100 | + """Authenticate the user and set the access token with its expiration.""" |
| 101 | + client = boto3.client("cognito-idp", region_name=COGNITO_REGION) |
| 102 | + aws = AWSSRP( |
| 103 | + username=self._username, |
| 104 | + password=self._password, |
| 105 | + pool_id=COGNITO_POOL_ID, |
| 106 | + client_id=COGNITO_CLIENT_ID, |
| 107 | + client=client, |
| 108 | + ) |
| 109 | + auth_response: dict = aws.authenticate_user() |
| 110 | + |
| 111 | + access_token = auth_response["AuthenticationResult"]["AccessToken"] |
| 112 | + expires_in = auth_response["AuthenticationResult"]["ExpiresIn"] |
| 113 | + |
| 114 | + self._token = access_token |
| 115 | + self._token_expiration = datetime.now() + timedelta(seconds=expires_in) |
| 116 | + |
| 117 | + |
| 118 | +async def async_get_api( |
| 119 | + username: str, password: str, *, session: Optional[ClientSession] = None |
| 120 | +) -> API: |
| 121 | + """Instantiate an authenticated API object. |
| 122 | +
|
| 123 | + :param session: An ``aiohttp`` ``ClientSession`` |
| 124 | + :type session: ``aiohttp.client.ClientSession`` |
| 125 | + :param email: A Phyn email address |
| 126 | + :type email: ``str`` |
| 127 | + :param password: A Phyn password |
| 128 | + :type password: ``str`` |
| 129 | + :rtype: :meth:`aiophyn.api.API` |
| 130 | + """ |
| 131 | + api = API(username, password, session=session) |
| 132 | + await api.async_authenticate() |
| 133 | + return api |
0 commit comments