Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Mobile app utility functions."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from typing import TYPE_CHECKING
7 
8 from homeassistant.components import cloud
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.core import HomeAssistant, callback
11 
12 from .const import (
13  ATTR_APP_DATA,
14  ATTR_PUSH_TOKEN,
15  ATTR_PUSH_URL,
16  ATTR_PUSH_WEBSOCKET_CHANNEL,
17  CONF_CLOUDHOOK_URL,
18  DATA_CONFIG_ENTRIES,
19  DATA_DEVICES,
20  DATA_NOTIFY,
21  DOMAIN,
22 )
23 
24 if TYPE_CHECKING:
25  from .notify import MobileAppNotificationService
26 
27 
28 @callback
29 def webhook_id_from_device_id(hass: HomeAssistant, device_id: str) -> str | None:
30  """Get webhook ID from device ID."""
31  if DOMAIN not in hass.data:
32  return None
33 
34  for cur_webhook_id, cur_device in hass.data[DOMAIN][DATA_DEVICES].items():
35  if cur_device.id == device_id:
36  return cur_webhook_id
37 
38  return None
39 
40 
41 @callback
42 def supports_push(hass: HomeAssistant, webhook_id: str) -> bool:
43  """Return if push notifications is supported."""
44  config_entry = hass.data[DOMAIN][DATA_CONFIG_ENTRIES][webhook_id]
45  app_data = config_entry.data[ATTR_APP_DATA]
46  return (
47  ATTR_PUSH_TOKEN in app_data and ATTR_PUSH_URL in app_data
48  ) or ATTR_PUSH_WEBSOCKET_CHANNEL in app_data
49 
50 
51 @callback
52 def get_notify_service(hass: HomeAssistant, webhook_id: str) -> str | None:
53  """Return the notify service for this webhook ID."""
54  notify_service: MobileAppNotificationService = hass.data[DOMAIN][DATA_NOTIFY]
55 
56  for target_service, target_webhook_id in notify_service.registered_targets.items():
57  if target_webhook_id == webhook_id:
58  return target_service
59 
60  return None
61 
62 
63 _CLOUD_HOOK_LOCK = asyncio.Lock()
64 
65 
67  hass: HomeAssistant, webhook_id: str, entry: ConfigEntry | None
68 ) -> str:
69  """Create a cloud hook."""
70  async with _CLOUD_HOOK_LOCK:
71  hook = await cloud.async_get_or_create_cloudhook(hass, webhook_id)
72  if entry:
73  hass.config_entries.async_update_entry(
74  entry, data={**entry.data, CONF_CLOUDHOOK_URL: hook}
75  )
76  return hook
bool supports_push(HomeAssistant hass, str webhook_id)
Definition: util.py:42
str async_create_cloud_hook(HomeAssistant hass, str webhook_id, ConfigEntry|None entry)
Definition: util.py:68
str|None get_notify_service(HomeAssistant hass, str webhook_id)
Definition: util.py:52
str|None webhook_id_from_device_id(HomeAssistant hass, str device_id)
Definition: util.py:29