| 1 |
"""YoLink client.""" |
| 2 |
|
| 3 |
from typing import Any, Dict |
| 4 |
|
| 5 |
from aiohttp import ClientError, ClientResponse |
| 6 |
from tenacity import retry, stop_after_attempt, retry_if_exception_type |
| 7 |
|
| 8 |
from .auth_mgr import YoLinkAuthMgr |
| 9 |
from .exception import YoLinkClientError, YoLinkDeviceConnectionFailed |
| 10 |
from .model import BRDP |
| 11 |
|
| 12 |
|
| 13 |
class YoLinkClient: |
| 14 |
"""YoLink client.""" |
| 15 |
|
| 16 |
def __init__(self, auth_mgr: YoLinkAuthMgr) -> None: |
| 17 |
"""Init YoLink client""" |
| 18 |
self._auth_mgr = auth_mgr |
| 19 |
|
| 20 |
async def request( |
| 21 |
self, |
| 22 |
method: str, |
| 23 |
url: str, |
| 24 |
auth_required: bool = True, |
| 25 |
**kwargs: Any, |
| 26 |
) -> ClientResponse: |
| 27 |
"""Proxy Request and add Auth/CV headers.""" |
| 28 |
headers = kwargs.pop("headers", {}) |
| 29 |
params = kwargs.pop("params", None) |
| 30 |
data = kwargs.pop("data", None) |
| 31 |
timeout = kwargs.pop("timeout", 8) |
| 32 |
|
| 33 |
|
| 34 |
extra_headers = kwargs.pop("extra_headers", None) |
| 35 |
extra_params = kwargs.pop("extra_params", None) |
| 36 |
extra_data = kwargs.pop("extra_data", None) |
| 37 |
if auth_required: |
| 38 |
|
| 39 |
await self._auth_mgr.check_and_refresh_token() |
| 40 |
|
| 41 |
headers["Authorization"] = self._auth_mgr.http_auth_header() |
| 42 |
|
| 43 |
if extra_headers: |
| 44 |
headers.update(extra_headers) |
| 45 |
if extra_params: |
| 46 |
|
| 47 |
params = params or {} |
| 48 |
params.update(extra_params) |
| 49 |
if extra_data: |
| 50 |
|
| 51 |
data = data or {} |
| 52 |
data.update(extra_data) |
| 53 |
return await self._auth_mgr.client_session().request( |
| 54 |
method, |
| 55 |
url, |
| 56 |
**kwargs, |
| 57 |
headers=headers, |
| 58 |
params=params, |
| 59 |
data=data, |
| 60 |
timeout=timeout, |
| 61 |
) |
| 62 |
|
| 63 |
async def get(self, url: str, **kwargs: Any) -> ClientResponse: |
| 64 |
"""Call http request with Get Method.""" |
| 65 |
return await self.request("GET", url, True, **kwargs) |
| 66 |
|
| 67 |
async def post(self, url: str, **kwargs: Any) -> ClientResponse: |
| 68 |
"""Call Http Request with POST Method""" |
| 69 |
return await self.request("POST", url, True, **kwargs) |
| 70 |
|
| 71 |
@retry( |
| 72 |
retry=retry_if_exception_type(YoLinkDeviceConnectionFailed), |
| 73 |
stop=stop_after_attempt(2), |
| 74 |
) |
| 75 |
async def execute(self, url: str, bsdp: Dict, **kwargs: Any) -> BRDP: |
| 76 |
"""Call YoLink Api""" |
| 77 |
try: |
| 78 |
yl_resp = await self.post(url, json=bsdp, **kwargs) |
| 79 |
yl_resp.raise_for_status() |
| 80 |
_yl_body = await yl_resp.text() |
| 81 |
brdp = BRDP.model_validate_json(_yl_body) |
| 82 |
brdp.check_response() |
| 83 |
except ClientError as client_err: |
| 84 |
raise YoLinkClientError( |
| 85 |
"-1003", "yolink client request failed!" |
| 86 |
) from client_err |
| 87 |
except YoLinkClientError as yl_client_err: |
| 88 |
raise yl_client_err |
| 89 |
return brdp |