Home Assistant Unofficial Reference 2024.12.1
nasweb_data.py
Go to the documentation of this file.
1 """Dataclass storing integration data in hass.data[DOMAIN]."""
2 
3 from dataclasses import dataclass, field
4 import logging
5 
6 from aiohttp.hdrs import METH_POST
7 
9  async_generate_id,
10  async_register as webhook_register,
11  async_unregister as webhook_unregister,
12 )
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.network import get_url
15 
16 from .const import DOMAIN, WEBHOOK_URL
17 from .coordinator import NotificationCoordinator
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 
22 @dataclass
23 class NASwebData:
24  """Class storing integration data."""
25 
26  notify_coordinator: NotificationCoordinator = field(
27  default_factory=NotificationCoordinator
28  )
29  webhook_id = ""
30 
31  def is_initialized(self) -> bool:
32  """Return True if instance was initialized and is ready for use."""
33  return bool(self.webhook_idwebhook_idwebhook_id)
34 
35  def can_be_deinitialized(self) -> bool:
36  """Return whether this instance can be deinitialized."""
37  return not self.notify_coordinator.has_coordinators()
38 
39  def initialize(self, hass: HomeAssistant) -> None:
40  """Initialize NASwebData instance."""
41  if self.is_initializedis_initialized():
42  return
43  new_webhook_id = async_generate_id()
44  webhook_register(
45  hass,
46  DOMAIN,
47  "NASweb",
48  new_webhook_id,
49  self.notify_coordinator.handle_webhook_request,
50  allowed_methods=[METH_POST],
51  )
52  self.webhook_idwebhook_idwebhook_id = new_webhook_id
53  _LOGGER.debug("Registered webhook: %s", self.webhook_idwebhook_idwebhook_id)
54 
55  def deinitialize(self, hass: HomeAssistant) -> None:
56  """Deinitialize NASwebData instance."""
57  if not self.is_initializedis_initialized():
58  return
59  webhook_unregister(hass, self.webhook_idwebhook_idwebhook_id)
60 
61  def get_webhook_url(self, hass: HomeAssistant) -> str:
62  """Return webhook url for Push API."""
63  hass_url = get_url(hass, allow_external=False)
64  return WEBHOOK_URL.format(internal_url=hass_url, webhook_id=self.webhook_idwebhook_idwebhook_id)
str get_url(HomeAssistant hass, *bool require_current_request=False, bool require_ssl=False, bool require_standard_port=False, bool require_cloud=False, bool allow_internal=True, bool allow_external=True, bool allow_cloud=True, bool|None allow_ip=None, bool|None prefer_external=None, bool prefer_cloud=False)
Definition: network.py:131