66 lines
2.4 KiB
Rust
66 lines
2.4 KiB
Rust
//! Tag-soup HTML (MOBI text, XHTML that is not well-formed) through html5ever into the same owned tree as XML.
|
|
//! The walk is depth-capped: below `max_depth` only text is collected, iteratively.
|
|
|
|
use crate::xml::{XEl, XNode};
|
|
use crate::{FormatError, Limits, Result};
|
|
use html5ever::tendril::TendrilSink;
|
|
use markup5ever_rcdom::{Handle, NodeData, RcDom};
|
|
|
|
/// Parses an HTML document; returns its `<html>` element (html5ever always makes one).
|
|
pub(crate) fn parse(text: &str, limits: &Limits) -> Result<XEl> {
|
|
if text.len() > limits.max_text {
|
|
return Err(FormatError::TooLarge("the text is larger than the limit".into()));
|
|
}
|
|
let dom = html5ever::parse_document(RcDom::default(), Default::default()).one(text);
|
|
let mut doc = XEl::new("#document");
|
|
let kids: Vec<Handle> = dom.document.children.borrow().clone();
|
|
for k in kids {
|
|
convert(&k, &mut doc, 0, limits.max_depth);
|
|
}
|
|
doc.elements()
|
|
.find(|e| e.is("html"))
|
|
.cloned()
|
|
.ok_or_else(|| FormatError::Malformed("HTML without a document element".into()))
|
|
}
|
|
|
|
fn convert(h: &Handle, parent: &mut XEl, depth: usize, max: usize) {
|
|
match &h.data {
|
|
NodeData::Text { contents } => parent.push_text(&contents.borrow()),
|
|
NodeData::Element { name, attrs, .. } => {
|
|
if depth >= max {
|
|
parent.push_text(&text_of(h));
|
|
return;
|
|
}
|
|
let mut el = XEl::new(&name.local);
|
|
for a in attrs.borrow().iter() {
|
|
let key = match &a.name.prefix {
|
|
Some(p) => format!("{p}:{}", a.name.local),
|
|
None => a.name.local.to_string(),
|
|
};
|
|
el.attrs.push((key, a.value.to_string()));
|
|
}
|
|
let kids: Vec<Handle> = h.children.borrow().clone();
|
|
for k in &kids {
|
|
convert(k, &mut el, depth + 1, max);
|
|
}
|
|
parent.children.push(XNode::El(el));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn text_of(h: &Handle) -> String {
|
|
let mut s = String::new();
|
|
let mut stack = vec![h.clone()];
|
|
while let Some(n) = stack.pop() {
|
|
match &n.data {
|
|
NodeData::Text { contents } => s.push_str(&contents.borrow()),
|
|
NodeData::Element { name, .. } if crate::sanitize::DROP.contains(&&*name.local) => continue,
|
|
_ => {}
|
|
}
|
|
let kids: Vec<Handle> = n.children.borrow().clone();
|
|
stack.extend(kids.into_iter().rev());
|
|
}
|
|
s
|
|
}
|