Allow more than one AirVisual config entry with the same API k… (#33072)

* Allow more than one AirVisual config entry with the same API key

* Add tests

* Correctly pop geography

* Code review

* Code review
This commit is contained in:
Aaron Bach 2020-03-24 12:39:38 -06:00 committed by GitHub
parent 109f083c5d
commit 0e2fa7700d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 169 additions and 86 deletions

View file

@ -1,5 +1,5 @@
"""Define a config flow manager for AirVisual."""
import logging
import asyncio
from pyairvisual import Client
from pyairvisual.errors import InvalidKeyError
@ -15,15 +15,14 @@ from homeassistant.const import (
from homeassistant.core import callback
from homeassistant.helpers import aiohttp_client, config_validation as cv
from .const import CONF_GEOGRAPHIES, DOMAIN # pylint: disable=unused-import
_LOGGER = logging.getLogger("homeassistant.components.airvisual")
from . import async_get_geography_id
from .const import DOMAIN # pylint: disable=unused-import
class AirVisualFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle an AirVisual config flow."""
VERSION = 1
VERSION = 2
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
@property
@ -68,35 +67,33 @@ class AirVisualFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
if not user_input:
return await self._show_form()
await self._async_set_unique_id(user_input[CONF_API_KEY])
geo_id = async_get_geography_id(user_input)
await self._async_set_unique_id(geo_id)
websession = aiohttp_client.async_get_clientsession(self.hass)
client = Client(websession, api_key=user_input[CONF_API_KEY])
try:
await client.api.nearest_city()
except InvalidKeyError:
return await self._show_form(errors={CONF_API_KEY: "invalid_api_key"})
data = {CONF_API_KEY: user_input[CONF_API_KEY]}
if user_input.get(CONF_GEOGRAPHIES):
data[CONF_GEOGRAPHIES] = user_input[CONF_GEOGRAPHIES]
else:
data[CONF_GEOGRAPHIES] = [
{
CONF_LATITUDE: user_input.get(
CONF_LATITUDE, self.hass.config.latitude
),
CONF_LONGITUDE: user_input.get(
CONF_LONGITUDE, self.hass.config.longitude
),
}
]
return self.async_create_entry(
title=f"Cloud API (API key: {user_input[CONF_API_KEY][:4]}...)", data=data
# If this is the first (and only the first) time we've seen this API key, check
# that it's valid:
checked_keys = self.hass.data.setdefault("airvisual_checked_api_keys", set())
check_keys_lock = self.hass.data.setdefault(
"airvisual_checked_api_keys_lock", asyncio.Lock()
)
async with check_keys_lock:
if user_input[CONF_API_KEY] not in checked_keys:
try:
await client.api.nearest_city()
except InvalidKeyError:
return await self._show_form(
errors={CONF_API_KEY: "invalid_api_key"}
)
checked_keys.add(user_input[CONF_API_KEY])
return self.async_create_entry(
title=f"Cloud API ({geo_id})", data=user_input
)
class AirVisualOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle an AirVisual options flow."""