feat: notifications through Apprise (v2.14.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhilandClaude Opus 5.5 committed 2026-11-10 14:30:01 -07:00
1 parent 815aff5443
commit 0465ff924b
19 files changed
+659 -17

No files matched your search

+2 -2
View File
@@ -465,5 +465,5 @@ def create_app(config=None):
# Package version (Semantic Versioning 2.0.0)
# See docs/standards/versioning-strategy.md for details
__version__ = "2.13.4"
__version_info__ = (2, 13, 4)
__version__ = "2.14.0"
__version_info__ = (2, 14, 0)
+19 -6
View File
@@ -258,12 +258,14 @@ def hidden_counts(harvest: Harvest) -> Dict[str, int]:
(("likes", "like"), ("reposts", "repost"), ("quotes", "quote"))}
def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest) -> None:
def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest,
quiet: bool = False) -> None:
"""
Upsert a check's responses for one note and silo. With a complete
harvest, that silo's responses for the note that weren't found are
marked invalid. Responses from people who opted out are removed (they
are counted instead, see `hidden_counts`).
are counted instead, see `hidden_counts`). With `quiet`, new responses
are stored as already notified (ADR-074 Decision 5).
"""
from starpunk.webmention_processor import _snippet
@@ -289,8 +291,9 @@ def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest) -> N
INSERT INTO webmentions (
source_url, target_url, target_note_id, mention_type, author_name, author_url,
author_photo, content_snippet, validation_status, moderation_status,
validated_at, source_published, origin, remote_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'valid', ?, CURRENT_TIMESTAMP, ?, ?, ?)
validated_at, source_published, origin, remote_id, notified_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'valid', ?, CURRENT_TIMESTAMP, ?, ?, ?,
CASE WHEN ? THEN CURRENT_TIMESTAMP END)
ON CONFLICT(source_url, target_url) DO UPDATE SET
target_note_id = excluded.target_note_id,
mention_type = excluded.mention_type,
@@ -307,7 +310,8 @@ def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest) -> N
updated_at = CURRENT_TIMESTAMP
""",
(r.source_url, target_url, note_id, r.kind, r.author_name or None, r.author_url or None,
r.author_photo or None, snippet, moderation, r.published, origin, r.remote_id),
r.author_photo or None, snippet, moderation, r.published, origin, r.remote_id,
1 if quiet else 0),
)
if dropped:
marks = ",".join("?" * len(dropped))
@@ -373,7 +377,11 @@ def check(row, target) -> None:
db = get_db(current_app)
site = current_app.config["SITE_URL"].rstrip("/")
harvest = target.client.responses(row["remote_id"], row["remote_url"] or "")
store(db, row["note_id"], f"{site}/note/{row['note_slug']}", row["target"], harvest)
# No notifications for history: a backfill, or a copy's first check on an
# older note (e.g. one linked after the fact). ADR-074 Decision 5.
quiet = bool(row["backfeed_backfill"]) or (
row["backfeed_checked_at"] is None and _age_seconds(row["note_created"]) > DAY)
store(db, row["note_id"], f"{site}/note/{row['note_slug']}", row["target"], harvest, quiet=quiet)
_store_counts(db, row["id"], hidden_counts(harvest))
@@ -398,6 +406,11 @@ def process_due(limit: int = 3) -> int:
if _is_denied(e):
denied[row["target"]] = f"Needs {SCOPES.get(row['target'], 'read access')}: {e}"
current_app.logger.error(f"Backfeed for {row['target']} stopped: {denied[row['target']]}")
from starpunk import notifications
site = current_app.config["SITE_URL"].rstrip("/")
notifications.problem(current_app.config, current_app.config["DATABASE_PATH"],
f"Backfeed for {SILO_NAMES.get(row['target'], row['target'])} stopped",
denied[row["target"]], f"{site}/admin/webmentions")
db.execute("UPDATE syndications SET backfeed_claimed_until = NULL WHERE id = ?", (row["id"],))
db.commit()
continue
+4
View File
@@ -149,6 +149,10 @@ def load_config(app, config_override=None):
# Backfeed of responses to crossposts (v2.13.0, ADR-073)
app.config["BACKFEED_ENABLED"] = os.getenv("BACKFEED_ENABLED", "false").lower() == "true"
app.config["BACKFEED_MAX_AGE_DAYS"] = int(os.getenv("BACKFEED_MAX_AGE_DAYS", "90"))
# Notifications through Apprise (v2.14.0, ADR-074)
app.config["NOTIFY_URLS"] = os.getenv("NOTIFY_URLS", "")
app.config["NOTIFY_EVENTS"] = os.getenv("NOTIFY_EVENTS", "reply,mention,quote,problems")
app.config["NOTIFY_PRIORITY"] = os.getenv("NOTIFY_PRIORITY", "normal")
# Apply overrides if provided
# CSRF protection for admin and consent forms (v2.11.0); on by default.
+236
View File
@@ -0,0 +1,236 @@
"""
Notifications through Apprise (v2.14.0, ADR-074)
The owner hears about new responses (received webmentions and backfeed
alike) and about crossposting problems, on whatever service the Apprise
URLs in NOTIFY_URLS point at (Gotify, ntfy, Pushover, email, an
apprise-api server…).
Responses are sent by a sweep (`sweep`) in the webmention worker, which
runs in one process at a time: each response with `notified_at` empty is
sent once and marked. Likes, reposts and bookmarks are grouped per note.
Failed sends are retried with backoff; responses still unsent after 24
hours are dropped. Problems (`problem`) are sent at once, without retry.
Nothing here may break validation, crossposting or backfeed: every send is
wrapped, and failures are only logged and shown in the admin.
"""
import html
import logging
import re
import sqlite3
import time
from typing import Dict, List, Optional, Tuple
from urllib.parse import parse_qsl, urlsplit
logger = logging.getLogger(__name__)
RESPONSE_EVENTS = ("reply", "mention", "quote", "like", "repost", "bookmark")
EVENTS = RESPONSE_EVENTS + ("problems",)
DEFAULT_EVENTS = "reply,mention,quote,problems"
GROUPED = ("like", "repost", "bookmark")
DROP_AFTER_HOURS = 24
MAX_BACKOFF = 15 * 60
SEND_TIMEOUT = 15
HEADINGS = {
"reply": "↩ Reply from {who}",
"mention": "💬 Mention from {who}",
"quote": "❝ Quote from {who}",
}
GROUP_HEADINGS = {
"like": ("♥", "like", "likes"),
"repost": ("🔁", "repost", "reposts"),
"bookmark": ("🔖", "bookmark", "bookmarks"),
}
# --- Settings ---------------------------------------------------------------------
def urls(config) -> List[str]:
"""NOTIFY_URLS as a list (space- or comma-separated)"""
return [u for u in re.split(r"[\s,]+", config.get("NOTIFY_URLS") or "") if u]
def events(config) -> set:
"""NOTIFY_EVENTS as a set of known event names"""
chosen = {e.strip().lower() for e in (config.get("NOTIFY_EVENTS") or DEFAULT_EVENTS).split(",")}
return chosen & set(EVENTS)
def enabled(config) -> bool:
return bool(urls(config))
def with_priority(url: str, priority: str) -> str:
"""The URL with `priority=` added, unless it sets one itself"""
if not priority or any(k == "priority" for k, _ in parse_qsl(urlsplit(url).query)):
return url
return url + ("&" if "?" in url else "?") + "priority=" + priority
# --- Sending ----------------------------------------------------------------------------
def _deliver(targets: List[str], title: str, body: str) -> Tuple[bool, str]:
"""Send one message to every URL. Returns (all sent, error text)."""
import apprise
sender = apprise.Apprise()
bad = [u.split("://", 1)[0] + "://…" for u in targets if not sender.add(u)]
if bad:
return False, f"Not a usable Apprise URL: {', '.join(bad)}"
with apprise.LogCapture(level=logging.WARNING, fmt="%(message)s") as log:
result = sender.notify(body, title=title, body_format=apprise.NotifyFormat.MARKDOWN,
timeout=SEND_TIMEOUT)
return bool(result), log.getvalue().strip()[:500]
def send(config, title: str, body: str) -> Tuple[bool, str]:
"""Send to all NOTIFY_URLS at NOTIFY_PRIORITY. Never raises."""
targets = [with_priority(u, config.get("NOTIFY_PRIORITY") or "normal") for u in urls(config)]
if not targets:
return False, "No NOTIFY_URLS set"
try:
ok, error = _deliver(targets, title, body)
except Exception as e: # a broken service mustn't break the caller
ok, error = False, f"{type(e).__name__}: {e}"
if not ok:
logger.warning(f"Notification '{title}' not sent: {error or 'unknown error'}")
return ok, error
def problem(config, db_path, title: str, detail: str, link: str) -> None:
"""A crosspost or backfeed problem, sent at once if 'problems' is selected"""
if not enabled(config) or "problems" not in events(config):
return
ok, error = send(config, f"⚠ {title}", f"{detail}\n\n[Open in StarPunk]({link})")
_record(db_path, ok, error)
def _record(db_path, ok: bool, error: str) -> None:
"""Remember the last failure for the admin page (cleared by a success)"""
try:
conn = sqlite3.connect(db_path)
try:
conn.execute("INSERT INTO site_state (key, value) VALUES ('notify_last_error', ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
("" if ok else time.strftime("%Y-%m-%d %H:%M:%S UTC ", time.gmtime())
+ (error or "unknown error"),))
conn.commit()
finally:
conn.close()
except sqlite3.Error as e:
logger.warning(f"Could not record notification result: {e}")
def last_error(db) -> str:
row = db.execute("SELECT value FROM site_state WHERE key = 'notify_last_error'").fetchone()
return row[0] if row else ""
# --- Messages -----------------------------------------------------------------------------
def _plain(snippet: Optional[str], limit: int = 300) -> str:
text = html.unescape(re.sub(r"<[^>]+>", " ", snippet or ""))
text = re.sub(r"\s+", " ", text).strip()
return text if len(text) <= limit else text[:limit - 1].rsplit(" ", 1)[0] + "…"
def _note_label(conn, note_id: int) -> str:
from starpunk.notes import get_note
try:
note = get_note(id=note_id, load_content=True)
label = " ".join((note.title or "").split()) if note else ""
except Exception:
label = ""
return (label[:57] + "…") if len(label) > 60 else (label or "a note")
def _messages(rows, site_url: str, conn) -> List[Tuple[str, str, List[int]]]:
"""(title, body, webmention ids) for a batch of responses"""
site = site_url.rstrip("/")
names = {"gotosocial": "GoToSocial", "bluesky": "Bluesky", "threads": "Threads"}
messages, groups = [], {}
for row in rows:
via = names.get(row["origin"]) if row["origin"] != "webmention" else None
who = (row["author_name"] or "someone") + (f" via {via}" if via else "")
pending = row["moderation_status"] == "pending"
link = (f"{site}/admin/webmentions/{row['id']}" if pending
else f"{site}/note/{row['slug']}#responses")
if row["mention_type"] in GROUPED:
groups.setdefault((row["target_note_id"], row["mention_type"], row["slug"], pending), []).append(
(row["id"], row["author_name"] or "someone", link))
continue
title = HEADINGS.get(row["mention_type"], "Response from {who}").format(who=who)
if pending:
title += " (awaiting moderation)"
text = _plain(row["content_snippet"])
body = (f"{text}\n\n" if text else "") + f"On “{_note_label(conn, row['target_note_id'])}”: [open]({link})"
messages.append((title, body, [row["id"]]))
for (note_id, kind, slug, pending), items in groups.items():
icon, one, many = GROUP_HEADINGS[kind]
n = len(items)
title = f"{icon} {n} new {one if n == 1 else many} on “{_note_label(conn, note_id)}”"
if pending:
title += " (awaiting moderation)"
people = ", ".join(name for _, name, _ in items[:5]) + (f" and {n - 5} more" if n > 5 else "")
messages.append((title, f"{people}\n\n[open]({items[0][2]})", [i for i, _, _ in items]))
return messages
# --- Sweep ----------------------------------------------------------------------------------
class Sweeper:
"""Sends new responses; one instance per webmention worker"""
def __init__(self):
self._failures = 0
self._next_try = 0.0
def run(self, config, db_path, site_url: str) -> int:
"""Send what's due. Returns how many responses were sent."""
if not enabled(config) or time.time() < self._next_try:
return 0
chosen = events(config)
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
# Too old to be news (an outage, say): drop quietly
dropped = conn.execute(
f"""UPDATE webmentions SET notified_at = CURRENT_TIMESTAMP
WHERE notified_at IS NULL
AND received_at < datetime('now', '-{DROP_AFTER_HOURS} hours')""").rowcount
if dropped:
logger.warning(f"Dropped {dropped} notification(s) older than {DROP_AFTER_HOURS} hours")
rows = conn.execute(
"""
SELECT w.*, n.slug FROM webmentions w JOIN notes n ON n.id = w.target_note_id
WHERE w.notified_at IS NULL AND w.validation_status = 'valid'
AND w.moderation_status IN ('approved', 'pending')
ORDER BY w.id LIMIT 100
"""
).fetchall()
skip = [r["id"] for r in rows if r["mention_type"] not in chosen]
if skip:
conn.execute(f"UPDATE webmentions SET notified_at = CURRENT_TIMESTAMP "
f"WHERE id IN ({','.join('?' * len(skip))})", skip)
conn.commit()
due = [r for r in rows if r["mention_type"] in chosen]
sent = 0
for title, body, ids in _messages(due, site_url, conn):
ok, error = send(config, title, body)
_record(db_path, ok, error)
if not ok:
self._failures += 1
self._next_try = time.time() + min(10 * 2 ** self._failures, MAX_BACKOFF)
break
self._failures = 0
conn.execute(f"UPDATE webmentions SET notified_at = CURRENT_TIMESTAMP "
f"WHERE id IN ({','.join('?' * len(ids))})", ids)
conn.commit()
sent += len(ids)
return sent
finally:
conn.close()
+29
View File
@@ -515,6 +515,7 @@ def webmentions():
status_filter=status_filter,
origin_filter=origin_filter,
backfeed=backfeed.status(),
notify=_notify_status(),
page=page,
total_pages=total_pages,
user_me=g.me
@@ -681,6 +682,34 @@ def revoke_token(token_id):
return redirect(url_for("admin.tokens"))
def _notify_status() -> dict:
"""Notification settings and last error for the Webmentions page (v2.14.0)"""
from starpunk import notifications
from starpunk.database import get_db
return {
"enabled": notifications.enabled(current_app.config),
"events": sorted(notifications.events(current_app.config)),
"priority": current_app.config.get("NOTIFY_PRIORITY") or "normal",
"services": [u.split("://", 1)[0] for u in notifications.urls(current_app.config)],
"last_error": notifications.last_error(get_db(current_app)),
}
@bp.route("/notifications/test", methods=["POST"])
@require_auth
def notifications_test():
"""Send a test notification to every NOTIFY_URLS service (v2.14.0)"""
from starpunk import notifications
ok, error = notifications.send(current_app.config, "StarPunk test notification",
"Notifications from StarPunk are working.")
notifications._record(current_app.config["DATABASE_PATH"], ok, error)
flash("Test notification sent" if ok else f"Test notification failed: {error or 'unknown error'}",
"success" if ok else "error")
return redirect(url_for("admin.webmentions"))
@bp.route("/backfeed/backfill", methods=["POST"])
@require_auth
def backfeed_backfill():
+7
View File
@@ -1464,6 +1464,13 @@ def _fail(db, row, error: SyndicationError) -> None:
f"Syndication {row['target']} for note {row['note_id']} failed "
f"(attempt {attempts}{', giving up' if failed else ''}): {error}"
)
if failed: # ADR-074: tell the owner, once, when we give up
from starpunk import notifications
target = get_targets().get(row["target"])
site = current_app.config["SITE_URL"].rstrip("/")
notifications.problem(current_app.config, current_app.config["DATABASE_PATH"],
f"Crosspost to {target.name if target else row['target']} failed",
str(error)[:300], f"{site}/admin/edit/{row['note_id']}")
def _target_title(url: Optional[str]) -> Optional[str]:
+7
View File
@@ -83,7 +83,9 @@ class WebmentionWorker(threading.Thread):
self._last_processed = None
self._lock_file = None
from starpunk.avatars import Upkeep
from starpunk.notifications import Sweeper
self._avatar_upkeep = Upkeep()
self._notifier = Sweeper()
def run(self):
"""
@@ -118,6 +120,11 @@ class WebmentionWorker(threading.Thread):
# Local copies of response avatars (v2.13.0)
self._avatar_upkeep.run(self.db_path, self.app.config['DATA_PATH'],
self.site_url)
# New responses to the owner (v2.14.0, ADR-074)
try:
self._notifier.run(self.app.config, self.db_path, self.site_url)
except Exception as e:
logger.error(f"Notification sweep failed: {e}", exc_info=True)
# Update last processed time
if processed > 0: