mod archive;
mod landmarks;
mod meta;
mod paths;
use crate::draft::{Draft, OutlineEntry, PictureData, Section, SourcePicture};
use crate::error::{Error, Result};
use crate::format::Format;
use crate::markdown;
use crate::options::ConvertOptions;
use crate::report::Warning;
use crate::xhtml;
use ::markdown::mdast::Node;
use ::markdown::{ParseOptions, to_mdast};
use archive::Archive;
use rbook::Epub;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Text,
Picture,
Other,
}
struct Item {
path: String,
name: String,
kind: Kind,
text: String,
}
struct Targets {
sections: HashMap<String, Target>,
pictures: HashSet<String>,
}
struct Target {
name: String,
ids: HashSet<String>,
}
impl Target {
fn destination(&self, id: Option<&str>) -> String {
markdown::destination(&self.name, id.filter(|id| self.ids.contains(*id)))
}
}
impl Targets {
fn link(&self, document: &str, href: &str) -> Option<String> {
let reference = paths::resolve(document, href)?;
let target = self.sections.get(&reference.path)?;
Some(target.destination(reference.fragment.as_deref()))
}
fn picture(&self, document: &str, src: &str) -> Option<String> {
let reference = paths::resolve(document, src)?;
self.pictures
.contains(&reference.path)
.then_some(reference.path)
}
}
pub(crate) fn read(source: &[u8], options: &ConvertOptions) -> Result<Draft> {
let limits = options.limits.book;
let mut archive = Archive::open(source, limits)?;
let epub = Epub::options()
.read(Cursor::new(source.to_vec()))
.map_err(|error| Error::source(Format::Epub, error))?;
let pictures = read_pictures(&epub, &mut archive)?;
let picture_names: HashSet<String> = pictures.iter().map(|p| p.name.clone()).collect();
let cover = epub
.manifest()
.cover_image()
.and_then(|entry| paths::resolve("", entry.href().as_str()))
.map(|reference| reference.path)
.filter(|path| picture_names.contains(path));
let mut items = read_items(&epub, &mut archive, &picture_names, limits.max_resources)?;
let mut targets = Targets {
sections: HashMap::new(),
pictures: picture_names,
};
let mut skipped = HashSet::new();
for item in &mut items {
let first = first_pass(item, &targets, cover.as_deref())?;
match first {
Some(ids) => {
targets.sections.insert(
item.path.clone(),
Target {
name: item.name.clone(),
ids,
},
);
}
None => {
skipped.insert(item.path.clone());
}
}
}
let mut draft = Draft::default();
for item in &items {
if skipped.contains(&item.path) {
continue;
}
let markdown = if item.kind == Kind::Picture {
let figure = markdown::image("", &markdown::encoded_path(&item.path), None);
format!("{figure}\n")
} else {
let document = xhtml::convert(
Format::Epub,
&item.text,
|href| targets.link(&item.path, href),
|src| Ok(targets.picture(&item.path, src)),
)?;
draft.warnings.extend(
document
.warnings
.into_iter()
.map(|kind| Warning::new(kind, &item.name)),
);
document.markdown
};
draft.sections.push(Section {
name: item.name.clone(),
markdown,
});
}
draft.meta = meta::read(&epub);
draft.pictures = pictures;
draft.cover = cover;
draft.outline = outline(&epub, &targets, &skipped);
draft.landmarks = landmarks::read(&epub, &targets, &skipped);
Ok(draft)
}
fn first_pass(
item: &Item,
targets: &Targets,
cover: Option<&str>,
) -> Result<Option<HashSet<String>>> {
if item.kind == Kind::Picture {
return Ok((cover != Some(item.path.as_str())).then(HashSet::new));
}
let document = xhtml::convert(
Format::Epub,
&item.text,
|_| None,
|src| Ok(targets.picture(&item.path, src)),
)?;
if document.markdown.trim().is_empty()
|| cover.is_some_and(|cover| shows_only(&document.markdown, cover))
{
return Ok(None);
}
let ids = document.parts().into_iter().flat_map(|part| part.ids);
Ok(Some(ids.collect()))
}
fn shows_only(markdown: &str, picture: &str) -> bool {
let destination = markdown::encoded_path(picture);
if !markdown.contains(&destination) {
return false;
}
let Ok(root) = to_mdast(markdown, &ParseOptions::gfm()) else {
return false;
};
let mut blocks = root
.children()
.into_iter()
.flatten()
.filter(|node| !matches!(node, Node::Definition(_)));
let (Some(Node::Paragraph(paragraph)), None) = (blocks.next(), blocks.next()) else {
return false;
};
match paragraph.children.as_slice() {
[Node::Image(image)] => image.url == destination,
[Node::Link(link)] => {
matches!(link.children.as_slice(), [Node::Image(image)] if image.url == destination)
}
_ => false,
}
}
fn read_pictures(epub: &Epub, archive: &mut Archive<'_>) -> Result<Vec<SourcePicture>> {
let mut pictures = Vec::new();
let mut seen = HashSet::new();
for entry in epub.manifest() {
if !entry
.media_type()
.to_ascii_lowercase()
.starts_with("image/")
{
continue;
}
let Some(reference) = paths::resolve("", entry.href().as_str()) else {
continue;
};
if !seen.insert(reference.path.clone()) {
continue;
}
if let Some(bytes) = archive.read(&reference.path)? {
pictures.push(SourcePicture {
name: reference.path,
data: PictureData::Encoded(bytes),
});
}
}
Ok(pictures)
}
fn read_items(
epub: &Epub,
archive: &mut Archive<'_>,
pictures: &HashSet<String>,
max_resources: usize,
) -> Result<Vec<Item>> {
let mut items = Vec::new();
let mut seen = HashSet::new();
let mut used = HashSet::new();
for (count, entry) in epub.spine().iter().enumerate() {
if count >= max_resources {
return Err(Error::Limit("the spine has too many items"));
}
let Some(manifest) = entry.manifest_entry() else {
continue;
};
let kind = kind(manifest.media_type());
let Some(reference) = paths::resolve("", manifest.href().as_str()) else {
continue;
};
let path = reference.path;
if kind == Kind::Other || !seen.insert(path.clone()) {
continue;
}
let text = match kind {
Kind::Picture if pictures.contains(&path) => String::new(),
Kind::Picture | Kind::Other => continue,
Kind::Text => match archive.read(&path)? {
Some(bytes) => decode(&bytes),
None => continue,
},
};
let name = unique_name(&paths::section_name(&path), &mut used);
items.push(Item {
path,
name,
kind,
text,
});
}
Ok(items)
}
fn kind(media_type: &str) -> Kind {
let media = media_type.trim().to_ascii_lowercase();
if media.starts_with("image/") && !media.contains("svg") {
Kind::Picture
} else if media.starts_with("text/") || media.contains("xml") || media.contains("html") {
Kind::Text
} else {
Kind::Other
}
}
fn unique_name(base: &str, used: &mut HashSet<String>) -> String {
let mut name = base.to_owned();
let mut number = 1_u32;
while !used.insert(name.clone()) {
number += 1;
name = format!("{base}~{number}");
}
name
}
fn decode(bytes: &[u8]) -> String {
match bytes {
[0xff, 0xfe, rest @ ..] => utf16(rest, u16::from_le_bytes),
[0xfe, 0xff, rest @ ..] => utf16(rest, u16::from_be_bytes),
[0xef, 0xbb, 0xbf, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
_ => String::from_utf8_lossy(bytes).into_owned(),
}
}
fn utf16(bytes: &[u8], unit: fn([u8; 2]) -> u16) -> String {
let (pairs, _) = bytes.as_chunks::<2>();
char::decode_utf16(pairs.iter().copied().map(unit))
.map(|unit| unit.unwrap_or(char::REPLACEMENT_CHARACTER))
.collect()
}
fn destination(targets: &Targets, skipped: &HashSet<String>, href: &str) -> Option<String> {
match paths::resolve("", href) {
Some(reference) if skipped.contains(&reference.path) => None,
Some(reference) => Some(match targets.sections.get(&reference.path) {
Some(target) => target.destination(reference.fragment.as_deref()),
None => href.to_owned(),
}),
None => Some(href.to_owned()),
}
}
fn outline(epub: &Epub, targets: &Targets, skipped: &HashSet<String>) -> Vec<OutlineEntry> {
let Some(contents) = epub.toc().contents() else {
return Vec::new();
};
contents
.flatten()
.filter_map(|entry| {
let target = destination(targets, skipped, entry.href()?.as_str())?;
Some(OutlineEntry {
level: u8::try_from(entry.depth()).unwrap_or(u8::MAX).max(1),
title: entry.label().trim().to_owned(),
target,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::{Kind, decode, kind, shows_only, unique_name};
use std::collections::HashSet;
#[test]
fn a_media_type_tells_text_from_pictures() {
assert_eq!(kind("application/xhtml+xml"), Kind::Text);
assert_eq!(kind("text/html"), Kind::Text);
assert_eq!(kind("Image/SVG+xml"), Kind::Text);
assert_eq!(kind("image/jpeg"), Kind::Picture);
assert_eq!(kind("application/pdf"), Kind::Other);
assert_eq!(kind(""), Kind::Other);
}
#[test]
fn names_are_made_unique() {
let mut used = HashSet::new();
assert_eq!(unique_name("a.xhtml", &mut used), "a.xhtml");
assert_eq!(unique_name("a.xhtml", &mut used), "a.xhtml~2");
assert_eq!(unique_name("a.xhtml", &mut used), "a.xhtml~3");
}
#[test]
fn text_is_decoded_by_its_byte_order_mark() {
let little: Vec<u8> = [0xff, 0xfe]
.into_iter()
.chain("Hé".encode_utf16().flat_map(u16::to_le_bytes))
.collect();
let big: Vec<u8> = [0xfe, 0xff]
.into_iter()
.chain("Hé".encode_utf16().flat_map(u16::to_be_bytes))
.chain([0x00])
.collect();
assert_eq!(decode(&little), "Hé");
assert_eq!(decode(&big), "Hé");
assert_eq!(decode(b"\xef\xbb\xbfHi"), "Hi");
assert_eq!(decode("Привет".as_bytes()), "Привет");
assert_eq!(decode(b"a\xffb"), "a\u{fffd}b");
assert_eq!(decode(&[0xff, 0xfe, 0x00, 0xd8]), "\u{fffd}");
}
#[test]
fn a_page_of_one_picture_is_recognised_by_its_markdown() {
let picture = "OEBPS/img/cover 1.jpg";
let only = "[cover]: #cover\n\n\n";
assert!(shows_only(only, picture));
assert!(shows_only(
"[](x.md)\n",
picture
));
assert!(!shows_only(
"Title\n\n\n",
picture
));
assert!(!shows_only(" text\n", picture));
assert!(!shows_only("\n", picture));
assert!(!shows_only(
"\n\n\n",
picture
));
assert!(!shows_only("", picture));
}
}