2024-01-18 09:57:33 +00:00
|
|
|
"""Module for HttpClientSession class."""
|
2024-01-19 20:06:50 +00:00
|
|
|
import asyncio
|
2024-02-03 14:28:20 +00:00
|
|
|
import logging
|
2024-01-18 17:32:26 +00:00
|
|
|
from typing import Any, Dict, Optional, Tuple, Union
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
import aiohttp
|
2024-01-29 15:26:00 +00:00
|
|
|
from yarl import URL
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
from .deviceconfig import DeviceConfig
|
2024-01-23 22:15:18 +00:00
|
|
|
from .exceptions import (
|
2024-02-21 15:52:55 +00:00
|
|
|
KasaException,
|
|
|
|
TimeoutError,
|
|
|
|
_ConnectionError,
|
2024-01-23 22:15:18 +00:00
|
|
|
)
|
2024-01-18 17:32:26 +00:00
|
|
|
from .json import loads as json_loads
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-02-03 14:28:20 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
def get_cookie_jar() -> aiohttp.CookieJar:
|
|
|
|
"""Return a new cookie jar with the correct options for device communication."""
|
|
|
|
return aiohttp.CookieJar(unsafe=True, quote_cookie=False)
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
class HttpClient:
|
|
|
|
"""HttpClient Class."""
|
|
|
|
|
|
|
|
def __init__(self, config: DeviceConfig) -> None:
|
|
|
|
self._config = config
|
2024-01-19 20:30:01 +00:00
|
|
|
self._client_session: aiohttp.ClientSession = None
|
2024-01-18 17:32:26 +00:00
|
|
|
self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False)
|
2024-01-29 15:26:00 +00:00
|
|
|
self._last_url = URL(f"http://{self._config.host}/")
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
@property
|
2024-01-18 17:32:26 +00:00
|
|
|
def client(self) -> aiohttp.ClientSession:
|
2024-01-18 09:57:33 +00:00
|
|
|
"""Return the underlying http client."""
|
|
|
|
if self._config.http_client and issubclass(
|
2024-01-18 17:32:26 +00:00
|
|
|
self._config.http_client.__class__, aiohttp.ClientSession
|
2024-01-18 09:57:33 +00:00
|
|
|
):
|
|
|
|
return self._config.http_client
|
|
|
|
|
2024-01-19 20:30:01 +00:00
|
|
|
if not self._client_session:
|
|
|
|
self._client_session = aiohttp.ClientSession(cookie_jar=get_cookie_jar())
|
|
|
|
return self._client_session
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
async def post(
|
|
|
|
self,
|
2024-01-29 15:26:00 +00:00
|
|
|
url: URL,
|
2024-01-18 09:57:33 +00:00
|
|
|
*,
|
|
|
|
params: Optional[Dict[str, Any]] = None,
|
|
|
|
data: Optional[bytes] = None,
|
2024-01-23 15:29:27 +00:00
|
|
|
json: Optional[Union[Dict, Any]] = None,
|
2024-01-18 09:57:33 +00:00
|
|
|
headers: Optional[Dict[str, str]] = None,
|
|
|
|
cookies_dict: Optional[Dict[str, str]] = None,
|
|
|
|
) -> Tuple[int, Optional[Union[Dict, bytes]]]:
|
2024-01-23 15:29:27 +00:00
|
|
|
"""Send an http post request to the device.
|
|
|
|
|
|
|
|
If the request is provided via the json parameter json will be returned.
|
|
|
|
"""
|
2024-02-03 14:28:20 +00:00
|
|
|
_LOGGER.debug("Posting to %s", url)
|
2024-01-18 09:57:33 +00:00
|
|
|
response_data = None
|
2024-01-18 17:32:26 +00:00
|
|
|
self._last_url = url
|
|
|
|
self.client.cookie_jar.clear()
|
2024-01-23 15:29:27 +00:00
|
|
|
return_json = bool(json)
|
|
|
|
# If json is not a dict send as data.
|
|
|
|
# This allows the json parameter to be used to pass other
|
|
|
|
# types of data such as async_generator and still have json
|
|
|
|
# returned.
|
|
|
|
if json and not isinstance(json, Dict):
|
|
|
|
data = json
|
|
|
|
json = None
|
2024-01-18 09:57:33 +00:00
|
|
|
try:
|
|
|
|
resp = await self.client.post(
|
|
|
|
url,
|
|
|
|
params=params,
|
|
|
|
data=data,
|
|
|
|
json=json,
|
|
|
|
timeout=self._config.timeout,
|
2024-01-18 17:32:26 +00:00
|
|
|
cookies=cookies_dict,
|
2024-01-18 09:57:33 +00:00
|
|
|
headers=headers,
|
|
|
|
)
|
2024-01-19 20:06:50 +00:00
|
|
|
async with resp:
|
|
|
|
if resp.status == 200:
|
|
|
|
response_data = await resp.read()
|
2024-01-23 15:29:27 +00:00
|
|
|
if return_json:
|
2024-01-19 20:06:50 +00:00
|
|
|
response_data = json_loads(response_data.decode())
|
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise _ConnectionError(
|
2024-01-23 22:15:18 +00:00
|
|
|
f"Device connection error: {self._config.host}: {ex}", ex
|
2024-01-18 09:57:33 +00:00
|
|
|
) from ex
|
2024-01-19 20:06:50 +00:00
|
|
|
except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as ex:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise TimeoutError(
|
2024-01-19 20:06:50 +00:00
|
|
|
"Unable to query the device, "
|
|
|
|
+ f"timed out: {self._config.host}: {ex}",
|
|
|
|
ex,
|
2024-01-18 09:57:33 +00:00
|
|
|
) from ex
|
|
|
|
except Exception as ex:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise KasaException(
|
2024-01-19 20:06:50 +00:00
|
|
|
f"Unable to query the device: {self._config.host}: {ex}", ex
|
2024-01-18 09:57:33 +00:00
|
|
|
) from ex
|
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
return resp.status, response_data
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
def get_cookie(self, cookie_name: str) -> Optional[str]:
|
2024-01-18 09:57:33 +00:00
|
|
|
"""Return the cookie with cookie_name."""
|
2024-01-18 17:32:26 +00:00
|
|
|
if cookie := self.client.cookie_jar.filter_cookies(self._last_url).get(
|
|
|
|
cookie_name
|
|
|
|
):
|
|
|
|
return cookie.value
|
|
|
|
return None
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
async def close(self) -> None:
|
2024-01-19 20:30:01 +00:00
|
|
|
"""Close the ClientSession."""
|
|
|
|
client = self._client_session
|
|
|
|
self._client_session = None
|
2024-01-18 09:57:33 +00:00
|
|
|
if client:
|
2024-01-18 17:32:26 +00:00
|
|
|
await client.close()
|