mod clean;
mod decode;
mod dom;
mod notes;
use crate::epub::{Resources, data_url};
use crate::model::Document;
use anyhow::{Context, Result};
use clean::Base;
use dom::{Dom, Space};
use std::collections::HashMap;
use std::path::Path;
use url::Url;
const SNIFF_BYTES: usize = 1024;
const PAGE_NAME: &str = "index.html";
const MAX_STYLE_BYTES: usize = 2 * 1024 * 1024;
pub type FetchPictures = dyn Fn(&[String]) -> HashMap<String, Vec<u8>>;
#[derive(Debug, Clone, Copy)]
pub enum Origin<'a> {
Bytes,
File(&'a Path),
Url {
url: &'a str,
charset: Option<&'a str>,
},
}
pub fn is_html(data: &[u8]) -> bool {
let data = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data);
let start = data
.iter()
.position(|byte| !byte.is_ascii_whitespace())
.unwrap_or(data.len());
let head = data[start..data.len().min(start + SNIFF_BYTES)].to_ascii_lowercase();
let starts = |prefix: &[u8]| head.starts_with(prefix);
starts(b"<!doctype html")
|| starts(b"<html")
|| starts(b"<head")
|| starts(b"<body")
|| ((starts(b"<?xml") || starts(b"<!--")) && head.windows(5).any(|window| window == b"<html"))
}
pub fn read(data: &[u8], origin: Origin<'_>, source: Option<String>) -> Result<Document> {
read_with(data, origin, source, &crate::source::web::fetch_pictures)
}
pub fn read_with(data: &[u8], origin: Origin<'_>, source: Option<String>, fetch: &FetchPictures) -> Result<Document> {
let charset = match origin {
Origin::Url { charset, .. } => charset,
_ => None,
};
let text = decode::decode(data, charset);
let mut dom = Dom::parse(&text);
drop(text);
let base_url = match origin {
Origin::Url { url, .. } => Some(Url::parse(url).with_context(|| format!("'{url}' is not a URL"))?),
Origin::File(path) => directory_url(path),
Origin::Bytes => None,
};
let base = match (&origin, &base_url) {
(Origin::Url { .. }, Some(url)) => Base::Url(url),
(Origin::File(_), Some(url)) => Base::File(url),
_ => Base::None,
};
let article = clean::article(&mut dom, &base);
notes::mark(&mut dom, article.root);
let mut head = Vec::new();
if let Some(title) = &article.title {
let element = dom.element("title", &[]);
let text = dom.text_node(title);
dom.append(element, text);
head.push(element);
}
let mut style_bytes = 0;
for &style in &article.styles {
style_bytes += dom.text(style).len();
if style_bytes <= MAX_STYLE_BYTES {
head.push(style);
}
}
if matches!(origin, Origin::File(_)) {
head.extend(&article.sheets);
}
let mut files = PageFiles {
fetched: match origin {
Origin::Url { .. } => fetch(&picture_urls(&dom, article.root)),
_ => HashMap::new(),
},
};
if matches!(origin, Origin::Url { .. }) {
fallback_pictures(&mut dom, article.root, &mut files, fetch);
}
for img in dom.find_all(article.root, "img") {
dom.remove_attr(img, clean::FALLBACK_ATTR);
}
remove_small_pictures(&mut dom, article.root, &files);
let xhtml = dom.to_xhtml(&head, article.root, article.lang.as_deref());
let name = match origin {
Origin::File(path) => path.file_name().and_then(std::ffi::OsStr::to_str).unwrap_or(PAGE_NAME),
_ => PAGE_NAME,
};
let book = crate::epub::html::read_documents(&files, &[(name, xhtml)], article.title.as_deref(), &article.authors)?;
let mut doc = crate::word::build_document(book, source);
doc.meta.source_format = Some("html".to_string());
Ok(doc)
}
fn fallback_pictures(dom: &mut Dom, root: dom::Id, files: &mut PageFiles, fetch: &FetchPictures) {
let missing: Vec<(dom::Id, Vec<String>)> = dom
.find_all(root, "img")
.into_iter()
.filter(|&img| {
dom.attr(img, "src")
.is_some_and(|src| !files.fetched.contains_key(src) && is_remote(src))
})
.filter_map(|img| {
let others = dom.attr(img, clean::FALLBACK_ATTR)?;
Some((
img,
others
.split_whitespace()
.filter(|url| is_remote(url))
.map(str::to_string)
.collect(),
))
})
.collect();
let mut urls: Vec<String> = Vec::new();
for (_, others) in &missing {
for url in others {
if !urls.contains(url) {
urls.push(url.clone());
}
}
}
if urls.is_empty() {
return;
}
files.fetched.extend(fetch(&urls));
for (img, others) in missing {
if let Some(found) = others.iter().find(|url| files.fetched.contains_key(*url)) {
dom.set_attr(img, "src", found);
}
}
}
fn is_remote(src: &str) -> bool {
src.starts_with("http://") || src.starts_with("https://")
}
fn remove_small_pictures(dom: &mut Dom, root: dom::Id, files: &PageFiles) {
for img in dom.find_all(root, "img") {
let Some(src) = dom.attr(img, "src") else {
continue;
};
let src = src.split_once('#').map_or(src, |(src, _)| src);
let small = files
.read(src)
.and_then(|data| crate::word::pixel_size(&data))
.is_some_and(|(width, height)| width < clean::MIN_PICTURE_PX || height < clean::MIN_PICTURE_PX);
if small {
dom.detach(img);
}
}
}
#[cfg(any(unix, windows, target_os = "wasi"))]
fn directory_url(path: &Path) -> Option<Url> {
let dir = path
.parent()
.filter(|dir| !dir.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let dir = std::fs::canonicalize(dir).ok()?;
Url::from_directory_path(dir).ok()
}
#[cfg(not(any(unix, windows, target_os = "wasi")))]
fn directory_url(_path: &Path) -> Option<Url> {
None
}
fn picture_urls(dom: &Dom, root: dom::Id) -> Vec<String> {
let mut urls: Vec<String> = Vec::new();
for node in dom.descendants(root) {
let src = match dom.space(node) {
Some(Space::Html) if dom.is(node, "img") => dom.attr(node, "src"),
Some(Space::Svg) if dom.name(node) == Some("image") => {
dom.attr(node, "xlink:href").or_else(|| dom.attr(node, "href"))
}
_ => None,
};
if let Some(src) = src
&& is_remote(src)
{
let src = src.split_once('#').map_or(src, |(src, _)| src).to_string();
if !urls.contains(&src) {
urls.push(src);
}
}
}
urls
}
#[derive(Debug, Default)]
struct PageFiles {
fetched: HashMap<String, Vec<u8>>,
}
impl Resources for PageFiles {
fn read(&self, path: &str) -> Option<Vec<u8>> {
if let Some(data) = data_url(path) {
return Some(data);
}
if let Some(data) = self.fetched.get(path) {
return Some(data.clone());
}
read_file_url(path)
}
}
#[cfg(any(unix, windows, target_os = "wasi"))]
fn read_file_url(path: &str) -> Option<Vec<u8>> {
let file = Url::parse(path)
.ok()
.filter(|url| url.scheme() == "file")?
.to_file_path()
.ok()?;
std::fs::read(file).ok()
}
#[cfg(not(any(unix, windows, target_os = "wasi")))]
fn read_file_url(_path: &str) -> Option<Vec<u8>> {
None
}
#[cfg(test)]
mod tests {
use super::is_html;
#[test]
fn pages_are_recognised() {
assert!(is_html(b"\xef\xbb\xbf <!DOCTYPE html><title>x</title>"));
assert!(is_html(b"<html lang=en>"));
assert!(is_html(
b"<?xml version=\"1.0\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"
));
assert!(is_html(b"<!-- saved from url -->\n<HTML>"));
assert!(!is_html(b"%PDF-1.7"));
assert!(!is_html(b"PK\x03\x04"));
assert!(!is_html(b"<?xml version=\"1.0\"?><svg/>"));
assert!(!is_html(b"# Markdown"));
}
}