Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Local Calendar integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from pathlib import Path
7 
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import Platform
10 from homeassistant.core import HomeAssistant
11 from homeassistant.exceptions import ConfigEntryNotReady
12 from homeassistant.util import slugify
13 
14 from .const import CONF_CALENDAR_NAME, CONF_STORAGE_KEY, DOMAIN, STORAGE_PATH
15 from .store import LocalCalendarStore
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
20 PLATFORMS: list[Platform] = [Platform.CALENDAR]
21 
22 
23 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
24  """Set up Local Calendar from a config entry."""
25  hass.data.setdefault(DOMAIN, {})
26 
27  if CONF_STORAGE_KEY not in entry.data:
28  hass.config_entries.async_update_entry(
29  entry,
30  data={
31  **entry.data,
32  CONF_STORAGE_KEY: slugify(entry.data[CONF_CALENDAR_NAME]),
33  },
34  )
35 
36  path = Path(hass.config.path(STORAGE_PATH.format(key=entry.data[CONF_STORAGE_KEY])))
37  store = LocalCalendarStore(hass, path)
38  try:
39  await store.async_load()
40  except OSError as err:
41  raise ConfigEntryNotReady("Failed to load file {path}: {err}") from err
42 
43  hass.data[DOMAIN][entry.entry_id] = store
44 
45  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
46 
47  return True
48 
49 
50 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
51  """Unload a config entry."""
52  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
53  hass.data[DOMAIN].pop(entry.entry_id)
54 
55  return unload_ok
56 
57 
58 async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
59  """Handle removal of an entry."""
60  key = slugify(entry.data[CONF_CALENDAR_NAME])
61  path = Path(hass.config.path(STORAGE_PATH.format(key=key)))
62 
63  def unlink(path: Path) -> None:
64  path.unlink(missing_ok=True)
65 
66  await hass.async_add_executor_job(unlink, path)
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:50
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:23
None async_remove_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:58
str slugify(str|None text, *str separator="_")
Definition: __init__.py:41