aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg
diff options
context:
space:
mode:
authorDennis Fink2026-11-12 22:07:12 +0100
committerDennis Fink2026-11-12 22:07:12 +0100
commitc7993952c585b66acad5275e39dbf91cf662b975 (patch)
tree976b3746444b3bd0bbb269bef9197c8b6a2e1696 /webmentions_ssg
parentb930b4425b91aa42abcec6c3443685065a5ca242 (diff)
downloadwebmentions-ssg-c7993952c585b66acad5275e39dbf91cf662b975.tar.gz
webmentions-ssg-c7993952c585b66acad5275e39dbf91cf662b975.zip
chore(core): enable stricter Ruff lint rules
Expand Ruff checks for bugbear, complexity, pathlib, return statements, simplifications, upgrades, and docstring style. Apply the resulting behavior-neutral cleanup across application and test code.
Diffstat (limited to 'webmentions_ssg')
-rw-r--r--webmentions_ssg/__init__.py7
-rw-r--r--webmentions_ssg/auth.py3
-rw-r--r--webmentions_ssg/cli.py15
-rw-r--r--webmentions_ssg/forms.py32
-rw-r--r--webmentions_ssg/models.py61
-rw-r--r--webmentions_ssg/net.py11
-rw-r--r--webmentions_ssg/tasks/consumer.py3
-rw-r--r--webmentions_ssg/tasks/discovery.py18
-rw-r--r--webmentions_ssg/tasks/extension.py40
-rw-r--r--webmentions_ssg/tasks/mentions.py7
-rw-r--r--webmentions_ssg/tasks/notifications.py1
-rw-r--r--webmentions_ssg/tasks/receiver.py14
-rw-r--r--webmentions_ssg/tasks/retention.py9
-rw-r--r--webmentions_ssg/tasks/scanner.py11
-rw-r--r--webmentions_ssg/tasks/sender.py6
-rw-r--r--webmentions_ssg/tasks/source_parser.py32
-rw-r--r--webmentions_ssg/views/admin.py21
-rw-r--r--webmentions_ssg/views/endpoint.py6
-rw-r--r--webmentions_ssg/views/session.py9
19 files changed, 111 insertions, 195 deletions
diff --git a/webmentions_ssg/__init__.py b/webmentions_ssg/__init__.py
index 63e9f13..46b78ea 100644
--- a/webmentions_ssg/__init__.py
+++ b/webmentions_ssg/__init__.py
@@ -25,8 +25,7 @@ from .views import register_routes
def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
- """
- Create and configure the Flask application.
+ """Create and configure the Flask application.
The application configuration is selected based on the development
environment unless an explicit configuration class is provided. Logging,
@@ -37,7 +36,6 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
development or production configuration automatically.
:return: Configured Flask application.
"""
-
development = os.environ.get("WEBMENTIONS_SSG_DEV", "").lower() in {
"1",
"true",
@@ -120,8 +118,7 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
@app.context_processor
def inject_version():
- """
- Add the application version to the template context.
+ """Add the application version to the template context.
:return: Template context containing the application version.
"""
diff --git a/webmentions_ssg/auth.py b/webmentions_ssg/auth.py
index 633aa82..b943404 100644
--- a/webmentions_ssg/auth.py
+++ b/webmentions_ssg/auth.py
@@ -44,8 +44,7 @@ def validate_password(password: str) -> None:
@AUTH.user_loader
def load_user(session_id: str) -> User | None:
- """
- Load a user from the database by identifier.
+ """Load a user from the database by identifier.
:param session_id: Database ID and password-hash fingerprint stored in the session.
:return: Matching user, or ``None`` if no user exists with the identifier.
diff --git a/webmentions_ssg/cli.py b/webmentions_ssg/cli.py
index 0387ba6..0fed7dd 100644
--- a/webmentions_ssg/cli.py
+++ b/webmentions_ssg/cli.py
@@ -22,7 +22,6 @@ USERS_CLI = AppGroup("users", help="Manage users.")
def _require_user(username: str):
"""Return a user by username or report a CLI-friendly error."""
-
user = DATABASE.session.scalar(sa.select(User).where(User.username == username))
if user is None:
raise click.ClickException(f"User {username!r} does not exist.")
@@ -33,14 +32,12 @@ def _require_user(username: str):
@click.option("--username", prompt="Username", help="Username for the new user.")
@click.password_option(confirmation_prompt=True)
def create_user(username: str, password: str) -> None:
- """
- Create a user with a securely hashed password.
+ """Create a user with a securely hashed password.
:param username: Username for the new user.
:param password: Plain-text password to hash and store.
:raises click.ClickException: If the credentials are invalid or the user exists.
"""
-
username = username.strip()
if not username:
raise click.ClickException("Username must not be empty.")
@@ -66,7 +63,6 @@ def create_user(username: str, password: str) -> None:
@USERS_CLI.command("list", help="List registered users.")
def list_users() -> None:
"""List user IDs and usernames in alphabetical order."""
-
users = DATABASE.session.scalars(sa.select(User).order_by(User.username)).all()
if not users:
click.echo("No users found.")
@@ -81,8 +77,7 @@ def list_users() -> None:
@click.argument("username")
@click.password_option(confirmation_prompt=True)
def set_user_password(username: str, password: str) -> None:
- """
- Change a user's password without displaying it.
+ """Change a user's password without displaying it.
:param username: Username of the account to update.
:param password: New plain-text password to hash and store.
@@ -103,8 +98,7 @@ def set_user_password(username: str, password: str) -> None:
@click.argument("username")
@click.option("-y", "--yes", is_flag=True, help="Skip the deletion confirmation.")
def delete_user(username: str, yes: bool) -> None:
- """
- Permanently delete a user after confirmation, unless --yes is passed.
+ """Permanently delete a user after confirmation, unless --yes is passed.
:param username: Username of the account to remove.
:param yes: Whether to skip the confirmation prompt.
@@ -127,8 +121,7 @@ MAIL_CLI = AppGroup("mail", help="Handle mail")
"--to", "recipient", help="Recipient address (defaults to NOTIFICATION_EMAIL)."
)
def send_test_mail(recipient: str | None) -> None:
- """
- Send a test email using the configured SMTP server.
+ """Send a test email using the configured SMTP server.
:param recipient: Optional recipient overriding NOTIFICATION_EMAIL.
:raises click.ClickException: If configuration is missing or sending fails.
diff --git a/webmentions_ssg/forms.py b/webmentions_ssg/forms.py
index a721dc6..d557907 100644
--- a/webmentions_ssg/forms.py
+++ b/webmentions_ssg/forms.py
@@ -73,16 +73,14 @@ class HTTPXURL:
class NotEqualTo:
- """
- Validate that a field does not equal another field.
+ """Validate that a field does not equal another field.
:param fieldname: Name of the field to compare against.
:param message: Optional validation error message.
"""
def __init__(self, fieldname: str, message: str | None = None) -> None:
- """
- Initialize the validator.
+ """Initialize the validator.
:param fieldname: Name of the field to compare against.
:param message: Optional validation error message.
@@ -91,8 +89,7 @@ class NotEqualTo:
self.message = message
def __call__(self, form: BaseForm, field: Field) -> None:
- """
- Validate that two fields do not contain equal values.
+ """Validate that two fields do not contain equal values.
:param form: Form containing the fields to compare.
:param field: Field being validated.
@@ -110,8 +107,7 @@ class NotEqualTo:
return
d = {
- "other_label": hasattr(other, "label")
- and other.label.text
+ "other_label": (hasattr(other, "label") and other.label.text)
or self.fieldname,
"other_name": self.fieldname,
}
@@ -122,23 +118,20 @@ class NotEqualTo:
class AllowedHostname:
- """
- Validate that a URL uses an allowed hostname.
+ """Validate that a URL uses an allowed hostname.
:param message: Optional validation error message.
"""
def __init__(self, message: str | None = None) -> None:
- """
- Initialize the validator.
+ """Initialize the validator.
:param message: Optional validation error message.
"""
self.message = message
def __call__(self, form: BaseForm, field: Field) -> None:
- """
- Validate that a URL uses an allowed hostname.
+ """Validate that a URL uses an allowed hostname.
:param form: Form containing the field.
:param field: Field containing the URL to validate.
@@ -175,9 +168,7 @@ class PublicIPLiteral:
class LoginForm(FlaskForm):
- """
- Form for authenticating a user.
- """
+ """Form for authenticating a user."""
username = StringField("Username", validators=[InputRequired()])
password = PasswordField("Password", validators=[InputRequired()])
@@ -185,8 +176,7 @@ class LoginForm(FlaskForm):
class EndpointForm(FlaskForm):
- """
- Form for receiving a Webmention.
+ """Form for receiving a Webmention.
The source must be a public HTTP or HTTPS URL distinct from the target.
The target must be an HTTP or HTTPS URL using an allowed hostname.
@@ -226,8 +216,6 @@ class EndpointForm(FlaskForm):
class AdminActionForm(FlaskForm):
- """
- Form for confirming an administrative action.
- """
+ """Form for confirming an administrative action."""
submit = SubmitField("Confirm")
diff --git a/webmentions_ssg/models.py b/webmentions_ssg/models.py
index 9442309..48d8532 100644
--- a/webmentions_ssg/models.py
+++ b/webmentions_ssg/models.py
@@ -43,9 +43,7 @@ class ReceivedStatus(StrEnum):
class SentWebmentionStatus(StrEnum):
- """
- Represent the outcome of a Webmention send attempt.
- """
+ """Represent the outcome of a Webmention send attempt."""
SENT = "sent"
UNSUPPORTED = "unsupported"
@@ -53,9 +51,7 @@ class SentWebmentionStatus(StrEnum):
class User(UserMixin, Base):
- """
- Represent an authenticated application user.
- """
+ """Represent an authenticated application user."""
__tablename__ = "users"
@@ -64,8 +60,7 @@ class User(UserMixin, Base):
password_hash: Mapped[str] = mapped_column(Text(), nullable=False)
def __repr__(self) -> str:
- """
- Return a developer-readable representation of the user.
+ """Return a developer-readable representation of the user.
:return: Representation containing the username.
"""
@@ -73,8 +68,7 @@ class User(UserMixin, Base):
@property
def password(self) -> Never:
- """
- Prevent access to the user's plain-text password.
+ """Prevent access to the user's plain-text password.
:raises AttributeError: Always, because the password is write-only.
"""
@@ -82,8 +76,7 @@ class User(UserMixin, Base):
@password.setter
def password(self, password: str) -> None:
- """
- Hash and store a new password.
+ """Hash and store a new password.
:param password: Plain-text password to hash.
"""
@@ -100,8 +93,7 @@ class User(UserMixin, Base):
return f"{self.id}:{fingerprint}"
def check_password(self, password: str) -> bool:
- """
- Check a plain-text password against the stored password hash.
+ """Check a plain-text password against the stored password hash.
:param password: Plain-text password to check.
:return: Whether the password matches the stored hash.
@@ -110,9 +102,7 @@ class User(UserMixin, Base):
class ReceivedWebmention(Base):
- """
- Represent a Webmention received for verification.
- """
+ """Represent a Webmention received for verification."""
__tablename__ = "received_webmentions"
@@ -159,8 +149,7 @@ class ReceivedWebmention(Base):
)
def __repr__(self) -> str:
- """
- Return a developer-readable representation of the received Webmention.
+ """Return a developer-readable representation of the received Webmention.
:return: Representation containing the identifier, source, and target.
"""
@@ -186,8 +175,7 @@ class ReceivedWebmention(Base):
@property
def verified(self) -> bool:
- """
- Return whether the Webmention has been successfully verified.
+ """Return whether the Webmention has been successfully verified.
:return: Whether the Webmention status is ``verified``.
"""
@@ -195,8 +183,7 @@ class ReceivedWebmention(Base):
@property
def created_at(self) -> datetime:
- """
- Return the creation time encoded in the Webmention UUID.
+ """Return the creation time encoded in the Webmention UUID.
:return: Creation time as a timezone-aware datetime.
"""
@@ -204,9 +191,7 @@ class ReceivedWebmention(Base):
class Source(Base):
- """
- Represent a generated source document containing outgoing Webmentions.
- """
+ """Represent a generated source document containing outgoing Webmentions."""
__tablename__ = "sources"
@@ -235,8 +220,7 @@ class Source(Base):
)
def __repr__(self) -> str:
- """
- Return a developer-readable representation of the source.
+ """Return a developer-readable representation of the source.
:return: Representation containing the identifier and public URL.
"""
@@ -244,8 +228,7 @@ class Source(Base):
@property
def created_at(self) -> datetime:
- """
- Return the creation time encoded in the source UUID.
+ """Return the creation time encoded in the source UUID.
:return: Creation time as a timezone-aware datetime.
"""
@@ -253,9 +236,7 @@ class Source(Base):
class SentWebmention(Base):
- """
- Represent an outgoing Webmention associated with a source.
- """
+ """Represent an outgoing Webmention associated with a source."""
__tablename__ = "sent_webmentions"
@@ -331,8 +312,7 @@ class SentWebmention(Base):
)
def __repr__(self) -> str:
- """
- Return a developer-readable representation of the sent Webmention.
+ """Return a developer-readable representation of the sent Webmention.
:return: Representation containing the identifier and target URL.
"""
@@ -346,6 +326,7 @@ class SentWebmention(Base):
self.active = active
self.attempt_count = 0
self.next_retry_at = None
+
if resend:
self.processed_revision = None
self.status = None
@@ -353,12 +334,12 @@ class SentWebmention(Base):
self.endpoint = None
self.response_status = None
self.status_url = None
+
return self
@property
def pending(self) -> bool:
- """
- Return whether the Webmention has an unprocessed source revision.
+ """Return whether the Webmention has an unprocessed source revision.
:return: Whether the desired revision still requires processing.
"""
@@ -369,8 +350,7 @@ class SentWebmention(Base):
@property
def created_at(self) -> datetime:
- """
- Return the creation time encoded in the Webmention UUID.
+ """Return the creation time encoded in the Webmention UUID.
:return: Creation time as a timezone-aware datetime.
"""
@@ -378,8 +358,7 @@ class SentWebmention(Base):
def uuid7_to_datetime(identifier: uuid.UUID) -> datetime:
- """
- Convert a UUID version 7 timestamp to a datetime.
+ """Convert a UUID version 7 timestamp to a datetime.
:param identifier: UUID whose embedded timestamp should be converted.
:return: Timestamp as a timezone-aware UTC datetime.
diff --git a/webmentions_ssg/net.py b/webmentions_ssg/net.py
index 01a9a80..b88e2d8 100644
--- a/webmentions_ssg/net.py
+++ b/webmentions_ssg/net.py
@@ -110,21 +110,28 @@ class PublicNetworkBackend(httpcore.SyncBackend):
else socket.AF_INET
)
sock = socket.socket(family, socket.SOCK_STREAM)
+
try:
sock.settimeout(
self._deadline.timeout(timeout, httpcore.ConnectTimeout)
)
+
if local_address is not None:
sock.bind((local_address, 0))
+
for option in socket_options or ():
sock.setsockopt(*option)
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+
# This numeric address is the *same* address just validated;
# no getaddrinfo or DNS resolver runs between check and connect.
sock.connect((address, port))
+
return DeadlineStream(SyncStream(sock), self._deadline)
except (TimeoutError, OSError) as exc:
sock.close()
+
if isinstance(exc, TimeoutError):
last_error = httpcore.ConnectTimeout(str(exc))
else:
@@ -157,6 +164,7 @@ def build_client(user_agent: str, *, accept: str | None = None) -> httpx.Client:
headers = {"User-Agent": user_agent}
if accept is not None:
headers["Accept"] = accept
+
return httpx.Client(
headers=headers,
timeout=httpx.Timeout(current_app.config["REQUEST_TIMEOUT"]),
@@ -225,8 +233,7 @@ def public_addresses(
def is_http_url(url: str) -> bool:
- """
- Check whether a URL is an absolute HTTP or HTTPS URL.
+ """Check whether a URL is an absolute HTTP or HTTPS URL.
:param url: URL to validate.
:return: Whether the URL uses HTTP or HTTPS and contains a hostname.
diff --git a/webmentions_ssg/tasks/consumer.py b/webmentions_ssg/tasks/consumer.py
index bf7189f..9010ef7 100644
--- a/webmentions_ssg/tasks/consumer.py
+++ b/webmentions_ssg/tasks/consumer.py
@@ -10,8 +10,7 @@ from .. import HUEY, create_app
def create_consumer() -> Huey:
- """
- Create and configure the Huey consumer.
+ """Create and configure the Huey consumer.
The application is initialized, task modules are imported to register their
tasks, and periodic scanner, notification and verification recovery tasks
diff --git a/webmentions_ssg/tasks/discovery.py b/webmentions_ssg/tasks/discovery.py
index 98f3fd5..ddf5817 100644
--- a/webmentions_ssg/tasks/discovery.py
+++ b/webmentions_ssg/tasks/discovery.py
@@ -30,8 +30,7 @@ class PermanentSenderError(SenderError):
def resolve_endpoint(response: httpx.Response, href: str) -> str:
- """
- Resolve and validate a discovered Webmention endpoint.
+ """Resolve and validate a discovered Webmention endpoint.
:param response: Response from which the endpoint was discovered.
:param href: Endpoint reference to resolve.
@@ -51,8 +50,7 @@ def resolve_endpoint(response: httpx.Response, href: str) -> str:
def parse_link_value(value: str) -> tuple[str, set[str]] | None:
- """
- Parse a Link header value into its target and relations.
+ """Parse a Link header value into its target and relations.
:param value: Link header value to parse.
:return: Link target and relation names, or ``None`` if the value is invalid.
@@ -81,8 +79,7 @@ def parse_link_value(value: str) -> tuple[str, set[str]] | None:
def endpoint_from_headers(response: httpx.Response) -> str | None:
- """
- Find a Webmention endpoint in the response Link headers.
+ """Find a Webmention endpoint in the response Link headers.
:param response: HTTP response whose headers should be inspected.
:return: First valid advertised Webmention endpoint, or ``None`` if none
@@ -105,8 +102,7 @@ def endpoint_from_headers(response: httpx.Response) -> str | None:
def endpoint_from_html(response: httpx.Response, body: bytes) -> str | None:
- """
- Find a Webmention endpoint in an HTML document.
+ """Find a Webmention endpoint in an HTML document.
``link`` and ``a`` elements are inspected in document order.
@@ -156,8 +152,7 @@ def read_target_body(response: httpx.Response) -> bytes:
def discover_webmention_endpoint(client: httpx.Client, target: str) -> str | None:
- """
- Discover the Webmention endpoint advertised by a target URL.
+ """Discover the Webmention endpoint advertised by a target URL.
Endpoint discovery first checks the response to a HEAD request and then falls
back to a GET request, inspecting both HTTP Link headers and supported HTML
@@ -202,8 +197,7 @@ def discover_webmention_endpoint(client: httpx.Client, target: str) -> str | Non
def post_webmention(
client: httpx.Client, *, endpoint: str, source: str, target: str
) -> tuple[int, str | None]:
- """
- Send a Webmention to a discovered endpoint.
+ """Send a Webmention to a discovered endpoint.
:param client: HTTP client to use for the request.
:param endpoint: Webmention endpoint URL.
diff --git a/webmentions_ssg/tasks/extension.py b/webmentions_ssg/tasks/extension.py
index 9f53f3b..f7072b2 100644
--- a/webmentions_ssg/tasks/extension.py
+++ b/webmentions_ssg/tasks/extension.py
@@ -20,16 +20,14 @@ R = TypeVar("R")
class Huey:
- """
- Provide Flask integration for a Huey instance.
+ """Provide Flask integration for a Huey instance.
The extension initializes a Huey backend from the Flask configuration and
wraps tasks so that they execute within an application context.
"""
def __init__(self, app: Flask | None = None) -> None:
- """
- Initialize the Huey extension.
+ """Initialize the Huey extension.
:param app: Flask application to initialize immediately, if provided.
"""
@@ -40,8 +38,7 @@ class Huey:
self.init_app(app)
def init_app(self, app: Flask) -> None:
- """
- Initialize Huey for a Flask application.
+ """Initialize Huey for a Flask application.
The backend and its storage options are derived from ``HUEY_URL`` and the
resulting extension is registered with the application.
@@ -80,8 +77,7 @@ class Huey:
@property
def huey(self) -> BaseHuey:
- """
- Return the initialized Huey instance.
+ """Return the initialized Huey instance.
:return: Configured Huey backend instance.
:raises RuntimeError: If the extension has not been initialized.
@@ -128,8 +124,7 @@ class Huey:
return decorator
def __getattr__(self, name: str) -> Any:
- """
- Forward an unknown attribute to the underlying Huey instance.
+ """Forward an unknown attribute to the underlying Huey instance.
:param name: Name of the attribute to retrieve.
:return: Attribute from the initialized Huey instance.
@@ -139,8 +134,7 @@ class Huey:
@staticmethod
def backend_from_url(url: str) -> tuple[type[BaseHuey], dict[str, Any]]:
- """
- Determine the Huey backend and storage options from a URL.
+ """Determine the Huey backend and storage options from a URL.
:param url: Huey backend URL.
:return: Huey backend class and keyword arguments for its storage backend.
@@ -157,20 +151,22 @@ class Huey:
from huey import PriorityRedisExpireHuey
return PriorityRedisExpireHuey, {"url": fixed_url}
- elif scheme.endswith("priority"):
+
+ if scheme.endswith("priority"):
from huey import PriorityRedisHuey
return PriorityRedisHuey, {"url": fixed_url}
- elif scheme.endswith("expire"):
+
+ if scheme.endswith("expire"):
from huey import RedisExpireHuey
return RedisExpireHuey, {"url": fixed_url}
- else:
- from huey import RedisHuey
- return RedisHuey, {"url": url}
+ from huey import RedisHuey
+
+ return RedisHuey, {"url": url}
- elif scheme == "sqlite":
+ if scheme == "sqlite":
from huey import SqliteHuey
prefix = "sqlite:///"
@@ -187,7 +183,7 @@ class Huey:
return SqliteHuey, {"filename": filename}
- elif scheme == "file":
+ if scheme == "file":
from huey import FileHuey
prefix = "file:///"
@@ -204,17 +200,17 @@ class Huey:
return FileHuey, {"path": path}
- elif scheme in {"postgres", "postgresql"}:
+ if scheme in {"postgres", "postgresql"}:
from huey import PostgresHuey
return PostgresHuey, {"dsn": url}
- elif scheme == "memory":
+ if scheme == "memory":
from huey import MemoryHuey
return MemoryHuey, {}
- elif scheme == "blackhole":
+ if scheme == "blackhole":
from huey import BlackHoleHuey
return BlackHoleHuey, {}
diff --git a/webmentions_ssg/tasks/mentions.py b/webmentions_ssg/tasks/mentions.py
index 4e5a5ca..42dd0b6 100644
--- a/webmentions_ssg/tasks/mentions.py
+++ b/webmentions_ssg/tasks/mentions.py
@@ -31,8 +31,7 @@ HTML_URL_ATTRIBUTES = {
def html_mentions_target(body: bytes, source_url: str, target_url: str) -> bool:
- """
- Check whether an HTML document mentions the target URL.
+ """Check whether an HTML document mentions the target URL.
URL references are resolved against the document's ``base`` element when
present, or against the source URL otherwise.
@@ -42,7 +41,6 @@ def html_mentions_target(body: bytes, source_url: str, target_url: str) -> bool:
:param target_url: Exact URL to look for.
:return: Whether a supported HTML URL attribute references the target URL.
"""
-
document = BeautifulSoup(body, "html.parser")
base_url = source_url
@@ -67,8 +65,7 @@ def html_mentions_target(body: bytes, source_url: str, target_url: str) -> bool:
def text_mentions_target(body: str, target_url: str) -> bool:
- """
- Check whether plain text contains the target IRI, ignoring trailing prose
+ """Check whether plain text contains the target IRI, ignoring trailing prose
punctuation but not extra URL path or query characters.
:param body: Plain-text document body.
diff --git a/webmentions_ssg/tasks/notifications.py b/webmentions_ssg/tasks/notifications.py
index 889030c..a6a9b2b 100644
--- a/webmentions_ssg/tasks/notifications.py
+++ b/webmentions_ssg/tasks/notifications.py
@@ -19,7 +19,6 @@ from ..models import ReceivedStatus, ReceivedWebmention
@huey.lock_task("send-webmention-digest")
def send_webmention_digest() -> None:
"""Send one digest of verified, previously unreported Webmentions."""
-
recipient = current_app.config.get("NOTIFICATION_EMAIL")
if not recipient:
return
diff --git a/webmentions_ssg/tasks/receiver.py b/webmentions_ssg/tasks/receiver.py
index feb6823..ada89f8 100644
--- a/webmentions_ssg/tasks/receiver.py
+++ b/webmentions_ssg/tasks/receiver.py
@@ -42,8 +42,7 @@ RECOVERY_EXHAUSTED_REASON = "Verification recovery limit reached"
def fetch_source(source_url: str) -> tuple[httpx.Response, bytes]:
- """
- Fetch a webmention source document.
+ """Fetch a webmention source document.
The request follows redirects while enforcing the configured timeout,
redirect limit, and maximum response size.
@@ -55,7 +54,6 @@ def fetch_source(source_url: str) -> tuple[httpx.Response, bytes]:
:raises VerificationError: If the source returns another unsuccessful HTTP
status or exceeds the configured maximum response size.
"""
-
try:
with (
build_client(
@@ -89,8 +87,7 @@ def fetch_source(source_url: str) -> tuple[httpx.Response, bytes]:
def source_mentions_target(source_url: str, target_url: str) -> bool:
- """
- Fetch a source and check whether it mentions the target URL.
+ """Fetch a source and check whether it mentions the target URL.
HTML and XHTML sources are inspected for supported URL attributes, while
plain-text sources are searched for the exact target IRI.
@@ -103,7 +100,6 @@ def source_mentions_target(source_url: str, target_url: str) -> bool:
:raises SourceGoneError: If the source explicitly reports that it is gone.
:raises TemporaryFetchError: If fetching the source fails temporarily.
"""
-
response, body = fetch_source(source_url)
media_type = (
@@ -129,8 +125,7 @@ def source_mentions_target(source_url: str, target_url: str) -> bool:
@huey.task(retries=2, retry_delay=50)
def verify_webmention(webmention_uuid: uuid.UUID) -> None:
- """
- Verify a received webmention and persist the result.
+ """Verify a received webmention and persist the result.
The transition into ``verifying`` is an atomic claim. Its ``updated_at``
timestamp acts as a lease version: if a reaper has reclaimed the row while
@@ -230,8 +225,7 @@ def verify_webmention(webmention_uuid: uuid.UUID) -> None:
def recover_stale_webmentions() -> int:
- """
- Requeue verification attempts that were abandoned or lost from the queue.
+ """Requeue verification attempts that were abandoned or lost from the queue.
Recover both stale ``verifying`` rows (workers that died) and stale
``received`` rows (tasks that were never enqueued or were lost). Conditional
diff --git a/webmentions_ssg/tasks/retention.py b/webmentions_ssg/tasks/retention.py
index bf79512..935f54b 100644
--- a/webmentions_ssg/tasks/retention.py
+++ b/webmentions_ssg/tasks/retention.py
@@ -39,8 +39,9 @@ def purge_old_received_webmentions() -> int:
)
db.session.commit()
- removed = result.rowcount
- if removed:
- current_app.logger.info("Purged %d old failed/deleted Webmentions", removed)
+ if result.rowcount:
+ current_app.logger.info(
+ "Purged %d old failed/deleted Webmentions", result.rowcount
+ )
- return removed
+ return result.rowcount
diff --git a/webmentions_ssg/tasks/scanner.py b/webmentions_ssg/tasks/scanner.py
index 1b1c6ef..6365ff9 100644
--- a/webmentions_ssg/tasks/scanner.py
+++ b/webmentions_ssg/tasks/scanner.py
@@ -21,8 +21,7 @@ from .source_parser import ScannedSource, SourceScanError, scan_source_file
def create_source(scanned: ScannedSource, scan_time: datetime) -> Source:
- """
- Create a source model from a newly discovered document.
+ """Create a source model from a newly discovered document.
A sent Webmention is created for each discovered target at the initial source
revision.
@@ -52,8 +51,7 @@ def create_source(scanned: ScannedSource, scan_time: datetime) -> Source:
def update_source(
source: Source, scanned: ScannedSource, scan_time: datetime
) -> Source:
- """
- Update an existing source from newly scanned data.
+ """Update an existing source from newly scanned data.
A changed or previously deleted source receives a new revision. Existing sent
Webmentions are updated to reflect the current targets, and newly discovered
@@ -103,8 +101,7 @@ def update_source(
def scan_sources() -> None:
- """
- Scan generated source documents and queue pending Webmentions.
+ """Scan generated source documents and queue pending Webmentions.
New and changed sources are persisted, missing sources are marked as deleted,
and Webmentions requiring processing are queued for sending. A scan that
@@ -157,7 +154,7 @@ def scan_sources_task() -> None:
for index_path in root.rglob("index.html"):
relative_path = index_path.relative_to(root)
- if relative_path.parent == Path("."):
+ if relative_path.parent == Path():
continue
seen_paths.add(relative_path.as_posix())
diff --git a/webmentions_ssg/tasks/sender.py b/webmentions_ssg/tasks/sender.py
index a9db128..3803463 100644
--- a/webmentions_ssg/tasks/sender.py
+++ b/webmentions_ssg/tasks/sender.py
@@ -33,8 +33,7 @@ from .discovery import (
def attempt_is_current(webmention: SentWebmention, revision: int) -> bool:
- """
- Check whether a send attempt still represents the desired revision.
+ """Check whether a send attempt still represents the desired revision.
The Webmention is refreshed from the database before comparing its desired
and processed revisions.
@@ -60,8 +59,7 @@ def retry_delay(attempt: int) -> timedelta:
@huey.task()
def send_webmention(webmention_uuid: uuid.UUID) -> None:
- """
- Discover a receiver endpoint and send a Webmention.
+ """Discover a receiver endpoint and send a Webmention.
The result of the attempt is stored on the corresponding sent Webmention.
Temporary failures are recorded with an exponential retry deadline. The
diff --git a/webmentions_ssg/tasks/source_parser.py b/webmentions_ssg/tasks/source_parser.py
index cb15ab6..1bd498c 100644
--- a/webmentions_ssg/tasks/source_parser.py
+++ b/webmentions_ssg/tasks/source_parser.py
@@ -72,8 +72,7 @@ class ScannedSource:
def source_url_for_path(relative_path: Path, base_url: str) -> str:
- """
- Derive the public source URL from a relative filesystem path.
+ """Derive the public source URL from a relative filesystem path.
:param relative_path: Path of the source document relative to the source root.
:param base_url: Base URL under which source documents are published.
@@ -87,8 +86,7 @@ def source_url_for_path(relative_path: Path, base_url: str) -> str:
def canonical_url(
document: BeautifulSoup, *, relative_path: Path, base_url: str | None
) -> str | None:
- """
- Return the canonical URL declared by a source document.
+ """Return the canonical URL declared by a source document.
Relative canonical URLs are resolved against the configured source base URL.
@@ -122,11 +120,11 @@ def canonical_url(
)
return resolved
+ return None
def property_urls(entry: dict[str, Any], property_name: str) -> Iterator[str]:
- """
- Yield URL values from a microformats property.
+ """Yield URL values from a microformats property.
:param entry: Parsed microformats entry.
:param property_name: Name of the property to inspect.
@@ -146,8 +144,7 @@ def property_urls(entry: dict[str, Any], property_name: str) -> Iterator[str]:
def parse_entry(element: Tag, base_url: str) -> dict[str, Any]:
- """
- Parse and validate an h-entry with mf2py.
+ """Parse and validate an h-entry with mf2py.
:param element: HTML element containing the h-entry.
:param base_url: Base URL used when parsing the microformats data.
@@ -180,8 +177,7 @@ def parse_entry(element: Tag, base_url: str) -> dict[str, Any]:
def primary_entry(
document: BeautifulSoup, source_url: str
) -> tuple[Tag, dict[str, Any]]:
- """
- Return and validate the primary h-entry of a source document.
+ """Return and validate the primary h-entry of a source document.
The document must contain exactly one h-entry whose ``u-url`` matches the
source URL.
@@ -211,8 +207,7 @@ def primary_entry(
def content_element(entry: Tag) -> Tag:
- """
- Return the e-content element of an h-entry.
+ """Return the e-content element of an h-entry.
:param entry: HTML element containing the h-entry.
:return: The h-entry's e-content element.
@@ -228,8 +223,7 @@ def content_element(entry: Tag) -> Tag:
def normalize_target(value: str, *, base_url: str, source_url: str) -> str | None:
- """
- Resolve and validate a possible Webmention target URL.
+ """Resolve and validate a possible Webmention target URL.
Empty values, non-HTTP URLs, and URLs referring to the source itself are
discarded.
@@ -240,9 +234,7 @@ def normalize_target(value: str, *, base_url: str, source_url: str) -> str | Non
:return: Normalized target URL, or ``None`` if the value is not a valid
Webmention target.
"""
- value = value.strip()
-
- if not value:
+ if not (value := value.strip()):
return None
target = urljoin(base_url, value)
@@ -264,8 +256,7 @@ def iter_targets(
source_url: str,
ignored_hostnames: Iterable[str] = (),
) -> Iterator[str]:
- """
- Yield outgoing Webmention targets from an h-entry.
+ """Yield outgoing Webmention targets from an h-entry.
Targets are collected from links in the entry content and supported
microformats reaction properties. Invalid, self-referencing, and ignored
@@ -328,8 +319,7 @@ def scan_source_file(
base_url: str | None,
ignored_hostnames: Iterable[str] = (),
) -> ScannedSource:
- """
- Scan one generated source document for outgoing Webmentions.
+ """Scan one generated source document for outgoing Webmentions.
:param path: Path of the generated HTML document.
:param root: Root directory containing generated source documents.
diff --git a/webmentions_ssg/views/admin.py b/webmentions_ssg/views/admin.py
index 46e3b18..2f3f3ab 100644
--- a/webmentions_ssg/views/admin.py
+++ b/webmentions_ssg/views/admin.py
@@ -24,8 +24,7 @@ from . import root_page
@root_page.route("/received")
@login_required
def received() -> ResponseReturnValue:
- """
- Display received Webmentions.
+ """Display received Webmentions.
:return: Rendered page containing the paginated received Webmentions.
"""
@@ -45,8 +44,7 @@ def received() -> ResponseReturnValue:
@root_page.post("/received/<uuid:identifier>/delete")
@login_required
def delete_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue:
- """
- Delete a received Webmention.
+ """Delete a received Webmention.
:param identifier: Identifier of the Webmention to delete.
:return: Redirect response to the received Webmentions view.
@@ -74,8 +72,7 @@ def delete_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue:
@root_page.post("/received/<uuid:identifier>/reverify")
@login_required
def reverify_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue:
- """
- Queue a received Webmention for reverification.
+ """Queue a received Webmention for reverification.
The Webmention status is reset before a new verification task is queued.
@@ -108,8 +105,7 @@ def reverify_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue:
@root_page.route("/sent")
@login_required
def sent() -> ResponseReturnValue:
- """
- Display sources with sent Webmentions.
+ """Display sources with sent Webmentions.
:return: Rendered page containing the paginated source list.
"""
@@ -130,8 +126,7 @@ def sent() -> ResponseReturnValue:
@root_page.post("/sent/rescan")
@login_required
def rescan_sent_sources() -> ResponseReturnValue:
- """
- Queue a manual scan of sent Webmention sources.
+ """Queue a manual scan of sent Webmention sources.
:return: Redirect response to the sent Webmentions view.
"""
@@ -145,8 +140,7 @@ def rescan_sent_sources() -> ResponseReturnValue:
@root_page.route("/sent/<uuid:source_identifier>")
@login_required
def sent_source(source_identifier: uuid.UUID) -> ResponseReturnValue:
- """
- Display the sent Webmentions associated with a source.
+ """Display the sent Webmentions associated with a source.
:param source_identifier: Identifier of the source to display.
:return: Rendered source details page.
@@ -179,8 +173,7 @@ def sent_source(source_identifier: uuid.UUID) -> ResponseReturnValue:
def resend_sent_webmention(
source_identifier: uuid.UUID, webmention_identifier: uuid.UUID
) -> ResponseReturnValue:
- """
- Queue an outgoing Webmention to be sent again.
+ """Queue an outgoing Webmention to be sent again.
The current desired source revision is reopened for processing so the
sender task does not treat the Webmention as already completed. Historical
diff --git a/webmentions_ssg/views/endpoint.py b/webmentions_ssg/views/endpoint.py
index 1c2fe13..baab397 100644
--- a/webmentions_ssg/views/endpoint.py
+++ b/webmentions_ssg/views/endpoint.py
@@ -99,8 +99,7 @@ def submit_received(source: str, target: str) -> tuple[uuid.UUID, bool] | None:
@LIMITER.limit(lambda: current_app.config["ENDPOINT_RATE_LIMIT"])
@CSRF.exempt
def endpoint() -> ResponseReturnValue:
- """
- Receive and queue a Webmention for verification.
+ """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
@@ -134,8 +133,7 @@ def endpoint() -> ResponseReturnValue:
@root_page.route("/status/<uuid:identifier>")
def status(identifier: uuid.UUID) -> ResponseReturnValue:
- """
- Display the verification status of a received Webmention.
+ """Display the verification status of a received Webmention.
:param identifier: Identifier of the Webmention to display.
:return: Rendered Webmention status page.
diff --git a/webmentions_ssg/views/session.py b/webmentions_ssg/views/session.py
index 7bd8a10..3f8a0f2 100644
--- a/webmentions_ssg/views/session.py
+++ b/webmentions_ssg/views/session.py
@@ -19,8 +19,7 @@ from . import root_page
@root_page.route("/")
def index() -> ResponseReturnValue:
- """
- Redirect to the received Webmentions view.
+ """Redirect to the received Webmentions view.
:return: Redirect response to the received Webmentions view.
"""
@@ -40,8 +39,7 @@ def index() -> ResponseReturnValue:
error_message="Too many login attempts. Please try again later.",
)
def login() -> ResponseReturnValue:
- """
- Authenticate a user and start a login session.
+ """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
@@ -84,8 +82,7 @@ def login() -> ResponseReturnValue:
@root_page.route("/logout", methods=("POST",))
@login_required
def logout() -> ResponseReturnValue:
- """
- End the current user's login session.
+ """End the current user's login session.
:return: Redirect response to the application index.
"""