aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/source_parser.py
blob: bd0700a766eededd9c32eb01f64cdaad5dd3357e (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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Extract canonical source URLs, content fingerprints, and outgoing links."""

import json
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from fnmatch import fnmatchcase
from itertools import chain
from pathlib import Path
from typing import Any
from urllib.parse import quote, urldefrag, urljoin

import mf2py
import xxhash
from bs4 import BeautifulSoup, Tag
from bs4.element import NavigableString, PageElement

from ..hostname import normalize_hostname
from ..net import is_http_url

REACTION_PROPERTIES = ("in-reply-to", "like-of", "repost-of", "bookmark-of")

BLOCK_LEVEL_TAGS = frozenset(
    {
        "address",
        "article",
        "aside",
        "blockquote",
        "br",
        "dd",
        "div",
        "dl",
        "dt",
        "figcaption",
        "figure",
        "footer",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "header",
        "hr",
        "li",
        "main",
        "ol",
        "p",
        "pre",
        "section",
        "table",
        "td",
        "th",
        "tr",
        "ul",
    }
)


class SourceScanError(Exception):
    """A source document cannot safely be processed."""


@dataclass(frozen=True)
class ScannedSource:
    path: str
    url: str
    content_hash: str
    targets: frozenset[str]


def source_url_for_path(relative_path: Path, base_url: str) -> str:
    """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.
    :returns: Public URL corresponding to the source document.
    """
    directory = relative_path.parent.as_posix()

    return urljoin(base_url, f"{quote(directory, safe='/')}/")


def declared_canonical_url(
    document: BeautifulSoup, *, relative_path: Path, base_url: str | None
) -> str | None:
    """Return the canonical URL declared by a source document.

    Relative canonical URLs are resolved against the configured source base URL.

    :param document: Parsed HTML source document.
    :param relative_path: Path of the source document relative to the source root.
    :param base_url: Configured source base URL, if available.
    :returns: Canonical URL, or ``None`` if none is declared.
    :raises SourceScanError: If the canonical URL is empty, cannot be resolved, or does
                             not resolve to an HTTP or HTTPS URL.
    """
    if (link := document.select_one('link[rel~="canonical"][href]')) is None:
        return None

    href = link.get("href")

    if not isinstance(href, str) or not (href := href.strip()):
        raise SourceScanError("Document contains an empty canonical URL")

    if is_http_url(href):
        return href

    if base_url is None:
        raise SourceScanError(
            "Document contains a relative canonical URL, but "
            "SITE_BASE_URL is not configured"
        )

    resolved = urljoin(source_url_for_path(relative_path, base_url), href)

    if not is_http_url(resolved):
        raise SourceScanError(
            f"Canonical URL is not a valid HTTP or HTTPS URL: {href!r}"
        )

    return resolved


def mf2_string_values(entry: dict[str, Any], property_name: str) -> Iterator[str]:
    """Yield URL values from a microformats property.

    :param entry: Parsed microformats entry.
    :param property_name: Name of the property to inspect.
    :returns: Iterator over string values of the property.
    """
    properties = entry.get("properties")

    if not isinstance(properties, dict):
        return

    values = properties.get(property_name)

    if not isinstance(values, list):
        return

    yield from (value for value in values if isinstance(value, str))


def parse_h_entry(element: Tag, base_url: str) -> dict[str, Any]:
    """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.
    :returns: Parsed h-entry.
    :raises SourceScanError: If parsing does not produce exactly one valid h-entry.
    """
    parsed = mf2py.parse(doc=str(element), url=base_url)

    if not isinstance(parsed, dict):
        raise SourceScanError("Microformats parser did not return a document object")

    items = parsed.get("items")

    if not isinstance(items, list) or len(items) != 1:
        raise SourceScanError("Expected exactly one parsed h-entry")

    entry = items[0]

    if not isinstance(entry, dict):
        raise SourceScanError("Parsed h-entry is not an object")

    types = entry.get("type")

    if not isinstance(types, list) or "h-entry" not in types:
        raise SourceScanError("Parsed microformats item is not an h-entry")

    return entry


def find_primary_h_entry(
    document: BeautifulSoup, source_url: str
) -> tuple[Tag, dict[str, Any]]:
    """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.

    :param document: Parsed HTML source document.
    :param source_url: Public URL of the source document.
    :returns: h-entry element and its parsed microformats representation.
    :raises SourceScanError: If the document does not contain exactly one h-entry or its
                             ``u-url`` does not match the source URL.
    """
    entries = document.find_all(class_="h-entry")

    if len(entries) != 1:
        raise SourceScanError(f"Expected exactly one h-entry, found {len(entries)}")

    entry_element = entries[0]
    mf2_entry = parse_h_entry(entry_element, source_url)

    urls = tuple(mf2_string_values(mf2_entry, "url"))

    if source_url not in urls:
        raise SourceScanError(
            f"The h-entry u-url does not match the source URL {source_url!r}: {urls!r}"
        )

    return entry_element, mf2_entry


def find_e_content(entry_element: Tag) -> Tag:
    """Return the e-content element of an h-entry.

    :param entry_element: HTML element containing the h-entry.
    :returns: The h-entry's e-content element.
    :raises SourceScanError: If the h-entry does not contain exactly one e-content
                             element.
    """
    contents = entry_element.find_all(class_="e-content")

    if len(contents) != 1:
        raise SourceScanError(f"Expected exactly one e-content, found {len(contents)}")

    return contents[0]


def normalize_target_url(value: str, *, base_url: str, source_url: str) -> str | None:
    """Resolve and validate a possible Webmention target URL.

    Empty values, non-HTTP URLs, and URLs referring to the source itself are
    discarded.

    :param value: URL reference to normalize.
    :param base_url: Base URL against which relative references are resolved.
    :param source_url: URL of the source document.
    :returns: Normalized target URL, or ``None`` if the value is not a valid Webmention
              target.
    """
    if not (value := value.strip()):
        return None

    target = urljoin(base_url, value)

    if not is_http_url(target):
        return None

    if urldefrag(target)[0] == urldefrag(source_url)[0]:
        return None

    return target


def iter_outgoing_targets(
    content: Tag,
    mf2_entry: dict[str, Any],
    *,
    base_url: str,
    source_url: str,
    ignored_hostnames: Iterable[str] = (),
) -> Iterator[str]:
    """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
    targets are excluded.

    :param content: e-content element of the h-entry.
    :param mf2_entry: Parsed microformats representation of the h-entry.
    :param base_url: Base URL against which relative targets are resolved.
    :param source_url: URL of the source document.
    :param ignored_hostnames: Hostname patterns whose targets should be ignored.
    :returns: Iterator over outgoing Webmention target URLs.
    """
    hrefs = (
        href
        for element in content.find_all("a", href=True)
        if isinstance(href := element.get("href"), str)
    )

    reactions = chain.from_iterable(
        mf2_string_values(mf2_entry, property_name)
        for property_name in REACTION_PROPERTIES
    )

    for value in chain(hrefs, reactions):
        target = normalize_target_url(value, base_url=base_url, source_url=source_url)
        if target is not None:
            try:
                hostname = normalize_hostname(target, from_url=True)
            except ValueError:
                continue
            if not any(fnmatchcase(hostname, pattern) for pattern in ignored_hostnames):
                yield target


def stable_content_text(content: Tag) -> str:
    """Extract stable reader-facing content without generated HTML attributes.

    :param content: Parsed e-content element to normalize.
    :returns: Normalized text used to fingerprint reader-facing content.
    """

    def extract(node: PageElement) -> str:
        if isinstance(node, NavigableString):
            return str(node)

        if not isinstance(node, Tag) or node.name in {"script", "style", "template"}:
            return ""

        # A relative-time label may change on every site build even though its
        # machine-readable date stays the same.
        if node.name == "time" and isinstance(value := node.get("datetime"), str):
            return value.strip()

        # Image-only posts also have meaningful content, despite having no text.
        if node.name == "img":
            return f" [image:{node.get('src', '')!s}:{node.get('alt', '')!s}] "

        text = "".join(extract(child) for child in node.children)
        return f" {text} " if node.name in BLOCK_LEVEL_TAGS else text

    return " ".join(extract(content).split())


def scan_source_file(
    path: Path,
    *,
    root: Path,
    base_url: str | None,
    ignored_hostnames: Iterable[str] = (),
) -> ScannedSource:
    """Scan one generated source document for outgoing Webmentions.

    :param path: Path of the generated HTML document.
    :param root: Root directory containing generated source documents.
    :param base_url: Configured source base URL, if available.
    :param ignored_hostnames: Hostname patterns whose targets should be ignored.
    :returns: Scanned source metadata and discovered targets.
    :raises SourceScanError: If the document cannot be safely interpreted as a
                             Webmention source.
    :raises OSError: If the source document cannot be read.
    """
    # Use the path as published for its URL, but read only files whose
    # resolved target stays inside the configured source directory. Resolving
    # before reading also protects against symlinked index.html files.
    resolved_root = root.resolve()
    resolved_path = path.resolve()
    if not resolved_path.is_relative_to(resolved_root):
        raise SourceScanError(f"Source document escapes source directory: {path}")

    relative_path = path.relative_to(root)
    document = BeautifulSoup(resolved_path.read_bytes(), "html5lib")

    source_url = declared_canonical_url(
        document, relative_path=relative_path, base_url=base_url
    )

    if source_url is None:
        if base_url is None:
            raise SourceScanError(
                "Document has no canonical URL and SITE_BASE_URL is not configured"
            )

        source_url = source_url_for_path(relative_path, base_url)

    entry_element, mf2_entry = find_primary_h_entry(document, source_url)

    content = find_e_content(entry_element)

    targets = frozenset(
        iter_outgoing_targets(
            content,
            mf2_entry,
            base_url=source_url,
            source_url=source_url,
            ignored_hostnames=ignored_hostnames,
        )
    )

    stable_content = stable_content_text(content)
    fingerprint = json.dumps(
        {"content": stable_content, "targets": sorted(targets)},
        ensure_ascii=False,
        separators=(",", ":"),
    )

    return ScannedSource(
        path=relative_path.as_posix(),
        url=source_url,
        content_hash=xxhash.xxh3_128_hexdigest(fingerprint.encode("utf-8")),
        targets=targets,
    )