# SPDX-FileCopyrightText: 2026 Dennis Fink # # 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. :return: 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. :return: 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