Move quiet hours from hub config to per-call service params
All checks were successful
Validate / Hassfest (push) Successful in 1m19s

Quiet hours are now specified per send_telegram_notification call via
quiet_hours_start/quiet_hours_end params instead of being a hub-wide
integration option. This allows different automations to use different
quiet hours windows (or none at all).

- Remove quiet_hours_start/end from config options UI and const.py
- Add quiet_hours_start/end as optional HH:MM params on the service
- Remove ignore_quiet_hours param (omit quiet hours params to send immediately)
- Queue stores quiet_hours_end per item; each unique end time gets its
  own async_track_time_change timer for replay
- On startup, items whose quiet hours have passed are sent immediately
- Add async_remove_indices() to NotificationQueue for selective removal
- Timers are cleaned up when no more items need them

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-19 12:04:20 +03:00
parent 678e8a6e62
commit 71b79cd919
8 changed files with 193 additions and 155 deletions

View File

@@ -4,12 +4,12 @@ from __future__ import annotations
import logging
from dataclasses import dataclass
from datetime import datetime
from datetime import datetime, time as dt_time
from homeassistant.config_entries import ConfigEntry, ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.event import async_track_time_change
from homeassistant.util import dt as dt_util
from .const import (
CONF_ALBUM_ID,
@@ -17,8 +17,6 @@ from .const import (
CONF_API_KEY,
CONF_HUB_NAME,
CONF_IMMICH_URL,
CONF_QUIET_HOURS_END,
CONF_QUIET_HOURS_START,
CONF_SCAN_INTERVAL,
CONF_TELEGRAM_CACHE_TTL,
DEFAULT_SCAN_INTERVAL,
@@ -41,8 +39,6 @@ class ImmichHubData:
api_key: str
scan_interval: int
telegram_cache_ttl: int
quiet_hours_start: str
quiet_hours_end: str
@dataclass
@@ -66,8 +62,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ImmichConfigEntry) -> bo
api_key = entry.data[CONF_API_KEY]
scan_interval = entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
telegram_cache_ttl = entry.options.get(CONF_TELEGRAM_CACHE_TTL, DEFAULT_TELEGRAM_CACHE_TTL)
quiet_hours_start = entry.options.get(CONF_QUIET_HOURS_START, "")
quiet_hours_end = entry.options.get(CONF_QUIET_HOURS_END, "")
# Store hub data
entry.runtime_data = ImmichHubData(
@@ -76,8 +70,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ImmichConfigEntry) -> bo
api_key=api_key,
scan_interval=scan_interval,
telegram_cache_ttl=telegram_cache_ttl,
quiet_hours_start=quiet_hours_start,
quiet_hours_end=quiet_hours_end,
)
# Create storage for persisting album state across restarts
@@ -108,6 +100,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ImmichConfigEntry) -> bo
"telegram_cache": telegram_cache,
"telegram_asset_cache": telegram_asset_cache,
"notification_queue": notification_queue,
"quiet_hours_unsubs": {}, # keyed by "HH:MM" end time
}
# Track loaded subentries to detect changes
@@ -120,12 +113,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ImmichConfigEntry) -> bo
# Forward platform setup once - platforms will iterate through subentries
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
# Register quiet hours end timer
_register_quiet_hours_timer(hass, entry)
# Check if there are queued notifications from before restart (outside quiet hours)
if notification_queue.has_pending() and not _is_quiet_hours(quiet_hours_start, quiet_hours_end):
hass.async_create_task(_process_notification_queue(hass, entry))
# Check if there are queued notifications from before restart
if notification_queue.has_pending():
_register_queue_timers(hass, entry)
# Process any items whose quiet hours have already ended
hass.async_create_task(_process_ready_notifications(hass, entry))
# Register update listener for options and subentry changes
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
@@ -182,11 +174,8 @@ async def _async_setup_subentry_coordinator(
_LOGGER.info("Coordinator for album '%s' set up successfully", album_name)
def _is_quiet_hours(start_str: str, end_str: str, hass: HomeAssistant | None = None) -> bool:
def _is_quiet_hours(start_str: str, end_str: str) -> bool:
"""Check if current time is within quiet hours."""
from datetime import time as dt_time
from homeassistant.util import dt as dt_util
if not start_str or not end_str:
return False
@@ -204,50 +193,64 @@ def _is_quiet_hours(start_str: str, end_str: str, hass: HomeAssistant | None = N
return now >= start_time or now < end_time
def _register_quiet_hours_timer(hass: HomeAssistant, entry: ImmichConfigEntry) -> None:
"""Register a timer to process the notification queue when quiet hours end."""
def _register_queue_timers(hass: HomeAssistant, entry: ImmichConfigEntry) -> None:
"""Register timers for each unique quiet_hours_end in the queue."""
entry_data = hass.data[DOMAIN][entry.entry_id]
queue: NotificationQueue = entry_data["notification_queue"]
unsubs: dict[str, list] = entry_data["quiet_hours_unsubs"]
# Cancel existing timer if any
unsub = entry_data.pop("quiet_hours_unsub", None)
# Collect unique end times from queued items
end_times: set[str] = set()
for item in queue.get_all():
end_str = item.get("params", {}).get("quiet_hours_end", "")
if end_str:
end_times.add(end_str)
for end_str in end_times:
if end_str in unsubs:
continue # Timer already registered for this end time
try:
end_time = dt_time.fromisoformat(end_str)
except ValueError:
_LOGGER.warning("Invalid quiet hours end time in queue: %s", end_str)
continue
async def _on_quiet_hours_end(_now: datetime, _end_str: str = end_str) -> None:
"""Handle quiet hours end — process matching queued notifications."""
_LOGGER.info("Quiet hours ended (%s), processing queued notifications", _end_str)
await _process_notifications_for_end_time(hass, entry, _end_str)
unsub = async_track_time_change(
hass, _on_quiet_hours_end, hour=end_time.hour, minute=end_time.minute, second=0
)
unsubs[end_str] = unsub
entry.async_on_unload(unsub)
_LOGGER.debug("Registered quiet hours timer for %s", end_str)
def _unregister_queue_timer(hass: HomeAssistant, entry: ImmichConfigEntry, end_str: str) -> None:
"""Unregister a quiet hours timer if no more items need it."""
entry_data = hass.data[DOMAIN][entry.entry_id]
queue: NotificationQueue = entry_data["notification_queue"]
unsubs: dict[str, list] = entry_data["quiet_hours_unsubs"]
# Check if any remaining items still use this end time
for item in queue.get_all():
if item.get("params", {}).get("quiet_hours_end", "") == end_str:
return # Still needed
unsub = unsubs.pop(end_str, None)
if unsub:
unsub()
end_str = entry.options.get(CONF_QUIET_HOURS_END, "")
start_str = entry.options.get(CONF_QUIET_HOURS_START, "")
if not end_str or not start_str:
return
try:
from datetime import time as dt_time
end_time = dt_time.fromisoformat(end_str)
except ValueError:
_LOGGER.warning("Invalid quiet hours end time: %s", end_str)
return
async def _on_quiet_hours_end(_now: datetime) -> None:
"""Handle quiet hours end — process queued notifications."""
queue: NotificationQueue = entry_data["notification_queue"]
if queue.has_pending():
_LOGGER.info("Quiet hours ended, processing queued notifications")
await _process_notification_queue(hass, entry)
unsub = async_track_time_change(
hass, _on_quiet_hours_end, hour=end_time.hour, minute=end_time.minute, second=0
)
entry_data["quiet_hours_unsub"] = unsub
entry.async_on_unload(unsub)
_LOGGER.debug("Registered quiet hours timer for %s", end_str)
_LOGGER.debug("Unregistered quiet hours timer for %s (no more items)", end_str)
async def _process_notification_queue(
async def _process_ready_notifications(
hass: HomeAssistant, entry: ImmichConfigEntry
) -> None:
"""Process all queued notifications via the HA service call."""
import asyncio
from homeassistant.helpers import entity_registry as er
"""Process queued notifications whose quiet hours have already ended."""
entry_data = hass.data[DOMAIN].get(entry.entry_id)
if not entry_data:
return
@@ -257,7 +260,68 @@ async def _process_notification_queue(
if not items:
return
# Find a fallback sensor entity for items that don't have entity_id stored
# Find items whose quiet hours have ended
ready_indices = []
for i, item in enumerate(items):
params = item.get("params", {})
start_str = params.get("quiet_hours_start", "")
end_str = params.get("quiet_hours_end", "")
if not _is_quiet_hours(start_str, end_str):
ready_indices.append(i)
if not ready_indices:
return
_LOGGER.info("Found %d queued notifications ready to send (quiet hours ended)", len(ready_indices))
await _send_queued_items(hass, entry, ready_indices)
async def _process_notifications_for_end_time(
hass: HomeAssistant, entry: ImmichConfigEntry, end_str: str
) -> None:
"""Process queued notifications matching a specific quiet_hours_end time."""
entry_data = hass.data[DOMAIN].get(entry.entry_id)
if not entry_data:
return
queue: NotificationQueue = entry_data["notification_queue"]
items = queue.get_all()
if not items:
return
# Find items matching this end time that are no longer in quiet hours
matching_indices = []
for i, item in enumerate(items):
params = item.get("params", {})
if params.get("quiet_hours_end", "") == end_str:
start_str = params.get("quiet_hours_start", "")
if not _is_quiet_hours(start_str, end_str):
matching_indices.append(i)
if not matching_indices:
return
_LOGGER.info("Processing %d queued notifications for quiet hours end %s", len(matching_indices), end_str)
await _send_queued_items(hass, entry, matching_indices)
# Clean up timer if no more items need it
_unregister_queue_timer(hass, entry, end_str)
async def _send_queued_items(
hass: HomeAssistant, entry: ImmichConfigEntry, indices: list[int]
) -> None:
"""Send specific queued notifications by index and remove them from the queue."""
import asyncio
from homeassistant.helpers import entity_registry as er
entry_data = hass.data[DOMAIN].get(entry.entry_id)
if not entry_data:
return
queue: NotificationQueue = entry_data["notification_queue"]
# Find a fallback sensor entity
ent_reg = er.async_get(hass)
fallback_entity_id = None
for ent in er.async_entries_for_config_entry(ent_reg, entry.entry_id):
@@ -269,29 +333,34 @@ async def _process_notification_queue(
_LOGGER.warning("No sensor entity found to process notification queue")
return
_LOGGER.info("Processing %d queued notifications", len(items))
for i, item in enumerate(items):
params = item.get("params", {})
items = queue.get_all()
sent_count = 0
for i in indices:
if i >= len(items):
continue
params = dict(items[i].get("params", {}))
try:
# Use stored entity_id from the original call, fall back to discovered one
target_entity_id = params.pop("entity_id", None) or fallback_entity_id
# Call the service with ignore_quiet_hours=True to prevent re-queuing
# Remove quiet hours params so the replay doesn't re-queue
params.pop("quiet_hours_start", None)
params.pop("quiet_hours_end", None)
await hass.services.async_call(
DOMAIN,
"send_telegram_notification",
{**params, "ignore_quiet_hours": True},
params,
target={"entity_id": target_entity_id},
blocking=True,
)
sent_count += 1
except Exception:
_LOGGER.exception("Failed to send queued notification %d/%d", i + 1, len(items))
_LOGGER.exception("Failed to send queued notification %d", i + 1)
# Small delay between notifications to avoid rate limiting
if i < len(items) - 1:
await asyncio.sleep(1)
await asyncio.sleep(1)
await queue.async_clear()
_LOGGER.info("Processed %d queued notifications", len(items))
# Remove sent items from queue (in reverse order to preserve indices)
await queue.async_remove_indices(sorted(indices, reverse=True))
_LOGGER.info("Sent %d/%d queued notifications", sent_count, len(indices))
async def _async_update_listener(
@@ -314,28 +383,25 @@ async def _async_update_listener(
# Handle options-only update
new_interval = entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
new_quiet_start = entry.options.get(CONF_QUIET_HOURS_START, "")
new_quiet_end = entry.options.get(CONF_QUIET_HOURS_END, "")
# Update hub data
entry.runtime_data.scan_interval = new_interval
entry.runtime_data.quiet_hours_start = new_quiet_start
entry.runtime_data.quiet_hours_end = new_quiet_end
# Update all subentry coordinators
subentries_data = entry_data["subentries"]
for subentry_data in subentries_data.values():
subentry_data.coordinator.update_scan_interval(new_interval)
# Re-register quiet hours timer
_register_quiet_hours_timer(hass, entry)
_LOGGER.info("Updated hub options (scan_interval=%d, quiet_hours=%s-%s)",
new_interval, new_quiet_start or "disabled", new_quiet_end or "disabled")
_LOGGER.info("Updated hub options (scan_interval=%d)", new_interval)
async def async_unload_entry(hass: HomeAssistant, entry: ImmichConfigEntry) -> bool:
"""Unload a config entry."""
# Cancel all quiet hours timers
entry_data = hass.data[DOMAIN].get(entry.entry_id, {})
for unsub in entry_data.get("quiet_hours_unsubs", {}).values():
unsub()
# Unload all platforms
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)