[format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
//! Liber's book formats (docs/FORMATS.md): EPUB 2/3, FB2, TXT and DRM-free MOBI/AZW3 in, one sanitized
|
||||
//! [`Document`] out. Pure: bytes in, values out. No file system, no network, no clock.
|
||||
//!
|
||||
//! ```
|
||||
//! let txt = "Chapter 1\n\nIt was a dark and stormy night.\n".as_bytes();
|
||||
//! let doc = liber_format::open(txt, Some("storm.txt"), &liber_format::Limits::default()).unwrap();
|
||||
//! assert_eq!(doc.format, liber_format::Format::Txt);
|
||||
//! assert_eq!(doc.chapters.len(), 1);
|
||||
//! ```
|
||||
|
||||
mod drm;
|
||||
mod entities;
|
||||
mod epub;
|
||||
mod fb2;
|
||||
mod html;
|
||||
mod mobi;
|
||||
pub mod position;
|
||||
mod sanitize;
|
||||
pub mod text;
|
||||
mod txt;
|
||||
mod xml;
|
||||
pub mod zip;
|
||||
|
||||
pub use position::{Anchor, Point, Quote, Resolved};
|
||||
pub use sanitize::{Element, Node};
|
||||
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The one sentence the app shows for a protected book.
|
||||
pub const DRM_MESSAGE: &str = "This book is DRM-protected, so Liber cannot open it.";
|
||||
|
||||
/// What a file is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Format {
|
||||
Epub,
|
||||
Fb2,
|
||||
Txt,
|
||||
Mobi,
|
||||
Azw3,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Format::Epub => "epub",
|
||||
Format::Fb2 => "fb2",
|
||||
Format::Txt => "txt",
|
||||
Format::Mobi => "mobi",
|
||||
Format::Azw3 => "azw3",
|
||||
Format::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a book did not open. [`FormatError::message`] is the sentence for the person.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum FormatError {
|
||||
#[error("DRM-protected")]
|
||||
Drm,
|
||||
/// A PDF: the app opens it read-only in its PDF view.
|
||||
#[error("a PDF")]
|
||||
Pdf,
|
||||
#[error("unsupported: {0}")]
|
||||
Unsupported(String),
|
||||
#[error("too large: {0}")]
|
||||
TooLarge(String),
|
||||
/// Zip slip, symlinks, entity declarations: refused, never sanitized around.
|
||||
#[error("unsafe: {0}")]
|
||||
Unsafe(String),
|
||||
#[error("malformed: {0}")]
|
||||
Malformed(String),
|
||||
}
|
||||
|
||||
impl FormatError {
|
||||
pub fn message(&self) -> String {
|
||||
match self {
|
||||
FormatError::Drm => DRM_MESSAGE.to_owned(),
|
||||
FormatError::Pdf => "This is a PDF: Liber opens it read-only.".to_owned(),
|
||||
FormatError::Unsupported(w) => format!("Liber cannot open this book: {w}."),
|
||||
FormatError::TooLarge(w) => format!("This book is too large to open safely: {w}."),
|
||||
FormatError::Unsafe(w) => format!("Liber refused this file because it is unsafe: {w}."),
|
||||
FormatError::Malformed(w) => format!("This book file is damaged: {w}."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, FormatError>;
|
||||
|
||||
/// Hard caps for one book. Every size read out of a file is checked against these before anything is allocated.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Limits {
|
||||
pub max_input: u64,
|
||||
pub max_entries: usize,
|
||||
pub max_entry: u64,
|
||||
pub max_total: u64,
|
||||
/// Inflated / compressed, for entries larger than 1 MiB.
|
||||
pub max_ratio: u64,
|
||||
pub max_xml: usize,
|
||||
pub max_depth: usize,
|
||||
pub max_chapters: usize,
|
||||
pub max_images: usize,
|
||||
pub max_text: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
Limits {
|
||||
max_input: 1024 * MIB,
|
||||
max_entries: 10_000,
|
||||
max_entry: 64 * MIB,
|
||||
max_total: 512 * MIB,
|
||||
max_ratio: 100,
|
||||
max_xml: 32 * MIB as usize,
|
||||
max_depth: 256,
|
||||
max_chapters: 5_000,
|
||||
max_images: 5_000,
|
||||
max_text: 256 * MIB as usize,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct Series {
|
||||
pub name: String,
|
||||
pub index: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct Metadata {
|
||||
pub title: Option<String>,
|
||||
pub authors: Vec<String>,
|
||||
pub language: Option<String>,
|
||||
pub identifiers: Vec<String>,
|
||||
/// The first valid ISBN among the identifiers, as ISBN-13.
|
||||
pub isbn: Option<String>,
|
||||
pub publisher: Option<String>,
|
||||
pub published: Option<String>,
|
||||
/// Plain text.
|
||||
pub description: Option<String>,
|
||||
pub subjects: Vec<String>,
|
||||
pub series: Option<Series>,
|
||||
}
|
||||
|
||||
/// One chapter: the sanitized tree and its serialization.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Chapter {
|
||||
/// Stable within the book: the spine path (EPUB) or `chapter-<n>`.
|
||||
pub href: String,
|
||||
pub title: Option<String>,
|
||||
pub linear: bool,
|
||||
/// `<div xmlns="http://www.w3.org/1999/xhtml">…</div>`: insert with an XML parser, never `innerHTML`.
|
||||
pub xhtml: String,
|
||||
/// SHA-256 of `xhtml`, hex.
|
||||
pub hash: String,
|
||||
/// Length of the chapter's text in UTF-16 code units.
|
||||
pub text_len: usize,
|
||||
#[serde(skip)]
|
||||
pub root: Element,
|
||||
}
|
||||
|
||||
impl Chapter {
|
||||
/// The chapter's text: every text node in document order, nothing added.
|
||||
pub fn text(&self) -> String {
|
||||
let mut s = String::new();
|
||||
self.root.collect_text(&mut s);
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct TocEntry {
|
||||
pub title: String,
|
||||
pub chapter: usize,
|
||||
pub fragment: Option<String>,
|
||||
pub children: Vec<TocEntry>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Image {
|
||||
pub index: usize,
|
||||
pub media_type: &'static str,
|
||||
#[serde(skip)]
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Document {
|
||||
pub format: Format,
|
||||
pub metadata: Metadata,
|
||||
pub chapters: Vec<Chapter>,
|
||||
pub toc: Vec<TocEntry>,
|
||||
/// `"<chapter>#<id>"` → the note's sanitized XHTML, for the footnote popover.
|
||||
pub footnotes: BTreeMap<String, String>,
|
||||
pub images: Vec<Image>,
|
||||
pub cover: Option<usize>,
|
||||
/// Things dropped on the way (remote images, unreadable chapters), for the import report.
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// The book's text fingerprint (docs/FORMATS.md §6).
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let mut all = String::new();
|
||||
for c in &self.chapters {
|
||||
c.root.collect_text(&mut all);
|
||||
all.push(' ');
|
||||
}
|
||||
text::fingerprint(&all)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the bytes are, by content (the name is only a hint for TXT and FB2).
|
||||
pub fn sniff(bytes: &[u8], name: Option<&str>) -> Option<Format> {
|
||||
if bytes.starts_with(b"%PDF-") {
|
||||
return Some(Format::Pdf);
|
||||
}
|
||||
if bytes.len() >= 68 && &bytes[60..68] == b"BOOKMOBI" {
|
||||
return Some(Format::Mobi);
|
||||
}
|
||||
if bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"PK\x05\x06") {
|
||||
let lower = name.map(|n| n.to_lowercase()).unwrap_or_default();
|
||||
return Some(if lower.ends_with(".fb2.zip") || lower.ends_with(".fbz") { Format::Fb2 } else { Format::Epub });
|
||||
}
|
||||
let head = &bytes[..bytes.len().min(4096)];
|
||||
if text::find(head, b"<FictionBook").is_some() {
|
||||
return Some(Format::Fb2);
|
||||
}
|
||||
Some(Format::Txt)
|
||||
}
|
||||
|
||||
/// Opens a book. `name` is the file name, used only as a hint (TXT title, `.fb2.zip`).
|
||||
pub fn open(bytes: &[u8], name: Option<&str>, limits: &Limits) -> Result<Document> {
|
||||
if bytes.len() as u64 > limits.max_input {
|
||||
return Err(FormatError::TooLarge(format!("the file is larger than {} MiB", limits.max_input >> 20)));
|
||||
}
|
||||
drm::refuse_other_containers(bytes)?;
|
||||
let mut doc = match sniff(bytes, name) {
|
||||
Some(Format::Pdf) => return Err(FormatError::Pdf),
|
||||
Some(Format::Mobi) => mobi::open(bytes, limits)?,
|
||||
Some(Format::Epub) => {
|
||||
let zip = zip::Zip::parse(bytes, limits)?;
|
||||
if is_fb2_zip(&zip) { fb2::open_zip(&zip, limits)? } else { epub::open(&zip, limits)? }
|
||||
}
|
||||
Some(Format::Fb2) => {
|
||||
if bytes.starts_with(b"PK") {
|
||||
fb2::open_zip(&zip::Zip::parse(bytes, limits)?, limits)?
|
||||
} else {
|
||||
fb2::open(bytes, limits)?
|
||||
}
|
||||
}
|
||||
_ => txt::open(bytes, name, limits)?,
|
||||
};
|
||||
if doc.chapters.is_empty() {
|
||||
return Err(FormatError::Malformed("the book has no readable text".into()));
|
||||
}
|
||||
doc.metadata.isbn = doc.metadata.identifiers.iter().find_map(|i| text::isbn13(i));
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
fn is_fb2_zip(zip: &zip::Zip) -> bool {
|
||||
zip.find("mimetype").is_none()
|
||||
&& zip.find("META-INF/container.xml").is_none()
|
||||
&& zip.entries().iter().filter(|e| !e.is_dir()).count() == 1
|
||||
&& zip.entries().iter().any(|e| e.name.to_lowercase().ends_with(".fb2"))
|
||||
}
|
||||
|
||||
/// Builds a chapter from its sanitized tree.
|
||||
pub(crate) fn chapter(href: String, title: Option<String>, linear: bool, root: Element) -> Chapter {
|
||||
let xhtml = sanitize::serialize(&root);
|
||||
let hash = text::sha256_hex(xhtml.as_bytes());
|
||||
let text_len = root.text_len_utf16();
|
||||
let title = title.or_else(|| root.first_heading()).map(|t| text::collapse(&t)).filter(|t| !t.is_empty());
|
||||
Chapter { href, title, linear, xhtml, hash, text_len, root }
|
||||
}
|
||||
Reference in New Issue
Block a user