Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@

[Camera Auto Notify](https://camera-autonotify.rhizomatics.org.uk/) automatic notifications from security cameras, so far supporting Frigate, OpenALPR and ANPR2MQTT. No blueprints, no automations, no YAML.

# v2.19.2

## 🐛 Bug fixes
- *Actions*: the `supernotify.*` actions, such as `supernotify.notify` and `supernotify.snooze`, are there from when Home Assistant starts, rather than only once Supernotify has loaded, so an automation using them no longer fails to validate while it starts, or if it failed to start. Until it has loaded, they say so with an error. Home Assistant's [action-setup](https://contributors.home-assistant.io/core/quality-scale/action-setup/) rule, needed for its Bronze quality level

# v2.19.1

## ✨ Enhancements
Expand Down
15 changes: 8 additions & 7 deletions custom_components/supernotify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ async def _async_reload(_call: ServiceCall) -> None:

async_register_admin_service(hass, DOMAIN, SERVICE_RELOAD, _async_reload)

from .actions import async_setup_actions

async_setup_actions(hass)

if not hass.config_entries.async_entries(DOMAIN):
from homeassistant.config_entries import SOURCE_IMPORT

Expand Down Expand Up @@ -301,7 +305,7 @@ def _async_remove_legacy_default_entities(hass: HomeAssistant) -> None:


async def async_setup_entry(hass: HomeAssistant, entry: SupernotifyConfigEntry) -> bool:
from .actions import async_describe_configured_names, async_register_engine_actions
from .actions import async_describe_configured_names
from .const import CONF_LLM_TOOLS, CONF_SENTENCE_COMMANDS
from .engine import build_supernotify_engine
from .notification import set_version
Expand All @@ -328,6 +332,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: SupernotifyConfigEntry)
translation_domain=DOMAIN, translation_key="setup_failed", translation_placeholders={"error": str(err)}
) from err

engine.full_config = full_config
entry.runtime_data = engine
# every recipient discovered gets a subentry, so all are listed and can be changed, and
# switched off with `enabled` - before the update listener, as the engine has them already
Expand All @@ -340,9 +345,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: SupernotifyConfigEntry)
# failure counter sensors (binary_sensor.py/sensor.py/switch.py) - see PLATFORMS above.
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

# Only once the counter sensors have restored their last values, so nothing is counted
# before then and lost
async_register_engine_actions(hass, engine, full_config)
# The supernotify.* actions only act once setup is complete and the entry is loaded, so after
# the counter sensors have restored their last values, and nothing is counted before then and lost
await async_describe_configured_names(hass, engine)

if entry.options.get(CONF_LLM_TOOLS, {}).get(CONF_SENTENCE_COMMANDS):
Expand Down Expand Up @@ -384,11 +388,8 @@ async def _async_update_listener(hass: HomeAssistant, entry: SupernotifyConfigEn


async def async_unload_entry(hass: HomeAssistant, entry: SupernotifyConfigEntry) -> bool:
from .actions import async_unregister_engine_actions

unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
engine: SupernotifyEngine | None = getattr(entry, "runtime_data", None)
if engine is not None:
engine.shutdown()
async_unregister_engine_actions(hass)
return unload_ok
81 changes: 37 additions & 44 deletions custom_components/supernotify/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,10 @@
from .target import Target

if TYPE_CHECKING:
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.json import JsonObjectType

from . import SupernotifyConfigEntry

_LOGGER = logging.getLogger(__name__)

# what the schema fills in for fields a supernotify.notify call left out
Expand Down Expand Up @@ -171,27 +172,15 @@ def merge_delivery_fields(data: dict[str, Any]) -> dict[str, Any]:
extra=vol.ALLOW_EXTRA,
)

ACTION_NAMES: Final[tuple[str, ...]] = (
"notify",
"enquire_archive",
"enquire_configuration",
"enquire_implicit_deliveries",
"enquire_deliveries_by_scenario",
"enquire_last_notification",
"enquire_active_scenarios",
"enquire_scenarios",
"enquire_occupancy",
"enquire_recipients",
"enquire_snoozes",
"clear_snoozes",
"snooze",
"silence",
"unsnooze",
"purge_archive",
"purge_media",
"refresh_entities",
"reset_overrides",
)

def _loaded_engine(hass: HomeAssistant) -> SupernotifyEngine:
"""The engine of the loaded config entry - there is only ever one - for an action to act on,
or a ServiceValidationError when it isn't loaded, such as while it starts or after a failed setup."""
entries: list[SupernotifyConfigEntry] = hass.config_entries.async_loaded_entries(DOMAIN)
if not entries:
raise ServiceValidationError(translation_domain=DOMAIN, translation_key="not_loaded")
return entries[0].runtime_data


SNOOZE_MAX_MINUTES: Final[int] = 7 * 24 * 60
SNOOZE_REASON: Final[str] = "Action"
Expand Down Expand Up @@ -235,20 +224,15 @@ def _json_safe(v: Any) -> Any: # ruff: ignore[any-type]


@callback
def async_register_engine_actions(hass: HomeAssistant, engine: SupernotifyEngine, config: ConfigType) -> None:
"""Register the domain-scoped supplemental/debugging/admin services.

Shared by the legacy YAML platform (async_get_service, below) and the config-entry setup
(async_setup_entry in __init__.py), so both setup paths expose the same services. These
are DOMAIN-scoped, not per config entry, so registration is guarded against being run
twice - see ACTION_NAMES/async_unregister_engine_actions for the
matching teardown.

enquire_configuration closes over the raw config dict rather than `service`, because
several of the fields it reports (delivery/transport/archive/dupe_check config, the full
set of configured scenarios/recipients) are either private on the registries after
initialize() or lossily reduced to derived values there - so `service` alone can't
reconstruct them.
def async_setup_actions(hass: HomeAssistant) -> None:
"""Register the supernotify.* actions, once, from async_setup, so they exist whether or not the
config entry is loaded, and automations using them always validate. Each action looks up the
loaded entry's engine when called, see _loaded_engine().

enquire_configuration reports the raw config (SupernotifyEngine.full_config) rather than the
engine's state, because several of the fields it reports (delivery/transport/archive/dupe_check
config, the full set of configured scenarios/recipients) are either private on the registries
after initialize() or lossily reduced to derived values there.
"""
if hass.services.has_service(DOMAIN, "enquire_configuration"):
return
Expand All @@ -269,6 +253,7 @@ async def action_notify(call: ServiceCall) -> JsonObjectType | None:
for it here. Requesting a response (supports_response=OPTIONAL) returns the notification's
contents either way.
"""
engine = _loaded_engine(hass)
data = merge_delivery_fields(lift_legacy_nested_data(dict(call.data)))
# extra_data is what Notification knows as `data`, and wins over any same-named key in a legacy `data`
if extra_data := data.pop(ATTR_EXTRA_DATA, None):
Expand Down Expand Up @@ -303,6 +288,7 @@ async def action_notify(call: ServiceCall) -> JsonObjectType | None:
return notification.contents() if notification else None

def supplemental_action_enquire_configuration(_call: ServiceCall) -> dict[str, Any]:
config = _loaded_engine(hass).full_config
return redact_secrets(
_json_safe({
CONF_DELIVERY: config.get(CONF_DELIVERY, {}),
Expand All @@ -326,44 +312,54 @@ def supplemental_action_enquire_configuration(_call: ServiceCall) -> dict[str, A

@callback
def supplemental_action_refresh_entities(_call: ServiceCall) -> None:
engine = _loaded_engine(hass)
# a callback, so run in the event loop - it writes entity state
engine.refresh_entities()

async def supplemental_action_reset_overrides(call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
# a coroutine, so run in the event loop - it writes entity state - and not a callback, as an
# admin action gives no response from one
kind: str | None = call.data.get(ATTR_KIND)
return {"reset": engine.reset_overrides((kind,) if kind else OVERRIDE_KINDS, call.context)}

def supplemental_action_enquire_implicit_deliveries(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return engine.enquire_implicit_deliveries()

def supplemental_action_enquire_deliveries_by_scenario(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return engine.enquire_deliveries_by_scenario()

def supplemental_action_enquire_last_notification(call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
diagnostics = call.data.get("diagnostics", False)
if engine.last_notification is None:
return {}
return redact_secrets(engine.last_notification.contents(diagnostics=diagnostics))

async def supplemental_action_enquire_active_scenarios(call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
trace = call.data.get("trace", False)
result: dict[str, Any] = {"scenarios": await engine.enquire_active_scenarios()}
if trace:
result["trace"] = await engine.trace_active_scenarios()
return result

def supplemental_action_enquire_scenarios(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return {"scenarios": engine.enquire_scenarios()}

async def supplemental_action_enquire_occupancy(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return {"scenarios": await engine.enquire_occupancy()}

def supplemental_action_enquire_snoozes(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return {"snoozes": engine.enquire_snoozes()}

def supplemental_action_clear_snoozes(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return {"cleared": engine.clear_snoozes()}

@callback
Expand All @@ -372,6 +368,7 @@ def snooze_command(cmd: CommandType, call: ServiceCall) -> dict[str, Any]:
unsnooze as a mobile action, voice sentence or the AI tool, for scripts, automations and dashboards,
and open to any user, where firing the mobile action event over the API needs an admin. Run in the
event loop like the others that change state."""
engine = _loaded_engine(hass)
scope = SNOOZE_SCOPES[call.data["scope"]]
name: str | None = call.data.get("name")
if isinstance(scope, QualifiedTargetType):
Expand Down Expand Up @@ -402,9 +399,11 @@ def snooze_command(cmd: CommandType, call: ServiceCall) -> dict[str, Any]:
return {"snoozes": engine.enquire_snoozes()}

def supplemental_action_enquire_recipients(_call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
return {"recipients": engine.enquire_recipients()}

async def supplemental_action_enquire_archive(call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
archive = engine.context.archive
if not archive.enabled or not archive.archive_directory:
raise ServiceValidationError(
Expand Down Expand Up @@ -455,6 +454,7 @@ def at_verbosity(contents: dict[str, Any]) -> dict[str, Any]:
return {"notifications": [at_verbosity(entry) for entry in entries], "count": len(entries)}

async def supplemental_action_purge_archive(call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
days = call.data.get("days")
if not engine.context.archive.enabled:
raise ServiceValidationError(
Expand All @@ -470,6 +470,7 @@ async def supplemental_action_purge_archive(call: ServiceCall) -> dict[str, Any]
}

async def supplemental_action_purge_media(call: ServiceCall) -> dict[str, Any]:
engine = _loaded_engine(hass)
days = call.data.get("days")
if not engine.context.media_storage.media_path:
raise ServiceValidationError(
Expand Down Expand Up @@ -631,11 +632,3 @@ async def async_describe_configured_names(hass: HomeAssistant, engine: Supernoti
"select": {"options": scenarios, "multiple": True, "custom_value": True}
}
async_set_service_schema(hass, DOMAIN, "notify", notify)


@callback
def async_unregister_engine_actions(hass: HomeAssistant) -> None:
"""Undo async_register_engine_actions."""
for name in ACTION_NAMES:
if hass.services.has_service(DOMAIN, name):
hass.services.async_remove(DOMAIN, name)
2 changes: 2 additions & 0 deletions custom_components/supernotify/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ def __init__(
) -> None:
"""Initialize the service."""
self.last_notification: Notification | None = None
# the full configuration it was built from, for supernotify.enquire_configuration - set by async_setup_entry
self.full_config: dict[str, Any] = {}
self.housekeeping: dict[str, Any] = housekeeping or {}
# The counts live only in these entities, which restore their own value across restarts;
# sensor.py hands them to Home Assistant once its platform loads
Expand Down
14 changes: 6 additions & 8 deletions custom_components/supernotify/quality_scale.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ rules:
# ==================

action-setup:
status: todo
status: done
comment: |
Only supernotify.reload is registered in async_setup (__init__.py). The supernotify.*
engine actions (actions.py async_register_engine_actions) are registered from
async_setup_entry and removed in async_unload_entry, so while the entry is not loaded
they don't exist and automations using them fail validation. The rule wants them
registered once in async_setup, looking up the loaded entry and raising a translated
ServiceValidationError when it isn't loaded. notify.supernotify itself is the legacy
notify service, which follows the entry.
actions.py async_setup_actions registers the supernotify.* actions once, from async_setup,
so they exist whether or not the config entry is loaded. Each looks up the loaded entry's
engine when called (_loaded_engine), raising a translated ServiceValidationError
(not_loaded) when there is none. notify.supernotify itself is the legacy notify service,
which follows the entry.

appropriate-polling:
status: exempt
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Supernotify konnte nicht gestartet werden und versucht es erneut: {error}"
},
"not_loaded": {
"message": "Supernotify ist nicht geladen, daher kann diese Aktion erst nach dem Start ausgeführt werden"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,9 @@
},
"setup_failed": {
"message": "Supernotify failed to start, and will retry: {error}"
},
"not_loaded": {
"message": "Supernotify isn't loaded, so this action can't run until it starts"
}
},
"selector": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Supernotify no pudo iniciarse y lo volverá a intentar: {error}"
},
"not_loaded": {
"message": "Supernotify no está cargado, así que esta acción no puede ejecutarse hasta que se inicie"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Supernotify n'a pas pu démarrer et va réessayer : {error}"
},
"not_loaded": {
"message": "Supernotify n'est pas chargé, cette action ne peut donc pas s'exécuter avant son démarrage"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Supernotify शुरू नहीं हो सका, और फिर से प्रयास करेगा: {error}"
},
"not_loaded": {
"message": "Supernotify लोड नहीं है, इसलिए यह कार्रवाई उसके शुरू होने तक नहीं चल सकता"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,9 @@
},
"setup_failed": {
"message": "Supernotify non è riuscito ad avviarsi e riproverà: {error}"
},
"not_loaded": {
"message": "Supernotify non è caricato, quindi questa azione non può essere eseguita finché non si avvia"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Supernotify の起動に失敗しました。再試行します: {error}"
},
"not_loaded": {
"message": "Supernotify が読み込まれていないため、起動するまでこのアクションは実行できません"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Supernotify kon niet starten en probeert het opnieuw: {error}"
},
"not_loaded": {
"message": "Supernotify is niet geladen, dus deze actie kan pas worden uitgevoerd als het is gestart"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "Nie udało się uruchomić Supernotify, nastąpi ponowna próba: {error}"
},
"not_loaded": {
"message": "Supernotify nie jest załadowany, więc ta akcja nie może zostać wykonana, dopóki się nie uruchomi"
}
},
"options": {
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/translations/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@
},
"setup_failed": {
"message": "O Supernotify não conseguiu iniciar e vai tentar novamente: {error}"
},
"not_loaded": {
"message": "O Supernotify não está carregado, por isso esta ação não pode ser executada até que seja iniciado"
}
},
"options": {
Expand Down
Loading
Loading