//! FictionBook 2 (and `.fb2.zip`): FB2's vocabulary mapped to XHTML, then the same sanitizer as every format. use crate::sanitize::{Resolver, is_remote, sanitize}; use crate::xml::{self, XEl, XNode}; use crate::zip::Zip; use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, Series, TocEntry, text}; use base64::Engine; use std::collections::{BTreeMap, HashMap}; pub(crate) fn open_zip(zip: &Zip, limits: &Limits) -> Result { let e = zip .entries() .iter() .find(|e| e.name.to_lowercase().ends_with(".fb2")) .ok_or_else(|| FormatError::Malformed("the archive holds no .fb2 file".into()))?; open(&zip.read_capped(e, limits.max_xml as u64)?, limits) } struct Ctx<'a> { binaries: HashMap, images: Vec, loaded: HashMap>, ids: HashMap, limits: &'a Limits, warnings: Vec, } impl Resolver for Ctx<'_> { fn link(&mut self, href: &str) -> Option { if is_remote(href) { return None; } let id = href.strip_prefix('#')?; let ch = self.ids.get(id)?; Some(format!("{ch}#{id}")) } fn image(&mut self, src: &str) -> Option { if is_remote(src) { self.warnings.push("a remote image was not loaded".into()); return None; } let id = src.strip_prefix('#')?.to_owned(); if let Some(r) = self.loaded.get(&id) { return *r; } let r = (|| { if self.images.len() >= self.limits.max_images { return None; } let (_, b64) = self.binaries.get(&id)?; let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect(); if clean.len() as u64 > self.limits.max_entry * 4 / 3 + 4 { return None; } let bytes = base64::engine::general_purpose::STANDARD.decode(clean).ok()?; let media_type = crate::epub::raster(&bytes)?; let index = self.images.len(); self.images.push(Image { index, media_type, bytes }); Some(index) })(); self.loaded.insert(id, r); r } } fn person(a: &XEl) -> Option { let part = |n: &str| a.child(n).map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); let name: Vec = ["first-name", "middle-name", "last-name"].iter().filter_map(|n| part(n)).collect(); if name.is_empty() { part("nickname") } else { Some(name.join(" ")) } } fn metadata(root: &XEl) -> Metadata { let mut m = Metadata::default(); let Some(desc) = root.child("description") else { return m }; if let Some(ti) = desc.child("title-info") { m.title = ti.child("book-title").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); m.authors = ti.children_named("author").filter_map(person).collect(); m.language = ti.child("lang").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); m.subjects = ti.children_named("genre").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()).collect(); m.description = ti.child("annotation").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); m.published = ti.child("date").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); if let Some(seq) = ti.child("sequence") && let Some(name) = seq.attr("name") { m.series = Some(Series { name: name.trim().to_owned(), index: seq.attr("number").and_then(|n| n.trim().parse().ok()), }); } } if let Some(pi) = desc.child("publish-info") { if let Some(isbn) = pi.child("isbn") { m.identifiers.push(text::collapse(&isbn.text())); } m.publisher = pi.child("publisher").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); if m.published.is_none() { m.published = pi.child("year").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); } } m } /// FB2 → XHTML vocabulary. `level` is the section depth (for heading levels). fn convert(e: &XEl, level: usize) -> XEl { let name = match e.local() { "section" => "section", "title" => ["h1", "h2", "h3", "h4", "h5", "h6"][(level + 1).min(5)], "subtitle" => "h6", "p" | "v" | "text-author" | "date" => "p", "emphasis" => "em", "strong" => "strong", "strikethrough" => "s", "sub" => "sub", "sup" => "sup", "code" => "code", "empty-line" => "br", "epigraph" | "cite" => "blockquote", "poem" | "stanza" | "annotation" => "div", "a" => "a", "image" => "img", "table" | "tr" | "td" | "th" => e.local(), _ => "span", }; let mut out = XEl::new(name); for (k, v) in &e.attrs { match xml::local(k) { "id" => out.attrs.push(("id".into(), v.clone())), "href" if name == "a" => out.attrs.push(("href".into(), v.clone())), "href" if name == "img" => out.attrs.push(("src".into(), v.clone())), "alt" | "title" | "colspan" | "rowspan" => out.attrs.push((xml::local(k).to_owned(), v.clone())), _ => {} } } let in_title = e.is("title"); let mut first = true; for c in &e.children { match c { XNode::Text(t) => out.push_text(t), XNode::El(child) => { let next = if e.is("section") { level + 1 } else { level }; let mut conv = convert(child, next); if in_title && child.is("p") { conv.name = "span".into(); if !first { out.children.push(XNode::El(XEl::new("br"))); } first = false; } out.children.push(XNode::El(conv)); } } } out } fn collect_ids(e: &XEl, chapter: usize, out: &mut HashMap) { if let Some(id) = e.attr("id") { out.entry(id.to_owned()).or_insert(chapter); } for d in e.descendants() { if let Some(id) = d.attr("id") { out.entry(id.to_owned()).or_insert(chapter); } } } pub(crate) fn open(bytes: &[u8], limits: &Limits) -> Result { let s = text::decode_xml(bytes); let root = xml::parse(&s, limits)?; if !root.is("FictionBook") { return Err(FormatError::Malformed("not a FictionBook document".into())); } let metadata = metadata(&root); let mut binaries = HashMap::new(); for b in root.children_named("binary") { if let Some(id) = b.attr("id") { binaries.insert(id.to_owned(), ("", b.text())); } } // Chapter sources: the main bodies' title pages and top-level sections, then the notes bodies. let mut sources: Vec<(XEl, bool, bool)> = Vec::new(); // (converted chapter, linear, notes) for body in root.children_named("body") { let notes = matches!(body.attr("name"), Some("notes" | "comments")); if notes { sources.push((convert(body, 0), false, true)); continue; } let mut front = XEl::new("div"); let mut sections = Vec::new(); for c in body.elements() { if c.is("section") { sections.push(convert(c, 0)); } else { front.children.push(XNode::El(convert(c, 0))); } } let empty = front.children.is_empty(); if !empty { sources.push((front, true, false)); } if sections.is_empty() && empty { sources.push((convert(body, 0), true, false)); } for s in sections { sources.push((s, true, false)); } } if sources.len() > limits.max_chapters { return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters))); } let mut ids = HashMap::new(); for (i, (src, _, _)) in sources.iter().enumerate() { collect_ids(src, i, &mut ids); } let mut ctx = Ctx { binaries, images: Vec::new(), loaded: HashMap::new(), ids, limits, warnings: Vec::new() }; let mut chapters = Vec::new(); let mut footnotes = BTreeMap::new(); let mut toc = Vec::new(); for (i, (src, linear, notes)) in sources.iter().enumerate() { let mut wrap = XEl::new("body"); wrap.children.push(XNode::El(src.clone())); let s = sanitize(&wrap, &mut ctx); if *notes { for sec in s.root.descendants() { if sec.name == "section" && let Some(id) = sec.attr("id") { let mut w = crate::Element::new("div"); w.children = sec.children.clone(); footnotes.insert(format!("{i}#{id}"), crate::sanitize::serialize(&w)); } } } let ch = crate::chapter(format!("chapter-{i}"), None, *linear, s.root); if let Some(t) = &ch.title && *linear { toc.push(TocEntry { title: t.clone(), chapter: i, fragment: None, children: vec![] }); } chapters.push(ch); } let cover = root .child("description") .and_then(|d| d.child("title-info")) .and_then(|t| t.child("coverpage")) .and_then(|c| c.child("image")) .and_then(|i| i.attr("href").map(str::to_owned)) .and_then(|h| ctx.image(&h)); Ok(Document { format: Format::Fb2, metadata, chapters, toc, footnotes, images: ctx.images, cover, warnings: ctx.warnings, }) }