Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Twitch component."""
2 
3 from __future__ import annotations
4 
5 from typing import cast
6 
7 from aiohttp.client_exceptions import ClientError, ClientResponseError
8 from twitchAPI.twitch import Twitch
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
15  LocalOAuth2Implementation,
16  OAuth2Session,
17  async_get_config_entry_implementation,
18 )
19 
20 from .const import DOMAIN, OAUTH_SCOPES, PLATFORMS
21 from .coordinator import TwitchCoordinator
22 
23 
24 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
25  """Set up Twitch from a config entry."""
26  implementation = cast(
27  LocalOAuth2Implementation,
28  await async_get_config_entry_implementation(hass, entry),
29  )
30  session = OAuth2Session(hass, entry, implementation)
31  try:
32  await session.async_ensure_token_valid()
33  except ClientResponseError as err:
34  if 400 <= err.status < 500:
36  "OAuth session is not valid, reauth required"
37  ) from err
38  raise ConfigEntryNotReady from err
39  except ClientError as err:
40  raise ConfigEntryNotReady from err
41 
42  access_token = entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN]
43  client = Twitch(
44  app_id=implementation.client_id,
45  authenticate_app=False,
46  )
47  client.auto_refresh_auth = False
48  await client.set_user_authentication(access_token, scope=OAUTH_SCOPES)
49 
50  coordinator = TwitchCoordinator(hass, client, session)
51 
52  await coordinator.async_config_entry_first_refresh()
53 
54  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
55 
56  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
57 
58  return True
59 
60 
61 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
62  """Unload Twitch config entry."""
63 
64  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:24
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:61
AbstractOAuth2Implementation async_get_config_entry_implementation(HomeAssistant hass, config_entries.ConfigEntry config_entry)