Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the Jellyfin integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult, OptionsFlow
12 from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME
13 from homeassistant.core import callback
14 from homeassistant.util.uuid import random_uuid_hex
15 
16 from . import JellyfinConfigEntry
17 from .client_wrapper import CannotConnect, InvalidAuth, create_client, validate_input
18 from .const import CONF_CLIENT_DEVICE_ID, DOMAIN, SUPPORTED_AUDIO_CODECS
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 STEP_USER_DATA_SCHEMA = vol.Schema(
23  {
24  vol.Required(CONF_URL): str,
25  vol.Required(CONF_USERNAME): str,
26  vol.Optional(CONF_PASSWORD, default=""): str,
27  }
28 )
29 
30 REAUTH_DATA_SCHEMA = vol.Schema(
31  {
32  vol.Optional(CONF_PASSWORD, default=""): str,
33  }
34 )
35 
36 
37 OPTIONAL_DATA_SCHEMA = vol.Schema(
38  {vol.Optional("audio_codec"): vol.In(SUPPORTED_AUDIO_CODECS)}
39 )
40 
41 
43  """Generate a random UUID4 string to identify ourselves."""
44  return random_uuid_hex()
45 
46 
47 class JellyfinConfigFlow(ConfigFlow, domain=DOMAIN):
48  """Handle a config flow for Jellyfin."""
49 
50  VERSION = 1
51 
52  def __init__(self) -> None:
53  """Initialize the Jellyfin config flow."""
54  self.client_device_idclient_device_id: str | None = None
55 
56  async def async_step_user(
57  self, user_input: dict[str, Any] | None = None
58  ) -> ConfigFlowResult:
59  """Handle a user defined configuration."""
60  errors: dict[str, str] = {}
61 
62  if user_input is not None:
63  if self.client_device_idclient_device_id is None:
65 
66  client = create_client(device_id=self.client_device_idclient_device_id)
67  try:
68  user_id, connect_result = await validate_input(
69  self.hass, user_input, client
70  )
71  except CannotConnect:
72  errors["base"] = "cannot_connect"
73  except InvalidAuth:
74  errors["base"] = "invalid_auth"
75  except Exception:
76  errors["base"] = "unknown"
77  _LOGGER.exception("Unexpected exception")
78  else:
79  entry_title = user_input[CONF_URL]
80 
81  server_info: dict[str, Any] = connect_result["Servers"][0]
82 
83  if server_name := server_info.get("Name"):
84  entry_title = server_name
85 
86  await self.async_set_unique_idasync_set_unique_id(user_id)
87  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
88 
89  return self.async_create_entryasync_create_entryasync_create_entry(
90  title=entry_title,
91  data={CONF_CLIENT_DEVICE_ID: self.client_device_idclient_device_id, **user_input},
92  )
93 
94  return self.async_show_formasync_show_formasync_show_form(
95  step_id="user",
96  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
97  STEP_USER_DATA_SCHEMA, user_input
98  ),
99  errors=errors,
100  )
101 
102  async def async_step_reauth(
103  self, entry_data: Mapping[str, Any]
104  ) -> ConfigFlowResult:
105  """Perform reauth upon an API authentication error."""
106  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
107 
109  self, user_input: dict[str, Any] | None = None
110  ) -> ConfigFlowResult:
111  """Dialog that informs the user that reauth is required."""
112  errors: dict[str, str] = {}
113 
114  if user_input is not None:
115  reauth_entry = self._get_reauth_entry_get_reauth_entry()
116  new_input = reauth_entry.data | user_input
117 
118  if self.client_device_idclient_device_id is None:
119  self.client_device_idclient_device_id = _generate_client_device_id()
120 
121  client = create_client(device_id=self.client_device_idclient_device_id)
122  try:
123  await validate_input(self.hass, new_input, client)
124  except CannotConnect:
125  errors["base"] = "cannot_connect"
126  except InvalidAuth:
127  errors["base"] = "invalid_auth"
128  except Exception:
129  errors["base"] = "unknown"
130  _LOGGER.exception("Unexpected exception")
131  else:
132  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=new_input)
133 
134  return self.async_show_formasync_show_formasync_show_form(
135  step_id="reauth_confirm", data_schema=REAUTH_DATA_SCHEMA, errors=errors
136  )
137 
138  @staticmethod
139  @callback
141  config_entry: JellyfinConfigEntry,
142  ) -> OptionsFlowHandler:
143  """Create the options flow."""
144  return OptionsFlowHandler()
145 
146 
148  """Handle an option flow for jellyfin."""
149 
150  async def async_step_init(
151  self, user_input: dict[str, Any] | None = None
152  ) -> ConfigFlowResult:
153  """Manage the options."""
154  if user_input is not None:
155  return self.async_create_entryasync_create_entry(title="", data=user_input)
156 
157  return self.async_show_formasync_show_form(
158  step_id="init",
159  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
160  OPTIONAL_DATA_SCHEMA, self.config_entryconfig_entryconfig_entry.options
161  ),
162  )
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:110
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:58
OptionsFlowHandler async_get_options_flow(JellyfinConfigEntry config_entry)
Definition: config_flow.py:142
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:104
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:152
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_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)
None config_entry(self, ConfigEntry value)
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)
JellyfinClient create_client(str device_id, str|None device_name=None)
VersionInfo validate_input(HomeAssistant hass, dict user_input)
Definition: config_flow.py:116
str random_uuid_hex()
Definition: uuid.py:6