diff --git a/custom_components/healthchecksio/config_flow.py b/custom_components/healthchecksio/config_flow.py index 9901d96..702e38d 100644 --- a/custom_components/healthchecksio/config_flow.py +++ b/custom_components/healthchecksio/config_flow.py @@ -3,10 +3,11 @@ from __future__ import annotations import asyncio +import json from collections import OrderedDict from logging import getLogger -import async_timeout +import aiohttp import voluptuous as vol from homeassistant import config_entries from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -125,22 +126,40 @@ async def _test_credentials( self, api_key, check, self_hosted, site_root, ping_endpoint ): """Return true if credentials is valid.""" + LOGGER.debug("Testing Credentials") + verify_ssl = not self_hosted or site_root.startswith("https") + session = async_get_clientsession(self.hass, verify_ssl) + timeout10 = aiohttp.ClientTimeout(total=10) + headers = {"X-Api-Key": api_key} + if self_hosted: + check_url = f"{site_root}/{ping_endpoint}/{check}" + else: + check_url = f"https://hc-ping.com/{check}" + await asyncio.sleep(1) # needed for self-hosted instances try: - verify_ssl = not self_hosted or site_root.startswith("https") - session = async_get_clientsession(self.hass, verify_ssl) - headers = {"X-Api-Key": api_key} - async with async_timeout.timeout(10): - LOGGER.info("Checking API Key") - await session.get(f"{site_root}/api/v1/checks/", headers=headers) - - LOGGER.info("Checking Check ID") - if self_hosted: - check_url = f"{site_root}/{ping_endpoint}/{check}" - else: - check_url = f"https://hc-ping.com/{check}" - await asyncio.sleep(1) # needed for self-hosted instances - await session.get(check_url) + check_response = await session.get(check_url, timeout=timeout10) + except (TimeoutError, aiohttp.ClientError): + LOGGER.exception("Could Not Send Check") + return False + else: + if check_response.ok: + LOGGER.debug("Send Check HTTP Status Code: %s", check_response.status) + else: + LOGGER.error("Send Check HTTP Status Code: %s", check_response.status) + return False + try: + request = await session.get( + f"{site_root}/api/v1/checks/", headers=headers, timeout=timeout10 + ) + except (TimeoutError, aiohttp.ClientError): + LOGGER.exception("Could Not Update Data") + return False + except (ValueError, json.decoder.JSONDecodeError): + LOGGER.exception("Data JSON Decode Error") + return False + else: + if not request.ok: + LOGGER.error("Got Data HTTP Status Code: %s", request.status) + return False + LOGGER.debug("Got Data HTTP Status Code: %s", request.status) return True - except Exception: # pylint: disable=broad-except - LOGGER.exception("Unknown error occurred") - return False diff --git a/custom_components/healthchecksio/coordinator.py b/custom_components/healthchecksio/coordinator.py index 247f755..c22fe6b 100644 --- a/custom_components/healthchecksio/coordinator.py +++ b/custom_components/healthchecksio/coordinator.py @@ -2,7 +2,6 @@ from __future__ import annotations -import asyncio from logging import getLogger from typing import TYPE_CHECKING, Any @@ -50,22 +49,11 @@ def __init__( async def _async_update_data(self) -> dict[str, Any]: """Update data.""" - try: - data = await self._session.get( - f"{self._site_root}/api/v1/checks/", - headers={"X-Api-Key": self._api_key}, - timeout=ClientTimeout(total=10), - ) - except Exception as error: - raise UpdateFailed(error) from error - check_url = ( f"https://hc-ping.com/{self._check_id}" if not self._self_hosted else f"{self._site_root}/{self._ping_endpoint}/{self._check_id}" ) - if self._self_hosted: - await asyncio.sleep(1) # needed for self-hosted instances try: await self._session.get( @@ -75,4 +63,12 @@ async def _async_update_data(self) -> dict[str, Any]: except Exception: LOGGER.exception("Could not ping") - return await data.json() + try: + data = await self._session.get( + f"{self._site_root}/api/v1/checks/", + headers={"X-Api-Key": self._api_key}, + timeout=ClientTimeout(total=10), + ) + return await data.json() + except Exception as error: + raise UpdateFailed(error) from error