1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# 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()
|