Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The file component."""
2 
3 from copy import deepcopy
4 from typing import Any
5 
6 from homeassistant.config_entries import ConfigEntry
7 from homeassistant.const import CONF_FILE_PATH, CONF_NAME, CONF_PLATFORM, Platform
8 from homeassistant.core import HomeAssistant
9 from homeassistant.exceptions import ConfigEntryNotReady
10 
11 from .const import DOMAIN
12 
13 PLATFORMS = [Platform.NOTIFY, Platform.SENSOR]
14 
15 
16 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
17  """Set up a file component entry."""
18  config = {**entry.data, **entry.options}
19  filepath: str = config[CONF_FILE_PATH]
20  if filepath and not await hass.async_add_executor_job(
21  hass.config.is_allowed_path, filepath
22  ):
23  raise ConfigEntryNotReady(
24  translation_domain=DOMAIN,
25  translation_key="dir_not_allowed",
26  translation_placeholders={"filename": filepath},
27  )
28 
29  await hass.config_entries.async_forward_entry_setups(
30  entry, [Platform(entry.data[CONF_PLATFORM])]
31  )
32  entry.async_on_unload(entry.add_update_listener(update_listener))
33 
34  return True
35 
36 
37 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
38  """Unload a config entry."""
39  return await hass.config_entries.async_unload_platforms(
40  entry, [entry.data[CONF_PLATFORM]]
41  )
42 
43 
44 async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
45  """Handle options update."""
46  await hass.config_entries.async_reload(entry.entry_id)
47 
48 
49 async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
50  """Migrate config entry."""
51  if config_entry.version > 2:
52  # Downgraded from future
53  return False
54 
55  if config_entry.version < 2:
56  # Move optional fields from data to options in config entry
57  data: dict[str, Any] = deepcopy(dict(config_entry.data))
58  options = {}
59  for key, value in config_entry.data.items():
60  if key not in (CONF_FILE_PATH, CONF_PLATFORM, CONF_NAME):
61  data.pop(key)
62  options[key] = value
63 
64  hass.config_entries.async_update_entry(
65  config_entry, version=2, data=data, options=options
66  )
67  return True
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:16
bool async_migrate_entry(HomeAssistant hass, ConfigEntry config_entry)
Definition: __init__.py:49
None update_listener(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:44
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:37