aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/views.py
blob: 3430ceab079fd0c74884c31e23a84d20cd2ee352 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

import uuid
from typing import cast
from urllib.parse import urlsplit

import sqlalchemy as sa
import sqlalchemy.exc as sa_exc
from flask import (
    Blueprint,
    Response,
    abort,
    flash,
    redirect,
    render_template,
    request,
    url_for,
)
from flask.typing import ResponseReturnValue
from flask_login import current_user, login_required, login_user, logout_user
from sqlalchemy.orm import selectinload

from . import CSRF, forms
from . import DATABASE as db
from .models import ReceivedWebmention, Source, User
from .tasks.receiver import verify_webmention
from .tasks.scanner import manual_scan_sources

root_page = Blueprint("root", __name__)


@root_page.route("/")
def index() -> ResponseReturnValue:
    """
    Redirect to the received Webmentions view.

    :return: Redirect response to the received Webmentions view.
    """
    return redirect(url_for("root.received"))


@root_page.route("/login", methods=["GET", "POST"])
def login() -> ResponseReturnValue:
    """
    Authenticate a user and start a login session.

    Authenticated users are redirected to the application index. After a
    successful login, the user is redirected to the requested local URL when
    provided.

    :return: Rendered login page or redirect response.
    """
    if current_user.is_authenticated:
        return redirect(url_for("root.index"))

    form = forms.LoginForm()

    if form.validate_on_submit():
        user = db.session.scalar(
            sa.select(User).where(User.username == form.username.data)
        )

        if user is None or not user.check_password(form.password.data):
            flash("Invalid username or password", "danger")
            return redirect(url_for("root.login"))

        login_user(user)

        next_page = request.args.get("next")
        if not next_page or urlsplit(next_page).netloc != "":
            next_page = url_for("root.index")
        return redirect(next_page)

    return render_template("login.html", form=form)


@root_page.route("/logout")
def logout() -> ResponseReturnValue:
    """
    End the current user's login session.

    :return: Redirect response to the application index.
    """
    logout_user()
    return redirect(url_for("root.index"))


@root_page.route("/received")
@login_required
def received() -> ResponseReturnValue:
    """
    Display received Webmentions.

    :return: Rendered page containing the paginated received Webmentions.
    """
    webmentions = db.paginate(
        sa.select(ReceivedWebmention).order_by(ReceivedWebmention.uuid.desc()),
        per_page=25,
    )

    return render_template(
        "received.html",
        title="Received Webmentions",
        webmentions=webmentions,
        action_form=forms.AdminActionForm(),
    )


@root_page.post("/received/<uuid:identifier>/delete")
@login_required
def delete_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue:
    """
    Delete a received Webmention.

    :param identifier: Identifier of the Webmention to delete.
    :return: Redirect response to the received Webmentions view.
    """
    form = forms.AdminActionForm()

    if not form.validate_on_submit():
        return abort(400)

    webmention = db.session.get(ReceivedWebmention, identifier)

    if webmention is None:
        return abort(404)

    db.session.delete(webmention)
    db.session.commit()

    flash(f"Webmention {webmention.uuid} deleted.", "success")

    return redirect(
        url_for("root.received", page=request.args.get("page", 1, type=int))
    )


@root_page.post("/received/<uuid:identifier>/reverify")
@login_required
def reverify_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue:
    """
    Queue a received Webmention for reverification.

    The Webmention status is reset before a new verification task is queued.

    :param identifier: Identifier of the Webmention to reverify.
    :return: Redirect response to the received Webmentions view.
    """
    form = forms.AdminActionForm()

    if not form.validate_on_submit():
        return abort(400)

    webmention = db.session.get(ReceivedWebmention, identifier)

    if webmention is None:
        return abort(404)

    webmention.status = "received"
    webmention.failure_reason = None

    db.session.commit()

    verify_webmention(identifier)

    flash(f"Webmention {webmention.uuid} queued for reverification.", "success")

    return redirect(
        url_for("root.received", page=request.args.get("page", 1, type=int))
    )


@root_page.route("/sent")
@login_required
def sent() -> ResponseReturnValue:
    """
    Display sources with sent Webmentions.

    :return: Rendered page containing the paginated source list.
    """
    sources = db.paginate(
        sa.select(Source)
        .options(selectinload(Source.sent_webmentions))
        .order_by(Source.last_seen_at.desc()),
        per_page=25,
    )
    return render_template(
        "sent.html",
        title="Sent Webmentions",
        sources=sources,
        action_form=forms.AdminActionForm(),
    )


@root_page.post("/sent/rescan")
@login_required
def rescan_sent_sources() -> ResponseReturnValue:
    """
    Queue a manual scan of sent Webmention sources.

    :return: Redirect response to the sent Webmentions view.
    """
    form = forms.AdminActionForm()
    if form.validate_on_submit():
        manual_scan_sources()
        flash("Source rescan queued.", "success")
    return redirect(url_for("root.sent"))


@root_page.route("/sent/<uuid:identifier>")
@login_required
def sent_source(identifier: uuid.UUID) -> ResponseReturnValue:
    """
    Display the sent Webmentions associated with a source.

    :param identifier: Identifier of the source to display.
    :return: Rendered source details page.
    """
    source = db.session.scalar(
        sa.select(Source)
        .options(selectinload(Source.sent_webmentions))
        .where(Source.uuid == identifier)
    )
    if source is None:
        return abort(404)

    webmentions = sorted(
        source.sent_webmentions, key=lambda webmention: webmention.target
    )
    return render_template(
        "sent_source.html",
        title="Sent Webmentions",
        source=source,
        webmentions=webmentions,
    )


@root_page.post("/endpoint")
@CSRF.exempt
def endpoint() -> ResponseReturnValue:
    """
    Receive and queue a Webmention for verification.

    Existing Webmentions with the same source and target are reset for
    reverification. Concurrent insertion of the same Webmention is handled by
    retrieving and updating the row created by the competing request.

    :return: HTTP 201 response with the Webmention status URL in the
        ``Location`` header, or validation errors with HTTP 400.
    """
    form = forms.EndpointForm(meta={"csrf": False})

    if not form.validate_on_submit():
        return form.errors, 400

    source = cast(str, form.source.data)
    target = cast(str, form.target.data)

    webmention = db.session.execute(
        sa.select(ReceivedWebmention).where(
            ReceivedWebmention.source == source, ReceivedWebmention.target == target
        )
    ).scalar_one_or_none()

    if webmention is None:
        identifier = uuid.uuid7()

        webmention = ReceivedWebmention(uuid=identifier, source=source, target=target)

        db.session.add(webmention)

        try:
            db.session.commit()
        except sa_exc.IntegrityError:
            db.session.rollback()

            # Another request may have inserted the same source/target pair
            # after our SELECT but before our COMMIT.
            webmention = db.session.execute(
                sa.select(ReceivedWebmention).where(
                    ReceivedWebmention.source == source,
                    ReceivedWebmention.target == target,
                )
            ).scalar_one()

            identifier = webmention.uuid
            webmention.status = "received"
            webmention.failure_reason = None

            db.session.commit()

    else:
        identifier = webmention.uuid

        # Re-sent webmention: re-verify the existing row.
        webmention.status = "received"
        webmention.failure_reason = None

        db.session.commit()

    verify_webmention(webmention.uuid)

    status_url = url_for("root.status", identifier=str(identifier), _external=True)

    return Response(status=201, headers={"Location": status_url})


@root_page.route("/status/<uuid:identifier>")
def status(identifier: uuid.UUID) -> ResponseReturnValue:
    """
    Display the verification status of a received Webmention.

    :param identifier: Identifier of the Webmention to display.
    :return: Rendered Webmention status page.
    """
    webmention = db.session.get(ReceivedWebmention, identifier)

    if webmention is None:
        return abort(404)

    return render_template(
        "status.html", title="Webmention status", webmention=webmention
    )