# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Send bounded digest notifications for verified incoming Webmentions.""" from datetime import UTC, datetime import sqlalchemy as sa from flask import current_app from flask_mail import Message from ..extensions import db, huey, mail from ..models import ReceivedWebmention, ReceivedWebmentionStatus def email_verified_digest() -> None: """Send one digest of verified, previously unreported Webmentions. Acquire the digest lock before notifying recipients about previously unreported verified mentions. """ # Resolve the lock against the current Huey backend, not the import-time one. with huey.lock_task("send-webmention-digest"): _send_digest_locked() def _send_digest_locked() -> None: """Do the work while the current backend's digest lock is held. Collect verified mentions, send the configured message, and persist notification timestamps. """ recipient = current_app.config.get("DIGEST_EMAIL") if not recipient: return cutoff = datetime.now(UTC) conditions = ( ReceivedWebmention.status == ReceivedWebmentionStatus.VERIFIED, ReceivedWebmention.notification_sent_at.is_(None), ReceivedWebmention.updated_at <= cutoff, ) count = ( db.session.scalar( sa.select(sa.func.count()) .select_from(ReceivedWebmention) .where(*conditions) ) or 0 ) if count == 0: return message = Message( subject=f"Webmention digest: {count} new verified", recipients=[recipient], body=( f"{count} new Webmentions have been verified.\n\n" "Visit your Webmentions administration page to review them.\n" ), ) mail.send(message) db.session.execute( sa.update(ReceivedWebmention) .where(*conditions) .values(notification_sent_at=cutoff) .execution_options(synchronize_session="fetch") ) db.session.commit()