Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Configuration flow for CalDav."""
2 
3 from collections.abc import Mapping
4 import logging
5 from typing import Any
6 
7 import caldav
8 from caldav.lib.error import AuthorizationError, DAVError
9 import requests
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME, CONF_VERIFY_SSL
14 from homeassistant.helpers import config_validation as cv
15 
16 from .const import DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
21 STEP_USER_DATA_SCHEMA = vol.Schema(
22  {
23  vol.Required(CONF_URL): str,
24  vol.Required(CONF_USERNAME): cv.string,
25  vol.Optional(CONF_PASSWORD, default=""): cv.string,
26  vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
27  }
28 )
29 
30 
31 class CalDavConfigFlow(ConfigFlow, domain=DOMAIN):
32  """Handle a config flow for caldav."""
33 
34  VERSION = 1
35 
36  async def async_step_user(
37  self, user_input: dict[str, Any] | None = None
38  ) -> ConfigFlowResult:
39  """Handle the initial step."""
40  errors: dict[str, str] = {}
41  if user_input is not None:
42  self._async_abort_entries_match_async_abort_entries_match(
43  {
44  CONF_URL: user_input[CONF_URL],
45  CONF_USERNAME: user_input[CONF_USERNAME],
46  }
47  )
48  if error := await self._test_connection_test_connection(user_input):
49  errors["base"] = error
50  else:
51  return self.async_create_entryasync_create_entryasync_create_entry(
52  title=user_input[CONF_USERNAME], data=user_input
53  )
54 
55  return self.async_show_formasync_show_formasync_show_form(
56  step_id="user",
57  data_schema=STEP_USER_DATA_SCHEMA,
58  errors=errors,
59  )
60 
61  async def _test_connection(self, user_input: dict[str, Any]) -> str | None:
62  """Test the connection to the CalDAV server and return an error if any."""
63  client = caldav.DAVClient(
64  user_input[CONF_URL],
65  username=user_input[CONF_USERNAME],
66  password=user_input[CONF_PASSWORD],
67  ssl_verify_cert=user_input[CONF_VERIFY_SSL],
68  )
69  try:
70  await self.hass.async_add_executor_job(client.principal)
71  except AuthorizationError as err:
72  _LOGGER.warning("Authorization Error connecting to CalDAV server: %s", err)
73  if err.reason == "Unauthorized":
74  return "invalid_auth"
75  # AuthorizationError can be raised if the url is incorrect or
76  # on some other unexpected server response.
77  return "cannot_connect"
78  except requests.ConnectionError as err:
79  _LOGGER.warning("Connection Error connecting to CalDAV server: %s", err)
80  return "cannot_connect"
81  except DAVError as err:
82  _LOGGER.warning("CalDAV client error: %s", err)
83  return "cannot_connect"
84  except Exception:
85  _LOGGER.exception("Unexpected exception")
86  return "unknown"
87  return None
88 
89  async def async_step_reauth(
90  self, entry_data: Mapping[str, Any]
91  ) -> ConfigFlowResult:
92  """Perform reauth upon an API authentication error."""
93  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
94 
96  self, user_input: dict[str, str] | None = None
97  ) -> ConfigFlowResult:
98  """Confirm reauth dialog."""
99  errors = {}
100  reauth_entry = self._get_reauth_entry_get_reauth_entry()
101  if user_input is not None:
102  user_input = {**reauth_entry.data, **user_input}
103 
104  if error := await self._test_connection_test_connection(user_input):
105  errors["base"] = error
106  else:
107  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=user_input)
108 
109  return self.async_show_formasync_show_formasync_show_form(
110  description_placeholders={
111  CONF_USERNAME: reauth_entry.data[CONF_USERNAME],
112  },
113  step_id="reauth_confirm",
114  data_schema=vol.Schema(
115  {
116  vol.Required(CONF_PASSWORD): str,
117  }
118  ),
119  errors=errors,
120  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:38
ConfigFlowResult async_step_reauth_confirm(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:97
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:91
str|None _test_connection(self, dict[str, Any] user_input)
Definition: config_flow.py:61
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)