2019-07-09 08:29:06 +00:00
|
|
|
"""Config flow to configure the Notion integration."""
|
2019-12-06 19:40:00 +00:00
|
|
|
from aionotion import async_get_client
|
|
|
|
from aionotion.errors import NotionError
|
2019-07-09 08:29:06 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
|
|
|
from homeassistant import config_entries
|
|
|
|
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
|
|
|
|
from homeassistant.core import callback
|
|
|
|
from homeassistant.helpers import aiohttp_client
|
|
|
|
|
|
|
|
from .const import DOMAIN
|
|
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def configured_instances(hass):
|
|
|
|
"""Return a set of configured Notion instances."""
|
|
|
|
return set(
|
2019-07-31 19:25:30 +00:00
|
|
|
entry.data[CONF_USERNAME] for entry in hass.config_entries.async_entries(DOMAIN)
|
|
|
|
)
|
2019-07-09 08:29:06 +00:00
|
|
|
|
|
|
|
|
|
|
|
@config_entries.HANDLERS.register(DOMAIN)
|
|
|
|
class NotionFlowHandler(config_entries.ConfigFlow):
|
|
|
|
"""Handle a Notion config flow."""
|
|
|
|
|
|
|
|
VERSION = 1
|
|
|
|
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
|
|
|
|
|
|
|
|
async def _show_form(self, errors=None):
|
|
|
|
"""Show the form to the user."""
|
2019-07-31 19:25:30 +00:00
|
|
|
data_schema = vol.Schema(
|
|
|
|
{vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
|
|
|
|
)
|
2019-07-09 08:29:06 +00:00
|
|
|
|
|
|
|
return self.async_show_form(
|
2019-07-31 19:25:30 +00:00
|
|
|
step_id="user", data_schema=data_schema, errors=errors or {}
|
2019-07-09 08:29:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
async def async_step_import(self, import_config):
|
|
|
|
"""Import a config entry from configuration.yaml."""
|
|
|
|
return await self.async_step_user(import_config)
|
|
|
|
|
|
|
|
async def async_step_user(self, user_input=None):
|
|
|
|
"""Handle the start of the config flow."""
|
|
|
|
|
|
|
|
if not user_input:
|
|
|
|
return await self._show_form()
|
|
|
|
|
|
|
|
if user_input[CONF_USERNAME] in configured_instances(self.hass):
|
2019-07-31 19:25:30 +00:00
|
|
|
return await self._show_form({CONF_USERNAME: "identifier_exists"})
|
2019-07-09 08:29:06 +00:00
|
|
|
|
|
|
|
session = aiohttp_client.async_get_clientsession(self.hass)
|
|
|
|
|
|
|
|
try:
|
|
|
|
await async_get_client(
|
2019-07-31 19:25:30 +00:00
|
|
|
user_input[CONF_USERNAME], user_input[CONF_PASSWORD], session
|
|
|
|
)
|
2019-07-09 08:29:06 +00:00
|
|
|
except NotionError:
|
2019-07-31 19:25:30 +00:00
|
|
|
return await self._show_form({"base": "invalid_credentials"})
|
2019-07-09 08:29:06 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
return self.async_create_entry(title=user_input[CONF_USERNAME], data=user_input)
|