Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Spotify."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from spotifyaio import SpotifyClient
10 
11 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult
12 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_NAME, CONF_TOKEN
13 from homeassistant.helpers import config_entry_oauth2_flow
14 from homeassistant.helpers.aiohttp_client import async_get_clientsession
15 
16 from .const import DOMAIN, SPOTIFY_SCOPES
17 
18 
20  config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
21 ):
22  """Config flow to handle Spotify OAuth2 authentication."""
23 
24  DOMAIN = DOMAIN
25  VERSION = 1
26 
27  @property
28  def logger(self) -> logging.Logger:
29  """Return logger."""
30  return logging.getLogger(__name__)
31 
32  @property
33  def extra_authorize_data(self) -> dict[str, Any]:
34  """Extra data that needs to be appended to the authorize url."""
35  return {"scope": ",".join(SPOTIFY_SCOPES)}
36 
37  async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
38  """Create an entry for Spotify."""
39  spotify = SpotifyClient(async_get_clientsession(self.hass))
40  spotify.authenticate(data[CONF_TOKEN][CONF_ACCESS_TOKEN])
41 
42  try:
43  current_user = await spotify.get_current_user()
44  except Exception: # noqa: BLE001
45  return self.async_abort(reason="connection_error")
46 
47  name = current_user.display_name
48 
49  await self.async_set_unique_id(current_user.user_id)
50 
51  if self.sourcesource == SOURCE_REAUTH:
52  self._abort_if_unique_id_mismatch(reason="reauth_account_mismatch")
53  return self.async_update_reload_and_abort(
54  self._get_reauth_entry(), title=name, data=data
55  )
56  return self.async_create_entry(title=name, data={**data, CONF_NAME: name})
57 
58  async def async_step_reauth(
59  self, entry_data: Mapping[str, Any]
60  ) -> ConfigFlowResult:
61  """Perform reauth upon migration of old entries."""
62  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
63 
65  self, user_input: dict[str, Any] | None = None
66  ) -> ConfigFlowResult:
67  """Confirm reauth dialog."""
68  reauth_entry = self._get_reauth_entry()
69  if user_input is None:
70  return self.async_show_form(
71  step_id="reauth_confirm",
72  description_placeholders={"account": reauth_entry.data["id"]},
73  errors={},
74  )
75 
76  return await self.async_step_pick_implementation(
77  user_input={"implementation": reauth_entry.data["auth_implementation"]}
78  )
ConfigFlowResult async_oauth_create_entry(self, dict[str, Any] data)
Definition: config_flow.py:37
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:66
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:60
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)