# 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, render_template from flask_mail import Message from ..extensions import db, huey, mail from ..models.received 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, ) # Freeze the list before sending. Only rows represented in this email may # be marked as notified, even if new verified mentions arrive meanwhile. mentions = db.session.execute( sa.select( ReceivedWebmention.uuid, ReceivedWebmention.source, ReceivedWebmention.target, ) .where(*conditions) .order_by(ReceivedWebmention.updated_at, ReceivedWebmention.uuid) ).all() if not mentions: return count = len(mentions) subject = f"{count} new verified webmention{'s' if count != 1 else ''} on your site" message = Message( subject=subject, recipients=[recipient], body=render_template( "emails/verified_digest.txt", count=count, mentions=mentions ), ) mail.send(message) db.session.execute( sa.update(ReceivedWebmention) .where( ReceivedWebmention.uuid.in_([mention.uuid for mention in mentions]), *conditions, ) .values(notification_sent_at=cutoff) .execution_options(synchronize_session="fetch") ) db.session.commit()