import nh3
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

ALLOWED_TAGS = {
    "a",
    "b",
    "blockquote",
    "br",
    "code",
    "dd",
    "del",
    "dl",
    "dt",
    "em",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "hr",
    "i",
    "kbd",
    "li",
    "ol",
    "p",
    "pre",
    "s",
    "strike",
    "strong",
    "sub",
    "sup",
    "table",
    "tbody",
    "td",
    "th",
    "thead",
    "tr",
    "ul",
}

ALLOWED_ATTRIBUTES = {
    "*": {"title"},
    "a": {
        "href",
        "title",
    },
    "th": {"align"},
    "td": {"align"},
}

ALLOWED_URL_SCHEMES = {
    "http",
    "https",
}

cleaner = nh3.Cleaner(
    tags=ALLOWED_TAGS,
    attributes=ALLOWED_ATTRIBUTES,
    url_schemes=ALLOWED_URL_SCHEMES,
)


@register.filter(name="sanitize_rss")
def sanitize_rss(value):
    if not value:
        return ""

    sanitized_html = cleaner.clean(value)

    return mark_safe(sanitized_html)
