Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for UptimeRobot integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from pyuptimerobot import (
9  UptimeRobot,
10  UptimeRobotAccount,
11  UptimeRobotApiError,
12  UptimeRobotApiResponse,
13  UptimeRobotAuthenticationException,
14  UptimeRobotException,
15 )
16 import voluptuous as vol
17 
18 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
19 from homeassistant.const import CONF_API_KEY
20 from homeassistant.helpers.aiohttp_client import async_get_clientsession
21 
22 from .const import API_ATTR_OK, DOMAIN, LOGGER
23 
24 STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): str})
25 
26 
27 class UptimeRobotConfigFlow(ConfigFlow, domain=DOMAIN):
28  """Handle a config flow for UptimeRobot."""
29 
30  VERSION = 1
31 
32  async def _validate_input(
33  self, data: dict[str, Any]
34  ) -> tuple[dict[str, str], UptimeRobotAccount | None]:
35  """Validate the user input allows us to connect."""
36  errors: dict[str, str] = {}
37  response: UptimeRobotApiResponse | UptimeRobotApiError | None = None
38  key: str = data[CONF_API_KEY]
39  if key.startswith(("ur", "m")):
40  LOGGER.error("Wrong API key type detected, use the 'main' API key")
41  errors["base"] = "not_main_key"
42  return errors, None
43  uptime_robot_api = UptimeRobot(key, async_get_clientsession(self.hass))
44 
45  try:
46  response = await uptime_robot_api.async_get_account_details()
47  except UptimeRobotAuthenticationException as exception:
48  LOGGER.error(exception)
49  errors["base"] = "invalid_api_key"
50  except UptimeRobotException as exception:
51  LOGGER.error(exception)
52  errors["base"] = "cannot_connect"
53  except Exception as exception: # noqa: BLE001
54  LOGGER.exception(exception)
55  errors["base"] = "unknown"
56  else:
57  if response.status != API_ATTR_OK:
58  errors["base"] = "unknown"
59  LOGGER.error(response.error.message)
60 
61  account: UptimeRobotAccount | None = (
62  response.data
63  if response and response.data and response.data.email
64  else None
65  )
66 
67  return errors, account
68 
69  async def async_step_user(
70  self, user_input: dict[str, Any] | None = None
71  ) -> ConfigFlowResult:
72  """Handle the initial step."""
73  if user_input is None:
74  return self.async_show_formasync_show_formasync_show_form(
75  step_id="user", data_schema=STEP_USER_DATA_SCHEMA
76  )
77 
78  errors, account = await self._validate_input_validate_input(user_input)
79  if account:
80  await self.async_set_unique_idasync_set_unique_id(str(account.user_id))
81  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
82  return self.async_create_entryasync_create_entryasync_create_entry(title=account.email, data=user_input)
83 
84  return self.async_show_formasync_show_formasync_show_form(
85  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
86  )
87 
88  async def async_step_reauth(
89  self, entry_data: Mapping[str, Any]
90  ) -> ConfigFlowResult:
91  """Return the reauth confirm step."""
92  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
93 
95  self, user_input: dict[str, Any] | None = None
96  ) -> ConfigFlowResult:
97  """Dialog that informs the user that reauth is required."""
98  if user_input is None:
99  return self.async_show_formasync_show_formasync_show_form(
100  step_id="reauth_confirm", data_schema=STEP_USER_DATA_SCHEMA
101  )
102  errors, account = await self._validate_input_validate_input(user_input)
103  if account:
104  if self.context.get("unique_id") and self.context["unique_id"] != str(
105  account.user_id
106  ):
107  errors["base"] = "reauth_failed_matching_account"
108  else:
109  existing_entry = await self.async_set_unique_idasync_set_unique_id(str(account.user_id))
110  if existing_entry:
111  self.hass.config_entries.async_update_entry(
112  existing_entry, data=user_input
113  )
114  await self.hass.config_entries.async_reload(existing_entry.entry_id)
115  return self.async_abortasync_abortasync_abort(reason="reauth_successful")
116  return self.async_abortasync_abortasync_abort(reason="reauth_failed_existing")
117 
118  return self.async_show_formasync_show_formasync_show_form(
119  step_id="reauth_confirm", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
120  )
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:90
tuple[dict[str, str], UptimeRobotAccount|None] _validate_input(self, dict[str, Any] data)
Definition: config_flow.py:34
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:96
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:71
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_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)
str
_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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
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)