Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for MyPermobil integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from mypermobil import (
10  MyPermobil,
11  MyPermobilAPIException,
12  MyPermobilClientException,
13  MyPermobilEulaException,
14 )
15 import voluptuous as vol
16 
17 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
18 from homeassistant.const import CONF_CODE, CONF_EMAIL, CONF_REGION, CONF_TOKEN, CONF_TTL
19 from homeassistant.core import HomeAssistant, async_get_hass
20 from homeassistant.helpers import selector
21 from homeassistant.helpers.aiohttp_client import async_get_clientsession
24  TextSelector,
25  TextSelectorConfig,
26  TextSelectorType,
27 )
28 
29 from .const import APPLICATION, DOMAIN
30 
31 _LOGGER = logging.getLogger(__name__)
32 
33 GET_EMAIL_SCHEMA = vol.Schema(
34  {
35  vol.Required(CONF_EMAIL): TextSelector(
36  TextSelectorConfig(type=TextSelectorType.EMAIL)
37  ),
38  }
39 )
40 
41 GET_TOKEN_SCHEMA = vol.Schema({vol.Required(CONF_CODE): cv.string})
42 
43 
44 class PermobilConfigFlow(ConfigFlow, domain=DOMAIN):
45  """Permobil config flow."""
46 
47  VERSION = 1
48  region_names: dict[str, str] = {}
49  data: dict[str, str] = {}
50 
51  def __init__(self) -> None:
52  """Initialize flow."""
53  hass: HomeAssistant = async_get_hass()
54  session = async_get_clientsession(hass)
55  self.p_apip_api = MyPermobil(APPLICATION, session=session)
56 
57  async def async_step_user(
58  self, user_input: dict[str, Any] | None = None
59  ) -> ConfigFlowResult:
60  """Invoke when a user initiates a flow via the user interface."""
61  errors: dict[str, str] = {}
62 
63  if user_input:
64  try:
65  self.p_apip_api.set_email(user_input[CONF_EMAIL])
66  except MyPermobilClientException:
67  _LOGGER.exception("Error validating email")
68  errors["base"] = "invalid_email"
69 
70  self.datadata.update(user_input)
71 
72  await self.async_set_unique_idasync_set_unique_id(self.datadata[CONF_EMAIL])
73  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
74 
75  if errors or not user_input:
76  return self.async_show_formasync_show_formasync_show_form(
77  step_id="user", data_schema=GET_EMAIL_SCHEMA, errors=errors
78  )
79  return await self.async_step_regionasync_step_region()
80 
81  async def async_step_region(
82  self, user_input: dict[str, Any] | None = None
83  ) -> ConfigFlowResult:
84  """Invoke when a user initiates a flow via the user interface."""
85  errors: dict[str, str] = {}
86  if not user_input:
87  # fetch the list of regions names and urls from the api
88  # for the user to select from.
89  try:
90  self.region_namesregion_names = await self.p_apip_api.request_region_names()
91  _LOGGER.debug(
92  "region names %s",
93  ",".join(list(self.region_namesregion_names.keys())),
94  )
95  except MyPermobilAPIException:
96  _LOGGER.exception("Error requesting regions")
97  errors["base"] = "region_fetch_error"
98 
99  else:
100  region_url = self.region_namesregion_names[user_input[CONF_REGION]]
101 
102  self.datadata[CONF_REGION] = region_url
103  self.p_apip_api.set_region(region_url)
104  _LOGGER.debug("region %s", self.p_apip_api.region)
105  try:
106  # tell backend to send code to the users email
107  await self.p_apip_api.request_application_code()
108  except MyPermobilAPIException:
109  _LOGGER.exception("Error requesting code")
110  errors["base"] = "code_request_error"
111 
112  if errors or not user_input:
113  # the error could either be that the fetch region did not pass
114  # or that the request application code failed
115  schema = vol.Schema(
116  {
117  vol.Required(CONF_REGION): selector.SelectSelector(
118  selector.SelectSelectorConfig(
119  options=list(self.region_namesregion_names.keys()),
120  mode=selector.SelectSelectorMode.DROPDOWN,
121  )
122  ),
123  }
124  )
125  return self.async_show_formasync_show_formasync_show_form(
126  step_id="region", data_schema=schema, errors=errors
127  )
128 
129  return await self.async_step_email_codeasync_step_email_code()
130 
132  self, user_input: dict[str, Any] | None = None
133  ) -> ConfigFlowResult:
134  """Second step in config flow to enter the email code."""
135  errors: dict[str, str] = {}
136 
137  if user_input:
138  try:
139  self.p_apip_api.set_code(user_input[CONF_CODE])
140  self.datadata.update(user_input)
141  token, ttl = await self.p_apip_api.request_application_token()
142  self.datadata[CONF_TOKEN] = token
143  self.datadata[CONF_TTL] = ttl
144  except (MyPermobilAPIException, MyPermobilClientException):
145  # the code did not pass validation by the api client
146  # or the backend returned an error when trying to validate the code
147  _LOGGER.exception("Error verifying code")
148  errors["base"] = "invalid_code"
149  except MyPermobilEulaException:
150  # The user has not accepted the EULA
151  errors["base"] = "unsigned_eula"
152 
153  if errors or not user_input:
154  return self.async_show_formasync_show_formasync_show_form(
155  step_id="email_code",
156  data_schema=GET_TOKEN_SCHEMA,
157  errors=errors,
158  description_placeholders={"app_name": "MyPermobil"},
159  )
160 
161  if self.sourcesourcesourcesource == SOURCE_REAUTH:
162  return self.async_update_reload_and_abortasync_update_reload_and_abort(
163  self._get_reauth_entry_get_reauth_entry(), title=self.datadata[CONF_EMAIL], data=self.datadata
164  )
165 
166  return self.async_create_entryasync_create_entryasync_create_entry(title=self.datadata[CONF_EMAIL], data=self.datadata)
167 
168  async def async_step_reauth(
169  self, entry_data: Mapping[str, Any]
170  ) -> ConfigFlowResult:
171  """Perform reauth upon an API authentication error."""
172  try:
173  email: str = entry_data[CONF_EMAIL]
174  region: str = entry_data[CONF_REGION]
175  self.p_apip_api.set_email(email)
176  self.p_apip_api.set_region(region)
177  self.datadata = {
178  CONF_EMAIL: email,
179  CONF_REGION: region,
180  }
181  await self.p_apip_api.request_application_code()
182  except MyPermobilAPIException:
183  _LOGGER.exception("Error requesting code for reauth")
184  return self.async_abortasync_abortasync_abort(reason="unknown")
185 
186  return await self.async_step_email_codeasync_step_email_code()
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:170
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:59
ConfigFlowResult async_step_email_code(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:133
ConfigFlowResult async_step_region(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:83
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
str|None source(self)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
HomeAssistant async_get_hass()
Definition: core.py:286
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)