File size: 3,297 Bytes
8ba65bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Conservative HTML sanitiser for captured source rich text.

Source product descriptions are rich text. They are reproduced structurally,
but only through an explicit tag/attribute allowlist, and every absolute
source-site link is rewritten to its local equivalent so the clone never sends
a visitor to the source origin.
"""

from __future__ import annotations

import re
from html.parser import HTMLParser
from urllib.parse import urlsplit

ALLOWED_TAGS = {
    "p", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li",
    "h2", "h3", "h4", "span", "a", "table", "thead", "tbody", "tr", "th", "td",
}
VOID_TAGS = {"br"}
ALLOWED_ATTRS = {"a": {"href"}}
SOURCE_HOSTS = {"www.backcountry.com", "backcountry.com", "content.backcountry.com"}


def localize(href: str) -> str | None:
    """Keep same-site links as local paths; drop links that leave the clone."""
    href = (href or "").strip()
    if not href:
        return None
    if href.startswith("/"):
        return href
    parts = urlsplit(href)
    if parts.scheme in ("http", "https") and parts.netloc in SOURCE_HOSTS:
        return (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
    if href.startswith("#"):
        return href
    return None


class _Sanitizer(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.parts: list[str] = []
        self._open: list[str] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag not in ALLOWED_TAGS:
            return
        if tag == "a":
            href = localize(dict(attrs).get("href") or "")
            if not href:
                # Unresolvable or external destination: keep the text, drop the link.
                self._open.append("")
                return
            self.parts.append(f'<a href="{_escape(href)}">')
        else:
            self.parts.append(f"<{tag}>")
        if tag not in VOID_TAGS:
            self._open.append(tag)

    def handle_endtag(self, tag: str) -> None:
        if tag not in ALLOWED_TAGS or tag in VOID_TAGS:
            return
        while self._open:
            open_tag = self._open.pop()
            if open_tag:
                self.parts.append(f"</{open_tag}>")
            if open_tag == tag or open_tag == "":
                break

    def handle_data(self, data: str) -> None:
        self.parts.append(_escape(data))

    def close_all(self) -> str:
        while self._open:
            open_tag = self._open.pop()
            if open_tag:
                self.parts.append(f"</{open_tag}>")
        return "".join(self.parts)


def _escape(text: str) -> str:
    return (text.replace("&", "&amp;").replace("<", "&lt;")
            .replace(">", "&gt;").replace('"', "&quot;"))


def clean_html(raw: str | None) -> str:
    if not raw:
        return ""
    parser = _Sanitizer()
    parser.feed(raw)
    parser.close()
    html = parser.close_all()
    return re.sub(r"\s+", " ", html).strip()


def to_text(raw: str | None) -> str:
    if not raw:
        return ""
    text = re.sub(r"<[^>]+>", " ", raw)
    text = (text.replace("&amp;", "&").replace("&lt;", "<")
            .replace("&gt;", ">").replace("&quot;", '"').replace("&nbsp;", " "))
    return re.sub(r"\s+", " ", text).strip()