Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for pyLoad 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 aiohttp import CookieJar
10 from pyloadapi.api import PyLoadAPI
11 from pyloadapi.exceptions import CannotConnect, InvalidAuth, ParserError
12 import voluptuous as vol
13 
14 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
15 from homeassistant.const import (
16  CONF_HOST,
17  CONF_NAME,
18  CONF_PASSWORD,
19  CONF_PORT,
20  CONF_SSL,
21  CONF_USERNAME,
22  CONF_VERIFY_SSL,
23 )
24 from homeassistant.core import HomeAssistant
25 from homeassistant.helpers.aiohttp_client import async_create_clientsession
28  TextSelector,
29  TextSelectorConfig,
30  TextSelectorType,
31 )
32 
33 from .const import DEFAULT_HOST, DEFAULT_NAME, DEFAULT_PORT, DOMAIN
34 
35 _LOGGER = logging.getLogger(__name__)
36 
37 STEP_USER_DATA_SCHEMA = vol.Schema(
38  {
39  vol.Required(CONF_HOST): str,
40  vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
41  vol.Required(CONF_SSL, default=False): cv.boolean,
42  vol.Required(CONF_VERIFY_SSL, default=True): bool,
43  vol.Required(CONF_USERNAME): TextSelector(
45  type=TextSelectorType.TEXT,
46  autocomplete="username",
47  ),
48  ),
49  vol.Required(CONF_PASSWORD): TextSelector(
51  type=TextSelectorType.PASSWORD,
52  autocomplete="current-password",
53  ),
54  ),
55  }
56 )
57 
58 REAUTH_SCHEMA = vol.Schema(
59  {
60  vol.Required(CONF_USERNAME): TextSelector(
62  type=TextSelectorType.TEXT,
63  autocomplete="username",
64  ),
65  ),
66  vol.Required(CONF_PASSWORD): TextSelector(
68  type=TextSelectorType.PASSWORD,
69  autocomplete="current-password",
70  ),
71  ),
72  }
73 )
74 
75 
76 async def validate_input(hass: HomeAssistant, user_input: dict[str, Any]) -> None:
77  """Validate the user input and try to connect to PyLoad."""
78 
80  hass,
81  user_input[CONF_VERIFY_SSL],
82  cookie_jar=CookieJar(unsafe=True),
83  )
84 
85  url = (
86  f"{"https" if user_input[CONF_SSL] else "http"}://"
87  f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}/"
88  )
89  pyload = PyLoadAPI(
90  session,
91  api_url=url,
92  username=user_input[CONF_USERNAME],
93  password=user_input[CONF_PASSWORD],
94  )
95 
96  await pyload.login()
97 
98 
99 class PyLoadConfigFlow(ConfigFlow, domain=DOMAIN):
100  """Handle a config flow for pyLoad."""
101 
102  VERSION = 1
103 
104  async def async_step_user(
105  self, user_input: dict[str, Any] | None = None
106  ) -> ConfigFlowResult:
107  """Handle the initial step."""
108  errors: dict[str, str] = {}
109  if user_input is not None:
110  self._async_abort_entries_match_async_abort_entries_match(
111  {CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]}
112  )
113  try:
114  await validate_input(self.hass, user_input)
115  except (CannotConnect, ParserError):
116  errors["base"] = "cannot_connect"
117  except InvalidAuth:
118  errors["base"] = "invalid_auth"
119  except Exception:
120  _LOGGER.exception("Unexpected exception")
121  errors["base"] = "unknown"
122  else:
123  title = user_input.pop(CONF_NAME, DEFAULT_NAME)
124  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
125 
126  return self.async_show_formasync_show_formasync_show_form(
127  step_id="user",
128  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
129  STEP_USER_DATA_SCHEMA, user_input
130  ),
131  errors=errors,
132  )
133 
134  async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
135  """Import config from yaml."""
136 
137  config = {
138  CONF_NAME: import_data.get(CONF_NAME),
139  CONF_HOST: import_data.get(CONF_HOST, DEFAULT_HOST),
140  CONF_PASSWORD: import_data.get(CONF_PASSWORD, ""),
141  CONF_PORT: import_data.get(CONF_PORT, DEFAULT_PORT),
142  CONF_SSL: import_data.get(CONF_SSL, False),
143  CONF_USERNAME: import_data.get(CONF_USERNAME, ""),
144  CONF_VERIFY_SSL: False,
145  }
146 
147  result = await self.async_step_userasync_step_userasync_step_user(config)
148 
149  if errors := result.get("errors"):
150  return self.async_abortasync_abortasync_abort(reason=errors["base"])
151  return result
152 
153  async def async_step_reauth(
154  self, entry_data: Mapping[str, Any]
155  ) -> ConfigFlowResult:
156  """Perform reauth upon an API authentication error."""
157  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
158 
160  self, user_input: dict[str, Any] | None = None
161  ) -> ConfigFlowResult:
162  """Dialog that informs the user that reauth is required."""
163  errors = {}
164  reauth_entry = self._get_reauth_entry_get_reauth_entry()
165 
166  if user_input is not None:
167  new_input = reauth_entry.data | user_input
168  try:
169  await validate_input(self.hass, new_input)
170  except (CannotConnect, ParserError):
171  errors["base"] = "cannot_connect"
172  except InvalidAuth:
173  errors["base"] = "invalid_auth"
174  except Exception:
175  _LOGGER.exception("Unexpected exception")
176  errors["base"] = "unknown"
177  else:
178  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=new_input)
179 
180  return self.async_show_formasync_show_formasync_show_form(
181  step_id="reauth_confirm",
182  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
183  REAUTH_SCHEMA,
184  {
185  CONF_USERNAME: user_input[CONF_USERNAME]
186  if user_input is not None
187  else reauth_entry.data[CONF_USERNAME]
188  },
189  ),
190  description_placeholders={CONF_NAME: reauth_entry.data[CONF_USERNAME]},
191  errors=errors,
192  )
193 
195  self, user_input: dict[str, Any] | None = None
196  ) -> ConfigFlowResult:
197  """Handle the reconfiguration flow."""
198  errors = {}
199  reconfig_entry = self._get_reconfigure_entry_get_reconfigure_entry()
200 
201  if user_input is not None:
202  try:
203  await validate_input(self.hass, user_input)
204  except (CannotConnect, ParserError):
205  errors["base"] = "cannot_connect"
206  except InvalidAuth:
207  errors["base"] = "invalid_auth"
208  except Exception:
209  _LOGGER.exception("Unexpected exception")
210  errors["base"] = "unknown"
211  else:
212  return self.async_update_reload_and_abortasync_update_reload_and_abort(
213  reconfig_entry,
214  data=user_input,
215  reload_even_if_entry_is_unchanged=False,
216  )
217 
218  return self.async_show_formasync_show_formasync_show_form(
219  step_id="reconfigure",
220  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
221  STEP_USER_DATA_SCHEMA,
222  user_input or reconfig_entry.data,
223  ),
224  description_placeholders={CONF_NAME: reconfig_entry.data[CONF_USERNAME]},
225  errors=errors,
226  )
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:161
ConfigFlowResult async_step_import(self, dict[str, Any] import_data)
Definition: config_flow.py:134
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:106
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:196
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:155
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_step_user(self, dict[str, Any]|None user_input=None)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
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)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_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)
None validate_input(HomeAssistant hass, dict[str, Any] user_input)
Definition: config_flow.py:76
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51