1 """Offer webhook triggered automation rules."""
3 from __future__
import annotations
5 from dataclasses
import dataclass
9 from aiohttp
import hdrs, web
10 import voluptuous
as vol
26 _LOGGER = logging.getLogger(__name__)
28 DEPENDENCIES = (
"webhook",)
30 CONF_ALLOWED_METHODS =
"allowed_methods"
31 CONF_LOCAL_ONLY =
"local_only"
33 TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
35 vol.Required(CONF_PLATFORM):
"webhook",
36 vol.Required(CONF_WEBHOOK_ID): cv.string,
37 vol.Optional(CONF_ALLOWED_METHODS): vol.All(
39 [vol.All(vol.Upper, vol.In(SUPPORTED_METHODS))],
42 vol.Optional(CONF_LOCAL_ONLY): bool,
46 WEBHOOK_TRIGGERS = f
"{DOMAIN}_triggers"
49 @dataclass(slots=True)
51 """Attached trigger settings."""
53 trigger_info: TriggerInfo
58 hass: HomeAssistant, webhook_id: str, request: web.Request
60 """Handle incoming webhook."""
61 base_result: dict[str, Any] = {
"platform":
"webhook",
"webhook_id": webhook_id}
63 if "json" in request.headers.get(hdrs.CONTENT_TYPE,
""):
64 base_result[
"json"] = await request.json()
66 base_result[
"data"] = await request.post()
68 base_result[
"query"] = request.query
69 base_result[
"description"] =
"webhook"
71 triggers: dict[str, list[TriggerInstance]] = hass.data.setdefault(
74 for trigger
in triggers[webhook_id]:
75 result = {**base_result, **trigger.trigger_info[
"trigger_data"]}
76 hass.async_run_hass_job(trigger.job, {
"trigger": result})
82 action: TriggerActionType,
83 trigger_info: TriggerInfo,
85 """Trigger based on incoming webhooks."""
86 webhook_id: str = config[CONF_WEBHOOK_ID]
87 local_only = config.get(CONF_LOCAL_ONLY,
True)
88 allowed_methods = config.get(CONF_ALLOWED_METHODS, DEFAULT_METHODS)
91 triggers: dict[str, list[TriggerInstance]] = hass.data.setdefault(
95 if webhook_id
not in triggers:
98 trigger_info[
"domain"],
102 local_only=local_only,
103 allowed_methods=allowed_methods,
105 triggers[webhook_id] = []
108 triggers[webhook_id].append(trigger_instance)
111 def unregister() -> None:
112 """Unregister webhook."""
113 triggers[webhook_id].
remove(trigger_instance)
114 if not triggers[webhook_id]:
116 triggers.pop(webhook_id)
bool remove(self, _T matcher)
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)
None _handle_webhook(HomeAssistant hass, str webhook_id, web.Request request)
None async_unregister(HomeAssistant hass, str webhook_id)
None async_register(HomeAssistant hass, str domain, str name, str webhook_id, Callable[[HomeAssistant, str, Request], Awaitable[Response|None]] handler, *bool|None local_only=False, Iterable[str]|None allowed_methods=None)