Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for Notion."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 from typing import Any
7 from uuid import UUID
8 
9 from aionotion.errors import InvalidCredentialsError, NotionError
10 from aionotion.listener.models import ListenerKind
11 
12 from homeassistant.config_entries import ConfigEntry
13 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
16 from homeassistant.helpers import entity_registry as er
17 
18 from .const import (
19  CONF_REFRESH_TOKEN,
20  CONF_USER_UUID,
21  DOMAIN,
22  LOGGER,
23  SENSOR_BATTERY,
24  SENSOR_DOOR,
25  SENSOR_GARAGE_DOOR,
26  SENSOR_LEAK,
27  SENSOR_MISSING,
28  SENSOR_SAFE,
29  SENSOR_SLIDING,
30  SENSOR_SMOKE_CO,
31  SENSOR_TEMPERATURE,
32  SENSOR_WINDOW_HINGED,
33 )
34 from .coordinator import NotionDataUpdateCoordinator
35 from .util import async_get_client_with_credentials, async_get_client_with_refresh_token
36 
37 PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]
38 
39 ATTR_SYSTEM_MODE = "system_mode"
40 ATTR_SYSTEM_NAME = "system_name"
41 
42 DEFAULT_SCAN_INTERVAL = timedelta(minutes=1)
43 
44 
45 # Define a map of old-API task types to new-API listener types:
46 TASK_TYPE_TO_LISTENER_MAP: dict[str, ListenerKind] = {
47  SENSOR_BATTERY: ListenerKind.BATTERY,
48  SENSOR_DOOR: ListenerKind.DOOR,
49  SENSOR_GARAGE_DOOR: ListenerKind.GARAGE_DOOR,
50  SENSOR_LEAK: ListenerKind.LEAK_STATUS,
51  SENSOR_MISSING: ListenerKind.CONNECTED,
52  SENSOR_SAFE: ListenerKind.SAFE,
53  SENSOR_SLIDING: ListenerKind.SLIDING_DOOR_OR_WINDOW,
54  SENSOR_SMOKE_CO: ListenerKind.SMOKE,
55  SENSOR_TEMPERATURE: ListenerKind.TEMPERATURE,
56  SENSOR_WINDOW_HINGED: ListenerKind.HINGED_WINDOW,
57 }
58 
59 
60 @callback
61 def is_uuid(value: str) -> bool:
62  """Return whether a string is a valid UUID."""
63  try:
64  UUID(value)
65  except ValueError:
66  return False
67  return True
68 
69 
70 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
71  """Set up Notion as a config entry."""
72  entry_updates: dict[str, Any] = {"data": {**entry.data}}
73 
74  if not entry.unique_id:
75  entry_updates["unique_id"] = entry.data[CONF_USERNAME]
76 
77  try:
78  if password := entry_updates["data"].pop(CONF_PASSWORD, None):
79  # If a password exists in the config entry data, use it to get a new client
80  # (and pop it from the new entry data):
81  client = await async_get_client_with_credentials(
82  hass, entry.data[CONF_USERNAME], password
83  )
84  else:
85  # If a password doesn't exist in the config entry data, we can safely assume
86  # that a refresh token and user UUID do, so we use them to get the client:
88  hass,
89  entry.data[CONF_USER_UUID],
90  entry.data[CONF_REFRESH_TOKEN],
91  )
92  except InvalidCredentialsError as err:
93  raise ConfigEntryAuthFailed("Invalid credentials") from err
94  except NotionError as err:
95  raise ConfigEntryNotReady("Config entry failed to load") from err
96 
97  # Update the Notion user UUID and refresh token if they've changed:
98  for key, value in (
99  (CONF_REFRESH_TOKEN, client.refresh_token),
100  (CONF_USER_UUID, client.user_uuid),
101  ):
102  if entry.data.get(key) == value:
103  continue
104  entry_updates["data"][key] = value
105 
106  hass.config_entries.async_update_entry(entry, **entry_updates)
107 
108  @callback
109  def async_save_refresh_token(refresh_token: str) -> None:
110  """Save a refresh token to the config entry data."""
111  LOGGER.debug("Saving new refresh token to HASS storage")
112  hass.config_entries.async_update_entry(
113  entry, data={**entry.data, CONF_REFRESH_TOKEN: refresh_token}
114  )
115 
116  # Create a callback to save the refresh token when it changes:
117  entry.async_on_unload(client.add_refresh_token_callback(async_save_refresh_token))
118 
119  coordinator = NotionDataUpdateCoordinator(hass, entry=entry, client=client)
120 
121  await coordinator.async_config_entry_first_refresh()
122  hass.data.setdefault(DOMAIN, {})
123  hass.data[DOMAIN][entry.entry_id] = coordinator
124 
125  @callback
126  def async_migrate_entity_entry(entry: er.RegistryEntry) -> dict[str, Any] | None:
127  """Migrate Notion entity entries.
128 
129  This migration focuses on unique IDs, which have changed because of a Notion API
130  change:
131 
132  Old Format: <sensor_id>_<task_type>
133  New Format: <listener_uuid>
134  """
135  if is_uuid(entry.unique_id):
136  # If the unique ID is already a UUID, we don't need to migrate it:
137  return None
138 
139  sensor_id_str, task_type = entry.unique_id.split("_", 1)
140  sensor = next(
141  sensor
142  for sensor in coordinator.data.sensors.values()
143  if sensor.id == int(sensor_id_str)
144  )
145  listener = next(
146  listener
147  for listener in coordinator.data.listeners.values()
148  if listener.sensor_id == sensor.uuid
149  and listener.definition_id == TASK_TYPE_TO_LISTENER_MAP[task_type].value
150  )
151 
152  return {"new_unique_id": listener.id}
153 
154  await er.async_migrate_entries(hass, entry.entry_id, async_migrate_entity_entry)
155  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
156 
157  return True
158 
159 
160 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
161  """Unload a Notion config entry."""
162  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
163  if unload_ok:
164  hass.data[DOMAIN].pop(entry.entry_id)
165 
166  return unload_ok
Client async_get_client_with_credentials(HomeAssistant hass, str email, str password)
Definition: util.py:16
Client async_get_client_with_refresh_token(HomeAssistant hass, str user_uuid, str refresh_token)
Definition: util.py:25
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:70
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:160
dict[str, Any]|None async_migrate_entity_entry(er.RegistryEntry entity_entry)
Definition: __init__.py:81