use std::collections::HashMap;
use std::sync::OnceLock;
use regex::{Captures, Regex};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockedTracker {
pub url: String,
pub host: String,
pub kind: String,
}
#[derive(Debug, Clone)]
pub struct StripResult {
pub html: String,
pub blocked: Vec<BlockedTracker>,
}
fn resource_attrs(tag: &str) -> &'static [&'static str] {
match tag {
"img" => &["src", "srcset", "lowsrc"],
"source" => &["src", "srcset"],
"image" | "use" => &["xlink:href", "href"],
"video" => &["src", "poster"],
"audio" | "track" | "iframe" | "embed" | "input" => &["src"],
"object" => &["data"],
"body" | "table" | "td" | "th" | "tr" => &["background"],
_ => &[],
}
}
fn drops_whole(tag: &str) -> bool {
tag == "img" || tag == "source"
}
const TRACKER_HINTS: [&str; 15] = [
"open.",
"track.",
"trk.",
"click.",
"email.",
"mailstat",
"pixel",
"beacon",
"sendgrid.net",
"mailchimp",
"list-manage",
"hubspot",
"mktoresp",
"omtrdc",
"doubleclick",
];
struct Patterns {
dimension: Regex,
remote: Regex,
css_url: Regex,
style_block: Regex,
tag: Regex,
host: Regex,
entity_hex: Regex,
entity_dec: Regex,
entity_named: Regex,
ignorable: Regex,
www: Regex,
link: Regex,
attrs: HashMap<&'static str, Regex>,
}
fn attr_regex(attr: &str) -> Regex {
Regex::new(&format!(r#"(?i)(^|[\s"'])({})\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))"#, regex::escape(attr)))
.expect("a valid attribute pattern")
}
fn patterns() -> &'static Patterns {
static CELL: OnceLock<Patterns> = OnceLock::new();
CELL.get_or_init(|| {
let mut attrs = HashMap::new();
for attr in ["src", "srcset", "lowsrc", "xlink:href", "href", "poster", "data", "background", "style"]
{
attrs.insert(attr, attr_regex(attr));
}
Patterns {
dimension: Regex::new(r#"(?i)\b(width|height)\s*=\s*["']?\s*([0-9]+)"#).unwrap(),
remote: Regex::new(r"(?i)^(https?:)?//").unwrap(),
css_url: Regex::new(r#"(?i)url\(\s*(?:"([^'")]+)"|'([^'")]+)'|([^'")]+))\s*\)"#).unwrap(),
style_block: Regex::new(r"(?is)<style\b[^>]*>(.*?)</style>").unwrap(),
tag: Regex::new(r#"<([a-zA-Z][A-Za-z0-9_:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>"#).unwrap(),
host: Regex::new(r"(?i)^(?:https?:)?//([^/?#]+)").unwrap(),
entity_hex: Regex::new(r"(?i)&#x([0-9a-f]+);?").unwrap(),
entity_dec: Regex::new(r"&#([0-9]+);?").unwrap(),
entity_named: Regex::new(r"(?i)&(amp|colon|sol|NewLine|Tab);").unwrap(),
ignorable: Regex::new(r"[\s\x00-\x1f]+").unwrap(),
www: Regex::new(r"(?i)^www\.").unwrap(),
link: Regex::new(r#"(?i)https?://[^\s<>"')]+"#).unwrap(),
attrs,
}
})
}
fn code_point(value: u32) -> String {
char::from_u32(value).map(String::from).unwrap_or_default()
}
fn canonical(value: &str) -> String {
let p = patterns();
let mut current = value.to_string();
for _ in 0..3 {
let step = p.entity_hex.replace_all(¤t, |caps: &Captures| {
u32::from_str_radix(&caps[1], 16).map(code_point).unwrap_or_default()
});
let step = p
.entity_dec
.replace_all(&step, |caps: &Captures| caps[1].parse::<u32>().map(code_point).unwrap_or_default());
let step =
p.entity_named.replace_all(&step, |caps: &Captures| match caps[1].to_lowercase().as_str() {
"amp" => "&",
"colon" => ":",
"sol" => "/",
_ => "",
});
if step == current {
break;
}
current = step.into_owned();
}
p.ignorable.replace_all(¤t, "").into_owned()
}
pub fn host_of(url: &str) -> String {
let p = patterns();
let canonical = canonical(url);
match p.host.captures(canonical.trim()) {
Some(caps) => p.www.replace(&caps[1], "").to_lowercase(),
None => String::new(),
}
}
fn is_remote(url: &str) -> bool {
patterns().remote.is_match(&canonical(url))
}
fn srcset_urls(value: &str) -> Vec<&str> {
value
.split(',')
.filter_map(|candidate| candidate.split_whitespace().next())
.filter(|url| !url.is_empty())
.collect()
}
fn attr_value(attrs: &str, attr: &str) -> Option<String> {
let regex = patterns().attrs.get(attr)?;
let caps = regex.captures(attrs)?;
Some(
caps.get(4)
.or_else(|| caps.get(5))
.or_else(|| caps.get(6))
.map(|m| m.as_str().to_string())
.unwrap_or_default(),
)
}
fn remove_attr(attrs: &str, attr: &str) -> String {
match patterns().attrs.get(attr) {
Some(regex) => regex.replace(attrs, "$1").into_owned(),
None => attrs.to_string(),
}
}
fn set_attr(attrs: &str, attr: &str, value: &str) -> String {
let quoted = value.replace('"', """);
match patterns().attrs.get(attr) {
Some(regex) => {
regex.replace(attrs, |caps: &Captures| format!("{}{attr}=\"{quoted}\"", &caps[1])).into_owned()
}
None => attrs.to_string(),
}
}
fn classify(tag: &str, url: &str) -> String {
let smallest =
patterns().dimension.captures_iter(tag).filter_map(|caps| caps[2].parse::<u64>().ok()).min();
if smallest.is_some_and(|value| value <= 3) {
return "pixel".into();
}
let host = host_of(url);
if TRACKER_HINTS.iter().any(|hint| host.contains(hint)) {
"pixel".into()
} else {
"image".into()
}
}
pub fn strip_remote_content(html: &str) -> StripResult {
let p = patterns();
let mut blocked: Vec<BlockedTracker> = Vec::new();
let mut seen: Vec<String> = Vec::new();
let record = |url: &str, tag: &str, blocked: &mut Vec<BlockedTracker>, seen: &mut Vec<String>| {
if seen.iter().any(|already| already == url) {
return;
}
seen.push(url.to_string());
blocked.push(BlockedTracker { url: url.to_string(), host: host_of(url), kind: classify(tag, url) });
};
let strip_css_urls = |css: &str, blocked: &mut Vec<BlockedTracker>, seen: &mut Vec<String>| -> String {
p.css_url
.replace_all(css, |caps: &Captures| {
let url = caps
.get(1)
.or_else(|| caps.get(2))
.or_else(|| caps.get(3))
.map(|m| m.as_str())
.unwrap_or_default();
if !is_remote(url) {
return caps[0].to_string();
}
record(url, "", blocked, seen);
"url()".to_string()
})
.into_owned()
};
let mut out = String::new();
let mut last = 0;
for caps in p.style_block.captures_iter(html) {
let css = caps.get(1).unwrap();
let cleaned = strip_css_urls(css.as_str(), &mut blocked, &mut seen);
out.push_str(&html[last..css.start()]);
out.push_str(&cleaned);
last = css.end();
}
out.push_str(&html[last..]);
let stage = out;
let mut result = String::new();
let mut last = 0;
for caps in p.tag.captures_iter(&stage) {
let whole = caps.get(0).unwrap();
let name = caps.get(1).unwrap().as_str();
let attrs = caps.get(2).unwrap().as_str();
let lower = name.to_lowercase();
result.push_str(&stage[last..whole.start()]);
last = whole.end();
let mut next_attrs = attrs.to_string();
let mut dropped = false;
for attr in resource_attrs(&lower) {
let Some(value) = attr_value(&next_attrs, attr) else { continue };
let candidates: Vec<String> = if *attr == "srcset" {
srcset_urls(&value).into_iter().map(str::to_string).collect()
} else {
vec![value.clone()]
};
let Some(remote) = candidates.into_iter().find(|url| is_remote(url)) else { continue };
record(&remote, whole.as_str(), &mut blocked, &mut seen);
if drops_whole(&lower) {
dropped = true;
break;
}
next_attrs = remove_attr(&next_attrs, attr);
}
if dropped {
continue;
}
if let Some(style) = attr_value(&next_attrs, "style").filter(|s| !s.is_empty()) {
let cleaned = strip_css_urls(&style, &mut blocked, &mut seen);
if cleaned != style {
next_attrs = set_attr(&next_attrs, "style", &cleaned);
}
}
if next_attrs == attrs {
result.push_str(whole.as_str());
} else {
result.push('<');
result.push_str(name);
result.push_str(&next_attrs);
result.push('>');
}
}
result.push_str(&stage[last..]);
StripResult { html: result, blocked }
}
pub fn find_tracking_links(text: &str) -> Vec<BlockedTracker> {
let mut out = Vec::new();
let mut seen: Vec<String> = Vec::new();
for found in patterns().link.find_iter(text) {
let url = found.as_str();
let host = host_of(url);
if seen.iter().any(|already| already == url) {
continue;
}
if !TRACKER_HINTS.iter().any(|hint| host.contains(hint)) {
continue;
}
seen.push(url.to_string());
out.push(BlockedTracker { url: url.to_string(), host, kind: "link".into() });
}
out
}
pub fn summarize_blocked(blocked: &[BlockedTracker]) -> String {
if blocked.is_empty() {
return "No trackers in this message.".into();
}
let mut hosts: Vec<&str> = Vec::new();
for tracker in blocked {
if !tracker.host.is_empty() && !hosts.contains(&tracker.host.as_str()) {
hosts.push(&tracker.host);
}
}
let noun = if blocked.len() == 1 { "tracker" } else { "trackers" };
match hosts.len() {
0 => format!("{} {noun} blocked.", blocked.len()),
1 => format!("{} {noun} blocked from {}.", blocked.len(), hosts[0]),
n => format!("{} {noun} blocked from {n} hosts.", blocked.len()),
}
}