Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure the Pi-hole 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 hole import Hole
10 from hole.exceptions import HoleError
11 import voluptuous as vol
12 
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import (
15  CONF_API_KEY,
16  CONF_HOST,
17  CONF_LOCATION,
18  CONF_NAME,
19  CONF_PORT,
20  CONF_SSL,
21  CONF_VERIFY_SSL,
22 )
23 from homeassistant.helpers.aiohttp_client import async_get_clientsession
24 
25 from .const import (
26  DEFAULT_LOCATION,
27  DEFAULT_NAME,
28  DEFAULT_SSL,
29  DEFAULT_VERIFY_SSL,
30  DOMAIN,
31 )
32 
33 _LOGGER = logging.getLogger(__name__)
34 
35 
36 class PiHoleFlowHandler(ConfigFlow, domain=DOMAIN):
37  """Handle a Pi-hole config flow."""
38 
39  VERSION = 1
40 
41  def __init__(self) -> None:
42  """Initialize the config flow."""
43  self._config_config: dict = {}
44 
45  async def async_step_user(
46  self, user_input: dict[str, Any] | None = None
47  ) -> ConfigFlowResult:
48  """Handle a flow initiated by the user."""
49  errors = {}
50 
51  if user_input is not None:
52  self._config_config = {
53  CONF_HOST: f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}",
54  CONF_NAME: user_input[CONF_NAME],
55  CONF_LOCATION: user_input[CONF_LOCATION],
56  CONF_SSL: user_input[CONF_SSL],
57  CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL],
58  }
59 
60  self._async_abort_entries_match_async_abort_entries_match(
61  {
62  CONF_HOST: f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}",
63  CONF_LOCATION: user_input[CONF_LOCATION],
64  }
65  )
66 
67  if not (errors := await self._async_try_connect_async_try_connect()):
68  return self.async_create_entryasync_create_entryasync_create_entry(
69  title=user_input[CONF_NAME], data=self._config_config
70  )
71 
72  if CONF_API_KEY in errors:
73  return await self.async_step_api_keyasync_step_api_key()
74 
75  user_input = user_input or {}
76  return self.async_show_formasync_show_formasync_show_form(
77  step_id="user",
78  data_schema=vol.Schema(
79  {
80  vol.Required(CONF_HOST, default=user_input.get(CONF_HOST, "")): str,
81  vol.Required(
82  CONF_PORT, default=user_input.get(CONF_PORT, 80)
83  ): vol.Coerce(int),
84  vol.Required(
85  CONF_NAME, default=user_input.get(CONF_NAME, DEFAULT_NAME)
86  ): str,
87  vol.Required(
88  CONF_LOCATION,
89  default=user_input.get(CONF_LOCATION, DEFAULT_LOCATION),
90  ): str,
91  vol.Required(
92  CONF_SSL,
93  default=user_input.get(CONF_SSL, DEFAULT_SSL),
94  ): bool,
95  vol.Required(
96  CONF_VERIFY_SSL,
97  default=user_input.get(CONF_VERIFY_SSL, DEFAULT_VERIFY_SSL),
98  ): bool,
99  }
100  ),
101  errors=errors,
102  )
103 
105  self, user_input: dict[str, Any] | None = None
106  ) -> ConfigFlowResult:
107  """Handle step to setup API key."""
108  errors = {}
109  if user_input is not None:
110  self._config_config[CONF_API_KEY] = user_input[CONF_API_KEY]
111  if not (errors := await self._async_try_connect_async_try_connect()):
112  return self.async_create_entryasync_create_entryasync_create_entry(
113  title=self._config_config[CONF_NAME],
114  data=self._config_config,
115  )
116 
117  return self.async_show_formasync_show_formasync_show_form(
118  step_id="api_key",
119  data_schema=vol.Schema({vol.Required(CONF_API_KEY): str}),
120  errors=errors,
121  )
122 
123  async def async_step_reauth(
124  self, entry_data: Mapping[str, Any]
125  ) -> ConfigFlowResult:
126  """Perform reauth upon an API authentication error."""
127  self._config_config = dict(entry_data)
128  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
129 
131  self,
132  user_input: dict[str, Any] | None = None,
133  ) -> ConfigFlowResult:
134  """Perform reauth confirm upon an API authentication error."""
135  errors = {}
136  if user_input is not None:
137  self._config_config = {**self._config_config, CONF_API_KEY: user_input[CONF_API_KEY]}
138  if not (errors := await self._async_try_connect_async_try_connect()):
139  return self.async_update_reload_and_abortasync_update_reload_and_abort(
140  self._get_reauth_entry_get_reauth_entry(), data=self._config_config
141  )
142 
143  return self.async_show_formasync_show_formasync_show_form(
144  step_id="reauth_confirm",
145  description_placeholders={
146  CONF_HOST: self._config_config[CONF_HOST],
147  CONF_LOCATION: self._config_config[CONF_LOCATION],
148  },
149  data_schema=vol.Schema({vol.Required(CONF_API_KEY): str}),
150  errors=errors,
151  )
152 
153  async def _async_try_connect(self) -> dict[str, str]:
154  session = async_get_clientsession(self.hass, self._config_config[CONF_VERIFY_SSL])
155  pi_hole = Hole(
156  self._config_config[CONF_HOST],
157  session,
158  location=self._config_config[CONF_LOCATION],
159  tls=self._config_config[CONF_SSL],
160  api_token=self._config_config.get(CONF_API_KEY),
161  )
162  try:
163  await pi_hole.get_data()
164  except HoleError as ex:
165  _LOGGER.debug("Connection failed: %s", ex)
166  return {"base": "cannot_connect"}
167  if not isinstance(pi_hole.data, dict):
168  return {CONF_API_KEY: "invalid_auth"}
169  return {}
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:133
ConfigFlowResult async_step_api_key(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:106
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:47
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:125
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)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
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)