diff --git a/custom_components/remote_homeassistant/rest_api.py b/custom_components/remote_homeassistant/rest_api.py index 92f362f..b4844fd 100644 --- a/custom_components/remote_homeassistant/rest_api.py +++ b/custom_components/remote_homeassistant/rest_api.py @@ -1,8 +1,12 @@ """Simple implementation to call Home Assistant REST API.""" +import logging + from homeassistant import exceptions from homeassistant.helpers.aiohttp_client import async_get_clientsession +_LOGGER = logging.getLogger(__name__) + API_URL = "{proto}://{host}:{port}/api/remote_homeassistant/discovery" @@ -27,7 +31,7 @@ class UnsupportedVersion(exceptions.HomeAssistantError): class EndpointMissing(exceptions.HomeAssistantError): - """Error to indicate there is invalid auth.""" + """Error to indicate endpoint is missing.""" async def async_get_discovery_info(hass, host, port, secure, access_token, verify_ssl): @@ -37,23 +41,46 @@ async def async_get_discovery_info(hass, host, port, secure, access_token, verif host=host, port=port, ) + + access_token = str(access_token).strip() + headers = { "Authorization": "Bearer " + access_token, "Content-Type": "application/json", } + session = async_get_clientsession(hass, verify_ssl) - # Fetch discovery info location for name and unique UUID async with session.get(url, headers=headers) as resp: if resp.status == 404: raise EndpointMissing() + if 400 <= resp.status < 500: + body = await resp.text() + _LOGGER.error( + "Remote Home Assistant auth/API error: status=%s, url=%s, body=%s", + resp.status, + url, + body[:500], + ) raise InvalidAuth() + if resp.status != 200: + body = await resp.text() + _LOGGER.error( + "Remote Home Assistant API problem: status=%s, url=%s, body=%s", + resp.status, + url, + body[:500], + ) raise ApiProblem() - json = await resp.json() - if not isinstance(json, dict): - raise BadResponse(f"Bad response data: {json}") - if "uuid" not in json: + + data = await resp.json() + + if not isinstance(data, dict): + raise BadResponse(f"Bad response data: {data}") + + if "uuid" not in data: raise UnsupportedVersion() - return json + + return data