aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/notifications.py
blob: fc1b475aa782e8f9643a98a9f441f79ff53e2c54 (plain) (blame)
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
# 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
from flask_mail import Message

from ..extensions import db, huey, mail
from ..models import ReceivedStatus, ReceivedWebmention


def send_webmention_digest() -> None:
    """Send one digest of verified, previously unreported Webmentions."""
    # Resolve the lock against the current Huey backend, not the import-time one.
    with huey.lock_task("send-webmention-digest"):
        _send_webmention_digest()


def _send_webmention_digest() -> None:
    """Do the work while the current backend's digest lock is held."""
    recipient = current_app.config.get("NOTIFICATION_EMAIL")
    if not recipient:
        return

    cutoff = datetime.now(UTC)

    conditions = (
        ReceivedWebmention.status == ReceivedStatus.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()