A plugin declaring provides: {"notify.channel": "<action>"} gets every
push, ask and clear of the person who installed it (notifications/channels.py),
the payload the HA webhook always got. Tried once, no retry; with no channel
a push is still in the app (an in_app record, ok) and on the browsers, which
stay core. Guests' own channel installs get their wording and guest link.
Removed: the webhook list (Settings → Webhooks, /api/webhooks*, forward(),
the seeded HA webhook) and integrations/home-assistant, now in the
home-assistant-push plugin (ai-agent-plugins). The old webhook's URL and PWA
package are carried over once into the plugin's data. /settings/webhooks
redirects to the plugin. Forms ha-push-as-a-plugin_yjj2n0,
browser-push-as-a-plugin_7id9we.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
329 lines
14 KiB
Python
329 lines
14 KiB
Python
"""
|
|
First-class notifications — the ai-agent backend as the homelab's notification
|
|
source of truth.
|
|
|
|
Everything that pushes to the phone now flows through here: the ``notify-done``
|
|
skill POSTs ``/api/notify`` (plain pushes) and ``/api/ask`` (choice questions
|
|
with tappable buttons), the backend records the event (SQLite beside ``/data/notifications.json``) and hands it to each
|
|
recipient's channels (``notifications/channels.py`` — a channel plugin such as
|
|
``home-assistant-push``, which renders the mobile notification and, for asks,
|
|
POSTs the tapped answer back to ``/api/ask/{id}/answer``).
|
|
|
|
Store shape (single JSON file, atomic rewrite, same pattern as ``meta.py``):
|
|
|
|
{ "webhooks": [ … ] # until 2026-11-25 — now the home-assistant-push
|
|
# plugin's config (read once: ``legacy_webhooks``)
|
|
"notifications": [ {"id", "kind": "notify"|"ask", "title", "body",
|
|
"type", "url", "image", "at", "sessionId",
|
|
"to": [user ids it was addressed to],
|
|
"delivered": [{"channel"|"target","ok","status","user"}],
|
|
# ask-only:
|
|
"options", "status", "answer", "answerIndex",
|
|
"answeredAt", "expiresAt"}, … ] }
|
|
|
|
The notification log is capped (newest kept). Ask long-polling is in-memory
|
|
(one ``threading.Event`` per pending ask) — a backend restart drops the wait,
|
|
and the asking script's own timeout handles that.
|
|
"""
|
|
|
|
import json
|
|
import pathlib
|
|
import sqlite3
|
|
import threading
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
_SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS notifications (
|
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
id TEXT NOT NULL UNIQUE,
|
|
kind TEXT,
|
|
status TEXT,
|
|
session_id TEXT,
|
|
at TEXT,
|
|
data_json TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS notifications_session ON notifications (session_id);
|
|
CREATE INDEX IF NOT EXISTS notifications_kind_status ON notifications (kind, status);
|
|
CREATE TABLE IF NOT EXISTS kv (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS _meta (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT
|
|
);
|
|
"""
|
|
|
|
_MAX_LOG = 1000
|
|
|
|
# How long an ask waits for a tap by default (mirrors ask.sh's default).
|
|
DEFAULT_ASK_TIMEOUT_S = 180
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
class NotifyStore:
|
|
"""The notification/ask log, backed by SQLite."""
|
|
|
|
def __init__(self, path: str):
|
|
self.path = pathlib.Path(path)
|
|
self.db_path = self.path.with_suffix(".db")
|
|
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._lock = threading.Lock()
|
|
self._waiters: dict[str, threading.Event] = {}
|
|
self._data: dict = {"notifications": []}
|
|
self._db = sqlite3.connect(str(self.db_path), check_same_thread=False)
|
|
self._db.execute("PRAGMA journal_mode=WAL")
|
|
self._db.execute("PRAGMA synchronous=NORMAL")
|
|
self._db.execute("PRAGMA busy_timeout=5000")
|
|
self._db.execute("PRAGMA journal_size_limit=16777216")
|
|
self._db.executescript(_SCHEMA)
|
|
self._db.commit()
|
|
self._load()
|
|
|
|
def _load(self) -> None:
|
|
migrated = self._db.execute(
|
|
"SELECT value FROM _meta WHERE key='migrated_mtime'"
|
|
).fetchone()
|
|
wh_row = self._db.execute("SELECT value FROM kv WHERE key='webhooks'").fetchone()
|
|
count = self._db.execute("SELECT COUNT(*) FROM notifications").fetchone()[0]
|
|
if migrated is None and wh_row is None and count == 0:
|
|
if self.path.exists():
|
|
try:
|
|
st_mtime = self.path.stat().st_mtime
|
|
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
webhooks = list(data.get("webhooks") or [])
|
|
notifs = list(data.get("notifications") or [])[-_MAX_LOG:]
|
|
except (OSError, ValueError):
|
|
webhooks, notifs, st_mtime = [], [], None
|
|
self._db.execute(
|
|
"INSERT OR REPLACE INTO kv (key, value) VALUES ('webhooks', ?)",
|
|
(json.dumps(webhooks),),
|
|
)
|
|
rows = []
|
|
for n in notifs:
|
|
if not isinstance(n, dict):
|
|
continue
|
|
nid = n.get("id") or ("ntf_" + uuid.uuid4().hex[:12])
|
|
if not n.get("id"):
|
|
n = {**n, "id": nid}
|
|
rows.append((
|
|
nid, n.get("kind") or "", n.get("status") or "",
|
|
n.get("sessionId") or "", n.get("at") or "", json.dumps(n),
|
|
))
|
|
if rows:
|
|
self._db.executemany(
|
|
"INSERT OR REPLACE INTO notifications "
|
|
"(id, kind, status, session_id, at, data_json) "
|
|
"VALUES (?,?,?,?,?,?)",
|
|
rows,
|
|
)
|
|
if st_mtime is not None:
|
|
self._db.execute(
|
|
"INSERT INTO _meta (key, value) VALUES ('migrated_mtime', ?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
(str(st_mtime),),
|
|
)
|
|
self._db.commit()
|
|
|
|
notifs: list[dict] = []
|
|
for (raw,) in self._db.execute(
|
|
"SELECT data_json FROM notifications ORDER BY seq ASC").fetchall():
|
|
try:
|
|
n = json.loads(raw)
|
|
if isinstance(n, dict):
|
|
notifs.append(n)
|
|
except (ValueError, TypeError):
|
|
continue
|
|
self._data = {"notifications": notifs}
|
|
|
|
# ── the webhooks of before the channel plugins ──────────────────────────
|
|
def legacy_webhooks(self) -> list[dict]:
|
|
"""The webhook list the hub kept until 2026-11-25 (Settings →
|
|
Webhooks) — read once, to carry the Home Assistant one over to the
|
|
``home-assistant-push`` plugin (``plugins/carryover.py``)."""
|
|
row = self._db.execute("SELECT value FROM kv WHERE key='webhooks'").fetchone()
|
|
try:
|
|
out = json.loads(row[0]) if row else []
|
|
except (ValueError, TypeError):
|
|
return []
|
|
return [w for w in out if isinstance(w, dict)] if isinstance(out, list) else []
|
|
|
|
def drop_legacy_webhooks(self) -> None:
|
|
with self._lock:
|
|
self._db.execute("DELETE FROM kv WHERE key='webhooks'")
|
|
self._db.commit()
|
|
|
|
# ── log ─────────────────────────────────────────────────────────────────
|
|
def record(self, entry: dict) -> dict:
|
|
if not entry.get("id"):
|
|
entry = {**entry, "id": "ntf_" + uuid.uuid4().hex[:12]}
|
|
raw = json.dumps(entry)
|
|
with self._lock:
|
|
self._data["notifications"].append(entry)
|
|
self._db.execute(
|
|
"INSERT OR REPLACE INTO notifications "
|
|
"(id, kind, status, session_id, at, data_json) VALUES (?,?,?,?,?,?)",
|
|
(entry["id"], entry.get("kind") or "", entry.get("status") or "",
|
|
entry.get("sessionId") or "", entry.get("at") or "", raw),
|
|
)
|
|
if len(self._data["notifications"]) > _MAX_LOG:
|
|
dropped = self._data["notifications"][:-_MAX_LOG]
|
|
self._data["notifications"] = \
|
|
self._data["notifications"][-_MAX_LOG:]
|
|
drop_ids = [d["id"] for d in dropped if d.get("id")]
|
|
if drop_ids:
|
|
self._db.execute(
|
|
f"DELETE FROM notifications WHERE id IN ({','.join('?' * len(drop_ids))})",
|
|
drop_ids,
|
|
)
|
|
self._db.commit()
|
|
return entry
|
|
|
|
def pending_ask_sessions(self) -> set[str]:
|
|
"""Session IDs with a pending ask (fast in-memory scan, no deep copy)."""
|
|
with self._lock:
|
|
return {e["sessionId"] for e in self._data["notifications"]
|
|
if e.get("kind") == "ask" and e.get("status") == "pending"
|
|
and e.get("sessionId")}
|
|
|
|
def log(self, limit: int = 200) -> list[dict]:
|
|
with self._lock:
|
|
out = list(self._data["notifications"])[-max(1, limit):]
|
|
out.reverse() # newest first
|
|
return json.loads(json.dumps(out))
|
|
|
|
def get(self, nid: str) -> dict | None:
|
|
with self._lock:
|
|
for n in self._data["notifications"]:
|
|
if n.get("id") == nid:
|
|
return json.loads(json.dumps(n))
|
|
return None
|
|
|
|
def _update(self, nid: str, patch: dict) -> dict | None:
|
|
with self._lock:
|
|
for idx, n in enumerate(self._data["notifications"]):
|
|
if n.get("id") == nid:
|
|
updated = {**n, **patch}
|
|
raw = json.dumps(updated)
|
|
self._db.execute(
|
|
"UPDATE notifications SET kind=?, status=?, session_id=?, at=?, "
|
|
"data_json=? WHERE id=?",
|
|
(updated.get("kind") or "", updated.get("status") or "",
|
|
updated.get("sessionId") or "", updated.get("at") or "",
|
|
raw, nid),
|
|
)
|
|
self._db.commit()
|
|
self._data["notifications"][idx] = updated
|
|
return json.loads(raw)
|
|
return None
|
|
|
|
# ── asks ────────────────────────────────────────────────────────────────
|
|
def create_ask(self, question: str, options: list[str], *,
|
|
type_: str = "", url: str = "", image: str = "",
|
|
session_id: str = "",
|
|
timeout_s: int = DEFAULT_ASK_TIMEOUT_S,
|
|
nid: str = "") -> dict:
|
|
"""``nid``: the notify CLI mints ids itself (``ask_`` + 12 hex) so an
|
|
ask created through a worker's outbox keeps the id the CLI printed."""
|
|
nid = nid or "ask_" + uuid.uuid4().hex[:12]
|
|
expires = datetime.now(timezone.utc) + timedelta(
|
|
seconds=max(10, timeout_s))
|
|
entry = {
|
|
"id": nid, "kind": "ask", "title": "Claude needs a choice",
|
|
"body": question, "type": type_ or "", "url": url or "",
|
|
"image": image or "",
|
|
"at": _now_iso(), "sessionId": session_id or "",
|
|
"delivered": [],
|
|
"options": list(options), "status": "pending",
|
|
"answer": None, "answerIndex": None, "answeredAt": None,
|
|
"expiresAt": expires.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
}
|
|
with self._lock:
|
|
self._waiters[nid] = threading.Event()
|
|
return self.record(entry)
|
|
|
|
def answer_ask(self, nid: str, index: int | None,
|
|
label: str | None) -> dict | None:
|
|
cur = self.get(nid)
|
|
if not cur or cur.get("kind") != "ask":
|
|
return None
|
|
options = cur.get("options") or []
|
|
if label is None and index is not None and 0 <= index < len(options):
|
|
label = options[index]
|
|
if index is None and label in options:
|
|
index = options.index(label)
|
|
out = self._update(nid, {
|
|
"status": "answered", "answer": label, "answerIndex": index,
|
|
"answeredAt": _now_iso(),
|
|
})
|
|
with self._lock:
|
|
ev = self._waiters.pop(nid, None)
|
|
if ev:
|
|
ev.set()
|
|
return out
|
|
|
|
def ask_status(self, nid: str) -> dict | None:
|
|
"""The ask with its *effective* status (pending past expiry → expired)."""
|
|
cur = self.get(nid)
|
|
if not cur or cur.get("kind") != "ask":
|
|
return None
|
|
if cur.get("status") == "pending":
|
|
try:
|
|
exp = datetime.strptime(cur.get("expiresAt") or "",
|
|
"%Y-%m-%dT%H:%M:%SZ")
|
|
if datetime.now(timezone.utc).replace(tzinfo=None) > exp:
|
|
cur = self._update(nid, {"status": "expired"}) or cur
|
|
except ValueError:
|
|
pass
|
|
return cur
|
|
|
|
def wait_for_answer(self, nid: str, wait_s: float) -> dict | None:
|
|
"""Block up to ``wait_s`` for the ask to be answered; returns the ask."""
|
|
with self._lock:
|
|
ev = self._waiters.get(nid)
|
|
if ev and wait_s > 0:
|
|
ev.wait(min(wait_s, 55.0))
|
|
return self.ask_status(nid)
|
|
|
|
def set_delivered(self, nid: str, delivered: list[dict],
|
|
to: list[str] | None = None) -> None:
|
|
self._update(nid, {"delivered": delivered} if to is None
|
|
else {"delivered": delivered, "to": to})
|
|
|
|
# ── notify action buttons ───────────────────────────────────────────────
|
|
# A plain push may carry extra buttons (``notify send --action-cmd``):
|
|
# ``actions: [{action: "<nid>__<i>", title}]``. The HA integration POSTs
|
|
# the tapped index to /api/notify/{id}/action exactly like an ask's
|
|
# answer, and the CLI's detached waiter long-polls GET /api/notify/{id}.
|
|
def watch_actions(self, nid: str) -> None:
|
|
with self._lock:
|
|
self._waiters[nid] = threading.Event()
|
|
|
|
def record_action(self, nid: str, index: int | None,
|
|
title: str | None) -> dict | None:
|
|
cur = self.get(nid)
|
|
if not cur or cur.get("kind") != "notify":
|
|
return None
|
|
actions = cur.get("actions") or []
|
|
if title is None and index is not None and 0 <= index < len(actions):
|
|
title = actions[index].get("title")
|
|
out = self._update(nid, {"status": "acted", "actionIndex": index,
|
|
"actionTitle": title,
|
|
"actedAt": _now_iso()})
|
|
with self._lock:
|
|
ev = self._waiters.pop(nid, None)
|
|
if ev:
|
|
ev.set()
|
|
return out
|
|
|
|
def wait_for_action(self, nid: str, wait_s: float) -> dict | None:
|
|
with self._lock:
|
|
ev = self._waiters.get(nid)
|
|
if ev and wait_s > 0:
|
|
ev.wait(min(wait_s, 55.0))
|
|
return self.get(nid)
|