aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/target_matching.py
blob: 4c3918b5420d8029624fae46af7e60d359fd8b0c (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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Pure HTML and text matching for received Webmention targets."""

from urllib.parse import urljoin

import rfc3987
from bs4 import BeautifulSoup

IRI_PATTERN = rfc3987.get_compiled_pattern("IRI")
TRAILING_IRI_PUNCTUATION = ".,;:!?"

HTML_URL_ATTRIBUTES = (
    ("a[href], area[href], link[href]", "href"),
    (
        (
            "audio[src], embed[src], iframe[src], img[src], "
            'input[type="image" i][src], script[src], '
            "audio source[src], video source[src], track[src], video[src]"
        ),
        "src",
    ),
    ("blockquote[cite], del[cite], ins[cite], q[cite]", "cite"),
)


def html_mentions_target(body: bytes, source_url: str, target_url: str) -> bool:
    """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.

    :param body: HTML document body.
    :param source_url: URL from which the document was retrieved.
    :param target_url: Exact URL to look for.
    :returns: Whether a supported HTML URL attribute references the target URL.
    """
    document = BeautifulSoup(body, "html.parser")
    base_url = source_url

    if (base_element := document.select_one("base[href]")) is not None and isinstance(
        base_href := base_element.get("href"), str
    ):
        base_url = urljoin(source_url, base_href.strip())

    for selector, attribute in HTML_URL_ATTRIBUTES:
        for element in document.select(selector):
            if not isinstance(reference := element.get(attribute), str):
                continue

            if urljoin(base_url, reference.strip()) == target_url:
                return True

    return False


def text_mentions_target(body: str, target_url: str) -> bool:
    """Check whether plain text contains the target IRI.

    Ignore trailing prose punctuation, but not extra URL path or query characters.

    :param body: Plain-text document body.
    :param target_url: Exact IRI to look for.
    :returns: Whether the target IRI occurs in the document.
    """
    for match in IRI_PATTERN.finditer(body):
        candidate = match.group()

        # A URL in prose can be followed by punctuation that the IRI pattern
        # consumes as part of its match. Only remove trailing punctuation,
        # leaving longer URLs (e.g. ``target/more``) unmatched.
        if not candidate.startswith(target_url):
            continue

        while candidate != target_url:
            if candidate[-1] in TRAILING_IRI_PUNCTUATION:
                candidate = candidate[:-1]
            elif candidate[-1] == ")" and candidate.count(")") > candidate.count("("):
                # Keep balanced parentheses that belong to the URL itself.
                candidate = candidate[:-1]
            else:
                break

        if candidate == target_url:
            return True

    return False