Branchwell

Clearwake / app / crates / clearwake-core / src / html.rs

1//! The page reader. Turns HTML into a calm list of blocks: headings,
2//! paragraphs, lists, quotes, code, pictures and simple search forms.
3//!
4//! Scripts never run and are never fetched. Styles are not applied. Hidden
5//! elements and anything labelled as an ad are left out. When a page marks
6//! its main content (`<main>` or `<article>`), site menus, side bars and
7//! footers are left out too.
8
9use crate::filter::Filter;
10use crate::url::Url;
11use alloc::string::{String, ToString};
12use alloc::vec::Vec;
13
14#[derive(Clone, Debug, PartialEq, Eq, Default)]
15pub struct Inline {
16 pub text: String,
17 /// Absolute address when this run is a link.
18 pub link: Option<String>,
19 pub bold: bool,
20 pub italic: bool,
21 pub code: bool,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct Form {
26 /// Absolute address the search goes to.
27 pub action: String,
28 pub hidden: Vec<(String, String)>,
29 pub field: String,
30 pub placeholder: String,
31 pub value: String,
32 pub submit: String,
33}
34
35impl Form {
36 /// The address to open when the person submits `text`.
37 pub fn target(&self, text: &str) -> String {
38 let mut s = self.action.clone();
39 s.push(if s.contains('?') { '&' } else { '?' });
40 let mut first = true;
41 for (k, v) in self.hidden.iter().chain(core::iter::once(&(self.field.clone(), String::from(text)))) {
42 if !first {
43 s.push('&');
44 }
45 first = false;
46 s.push_str(&crate::url::encode_component(k));
47 s.push('=');
48 s.push_str(&crate::url::encode_component(v));
49 }
50 s
51 }
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub enum Block {
56 Heading { level: u8, spans: Vec<Inline> },
57 Paragraph { spans: Vec<Inline>, quote: bool },
58 ListItem { depth: u8, marker: String, spans: Vec<Inline> },
59 Code(String),
60 Image { src: String, alt: String, width: Option<u32>, height: Option<u32>, link: Option<String> },
61 Rule,
62 Form(Form),
63}
64
65#[derive(Clone, Debug, Default)]
66pub struct Stats {
67 /// Scripts that the page asked for and Clearwake never loaded.
68 pub scripts_skipped: u32,
69 /// Pictures and frames from ad or tracker addresses.
70 pub blocked: u32,
71 /// Elements labelled as ads or hidden.
72 pub hidden: u32,
73}
74
75#[derive(Clone, Debug)]
76pub struct Document {
77 pub url: Url,
78 pub title: String,
79 pub blocks: Vec<Block>,
80 pub stats: Stats,
81}
82
83impl Document {
84 /// All picture addresses on the page, in order, without repeats.
85 pub fn image_urls(&self) -> Vec<String> {
86 let mut v: Vec<String> = Vec::new();
87 for b in &self.blocks {
88 if let Block::Image { src, .. } = b {
89 if !v.contains(src) {
90 v.push(src.clone());
91 }
92 }
93 }
94 v
95 }
96
97 /// The page as plain text, one block per paragraph.
98 pub fn plain_text(&self) -> String {
99 let mut s = String::new();
100 for b in &self.blocks {
101 match b {
102 Block::Heading { spans, .. } | Block::Paragraph { spans, .. } | Block::ListItem { spans, .. } => {
103 for sp in spans {
104 s.push_str(&sp.text);
105 }
106 }
107 Block::Code(c) => s.push_str(c),
108 Block::Image { alt, .. } => s.push_str(alt),
109 Block::Rule => s.push_str("---"),
110 Block::Form(f) => s.push_str(&f.submit),
111 }
112 s.push('\n');
113 }
114 s
115 }
116}
117
118const MAX_BLOCKS: usize = 20_000;
119
120const VOID: &[&str] = &[
121 "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", "keygen",
122];
123
124/// Elements that never show: their whole contents are dropped.
125const DROP: &[&str] = &[
126 "head", "script", "style", "template", "svg", "math", "iframe", "object", "canvas", "video", "audio", "select", "button",
127 "dialog", "map", "frameset", "textarea", "datalist", "portal",
128];
129
130/// Dropped only when the page marks its main content.
131const CHROME: &[&str] = &["nav", "footer", "aside", "header"];
132
133const BLOCKS: &[&str] = &[
134 "address", "article", "aside", "blockquote", "body", "center", "dd", "details", "dialog", "dir", "div", "dl", "dt",
135 "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr",
136 "html", "li", "main", "menu", "nav", "ol", "p", "pre", "section", "summary", "table", "tbody", "td", "tfoot", "th",
137 "thead", "tr", "ul", "caption", "legend", "label",
138];
139
140const AD_WORDS: &[&str] = &[
141 "ad", "ads", "advert", "adverts", "advertisement", "advertising", "adsbygoogle", "ad-slot", "ad-container", "ad-wrapper",
142 "ad-banner", "ad-unit", "adunit", "ad_unit", "dfp-ad", "google-ad", "sponsored", "sponsored-content", "promoted",
143 "taboola", "outbrain", "cookie-banner", "cookie-consent", "newsletter-popup", "paywall-overlay",
144];
145
146struct Tag {
147 name: String,
148 attrs: Vec<(String, String)>,
149 end: bool,
150 self_closing: bool,
151}
152
153impl Tag {
154 fn attr(&self, n: &str) -> Option<&str> {
155 self.attrs.iter().find(|(k, _)| k == n).map(|(_, v)| v.as_str())
156 }
157}
158
159struct Open {
160 name: String,
161 link: Option<String>,
162}
163
164struct Builder<'f> {
165 base: Url,
166 filter: &'f Filter,
167 drop_chrome: bool,
168 blocks: Vec<Block>,
169 spans: Vec<Inline>,
170 stack: Vec<Open>,
171 /// Depth of the stack at which a dropped element began.
172 skip_at: Option<usize>,
173 heading: u8,
174 list: Vec<(bool, u32)>,
175 item: Option<(u8, String)>,
176 quote: u32,
177 pre: Option<String>,
178 form: Option<Form>,
179 title: String,
180 stats: Stats,
181}
182
183/// Read a page. `url` is the address it came from (used to resolve links).
184pub fn parse(source: &str, url: &Url, filter: &Filter) -> Document {
185 let lower_has = |needle: &str| find_ci(source, needle).is_some();
186 let drop_chrome = lower_has("<main") || lower_has("<article");
187 let mut b = Builder {
188 base: url.clone(),
189 filter,
190 drop_chrome,
191 blocks: Vec::new(),
192 spans: Vec::new(),
193 stack: Vec::new(),
194 skip_at: None,
195 heading: 0,
196 list: Vec::new(),
197 item: None,
198 quote: 0,
199 pre: None,
200 form: None,
201 title: String::new(),
202 stats: Stats::default(),
203 };
204 tokenize(source, &mut b);
205 b.flush();
206 let title = collapse(&b.title).trim().to_string();
207 Document { url: url.clone(), title, blocks: b.blocks, stats: b.stats }
208}
209
210fn tokenize(src: &str, b: &mut Builder) {
211 let bytes = src.as_bytes();
212 let mut i = 0;
213 let mut text_start = 0;
214 while i < bytes.len() {
215 if bytes[i] != b'<' {
216 i += 1;
217 continue;
218 }
219 let rest = &src[i..];
220 if rest.starts_with("<!--") {
221 b.text(&src[text_start..i]);
222 let end = rest.find("-->").map(|e| i + e + 3).unwrap_or(src.len());
223 i = end;
224 text_start = i;
225 continue;
226 }
227 if rest.starts_with("<!") || rest.starts_with("<?") {
228 b.text(&src[text_start..i]);
229 let end = rest.find('>').map(|e| i + e + 1).unwrap_or(src.len());
230 i = end;
231 text_start = i;
232 continue;
233 }
234 let next = bytes.get(i + 1).copied().unwrap_or(0);
235 let is_tag = next.is_ascii_alphabetic() || (next == b'/' && bytes.get(i + 2).is_some_and(|c| c.is_ascii_alphabetic()));
236 if !is_tag {
237 i += 1;
238 continue;
239 }
240 b.text(&src[text_start..i]);
241 let (tag, end) = read_tag(src, i);
242 i = end;
243 text_start = i;
244 // Raw text elements: skip straight to their end tag.
245 if !tag.end && !tag.self_closing && (tag.name == "script" || tag.name == "style" || tag.name == "textarea" || tag.name == "title" || tag.name == "xmp" || tag.name == "plaintext") {
246 let close = {
247 let mut c = String::from("</");
248 c.push_str(&tag.name);
249 c
250 };
251 let body_end = find_ci(&src[i..], &close).map(|e| i + e).unwrap_or(src.len());
252 let body = &src[i..body_end];
253 match tag.name.as_str() {
254 "title" => {
255 if b.title.is_empty() && !b.has_open(&["svg"]) {
256 b.title = decode_entities(body);
257 }
258 }
259 "script" => b.stats.scripts_skipped += 1,
260 _ => {}
261 }
262 i = src[body_end..].find('>').map(|e| body_end + e + 1).unwrap_or(src.len());
263 text_start = i;
264 continue;
265 }
266 b.tag(tag);
267 if b.blocks.len() > MAX_BLOCKS {
268 return;
269 }
270 }
271 b.text(&src[text_start..]);
272}
273
274fn read_tag(src: &str, start: usize) -> (Tag, usize) {
275 let bytes = src.as_bytes();
276 let mut i = start + 1;
277 let end = bytes.get(i) == Some(&b'/');
278 if end {
279 i += 1;
280 }
281 let ns = i;
282 while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' && bytes[i] != b'/' {
283 i += 1;
284 }
285 let name = src[ns..i].to_ascii_lowercase();
286 let mut attrs = Vec::new();
287 let mut self_closing = false;
288 loop {
289 while i < bytes.len() && (bytes[i].is_ascii_whitespace() || (bytes[i] == b'/' && bytes.get(i + 1) != Some(&b'>'))) {
290 i += 1;
291 }
292 if i >= bytes.len() {
293 break;
294 }
295 if bytes[i] == b'>' {
296 i += 1;
297 break;
298 }
299 if bytes[i] == b'/' {
300 self_closing = true;
301 i += 1;
302 continue;
303 }
304 let ks = i;
305 while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'=' && bytes[i] != b'>' && !(bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'>')) {
306 i += 1;
307 }
308 let key = src[ks..i].to_ascii_lowercase();
309 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
310 i += 1;
311 }
312 let mut val = String::new();
313 if bytes.get(i) == Some(&b'=') {
314 i += 1;
315 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
316 i += 1;
317 }
318 match bytes.get(i) {
319 Some(&q) if q == b'"' || q == b'\'' => {
320 let vs = i + 1;
321 let ve = src[vs..].find(q as char).map(|e| vs + e).unwrap_or(src.len());
322 val = decode_entities(&src[vs..ve]);
323 i = (ve + 1).min(src.len());
324 }
325 _ => {
326 let vs = i;
327 while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
328 i += 1;
329 }
330 val = decode_entities(&src[vs..i]);
331 }
332 }
333 }
334 if !key.is_empty() && attrs.len() < 64 {
335 attrs.push((key, val));
336 }
337 }
338 (Tag { name, attrs, end, self_closing }, i)
339}
340
341impl<'f> Builder<'f> {
342 fn skipping(&self) -> bool {
343 self.skip_at.is_some()
344 }
345
346 fn current_link(&self) -> Option<String> {
347 self.stack.iter().rev().find_map(|o| o.link.clone())
348 }
349
350 fn has_open(&self, names: &[&str]) -> bool {
351 self.stack.iter().any(|o| names.contains(&o.name.as_str()))
352 }
353
354 fn text(&mut self, raw: &str) {
355 if raw.is_empty() || self.skipping() {
356 return;
357 }
358 if let Some(pre) = &mut self.pre {
359 pre.push_str(&decode_entities(raw));
360 return;
361 }
362 let t = collapse(&decode_entities(raw));
363 if t.is_empty() || (t == " " && self.spans.is_empty()) {
364 return;
365 }
366 let link = self.current_link();
367 let bold = self.heading == 0 && self.has_open(&["b", "strong"]);
368 let italic = self.has_open(&["i", "em", "cite", "var"]);
369 let code = self.has_open(&["code", "kbd", "samp", "tt"]);
370 let mut t = t;
371 if self.spans.last().is_some_and(|s| s.text.ends_with(' ') || s.text.ends_with('\n')) && t.starts_with(' ') {
372 t.remove(0);
373 if t.is_empty() {
374 return;
375 }
376 }
377 if let Some(last) = self.spans.last_mut() {
378 if last.link == link && last.bold == bold && last.italic == italic && last.code == code {
379 last.text.push_str(&t);
380 return;
381 }
382 }
383 self.spans.push(Inline { text: t, link, bold, italic, code });
384 }
385
386 fn flush(&mut self) {
387 let mut spans = core::mem::take(&mut self.spans);
388 // Trim the ends.
389 while spans.first().is_some_and(|s| s.text.trim().is_empty()) {
390 spans.remove(0);
391 }
392 while spans.last().is_some_and(|s| s.text.trim().is_empty()) {
393 spans.pop();
394 }
395 if let Some(f) = spans.first_mut() {
396 f.text = f.text.trim_start().to_string();
397 }
398 if let Some(l) = spans.last_mut() {
399 l.text = l.text.trim_end().to_string();
400 }
401 if spans.is_empty() {
402 return;
403 }
404 let block = if self.heading > 0 {
405 Block::Heading { level: self.heading, spans }
406 } else if let Some((depth, marker)) = self.item.take() {
407 Block::ListItem { depth, marker, spans }
408 } else {
409 Block::Paragraph { spans, quote: self.quote > 0 }
410 };
411 self.blocks.push(block);
412 }
413
414 fn is_hidden(&self, t: &Tag) -> bool {
415 if t.attr("hidden").is_some() || t.attr("aria-hidden") == Some("true") {
416 return true;
417 }
418 if let Some(st) = t.attr("style") {
419 let s: String = st.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
420 if s.contains("display:none") || s.contains("visibility:hidden") {
421 return true;
422 }
423 }
424 for key in ["class", "id"] {
425 if let Some(v) = t.attr(key) {
426 for word in v.split_ascii_whitespace() {
427 let w = word.to_ascii_lowercase();
428 if AD_WORDS.contains(&w.as_str()) || w.starts_with("ad-slot") || w.starts_with("google_ads") || w.starts_with("div-gpt-ad") {
429 return true;
430 }
431 }
432 }
433 }
434 false
435 }
436
437 fn resolve(&self, href: &str) -> Option<Url> {
438 self.base.join(href)
439 }
440
441 fn tag(&mut self, t: Tag) {
442 let name = t.name.as_str();
443 if t.end {
444 self.end_tag(name);
445 return;
446 }
447 let void = VOID.contains(&name);
448
449 if self.skipping() {
450 if !void && !t.self_closing {
451 self.stack.push(Open { name: t.name.clone(), link: None });
452 }
453 return;
454 }
455
456 if name == "base" {
457 if let Some(u) = t.attr("href").and_then(|h| self.base.join(h)) {
458 self.base = u;
459 }
460 return;
461 }
462
463 let dropped = DROP.contains(&name) || (self.drop_chrome && CHROME.contains(&name)) || self.is_hidden(&t);
464 if dropped {
465 if name == "iframe" {
466 if let Some(u) = t.attr("src").and_then(|s| self.resolve(s)) {
467 if self.filter.blocks(&u) {
468 self.stats.blocked += 1;
469 }
470 }
471 } else if !DROP.contains(&name) && !CHROME.contains(&name) {
472 self.stats.hidden += 1;
473 }
474 if !void && !t.self_closing {
475 self.skip_at = Some(self.stack.len());
476 self.stack.push(Open { name: t.name.clone(), link: None });
477 }
478 return;
479 }
480
481 if BLOCKS.contains(&name) {
482 self.flush();
483 }
484
485 match name {
486 "br" => {
487 if let Some(p) = &mut self.pre {
488 p.push('\n');
489 } else if !self.spans.is_empty() {
490 let link = self.current_link();
491 self.spans.push(Inline { text: String::from("\n"), link, ..Default::default() });
492 }
493 }
494 "hr" => {
495 self.blocks.push(Block::Rule);
496 }
497 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
498 self.heading = name.as_bytes()[1] - b'0';
499 }
500 "blockquote" => self.quote += 1,
501 "pre" => {
502 self.pre = Some(String::new());
503 }
504 "ul" | "menu" | "dir" => self.list.push((false, 0)),
505 "ol" => {
506 let start = t.attr("start").and_then(|s| s.trim().parse::<u32>().ok()).unwrap_or(1);
507 self.list.push((true, start.saturating_sub(1)));
508 }
509 "li" => {
510 let depth = self.list.len().max(1) as u8;
511 let marker = match self.list.last_mut() {
512 Some((true, n)) => {
513 *n += 1;
514 let mut m = n.to_string();
515 m.push('.');
516 m
517 }
518 _ => String::from("•"),
519 };
520 self.item = Some((depth, marker));
521 }
522 "img" => self.image(&t),
523 "form" => {
524 let method = t.attr("method").unwrap_or("get").to_ascii_lowercase();
525 let action = t.attr("action").unwrap_or("");
526 let target = if action.trim().is_empty() { Some(self.base.clone()) } else { self.resolve(action) };
527 self.form = match (method.as_str(), target) {
528 ("get", Some(u)) => {
529 let mut a = u.clone();
530 a.query = None;
531 let mut hidden = Vec::new();
532 if let Some(q) = &u.query {
533 for pair in q.split('&') {
534 let mut kv = pair.splitn(2, '=');
535 let k = crate::url::decode_component(kv.next().unwrap_or(""));
536 let v = crate::url::decode_component(kv.next().unwrap_or(""));
537 if !k.is_empty() {
538 hidden.push((k, v));
539 }
540 }
541 }
542 Some(Form { action: a.to_string(), hidden, field: String::new(), placeholder: String::new(), value: String::new(), submit: String::new() })
543 }
544 _ => None,
545 };
546 }
547 "input" => {
548 if let Some(f) = &mut self.form {
549 let ty = t.attr("type").unwrap_or("text").to_ascii_lowercase();
550 let n = t.attr("name").unwrap_or("").to_string();
551 let v = t.attr("value").unwrap_or("").to_string();
552 match ty.as_str() {
553 "hidden" if !n.is_empty() => f.hidden.push((n, v)),
554 "text" | "search" | "" if !n.is_empty() && f.field.is_empty() => {
555 f.field = n;
556 f.value = v;
557 f.placeholder = t.attr("placeholder").or(t.attr("aria-label")).unwrap_or("").to_string();
558 }
559 "submit" if f.submit.is_empty() => f.submit = v,
560 _ => {}
561 }
562 }
563 }
564 _ => {}
565 }
566
567 if !void && !t.self_closing {
568 let link = if name == "a" {
569 t.attr("href").and_then(|h| self.resolve(h)).map(|u| u.to_string())
570 } else {
571 None
572 };
573 self.stack.push(Open { name: t.name.clone(), link });
574 }
575 }
576
577 fn image(&mut self, t: &Tag) {
578 let mut src = t.attr("src").unwrap_or("").trim().to_string();
579 if src.is_empty() || src.starts_with("data:") {
580 for k in ["data-src", "data-lazy-src", "data-original"] {
581 if let Some(v) = t.attr(k) {
582 if !v.trim().is_empty() {
583 src = v.trim().to_string();
584 break;
585 }
586 }
587 }
588 }
589 if src.is_empty() || src.starts_with("data:") {
590 if let Some(set) = t.attr("srcset").or(t.attr("data-srcset")) {
591 if let Some(first) = set.split(',').next() {
592 src = first.split_ascii_whitespace().next().unwrap_or("").to_string();
593 }
594 }
595 }
596 let dim = |k: &str| t.attr(k).and_then(|v| v.trim().trim_end_matches("px").parse::<u32>().ok());
597 let (w, h) = (dim("width"), dim("height"));
598 if w.is_some_and(|w| w <= 2) || h.is_some_and(|h| h <= 2) {
599 // Tracking pixel.
600 self.stats.blocked += 1;
601 return;
602 }
603 let Some(u) = self.resolve(&src) else { return };
604 if u.scheme != "http" && u.scheme != "https" {
605 return;
606 }
607 if self.filter.blocks(&u) {
608 self.stats.blocked += 1;
609 return;
610 }
611 let alt = collapse(t.attr("alt").unwrap_or("")).trim().to_string();
612 let link = self.current_link();
613 self.flush();
614 self.blocks.push(Block::Image { src: u.to_string(), alt, width: w, height: h, link });
615 }
616
617 fn end_tag(&mut self, name: &str) {
618 let Some(pos) = self.stack.iter().rposition(|o| o.name == name) else {
619 return;
620 };
621 if let Some(at) = self.skip_at {
622 if pos < at {
623 // A stray end tag for something outside the dropped element.
624 return;
625 }
626 self.stack.truncate(pos);
627 if pos == at {
628 self.skip_at = None;
629 }
630 return;
631 }
632 // Close everything opened inside this element too.
633 let closing: Vec<String> = self.stack[pos..].iter().map(|o| o.name.clone()).collect();
634 for n in closing.iter().rev() {
635 self.close(n);
636 }
637 self.stack.truncate(pos);
638 }
639
640 fn close(&mut self, name: &str) {
641 if BLOCKS.contains(&name) && name != "pre" {
642 self.flush();
643 }
644 match name {
645 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => self.heading = 0,
646 "blockquote" => self.quote = self.quote.saturating_sub(1),
647 "pre" => {
648 if let Some(p) = self.pre.take() {
649 let p = p.trim_matches('\n').to_string();
650 if !p.trim().is_empty() {
651 self.blocks.push(Block::Code(p));
652 }
653 }
654 }
655 "ul" | "ol" | "menu" | "dir" => {
656 self.list.pop();
657 self.item = None;
658 }
659 "li" => self.item = None,
660 "form" => {
661 if let Some(f) = self.form.take() {
662 if !f.field.is_empty() {
663 self.blocks.push(Block::Form(f));
664 }
665 }
666 }
667 _ => {}
668 }
669 }
670}
671
672/// Collapse every run of whitespace into one space.
673fn collapse(s: &str) -> String {
674 let mut out = String::with_capacity(s.len());
675 let mut space = false;
676 for c in s.chars() {
677 if c.is_whitespace() && c != '\u{a0}' {
678 if !space {
679 out.push(' ');
680 space = true;
681 }
682 } else {
683 out.push(if c == '\u{a0}' { ' ' } else { c });
684 space = false;
685 }
686 }
687 out
688}
689
690/// Case-insensitive search for an ASCII needle.
691fn find_ci(hay: &str, needle: &str) -> Option<usize> {
692 let h = hay.as_bytes();
693 let n = needle.as_bytes();
694 if n.is_empty() || h.len() < n.len() {
695 return None;
696 }
697 (0..=h.len() - n.len()).find(|&i| h[i..i + n.len()].eq_ignore_ascii_case(n))
698}
699
700/// Decode character references like `&amp;`, `&#8217;` and `&#x2014;`.
701pub fn decode_entities(s: &str) -> String {
702 if !s.contains('&') {
703 return s.to_string();
704 }
705 let mut out = String::with_capacity(s.len());
706 let mut rest = s;
707 while let Some(i) = rest.find('&') {
708 out.push_str(&rest[..i]);
709 rest = &rest[i..];
710 let end = rest[1..].find(|c: char| c == ';' || c == '&' || c.is_whitespace() || c == '<').map(|e| e + 1);
711 let (name, consumed) = match end {
712 Some(e) if rest.as_bytes()[e] == b';' && e <= 33 => (&rest[1..e], e + 1),
713 Some(e) if e <= 33 => (&rest[1..e], e),
714 None if rest.len() <= 33 => (&rest[1..], rest.len()),
715 _ => ("", 0),
716 };
717 let decoded = if let Some(num) = name.strip_prefix('#') {
718 let v = if let Some(hex) = num.strip_prefix(['x', 'X']) { u32::from_str_radix(hex, 16).ok() } else { num.parse::<u32>().ok() };
719 v.map(|v| char::from_u32(v).unwrap_or('\u{fffd}'))
720 } else {
721 named_entity(name)
722 };
723 match decoded {
724 Some(c) if consumed > 0 => {
725 out.push(c);
726 rest = &rest[consumed..];
727 }
728 _ => {
729 out.push('&');
730 rest = &rest[1..];
731 }
732 }
733 }
734 out.push_str(rest);
735 out
736}
737
738fn named_entity(n: &str) -> Option<char> {
739 Some(match n {
740 "amp" | "AMP" => '&',
741 "lt" | "LT" => '<',
742 "gt" | "GT" => '>',
743 "quot" | "QUOT" => '"',
744 "apos" => '\'',
745 "nbsp" => '\u{a0}',
746 "ndash" => '–',
747 "mdash" => '—',
748 "hellip" => '…',
749 "lsquo" => '‘',
750 "rsquo" => '’',
751 "ldquo" => '“',
752 "rdquo" => '”',
753 "laquo" => '«',
754 "raquo" => '»',
755 "middot" => '·',
756 "bull" => '•',
757 "copy" => '©',
758 "reg" => '®',
759 "trade" => '™',
760 "deg" => '°',
761 "times" => '×',
762 "divide" => '÷',
763 "plusmn" => '±',
764 "frac12" => '½',
765 "frac14" => '¼',
766 "frac34" => '¾',
767 "eacute" => 'é',
768 "egrave" => 'è',
769 "aacute" => 'á',
770 "agrave" => 'à',
771 "iacute" => 'í',
772 "oacute" => 'ó',
773 "uacute" => 'ú',
774 "ntilde" => 'ñ',
775 "ccedil" => 'ç',
776 "uuml" => 'ü',
777 "ouml" => 'ö',
778 "auml" => 'ä',
779 "szlig" => 'ß',
780 "euro" => '€',
781 "pound" => '£',
782 "yen" => '¥',
783 "cent" => '¢',
784 "sect" => '§',
785 "para" => '¶',
786 "larr" => '←',
787 "rarr" => '→',
788 "uarr" => '↑',
789 "darr" => '↓',
790 "thinsp" | "ensp" | "emsp" => ' ',
791 "zwj" | "zwnj" | "shy" => '\u{200b}',
792 _ => return None,
793 })
794}
795
796/// Turn downloaded bytes into text, honouring the declared character set
797/// for the common Western single-byte encodings. Everything else is read as
798/// UTF-8.
799pub fn decode_bytes(bytes: &[u8], content_type: &str) -> String {
800 let mut charset = content_type.to_ascii_lowercase();
801 if !charset.contains("charset=") {
802 let head = &bytes[..bytes.len().min(2048)];
803 let head = String::from_utf8_lossy(head).to_ascii_lowercase();
804 if let Some(i) = head.find("charset=") {
805 charset = head[i..].to_string();
806 }
807 }
808 let latin = ["charset=iso-8859-1", "charset=\"iso-8859-1", "charset=windows-1252", "charset=\"windows-1252", "charset=latin1", "charset=us-ascii"];
809 if latin.iter().any(|l| charset.contains(l)) {
810 return bytes.iter().map(|&b| cp1252(b)).collect();
811 }
812 String::from_utf8_lossy(bytes).into_owned()
813}
814
815fn cp1252(b: u8) -> char {
816 const HI: [char; 32] = [
817 '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“',
818 '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{9d}', 'ž', 'Ÿ',
819 ];
820 if (0x80..0xa0).contains(&b) { HI[(b - 0x80) as usize] } else { b as char }
821}
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826
827 fn doc(html: &str) -> Document {
828 parse(html, &Url::parse("https://site.example/a/page.html").unwrap(), &Filter::new())
829 }
830
831 #[test]
832 fn basic_page() {
833 let d = doc("<!doctype html><html><head><title>Hi &amp; bye</title><script>alert(1)</script><style>p{}</style></head>\
834 <body><h1>Head <b>line</b></h1><p>Hello <a href=\"/x\">world</a>, <em>friend</em>.</p><ul><li>one<li>two</ul>\
835 <ol start=3><li>c</li></ol><pre> a\n b</pre><hr><blockquote>q</blockquote></body></html>");
836 assert_eq!(d.title, "Hi & bye");
837 assert_eq!(d.stats.scripts_skipped, 1);
838 assert_eq!(d.blocks[0], Block::Heading { level: 1, spans: vec![Inline { text: "Head line".into(), ..Default::default() }] });
839 match &d.blocks[1] {
840 Block::Paragraph { spans, quote: false } => {
841 assert_eq!(spans[0].text, "Hello ");
842 assert_eq!(spans[1].text, "world");
843 assert_eq!(spans[1].link.as_deref(), Some("https://site.example/x"));
844 assert!(spans[3].italic);
845 }
846 b => panic!("{:?}", b),
847 }
848 assert!(matches!(&d.blocks[2], Block::ListItem { marker, .. } if marker == "•"));
849 assert!(matches!(&d.blocks[3], Block::ListItem { spans, .. } if spans[0].text == "two"));
850 assert!(matches!(&d.blocks[4], Block::ListItem { marker, .. } if marker == "3."));
851 assert_eq!(d.blocks[5], Block::Code(" a\n b".into()));
852 assert_eq!(d.blocks[6], Block::Rule);
853 assert!(matches!(&d.blocks[7], Block::Paragraph { quote: true, .. }));
854 }
855
856 #[test]
857 fn ads_and_hidden_are_dropped() {
858 let d = doc("<p>Keep</p><div class=\"ad-slot top\"><p>Buy now</p></div><div id=ads><p>x</p></div>\
859 <p hidden>h</p><p style=\"display: none\">n</p><img src=\"https://securepubads.g.doubleclick.net/x.gif\">\
860 <img src=\"/t.gif\" width=1 height=1><img src=\"pic.jpg\" alt=\"A cat\"><iframe src=\"https://ads.adnxs.com/\"></iframe><p>End</p>");
861 let text = d.plain_text();
862 assert!(text.contains("Keep") && text.contains("End") && text.contains("A cat"));
863 assert!(!text.contains("Buy now"));
864 assert!(!text.lines().any(|l| l == "h" || l == "n" || l == "x"));
865 assert_eq!(d.image_urls(), vec!["https://site.example/a/pic.jpg".to_string()]);
866 assert_eq!(d.stats.blocked, 3);
867 }
868
869 #[test]
870 fn main_content_wins() {
871 let d = doc("<header><a href=/>Logo</a></header><nav>Menu</nav><main><p>Story</p></main><footer>Foot</footer>");
872 assert_eq!(d.plain_text(), "Story\n");
873 }
874
875 #[test]
876 fn search_form() {
877 let d = doc("<form action=\"/search?lang=en\"><input type=hidden name=src value=web><input name=q placeholder=Search><input type=submit value=Go></form>");
878 match &d.blocks[0] {
879 Block::Form(f) => {
880 assert_eq!(f.target("red fox"), "https://site.example/search?lang=en&src=web&q=red+fox");
881 assert_eq!(f.submit, "Go");
882 }
883 b => panic!("{:?}", b),
884 }
885 }
886
887 #[test]
888 fn entities_and_charsets() {
889 assert_eq!(decode_entities("a &lt;b&gt; &#8217; &#x2014; &bogus; & x"), "a <b> ’ — &bogus; & x");
890 assert_eq!(decode_bytes(b"caf\xe9", "text/html; charset=ISO-8859-1"), "café");
891 assert_eq!(decode_bytes("café".as_bytes(), "text/html"), "café");
892 }
893
894 #[test]
895 fn broken_markup_does_not_panic() {
896 for s in ["<", "<a", "<a href='", "<p>&", "</div></div><p>x", "<!--", "<script>", "<b><i>x</b></i>", "<img src=>", "&#99999999;"] {
897 let _ = doc(s);
898 }
899 }
900}