//! 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