diff options
Diffstat (limited to 'webmentions_ssg')
| -rw-r--r-- | webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py | 71 | ||||
| -rw-r--r-- | webmentions_ssg/models/received.py | 75 | ||||
| -rw-r--r-- | webmentions_ssg/static/styles/style.css | 4 | ||||
| -rw-r--r-- | webmentions_ssg/tasks/retention.py | 7 | ||||
| -rw-r--r-- | webmentions_ssg/tasks/verification.py | 59 | ||||
| -rw-r--r-- | webmentions_ssg/templates/base.html | 2 | ||||
| -rw-r--r-- | webmentions_ssg/templates/received.html | 132 | ||||
| -rw-r--r-- | webmentions_ssg/templates/received_detail.html | 148 | ||||
| -rw-r--r-- | webmentions_ssg/views/endpoint.py | 28 | ||||
| -rw-r--r-- | webmentions_ssg/views/received.py | 82 |
10 files changed, 507 insertions, 101 deletions
diff --git a/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py b/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py new file mode 100644 index 0000000..db63011 --- /dev/null +++ b/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Record received Webmention lifecycle transitions. + +Revision ID: ef8a9b6c2d41 +Revises: a4f91c2e08d7 +""" + +import sqlalchemy as sa +from alembic import op + +revision = "ef8a9b6c2d41" +down_revision = "a4f91c2e08d7" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "received_webmention_status_events", + sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), + sa.Column("webmention_uuid", sa.Uuid(), nullable=False), + sa.Column( + "status", + sa.Enum( + "received", + "verifying", + "verified", + "failed", + "source_removed", + name="received_webmention_status", + native_enum=False, + ), + nullable=False, + ), + sa.Column("action", sa.String(length=80), nullable=False), + sa.Column("failure_reason", sa.Text(), nullable=True), + sa.Column("recovery_attempts", sa.Integer(), nullable=False), + sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint( + ["webmention_uuid"], + ["received_webmentions.uuid"], + ondelete="CASCADE", + ), + ) + op.create_index( + "ix_received_webmention_status_events_webmention_id", + "received_webmention_status_events", + ["webmention_uuid", "id"], + ) + + # Existing rows have no saved transitions; record just the last known state. + op.execute( + sa.text( + """INSERT INTO received_webmention_status_events + (webmention_uuid, status, action, failure_reason, recovery_attempts, occurred_at) + SELECT uuid, status, 'Existing status at upgrade', + failure_reason, recovery_attempts, updated_at + FROM received_webmentions""" + ) + ) + + +def downgrade(): + op.drop_index( + "ix_received_webmention_status_events_webmention_id", + table_name="received_webmention_status_events", + ) + op.drop_table("received_webmention_status_events") diff --git a/webmentions_ssg/models/received.py b/webmentions_ssg/models/received.py index a9047ad..5aa0649 100644 --- a/webmentions_ssg/models/received.py +++ b/webmentions_ssg/models/received.py @@ -8,9 +8,11 @@ from datetime import UTC, datetime from enum import StrEnum from uuid import UUID +import sqlalchemy as sa from sqlalchemy import ( DateTime, Enum, + ForeignKey, Index, Integer, String, @@ -18,9 +20,9 @@ from sqlalchemy import ( UniqueConstraint, Uuid, ) -from sqlalchemy.orm import Mapped, mapped_column, validates +from sqlalchemy.orm import Mapped, mapped_column, relationship, validates -from ..extensions import Base +from ..extensions import Base, db from .utils import source_target_digest, uuid7_to_datetime @@ -83,6 +85,10 @@ class ReceivedWebmention(Base): DateTime(timezone=True), nullable=True, default=None ) + status_events: Mapped[list[ReceivedWebmentionStatusEvent]] = relationship( + back_populates="webmention", cascade="all, delete-orphan" + ) + __table_args__ = ( UniqueConstraint( "source_target_digest", name="uq_webmention_source_target_digest" @@ -129,3 +135,68 @@ class ReceivedWebmention(Base): def created_at(self) -> datetime: """Return the creation time encoded in the Webmention UUID.""" return uuid7_to_datetime(self.uuid) + + +class ReceivedWebmentionStatusEvent(Base): + """A persisted lifecycle transition for a received Webmention. + + Events record observed transitions rather than reconstructing missing history + from the current status. They are private to the authenticated admin view. + """ + + __tablename__ = "received_webmention_status_events" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + webmention_uuid: Mapped[UUID] = mapped_column( + Uuid(as_uuid=True), + ForeignKey("received_webmentions.uuid", ondelete="CASCADE"), + nullable=False, + ) + status: Mapped[ReceivedWebmentionStatus] = mapped_column( + Enum( + ReceivedWebmentionStatus, + name="received_webmention_status", + values_callable=lambda enum_type: [member.value for member in enum_type], + native_enum=False, + ), + nullable=False, + ) + action: Mapped[str] = mapped_column(String(80), nullable=False) + failure_reason: Mapped[str | None] = mapped_column(Text(), nullable=True) + recovery_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0) + occurred_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False + ) + + webmention: Mapped[ReceivedWebmention] = relationship( + back_populates="status_events" + ) + + __table_args__ = ( + Index( + "ix_received_webmention_status_events_webmention_id", + "webmention_uuid", + "id", + ), + ) + + +def purge_orphaned_received_events() -> None: + """Remove status events whose parent Webmention no longer exists. + + Provides a fallback when database-level ON DELETE CASCADE is not + enforced (e.g. SQLite with foreign-key enforcement disabled). + + Run after deleting parent rows in the same transaction so that + events belonging to surviving rows are preserved. + """ + db.session.execute( + sa.delete(ReceivedWebmentionStatusEvent).where( + ~sa.exists( + sa.select(ReceivedWebmention.uuid).where( + ReceivedWebmention.uuid + == ReceivedWebmentionStatusEvent.webmention_uuid + ) + ) + ) + ) diff --git a/webmentions_ssg/static/styles/style.css b/webmentions_ssg/static/styles/style.css new file mode 100644 index 0000000..9668ba5 --- /dev/null +++ b/webmentions_ssg/static/styles/style.css @@ -0,0 +1,4 @@ +.text-pre-formatted { + white-space: pre-wrap; + overflow-wrap: break-word; +} diff --git a/webmentions_ssg/tasks/retention.py b/webmentions_ssg/tasks/retention.py index b4b6a83..09e4cfd 100644 --- a/webmentions_ssg/tasks/retention.py +++ b/webmentions_ssg/tasks/retention.py @@ -11,7 +11,11 @@ from flask import current_app from ..db_helpers import rows_affected from ..extensions import db -from ..models.received import ReceivedWebmention, ReceivedWebmentionStatus +from ..models.received import ( + ReceivedWebmention, + ReceivedWebmentionStatus, + purge_orphaned_received_events, +) def purge_old_received_webmentions() -> int: @@ -41,6 +45,7 @@ def purge_old_received_webmentions() -> int: ReceivedWebmention.updated_at < cutoff, ) ) + purge_orphaned_received_events() db.session.commit() count = rows_affected(result) diff --git a/webmentions_ssg/tasks/verification.py b/webmentions_ssg/tasks/verification.py index ca45777..87e64de 100644 --- a/webmentions_ssg/tasks/verification.py +++ b/webmentions_ssg/tasks/verification.py @@ -15,7 +15,11 @@ from flask import current_app from ..db_helpers import rows_affected from ..extensions import db, huey -from ..models.received import ReceivedWebmention, ReceivedWebmentionStatus +from ..models.received import ( + ReceivedWebmention, + ReceivedWebmentionStatus, + ReceivedWebmentionStatusEvent, +) from ..moderation_policy import rejection_reason from ..net import ( AddressResolutionError, @@ -185,6 +189,15 @@ def claim_for_verification(webmention_uuid: uuid.UUID) -> VerificationClaim | No db.session.rollback() return None + db.session.add( + ReceivedWebmentionStatusEvent( + webmention_uuid=webmention_uuid, + status=ReceivedWebmentionStatus.VERIFYING, + action="Verification started", + occurred_at=claim.lease_started_at, + recovery_attempts=webmention.recovery_attempts, + ) + ) db.session.commit() return claim @@ -234,6 +247,7 @@ def store_verification_outcome( :param reason: Optional explanation for a failed or source-removed Webmention. :returns: ``True`` if the worker still owned the lease and persisted the outcome. """ + at = datetime.now(UTC) changed = db.session.execute( sa.update(ReceivedWebmention) .where( @@ -241,10 +255,29 @@ def store_verification_outcome( ReceivedWebmention.status == ReceivedWebmentionStatus.VERIFYING, ReceivedWebmention.updated_at == claim.lease_started_at, ) - .values(status=status, failure_reason=reason, updated_at=datetime.now(UTC)) + .values(status=status, failure_reason=reason, updated_at=at) + ) + if rows_affected(changed) != 1: + db.session.rollback() + return False + + recovery_attempts = db.session.scalar( + sa.select(ReceivedWebmention.recovery_attempts).where( + ReceivedWebmention.uuid == claim.webmention_uuid + ) + ) + db.session.add( + ReceivedWebmentionStatusEvent( + webmention_uuid=claim.webmention_uuid, + status=status, + action="Verification completed", + occurred_at=at, + failure_reason=reason, + recovery_attempts=recovery_attempts or 0, + ) ) db.session.commit() - return rows_affected(changed) == 1 + return True @huey.task(retries=2, retry_delay=50) @@ -345,6 +378,26 @@ def recover_stale_verifications() -> int: db.session.rollback() continue + db.session.add( + ReceivedWebmentionStatusEvent( + webmention_uuid=identifier, + status=( + ReceivedWebmentionStatus.FAILED + if at_limit + else ReceivedWebmentionStatus.RECEIVED + ), + action=( + "Recovery limit exhausted" + if at_limit + else "Stale verification recovered" + ), + occurred_at=now, + failure_reason=RECOVERY_EXHAUSTED_REASON if at_limit else None, + recovery_attempts=( + recovery_attempts if at_limit else recovery_attempts + 1 + ), + ) + ) db.session.commit() if at_limit: diff --git a/webmentions_ssg/templates/base.html b/webmentions_ssg/templates/base.html index 3395dd5..c7af077 100644 --- a/webmentions_ssg/templates/base.html +++ b/webmentions_ssg/templates/base.html @@ -43,7 +43,7 @@ SPDX-License-Identifier: BSD-3-Clause </a> {% if current_user.is_authenticated %} <div class="navbar-nav flex-row gap-3"> - <a class="nav-link{% if request.endpoint == 'webmentions.received_list' %} active{% endif %}" + <a class="nav-link{% if request.endpoint in ('webmentions.received_list', 'webmentions.received_detail') %} active{% endif %}" href='{{ url_for("webmentions.received_list") }}'>Received</a> <a class="nav-link{% if request.endpoint and request.endpoint.startswith('webmentions.moderation') %} active{% endif %}" href="{{ url_for('webmentions.moderation') }}">Source rules</a> diff --git a/webmentions_ssg/templates/received.html b/webmentions_ssg/templates/received.html index 5fd9866..b8099aa 100644 --- a/webmentions_ssg/templates/received.html +++ b/webmentions_ssg/templates/received.html @@ -160,85 +160,63 @@ SPDX-License-Identifier: BSD-3-Clause data-confirm-class="btn-danger">Delete all declined</button> </div> {% if webmentions.items %} - <table class="table table-bordered table-striped table-hover align-middle"> - <thead> - <tr> - <th scope="col"> - <input type="checkbox" - class="form-check-input" - id="received-select-all" - aria-label="Select all Webmentions on this page"> - </th> - {{ sortable_header('Status', 'status') }} - {{ sortable_header('Source', 'source') }} - {{ sortable_header('Target', 'target') }} - {{ sortable_header('Received', 'received') }} - {{ sortable_header('Updated', 'updated') }} - <th scope="col">Reason</th> - <th scope="col">Actions</th> - </tr> - </thead> - <tbody> - {% for webmention in webmentions %} - {% set style = received_status_presentation.get(webmention.status, {"row_class": "table-danger", "badge_class": "text-bg-danger", "label": "Declined"}) %} - <tr class="{{ style.row_class }}"> - <td> + <div class="table-responsive"> + <table class="table table-bordered table-striped table-hover align-middle"> + <thead> + <tr> + <th scope="col"> <input type="checkbox" - class="form-check-input received-select" - value="{{ webmention.uuid }}" - aria-label="Select webmention {{ webmention.uuid }}"> - </td> - <td><span class="badge {{ style.badge_class }}">{{ style.label }}</span></td> - <td class="text-break"> - <a href="{{ webmention.source }}">{{ webmention.source }}</a> - </td> - <td class="text-break"> - <a href="{{ webmention.target }}">{{ webmention.target }}</a> - </td> - <td class="text-nowrap"> - <time datetime="{{ webmention.created_at.isoformat() }}"> - {{ webmention.created_at.strftime("%Y-%m-%d %H:%M:%S") }} - </time> - </td> - <td class="text-nowrap"> - <time datetime="{{ webmention.updated_at.isoformat() }}"> - {{ webmention.updated_at.strftime("%Y-%m-%d %H:%M:%S") }} - </time> - </td> - <td>{{ webmention.failure_reason or "—" }}</td> - <td class="text-nowrap"> - <button type="button" - class="btn btn-sm btn-primary" - data-bs-toggle="modal" - data-bs-target="#confirmation-modal" - data-action="{{ url_for('webmentions.reverify_received_webmention', webmention_uuid=webmention.uuid, page=webmentions.page, **filters) }}" - data-title="Reverify webmention?" - data-message="The webmention will be fetched and verified again." - data-confirm-label="Reverify" - data-confirm-class="btn-primary">Reverify</button> - <button type="button" - class="btn btn-sm btn-warning" - data-bs-toggle="modal" - data-bs-target="#confirmation-modal" - data-action="{{ url_for('webmentions.block_received_source', webmention_uuid=webmention.uuid, page=webmentions.page, **filters) }}" - data-title="Block this source domain?" - data-message="Future Webmentions from this source hostname and its subdomains will be rejected." - data-confirm-label="Block domain" - data-confirm-class="btn-warning">Block this domain</button> - <button type="button" - class="btn btn-sm btn-danger" - data-bs-toggle="modal" - data-bs-target="#confirmation-modal" - data-action="{{ url_for('webmentions.delete_received_webmention', webmention_uuid=webmention.uuid, page=webmentions.page, **filters) }}" - data-title="Delete webmention?" - data-message="This permanently deletes the webmention and cannot be undone." - data-confirm-label="Delete" - data-confirm-class="btn-danger">Delete</button> - </td> + class="form-check-input" + id="received-select-all" + aria-label="Select all Webmentions on this page"> + </th> + {{ sortable_header('Status', 'status') }} + {{ sortable_header('Source', 'source') }} + {{ sortable_header('Target', 'target') }} + {{ sortable_header('Received', 'received') }} + {{ sortable_header('Updated', 'updated') }} + <th scope="col">Details</th> </tr> - {% endfor %} - </tbody> - </table> + </thead> + <tbody> + {% for webmention in webmentions %} + {% set style = received_status_presentation.get(webmention.status, {"row_class": "table-danger", "badge_class": "text-bg-danger", "label": "Declined"}) %} + <tr class="{{ style.row_class }}"> + <td> + <input type="checkbox" + class="form-check-input received-select" + value="{{ webmention.uuid }}" + aria-label="Select webmention {{ webmention.uuid }}"> + </td> + <td><span class="badge {{ style.badge_class }}">{{ style.label }}</span></td> + <td> + <a href="{{ webmention.source }}">{{ webmention.source }}</a> + </td> + <td> + <a href="{{ webmention.target }}">{{ webmention.target }}</a> + </td> + <td class="text-nowrap"> + <time datetime="{{ webmention.created_at.isoformat() }}" + title="{{ webmention.created_at.strftime('%Y-%m-%d %H:%M:%S') }} UTC"> + {{ webmention.created_at.strftime("%Y-%m-%d %H:%M:%S") }} + </time> + </td> + <td class="text-nowrap"> + <time datetime="{{ webmention.updated_at.isoformat() }}" + title="{{ webmention.updated_at.strftime('%Y-%m-%d %H:%M:%S') }} UTC"> + {{ webmention.updated_at.strftime("%Y-%m-%d %H:%M:%S") }} + </time> + </td> + <td> + <a class="btn btn-sm btn-primary" + href="{{ url_for('webmentions.received_detail', webmention_uuid=webmention.uuid, page=webmentions.page, **filters) }}" + aria-label="Details for Webmention {{ webmention.uuid }}">Details</a> + </td> + </tr> + {% endfor %} + </tbody> + </table> + </div> {% if webmentions.pages > 1 %} <div class="mt-3">{{ render_pagination(webmentions, args=filters) }}</div> {% endif %} diff --git a/webmentions_ssg/templates/received_detail.html b/webmentions_ssg/templates/received_detail.html new file mode 100644 index 0000000..091e2e4 --- /dev/null +++ b/webmentions_ssg/templates/received_detail.html @@ -0,0 +1,148 @@ +<!-- +SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> + +SPDX-License-Identifier: BSD-3-Clause +--> +{% extends "base.html" %} + +{% set status_presentation = { + "received": { + "badge": "text-bg-info", + "label": "Pending" + }, + "verifying": { + "badge": "text-bg-warning", + "label": "Verifying" + }, + "verified": { + "badge": "text-bg-success", + "label": "Verified" + }, + "failed": { + "badge": "text-bg-danger", + "label": "Declined (failed)" + }, + "source_removed": { + "badge": "text-bg-danger", + "label": "Declined (source removed)" + } +} %} + +{% block styles %} + {{ super() }} + <link rel="stylesheet" + href="{{ url_for('static', filename='styles/style.css') }}"> +{% endblock %} + +{% block content %} + <div class="mb-3"> + <a href="{{ url_for('webmentions.received_list', page=page, **filters) }}">← Back to received Webmentions</a> + </div> + <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4"> + <h1 class="mb-0">Received Webmention</h1> + {% set style = status_presentation.get(webmention.status, {"badge": "text-bg-secondary", "label": "Unknown"}) %} + <span class="badge fs-6 {{ style.badge }}">{{ style.label }}</span> + </div> + <section aria-labelledby="mention-details-heading" class="card mb-4"> + <div class="card-body"> + <h2 id="mention-details-heading" class="h4 card-title mb-3">Details</h2> + <dl class="row mb-0"> + <dt class="col-md-3">Source</dt> + <dd class="col-md-9 text-break"> + <a href="{{ webmention.source }}">{{ webmention.source }}</a> + </dd> + <dt class="col-md-3">Target</dt> + <dd class="col-md-9 text-break"> + <a href="{{ webmention.target }}">{{ webmention.target }}</a> + </dd> + <dt class="col-md-3">Received</dt> + <dd class="col-md-9"> + <time datetime="{{ webmention.created_at.isoformat() }}">{{ webmention.created_at.strftime("%Y-%m-%d %H:%M:%S") }} UTC</time> + </dd> + <dt class="col-md-3">Last updated</dt> + <dd class="col-md-9"> + <time datetime="{{ webmention.updated_at.isoformat() }}">{{ webmention.updated_at.strftime("%Y-%m-%d %H:%M:%S") }} UTC</time> + </dd> + <dt class="col-md-3">Recovery attempts</dt> + <dd class="col-md-9"> + {{ webmention.recovery_attempts }} <span class="text-body-secondary small">(automatic stale-verification recoveries; resets when verification is explicitly reopened)</span> + </dd> + <dt class="col-md-3">Webmention ID</dt> + <dd class="col-md-9"> + <code class="text-break">{{ webmention.uuid }}</code> + </dd> + <dt class="col-md-3">Public status</dt> + <dd class="col-md-9"> + <a href="{{ url_for('webmentions.webmention_status', identifier=webmention.uuid, _external=True) }}">View public status page</a> + </dd> + <dt class="col-md-3">Failure reason</dt> + <dd class="col-md-9"> + {% if webmention.failure_reason %} + <div class="text-break text-pre-formatted">{{ webmention.failure_reason }}</div> + {% else %} + <span class="text-body-secondary">None</span> + {% endif %} + </dd> + </dl> + </div> + </section> + <div class="d-flex flex-wrap gap-2 mb-4" aria-label="Webmention actions"> + <button type="button" + class="btn btn-sm btn-primary" + data-bs-toggle="modal" + data-bs-target="#confirmation-modal" + data-action="{{ url_for('webmentions.reverify_received_webmention', webmention_uuid=webmention.uuid, return_to='detail', page=page, **filters) }}" + data-title="Reverify webmention?" + data-message="The webmention will be fetched and verified again." + data-confirm-label="Reverify" + data-confirm-class="btn-primary">Reverify</button> + <button type="button" + class="btn btn-sm btn-warning" + data-bs-toggle="modal" + data-bs-target="#confirmation-modal" + data-action="{{ url_for('webmentions.block_received_source', webmention_uuid=webmention.uuid, return_to='detail', page=page, **filters) }}" + data-title="Block this source domain?" + data-message="Future Webmentions from this source hostname and its subdomains will be rejected." + data-confirm-label="Block domain" + data-confirm-class="btn-warning">Block this domain</button> + <button type="button" + class="btn btn-sm btn-danger" + data-bs-toggle="modal" + data-bs-target="#confirmation-modal" + data-action="{{ url_for('webmentions.delete_received_webmention', webmention_uuid=webmention.uuid, page=page, **filters) }}" + data-title="Delete webmention?" + data-message="This permanently deletes the webmention and cannot be undone." + data-confirm-label="Delete" + data-confirm-class="btn-danger">Delete</button> + </div> + <section aria-labelledby="status-history-heading"> + <h2 class="h4 mb-3" id="status-history-heading">Status history</h2> + {% if history %} + <ol class="list-group list-group-numbered mb-3"> + {% for event in history %} + {% set event_style = status_presentation.get(event.status, {"badge": "text-bg-secondary", "label": "Unknown"}) %} + <li class="list-group-item"> + <div class="d-flex flex-wrap align-items-center gap-2 mb-1"> + <span class="badge {{ event_style.badge }}">{{ event_style.label }}</span> + <strong>{{ event.action }}</strong> + <time class="ms-auto text-body-secondary small" + datetime="{{ event.occurred_at.isoformat() }}">{{ event.occurred_at.strftime("%Y-%m-%d %H:%M:%S") }} UTC</time> + </div> + <div class="small text-body-secondary">Recovery attempts: {{ event.recovery_attempts }}</div> + {% if event.failure_reason %} + <div class="mt-2 text-break text-pre-formatted">{{ event.failure_reason }}</div> + {% endif %} + </li> + {% endfor %} + </ol> + {% else %} + <p class="text-body-secondary">No historical transitions were recorded for this Webmention. Its current status appears above.</p> + {% endif %} + </section> + {% include "includes/confirmation_modal.html" %} +{% endblock %} + +{% block scripts %} + {{ super() }} + <script src="{{ url_for('static', filename='js/confirmation-modal.js') }}"></script> +{% endblock %} diff --git a/webmentions_ssg/views/endpoint.py b/webmentions_ssg/views/endpoint.py index 322e0f0..36c4693 100644 --- a/webmentions_ssg/views/endpoint.py +++ b/webmentions_ssg/views/endpoint.py @@ -17,7 +17,11 @@ from flask.typing import ResponseReturnValue from ..db_helpers import rows_affected from ..extensions import csrf, db, limiter from ..forms.endpoint import WebmentionSubmissionForm -from ..models.received import ReceivedWebmention +from ..models.received import ( + ReceivedWebmention, + ReceivedWebmentionStatus, + ReceivedWebmentionStatusEvent, +) from ..models.utils import source_target_digest from ..moderation_policy import rejection_reason from ..tasks.verification import verify_webmention @@ -66,6 +70,14 @@ def try_insert_received_webmention( """ webmention = ReceivedWebmention(uuid=uuid.uuid7(), source=source, target=target) db.session.add(webmention) + webmention.status_events.append( + ReceivedWebmentionStatusEvent( + webmention_uuid=webmention.uuid, + status=ReceivedWebmentionStatus.RECEIVED, + action="Received submission", + occurred_at=webmention.created_at, + ) + ) try: db.session.commit() @@ -98,8 +110,20 @@ def reopen_if_cooldown_elapsed(webmention: ReceivedWebmention) -> bool: .values(ReceivedWebmention.reopen_verification_values(at=now)) .execution_options(synchronize_session=False) ) + if rows_affected(result) != 1: + db.session.rollback() + return False + + db.session.add( + ReceivedWebmentionStatusEvent( + webmention_uuid=webmention.uuid, + status=ReceivedWebmentionStatus.RECEIVED, + action="Resubmitted after cooldown", + occurred_at=now, + ) + ) db.session.commit() - return rows_affected(result) == 1 + return True def record_submission(source: str, target: str) -> tuple[uuid.UUID, bool] | None: diff --git a/webmentions_ssg/views/received.py b/webmentions_ssg/views/received.py index 7d633ab..84c5750 100644 --- a/webmentions_ssg/views/received.py +++ b/webmentions_ssg/views/received.py @@ -22,7 +22,12 @@ from ..forms.received import ( ReceivedWebmentionFilterForm, default_received_page_size, ) -from ..models.received import ReceivedWebmention, ReceivedWebmentionStatus +from ..models.received import ( + ReceivedWebmention, + ReceivedWebmentionStatus, + ReceivedWebmentionStatusEvent, + purge_orphaned_received_events, +) from ..moderation_policy import domain_from_url from ..tasks.verification import verify_webmention from .blueprint import webmentions_bp @@ -169,6 +174,46 @@ def received_list() -> ResponseReturnValue: ) +@webmentions_bp.get("/received/<uuid:webmention_uuid>") +@login_required +def received_detail(webmention_uuid: uuid.UUID) -> ResponseReturnValue: + """Display a private received Webmention detail and its recorded history.""" + filters = received_filter_args(received_filter_form()) + webmention = db.get_or_404(ReceivedWebmention, webmention_uuid) + history = db.session.scalars( + sa.select(ReceivedWebmentionStatusEvent) + .where(ReceivedWebmentionStatusEvent.webmention_uuid == webmention_uuid) + .order_by(ReceivedWebmentionStatusEvent.id.desc()) + ).all() + page = request.args.get("page", 1, type=int) + return render_template( + "received_detail.html", + title="Received Webmention details", + webmention=webmention, + history=history, + filters=filters, + page=page, + action_form=ConfirmActionForm(), + ) + + +def received_action_redirect( + webmention_uuid: uuid.UUID, filters: ReceivedFilterArgs +) -> ResponseReturnValue: + """Return to details for detail actions, otherwise to the filtered list.""" + page = request.args.get("page", 1, type=int) + if request.args.get("return_to") == "detail": + return redirect( + url_for( + "webmentions.received_detail", + webmention_uuid=webmention_uuid, + page=page, + **filters, + ) + ) + return redirect(url_for("webmentions.received_list", page=page, **filters)) + + @webmentions_bp.post("/received/<uuid:webmention_uuid>/delete") @login_required def delete_received_webmention(webmention_uuid: uuid.UUID) -> ResponseReturnValue: @@ -214,6 +259,14 @@ def reverify_received_webmention(webmention_uuid: uuid.UUID) -> ResponseReturnVa webmention = db.get_or_404(ReceivedWebmention, webmention_uuid) webmention.reopen_verification() + db.session.add( + ReceivedWebmentionStatusEvent( + webmention_uuid=webmention_uuid, + status=ReceivedWebmentionStatus.RECEIVED, + action="Manually queued for reverification", + occurred_at=webmention.updated_at, + ) + ) db.session.commit() @@ -221,13 +274,7 @@ def reverify_received_webmention(webmention_uuid: uuid.UUID) -> ResponseReturnVa flash(f"Webmention {webmention.uuid} queued for reverification.", "success") - return redirect( - url_for( - "webmentions.received_list", - page=request.args.get("page", 1, type=int), - **filters, - ) - ) + return received_action_redirect(webmention_uuid, filters) def selected_received_webmentions() -> list[ReceivedWebmention]: @@ -274,6 +321,14 @@ def reverify_selected_received_webmentions() -> ResponseReturnValue: identifiers = [webmention.uuid for webmention in webmentions] for webmention in webmentions: webmention.reopen_verification() + db.session.add( + ReceivedWebmentionStatusEvent( + webmention_uuid=webmention.uuid, + status=ReceivedWebmentionStatus.RECEIVED, + action="Manually queued for reverification", + occurred_at=webmention.updated_at, + ) + ) db.session.commit() for identifier in identifiers: @@ -301,6 +356,8 @@ def delete_selected_received_webmentions() -> ResponseReturnValue: for webmention in webmentions: db.session.delete(webmention) + db.session.flush() + purge_orphaned_received_events() db.session.commit() flash(f"{len(webmentions)} Webmentions deleted.", "success") @@ -326,6 +383,7 @@ def delete_all_declined_received_webmentions() -> ResponseReturnValue: ReceivedWebmention.status.in_(RECEIVED_STATUS_FILTERS["declined"]) ) ) + purge_orphaned_received_events() db.session.commit() count = rows_affected(result) @@ -382,10 +440,4 @@ def block_received_source(webmention_uuid: uuid.UUID) -> ResponseReturnValue: block_domains({domain}) flash(f"Source domain {domain} blocked.", "success") - return redirect( - url_for( - "webmentions.received_list", - page=request.args.get("page", 1, type=int), - **filters, - ) - ) + return received_action_redirect(webmention_uuid, filters) |
