//! The page reader. Turns HTML into a calm list of blocks: headings, //! paragraphs, lists, quotes, code, pictures and simple search forms. //! //! Scripts never run and are never fetched. Styles are not applied. Hidden //! elements and anything labelled as an ad are left out. When a page marks //! its main content (`
` or `
`), site menus, side bars and //! footers are left out too. use crate::filter::Filter; use crate::url::Url; use alloc::string::{String, ToString}; use alloc::vec::Vec; #[derive(Clone, Debug, PartialEq, Eq, Default)] pub struct Inline { pub text: String, /// Absolute address when this run is a link. pub link: Option, pub bold: bool, pub italic: bool, pub code: bool, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Form { /// Absolute address the search goes to. pub action: String, pub hidden: Vec<(String, String)>, pub field: String, pub placeholder: String, pub value: String, pub submit: String, } impl Form { /// The address to open when the person submits `text`. pub fn target(&self, text: &str) -> String { let mut s = self.action.clone(); s.push(if s.contains('?') { '&' } else { '?' }); let mut first = true; for (k, v) in self.hidden.iter().chain(core::iter::once(&(self.field.clone(), String::from(text)))) { if !first { s.push('&'); } first = false; s.push_str(&crate::url::encode_component(k)); s.push('='); s.push_str(&crate::url::encode_component(v)); } s } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Block { Heading { level: u8, spans: Vec }, Paragraph { spans: Vec, quote: bool }, ListItem { depth: u8, marker: String, spans: Vec }, Code(String), Image { src: String, alt: String, width: Option, height: Option, link: Option }, Rule, Form(Form), } #[derive(Clone, Debug, Default)] pub struct Stats { /// Scripts that the page asked for and Clearwake never loaded. pub scripts_skipped: u32, /// Pictures and frames from ad or tracker addresses. pub blocked: u32, /// Elements labelled as ads or hidden. pub hidden: u32, } #[derive(Clone, Debug)] pub struct Document { pub url: Url, pub title: String, pub blocks: Vec, pub stats: Stats, } impl Document { /// All picture addresses on the page, in order, without repeats. pub fn image_urls(&self) -> Vec { let mut v: Vec = Vec::new(); for b in &self.blocks { if let Block::Image { src, .. } = b { if !v.contains(src) { v.push(src.clone()); } } } v } /// The page as plain text, one block per paragraph. pub fn plain_text(&self) -> String { let mut s = String::new(); for b in &self.blocks { match b { Block::Heading { spans, .. } | Block::Paragraph { spans, .. } | Block::ListItem { spans, .. } => { for sp in spans { s.push_str(&sp.text); } } Block::Code(c) => s.push_str(c), Block::Image { alt, .. } => s.push_str(alt), Block::Rule => s.push_str("---"), Block::Form(f) => s.push_str(&f.submit), } s.push('\n'); } s } } const MAX_BLOCKS: usize = 20_000; const VOID: &[&str] = &[ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", "keygen", ]; /// Elements that never show: their whole contents are dropped. const DROP: &[&str] = &[ "head", "script", "style", "template", "svg", "math", "iframe", "object", "canvas", "video", "audio", "select", "button", "dialog", "map", "frameset", "textarea", "datalist", "portal", ]; /// Dropped only when the page marks its main content. const CHROME: &[&str] = &["nav", "footer", "aside", "header"]; const BLOCKS: &[&str] = &[ "address", "article", "aside", "blockquote", "body", "center", "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "html", "li", "main", "menu", "nav", "ol", "p", "pre", "section", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", "caption", "legend", "label", ]; const AD_WORDS: &[&str] = &[ "ad", "ads", "advert", "adverts", "advertisement", "advertising", "adsbygoogle", "ad-slot", "ad-container", "ad-wrapper", "ad-banner", "ad-unit", "adunit", "ad_unit", "dfp-ad", "google-ad", "sponsored", "sponsored-content", "promoted", "taboola", "outbrain", "cookie-banner", "cookie-consent", "newsletter-popup", "paywall-overlay", ]; struct Tag { name: String, attrs: Vec<(String, String)>, end: bool, self_closing: bool, } impl Tag { fn attr(&self, n: &str) -> Option<&str> { self.attrs.iter().find(|(k, _)| k == n).map(|(_, v)| v.as_str()) } } struct Open { name: String, link: Option, } struct Builder<'f> { base: Url, filter: &'f Filter, drop_chrome: bool, blocks: Vec, spans: Vec, stack: Vec, /// Depth of the stack at which a dropped element began. skip_at: Option, heading: u8, list: Vec<(bool, u32)>, item: Option<(u8, String)>, quote: u32, pre: Option, form: Option
, title: String, stats: Stats, } /// Read a page. `url` is the address it came from (used to resolve links). pub fn parse(source: &str, url: &Url, filter: &Filter) -> Document { let lower_has = |needle: &str| find_ci(source, needle).is_some(); let drop_chrome = lower_has("").map(|e| i + e + 3).unwrap_or(src.len()); i = end; text_start = i; continue; } if rest.starts_with("').map(|e| i + e + 1).unwrap_or(src.len()); i = end; text_start = i; continue; } let next = bytes.get(i + 1).copied().unwrap_or(0); let is_tag = next.is_ascii_alphabetic() || (next == b'/' && bytes.get(i + 2).is_some_and(|c| c.is_ascii_alphabetic())); if !is_tag { i += 1; continue; } b.text(&src[text_start..i]); let (tag, end) = read_tag(src, i); i = end; text_start = i; // Raw text elements: skip straight to their end tag. if !tag.end && !tag.self_closing && (tag.name == "script" || tag.name == "style" || tag.name == "textarea" || tag.name == "title" || tag.name == "xmp" || tag.name == "plaintext") { let close = { let mut c = String::from(" { if b.title.is_empty() && !b.has_open(&["svg"]) { b.title = decode_entities(body); } } "script" => b.stats.scripts_skipped += 1, _ => {} } i = src[body_end..].find('>').map(|e| body_end + e + 1).unwrap_or(src.len()); text_start = i; continue; } b.tag(tag); if b.blocks.len() > MAX_BLOCKS { return; } } b.text(&src[text_start..]); } fn read_tag(src: &str, start: usize) -> (Tag, usize) { let bytes = src.as_bytes(); let mut i = start + 1; let end = bytes.get(i) == Some(&b'/'); if end { i += 1; } let ns = i; while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' && bytes[i] != b'/' { i += 1; } let name = src[ns..i].to_ascii_lowercase(); let mut attrs = Vec::new(); let mut self_closing = false; loop { while i < bytes.len() && (bytes[i].is_ascii_whitespace() || (bytes[i] == b'/' && bytes.get(i + 1) != Some(&b'>'))) { i += 1; } if i >= bytes.len() { break; } if bytes[i] == b'>' { i += 1; break; } if bytes[i] == b'/' { self_closing = true; i += 1; continue; } let ks = i; while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'=' && bytes[i] != b'>' && !(bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'>')) { i += 1; } let key = src[ks..i].to_ascii_lowercase(); while i < bytes.len() && bytes[i].is_ascii_whitespace() { i += 1; } let mut val = String::new(); if bytes.get(i) == Some(&b'=') { i += 1; while i < bytes.len() && bytes[i].is_ascii_whitespace() { i += 1; } match bytes.get(i) { Some(&q) if q == b'"' || q == b'\'' => { let vs = i + 1; let ve = src[vs..].find(q as char).map(|e| vs + e).unwrap_or(src.len()); val = decode_entities(&src[vs..ve]); i = (ve + 1).min(src.len()); } _ => { let vs = i; while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' { i += 1; } val = decode_entities(&src[vs..i]); } } } if !key.is_empty() && attrs.len() < 64 { attrs.push((key, val)); } } (Tag { name, attrs, end, self_closing }, i) } impl<'f> Builder<'f> { fn skipping(&self) -> bool { self.skip_at.is_some() } fn current_link(&self) -> Option { self.stack.iter().rev().find_map(|o| o.link.clone()) } fn has_open(&self, names: &[&str]) -> bool { self.stack.iter().any(|o| names.contains(&o.name.as_str())) } fn text(&mut self, raw: &str) { if raw.is_empty() || self.skipping() { return; } if let Some(pre) = &mut self.pre { pre.push_str(&decode_entities(raw)); return; } let t = collapse(&decode_entities(raw)); if t.is_empty() || (t == " " && self.spans.is_empty()) { return; } let link = self.current_link(); let bold = self.heading == 0 && self.has_open(&["b", "strong"]); let italic = self.has_open(&["i", "em", "cite", "var"]); let code = self.has_open(&["code", "kbd", "samp", "tt"]); let mut t = t; if self.spans.last().is_some_and(|s| s.text.ends_with(' ') || s.text.ends_with('\n')) && t.starts_with(' ') { t.remove(0); if t.is_empty() { return; } } if let Some(last) = self.spans.last_mut() { if last.link == link && last.bold == bold && last.italic == italic && last.code == code { last.text.push_str(&t); return; } } self.spans.push(Inline { text: t, link, bold, italic, code }); } fn flush(&mut self) { let mut spans = core::mem::take(&mut self.spans); // Trim the ends. while spans.first().is_some_and(|s| s.text.trim().is_empty()) { spans.remove(0); } while spans.last().is_some_and(|s| s.text.trim().is_empty()) { spans.pop(); } if let Some(f) = spans.first_mut() { f.text = f.text.trim_start().to_string(); } if let Some(l) = spans.last_mut() { l.text = l.text.trim_end().to_string(); } if spans.is_empty() { return; } let block = if self.heading > 0 { Block::Heading { level: self.heading, spans } } else if let Some((depth, marker)) = self.item.take() { Block::ListItem { depth, marker, spans } } else { Block::Paragraph { spans, quote: self.quote > 0 } }; self.blocks.push(block); } fn is_hidden(&self, t: &Tag) -> bool { if t.attr("hidden").is_some() || t.attr("aria-hidden") == Some("true") { return true; } if let Some(st) = t.attr("style") { let s: String = st.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); if s.contains("display:none") || s.contains("visibility:hidden") { return true; } } for key in ["class", "id"] { if let Some(v) = t.attr(key) { for word in v.split_ascii_whitespace() { let w = word.to_ascii_lowercase(); if AD_WORDS.contains(&w.as_str()) || w.starts_with("ad-slot") || w.starts_with("google_ads") || w.starts_with("div-gpt-ad") { return true; } } } } false } fn resolve(&self, href: &str) -> Option { self.base.join(href) } fn tag(&mut self, t: Tag) { let name = t.name.as_str(); if t.end { self.end_tag(name); return; } let void = VOID.contains(&name); if self.skipping() { if !void && !t.self_closing { self.stack.push(Open { name: t.name.clone(), link: None }); } return; } if name == "base" { if let Some(u) = t.attr("href").and_then(|h| self.base.join(h)) { self.base = u; } return; } let dropped = DROP.contains(&name) || (self.drop_chrome && CHROME.contains(&name)) || self.is_hidden(&t); if dropped { if name == "iframe" { if let Some(u) = t.attr("src").and_then(|s| self.resolve(s)) { if self.filter.blocks(&u) { self.stats.blocked += 1; } } } else if !DROP.contains(&name) && !CHROME.contains(&name) { self.stats.hidden += 1; } if !void && !t.self_closing { self.skip_at = Some(self.stack.len()); self.stack.push(Open { name: t.name.clone(), link: None }); } return; } if BLOCKS.contains(&name) { self.flush(); } match name { "br" => { if let Some(p) = &mut self.pre { p.push('\n'); } else if !self.spans.is_empty() { let link = self.current_link(); self.spans.push(Inline { text: String::from("\n"), link, ..Default::default() }); } } "hr" => { self.blocks.push(Block::Rule); } "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { self.heading = name.as_bytes()[1] - b'0'; } "blockquote" => self.quote += 1, "pre" => { self.pre = Some(String::new()); } "ul" | "menu" | "dir" => self.list.push((false, 0)), "ol" => { let start = t.attr("start").and_then(|s| s.trim().parse::().ok()).unwrap_or(1); self.list.push((true, start.saturating_sub(1))); } "li" => { let depth = self.list.len().max(1) as u8; let marker = match self.list.last_mut() { Some((true, n)) => { *n += 1; let mut m = n.to_string(); m.push('.'); m } _ => String::from("•"), }; self.item = Some((depth, marker)); } "img" => self.image(&t), "form" => { let method = t.attr("method").unwrap_or("get").to_ascii_lowercase(); let action = t.attr("action").unwrap_or(""); let target = if action.trim().is_empty() { Some(self.base.clone()) } else { self.resolve(action) }; self.form = match (method.as_str(), target) { ("get", Some(u)) => { let mut a = u.clone(); a.query = None; let mut hidden = Vec::new(); if let Some(q) = &u.query { for pair in q.split('&') { let mut kv = pair.splitn(2, '='); let k = crate::url::decode_component(kv.next().unwrap_or("")); let v = crate::url::decode_component(kv.next().unwrap_or("")); if !k.is_empty() { hidden.push((k, v)); } } } Some(Form { action: a.to_string(), hidden, field: String::new(), placeholder: String::new(), value: String::new(), submit: String::new() }) } _ => None, }; } "input" => { if let Some(f) = &mut self.form { let ty = t.attr("type").unwrap_or("text").to_ascii_lowercase(); let n = t.attr("name").unwrap_or("").to_string(); let v = t.attr("value").unwrap_or("").to_string(); match ty.as_str() { "hidden" if !n.is_empty() => f.hidden.push((n, v)), "text" | "search" | "" if !n.is_empty() && f.field.is_empty() => { f.field = n; f.value = v; f.placeholder = t.attr("placeholder").or(t.attr("aria-label")).unwrap_or("").to_string(); } "submit" if f.submit.is_empty() => f.submit = v, _ => {} } } } _ => {} } if !void && !t.self_closing { let link = if name == "a" { t.attr("href").and_then(|h| self.resolve(h)).map(|u| u.to_string()) } else { None }; self.stack.push(Open { name: t.name.clone(), link }); } } fn image(&mut self, t: &Tag) { let mut src = t.attr("src").unwrap_or("").trim().to_string(); if src.is_empty() || src.starts_with("data:") { for k in ["data-src", "data-lazy-src", "data-original"] { if let Some(v) = t.attr(k) { if !v.trim().is_empty() { src = v.trim().to_string(); break; } } } } if src.is_empty() || src.starts_with("data:") { if let Some(set) = t.attr("srcset").or(t.attr("data-srcset")) { if let Some(first) = set.split(',').next() { src = first.split_ascii_whitespace().next().unwrap_or("").to_string(); } } } let dim = |k: &str| t.attr(k).and_then(|v| v.trim().trim_end_matches("px").parse::().ok()); let (w, h) = (dim("width"), dim("height")); if w.is_some_and(|w| w <= 2) || h.is_some_and(|h| h <= 2) { // Tracking pixel. self.stats.blocked += 1; return; } let Some(u) = self.resolve(&src) else { return }; if u.scheme != "http" && u.scheme != "https" { return; } if self.filter.blocks(&u) { self.stats.blocked += 1; return; } let alt = collapse(t.attr("alt").unwrap_or("")).trim().to_string(); let link = self.current_link(); self.flush(); self.blocks.push(Block::Image { src: u.to_string(), alt, width: w, height: h, link }); } fn end_tag(&mut self, name: &str) { let Some(pos) = self.stack.iter().rposition(|o| o.name == name) else { return; }; if let Some(at) = self.skip_at { if pos < at { // A stray end tag for something outside the dropped element. return; } self.stack.truncate(pos); if pos == at { self.skip_at = None; } return; } // Close everything opened inside this element too. let closing: Vec = self.stack[pos..].iter().map(|o| o.name.clone()).collect(); for n in closing.iter().rev() { self.close(n); } self.stack.truncate(pos); } fn close(&mut self, name: &str) { if BLOCKS.contains(&name) && name != "pre" { self.flush(); } match name { "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => self.heading = 0, "blockquote" => self.quote = self.quote.saturating_sub(1), "pre" => { if let Some(p) = self.pre.take() { let p = p.trim_matches('\n').to_string(); if !p.trim().is_empty() { self.blocks.push(Block::Code(p)); } } } "ul" | "ol" | "menu" | "dir" => { self.list.pop(); self.item = None; } "li" => self.item = None, "form" => { if let Some(f) = self.form.take() { if !f.field.is_empty() { self.blocks.push(Block::Form(f)); } } } _ => {} } } } /// Collapse every run of whitespace into one space. fn collapse(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut space = false; for c in s.chars() { if c.is_whitespace() && c != '\u{a0}' { if !space { out.push(' '); space = true; } } else { out.push(if c == '\u{a0}' { ' ' } else { c }); space = false; } } out } /// Case-insensitive search for an ASCII needle. fn find_ci(hay: &str, needle: &str) -> Option { let h = hay.as_bytes(); let n = needle.as_bytes(); if n.is_empty() || h.len() < n.len() { return None; } (0..=h.len() - n.len()).find(|&i| h[i..i + n.len()].eq_ignore_ascii_case(n)) } /// Decode character references like `&`, `’` and `—`. pub fn decode_entities(s: &str) -> String { if !s.contains('&') { return s.to_string(); } let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(i) = rest.find('&') { out.push_str(&rest[..i]); rest = &rest[i..]; let end = rest[1..].find(|c: char| c == ';' || c == '&' || c.is_whitespace() || c == '<').map(|e| e + 1); let (name, consumed) = match end { Some(e) if rest.as_bytes()[e] == b';' && e <= 33 => (&rest[1..e], e + 1), Some(e) if e <= 33 => (&rest[1..e], e), None if rest.len() <= 33 => (&rest[1..], rest.len()), _ => ("", 0), }; let decoded = if let Some(num) = name.strip_prefix('#') { let v = if let Some(hex) = num.strip_prefix(['x', 'X']) { u32::from_str_radix(hex, 16).ok() } else { num.parse::().ok() }; v.map(|v| char::from_u32(v).unwrap_or('\u{fffd}')) } else { named_entity(name) }; match decoded { Some(c) if consumed > 0 => { out.push(c); rest = &rest[consumed..]; } _ => { out.push('&'); rest = &rest[1..]; } } } out.push_str(rest); out } fn named_entity(n: &str) -> Option { Some(match n { "amp" | "AMP" => '&', "lt" | "LT" => '<', "gt" | "GT" => '>', "quot" | "QUOT" => '"', "apos" => '\'', "nbsp" => '\u{a0}', "ndash" => '–', "mdash" => '—', "hellip" => '…', "lsquo" => '‘', "rsquo" => '’', "ldquo" => '“', "rdquo" => '”', "laquo" => '«', "raquo" => '»', "middot" => '·', "bull" => '•', "copy" => '©', "reg" => '®', "trade" => '™', "deg" => '°', "times" => '×', "divide" => '÷', "plusmn" => '±', "frac12" => '½', "frac14" => '¼', "frac34" => '¾', "eacute" => 'é', "egrave" => 'è', "aacute" => 'á', "agrave" => 'à', "iacute" => 'í', "oacute" => 'ó', "uacute" => 'ú', "ntilde" => 'ñ', "ccedil" => 'ç', "uuml" => 'ü', "ouml" => 'ö', "auml" => 'ä', "szlig" => 'ß', "euro" => '€', "pound" => '£', "yen" => '¥', "cent" => '¢', "sect" => '§', "para" => '¶', "larr" => '←', "rarr" => '→', "uarr" => '↑', "darr" => '↓', "thinsp" | "ensp" | "emsp" => ' ', "zwj" | "zwnj" | "shy" => '\u{200b}', _ => return None, }) } /// Turn downloaded bytes into text, honouring the declared character set /// for the common Western single-byte encodings. Everything else is read as /// UTF-8. pub fn decode_bytes(bytes: &[u8], content_type: &str) -> String { let mut charset = content_type.to_ascii_lowercase(); if !charset.contains("charset=") { let head = &bytes[..bytes.len().min(2048)]; let head = String::from_utf8_lossy(head).to_ascii_lowercase(); if let Some(i) = head.find("charset=") { charset = head[i..].to_string(); } } let latin = ["charset=iso-8859-1", "charset=\"iso-8859-1", "charset=windows-1252", "charset=\"windows-1252", "charset=latin1", "charset=us-ascii"]; if latin.iter().any(|l| charset.contains(l)) { return bytes.iter().map(|&b| cp1252(b)).collect(); } String::from_utf8_lossy(bytes).into_owned() } fn cp1252(b: u8) -> char { const HI: [char; 32] = [ '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{9d}', 'ž', 'Ÿ', ]; if (0x80..0xa0).contains(&b) { HI[(b - 0x80) as usize] } else { b as char } } #[cfg(test)] mod tests { use super::*; fn doc(html: &str) -> Document { parse(html, &Url::parse("https://site.example/a/page.html").unwrap(), &Filter::new()) } #[test] fn basic_page() { let d = doc("Hi & bye\

Head line

Hello world, friend.

  • one
  • two
\
  1. c
  a\n  b

q
"); assert_eq!(d.title, "Hi & bye"); assert_eq!(d.stats.scripts_skipped, 1); assert_eq!(d.blocks[0], Block::Heading { level: 1, spans: vec![Inline { text: "Head line".into(), ..Default::default() }] }); match &d.blocks[1] { Block::Paragraph { spans, quote: false } => { assert_eq!(spans[0].text, "Hello "); assert_eq!(spans[1].text, "world"); assert_eq!(spans[1].link.as_deref(), Some("https://site.example/x")); assert!(spans[3].italic); } b => panic!("{:?}", b), } assert!(matches!(&d.blocks[2], Block::ListItem { marker, .. } if marker == "•")); assert!(matches!(&d.blocks[3], Block::ListItem { spans, .. } if spans[0].text == "two")); assert!(matches!(&d.blocks[4], Block::ListItem { marker, .. } if marker == "3.")); assert_eq!(d.blocks[5], Block::Code(" a\n b".into())); assert_eq!(d.blocks[6], Block::Rule); assert!(matches!(&d.blocks[7], Block::Paragraph { quote: true, .. })); } #[test] fn ads_and_hidden_are_dropped() { let d = doc("

Keep

Buy now

x

\

n

\ \"A

End

"); let text = d.plain_text(); assert!(text.contains("Keep") && text.contains("End") && text.contains("A cat")); assert!(!text.contains("Buy now")); assert!(!text.lines().any(|l| l == "h" || l == "n" || l == "x")); assert_eq!(d.image_urls(), vec!["https://site.example/a/pic.jpg".to_string()]); assert_eq!(d.stats.blocked, 3); } #[test] fn main_content_wins() { let d = doc("
Logo

Story

Foot
"); assert_eq!(d.plain_text(), "Story\n"); } #[test] fn search_form() { let d = doc(""); match &d.blocks[0] { Block::Form(f) => { assert_eq!(f.target("red fox"), "https://site.example/search?lang=en&src=web&q=red+fox"); assert_eq!(f.submit, "Go"); } b => panic!("{:?}", b), } } #[test] fn entities_and_charsets() { assert_eq!(decode_entities("a <b> ’ — &bogus; & x"), "a ’ — &bogus; & x"); assert_eq!(decode_bytes(b"caf\xe9", "text/html; charset=ISO-8859-1"), "café"); assert_eq!(decode_bytes("café".as_bytes(), "text/html"), "café"); } #[test] fn broken_markup_does_not_panic() { for s in ["<", "