Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The habitica integration."""
2 
3 from http import HTTPStatus
4 
5 from aiohttp import ClientResponseError
6 from habitipy.aio import HabitipyAsync
7 
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import (
10  APPLICATION_NAME,
11  CONF_API_KEY,
12  CONF_NAME,
13  CONF_URL,
14  CONF_VERIFY_SSL,
15  Platform,
16  __version__,
17 )
18 from homeassistant.core import HomeAssistant
19 from homeassistant.exceptions import ConfigEntryNotReady
20 from homeassistant.helpers import config_validation as cv
21 from homeassistant.helpers.aiohttp_client import async_get_clientsession
22 from homeassistant.helpers.typing import ConfigType
23 
24 from .const import CONF_API_USER, DEVELOPER_ID, DOMAIN
25 from .coordinator import HabiticaDataUpdateCoordinator
26 from .services import async_setup_services
27 from .types import HabiticaConfigEntry
28 
29 CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
30 
31 
32 PLATFORMS = [
33  Platform.BINARY_SENSOR,
34  Platform.BUTTON,
35  Platform.CALENDAR,
36  Platform.SENSOR,
37  Platform.SWITCH,
38  Platform.TODO,
39 ]
40 
41 
42 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
43  """Set up the Habitica service."""
44 
46  return True
47 
48 
50  hass: HomeAssistant, config_entry: HabiticaConfigEntry
51 ) -> bool:
52  """Set up habitica from a config entry."""
53 
54  class HAHabitipyAsync(HabitipyAsync):
55  """Closure API class to hold session."""
56 
57  def __call__(self, **kwargs):
58  return super().__call__(websession, **kwargs)
59 
60  def _make_headers(self) -> dict[str, str]:
61  headers = super()._make_headers()
62  headers.update(
63  {"x-client": f"{DEVELOPER_ID} - {APPLICATION_NAME} {__version__}"}
64  )
65  return headers
66 
67  websession = async_get_clientsession(
68  hass, verify_ssl=config_entry.data.get(CONF_VERIFY_SSL, True)
69  )
70 
71  api = await hass.async_add_executor_job(
72  HAHabitipyAsync,
73  {
74  "url": config_entry.data[CONF_URL],
75  "login": config_entry.data[CONF_API_USER],
76  "password": config_entry.data[CONF_API_KEY],
77  },
78  )
79  try:
80  user = await api.user.get(userFields="profile")
81  except ClientResponseError as e:
82  if e.status == HTTPStatus.TOO_MANY_REQUESTS:
83  raise ConfigEntryNotReady(
84  translation_domain=DOMAIN,
85  translation_key="setup_rate_limit_exception",
86  ) from e
87  raise ConfigEntryNotReady(e) from e
88 
89  if not config_entry.data.get(CONF_NAME):
90  name = user["profile"]["name"]
91  hass.config_entries.async_update_entry(
92  config_entry,
93  data={**config_entry.data, CONF_NAME: name},
94  )
95 
96  coordinator = HabiticaDataUpdateCoordinator(hass, api)
97  await coordinator.async_config_entry_first_refresh()
98 
99  config_entry.runtime_data = coordinator
100  await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
101 
102  return True
103 
104 
105 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
106  """Unload a config entry."""
107  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
bool async_setup_entry(HomeAssistant hass, HabiticaConfigEntry config_entry)
Definition: __init__.py:51
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:105
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:42
None async_setup_services(HomeAssistant hass)
Definition: __init__.py:72
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)