mod meta;
mod text;
mod tree;
use crate::draft::{Draft, PictureData, Section, SourcePicture};
use crate::error::{Error, Result};
use crate::format::Format;
use crate::options::ConvertOptions;
use crate::report::{Warning, WarningKind};
use base64::Engine as _;
use base64::alphabet::STANDARD;
use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
use mbook::Limits;
use std::collections::{HashMap, HashSet};
use std::io::{Cursor, Read};
use text::Renderer;
use tree::{Binary, Document, Element};
use zip::ZipArchive;
const NOTE_BODIES: [&str; 2] = ["notes", "comments"];
const ROOT: &str = "FictionBook";
const LENIENT: GeneralPurpose = GeneralPurpose::new(
&STANDARD,
GeneralPurposeConfig::new()
.with_decode_padding_mode(DecodePaddingMode::Indifferent)
.with_decode_allow_trailing_bits(true),
);
pub(crate) fn read(source: &[u8], options: &ConvertOptions) -> Result<Draft> {
let limits = &options.limits.book;
let unpacked;
let xml = if source.starts_with(b"PK\x03\x04") {
unpacked = unpack(source, limits)?;
unpacked.as_slice()
} else {
source
};
let document = tree::parse(xml, limits)?;
if document.root.name != ROOT {
return Err(Error::source(
Format::Fb2,
format!("the root element is `{}`, not `{ROOT}`", document.root.name),
));
}
Ok(convert(&document))
}
fn unpack(source: &[u8], limits: &Limits) -> Result<Vec<u8>> {
let failed = |error| Error::source(Format::Fb2, error);
let mut archive = ZipArchive::new(Cursor::new(source)).map_err(failed)?;
let index = (0..archive.len())
.find(|&index| {
archive
.name_for_index(index)
.and_then(std::result::Result::ok)
.is_some_and(|name| name.to_ascii_lowercase().ends_with(".fb2"))
})
.ok_or_else(|| Error::source(Format::Fb2, "the archive holds no .fb2 file"))?;
if archive.by_index_raw(index).map_err(failed)?.encrypted() {
return Err(Error::Protected(Format::Fb2));
}
let max = limits.max_file_bytes;
let too_large = || Error::Limit("the .fb2 file in the archive is larger than the limit");
let entry = archive.by_index(index).map_err(failed)?;
if entry.size() > max {
return Err(too_large());
}
let mut data = Vec::new();
entry
.take(max.saturating_add(1))
.read_to_end(&mut data)
.map_err(|error| Error::source(Format::Fb2, error))?;
if u64::try_from(data.len()).map_or(true, |length| length > max) {
return Err(too_large());
}
Ok(data)
}
fn convert(document: &Document) -> Draft {
let root = &document.root;
let (pictures, mut warnings) = pictures(&document.binaries);
let names: HashSet<String> = pictures
.iter()
.map(|picture| picture.name.clone())
.collect();
let cover = root
.child("description")
.and_then(|description| description.child("title-info"))
.and_then(|info| info.child("coverpage"))
.and_then(|covers| covers.child("image"))
.and_then(|image| image.attr("href"))
.and_then(|href| href.trim().strip_prefix('#'))
.filter(|id| names.contains(*id))
.map(str::to_owned);
let mut notes = HashMap::new();
for body in root.named("body").filter(|body| is_notes(body)) {
collect_notes(body, &mut notes);
}
let mut renderer = Renderer::new(notes, names);
let texts = root
.named("body")
.find(|body| !is_notes(body))
.map(|body| renderer.render_body(body))
.unwrap_or_default();
let sections = texts
.into_iter()
.filter(|(_, markdown)| !markdown.trim().is_empty())
.map(|(name, markdown)| Section {
markdown: renderer.resolve(&markdown),
name,
})
.collect();
warnings.append(&mut renderer.warnings);
#[cfg_attr(
not(outlines),
expect(
clippy::needless_update,
reason = "builds with outlines have one more field"
)
)]
let draft = Draft {
meta: meta::read(root),
sections,
pictures,
cover,
warnings,
..Draft::default()
};
draft
}
fn is_notes(body: &Element) -> bool {
body.attr("name").is_some_and(|name| {
NOTE_BODIES
.iter()
.any(|note| name.trim().eq_ignore_ascii_case(note))
})
}
fn collect_notes<'a>(parent: &'a Element, notes: &mut HashMap<String, &'a Element>) {
for section in parent.named("section") {
if let Some(id) = section.attr("id") {
notes.entry(id.trim().to_owned()).or_insert(section);
}
collect_notes(section, notes);
}
}
fn pictures(binaries: &[Binary]) -> (Vec<SourcePicture>, Vec<Warning>) {
let mut pictures = Vec::new();
let mut warnings = Vec::new();
for binary in binaries {
match LENIENT.decode(&binary.data) {
Ok(data) if !data.is_empty() => pictures.push(SourcePicture {
name: binary.id.clone(),
data: PictureData::Encoded(data),
}),
_ => warnings.push(Warning::whole_book(WarningKind::PictureDropped(
binary.id.clone(),
))),
}
}
(pictures, warnings)
}