mod error;
mod fonts;
mod images;
pub use error::{Error, Source};
use error::from_zip;
use std::io::{Read, Seek, Write};
use zip::write::SimpleFileOptions;
use zip::{CompressionMethod, ZipArchive, ZipWriter};
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Options {
pub max_width: u32,
pub max_height: u32,
pub jpeg_quality: u8,
pub sharpen: f32,
}
impl Default for Options {
fn default() -> Self {
Self {
max_width: 440,
max_height: 733,
jpeg_quality: 92,
sharpen: 0.8,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Report {
pub fonts_removed: usize,
pub font_bytes: u64,
pub images_changed: usize,
pub images_kept: usize,
pub image_bytes_before: u64,
pub image_bytes_after: u64,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Progress<'a> {
pub done: usize,
pub total: usize,
pub entry: &'a str,
}
enum Action {
Skip,
CopyRaw,
Rewrite(fn(&str) -> anyhow::Result<Option<String>>),
Image(images::Kind),
}
fn decide(name: &str) -> Action {
let lower = name.to_ascii_lowercase();
if name == "mimetype" || fonts::is_font(name) {
Action::Skip
} else if lower.ends_with(".css") {
Action::Rewrite(fonts::strip_font_faces)
} else if lower.ends_with(".opf") {
Action::Rewrite(fonts::remove_manifest_items)
} else if lower == "meta-inf/encryption.xml" {
Action::Rewrite(fonts::clean_encryption)
} else if let Some(kind) = images::kind_of(name) {
Action::Image(kind)
} else {
Action::CopyRaw
}
}
pub fn optimize<R, W>(input: R, output: W, opts: &Options) -> Result<Report, Error>
where
R: Read + Seek,
W: Write + Seek,
{
optimize_with_progress(input, output, opts, |_| {})
}
pub fn optimize_with_progress<R, W, F>(
input: R,
output: W,
opts: &Options,
mut on_progress: F,
) -> Result<Report, Error>
where
R: Read + Seek,
W: Write + Seek,
F: FnMut(Progress<'_>),
{
let mut archive = ZipArchive::new(input).map_err(|e| Error::InvalidZip(Box::new(e)))?;
let mut writer = ZipWriter::new(output);
let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
let deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
writer.start_file("mimetype", stored).map_err(from_zip)?;
writer.write_all(b"application/epub+zip")?;
let names = (0..archive.len())
.map(|i| {
Ok(archive
.by_index_raw(i)
.map_err(from_zip)?
.name()
.map_err(from_zip)?
.into_owned())
})
.collect::<Result<Vec<String>, Error>>()?;
let kept_files: Vec<&str> = names
.iter()
.filter(|n| !n.ends_with('/') && !matches!(decide(n), Action::Skip))
.map(String::as_str)
.collect();
let mut report = Report::default();
let total = archive.len();
for i in 0..total {
let (name, size) = {
let entry = archive.by_index_raw(i).map_err(from_zip)?;
(
entry.name().map_err(from_zip)?.into_owned(),
entry.compressed_size(),
)
};
on_progress(Progress {
done: i,
total,
entry: &name,
});
if name.ends_with('/') {
if kept_files.iter().any(|f| f.starts_with(name.as_str())) {
writer
.raw_copy_file(archive.by_index_raw(i).map_err(from_zip)?)
.map_err(from_zip)?;
}
continue;
}
match decide(&name) {
Action::Skip => {
if fonts::is_font(&name) {
report.fonts_removed += 1;
report.font_bytes += size;
}
}
Action::CopyRaw => writer
.raw_copy_file(archive.by_index_raw(i).map_err(from_zip)?)
.map_err(from_zip)?,
Action::Rewrite(transform) => {
let mut bytes = Vec::new();
archive
.by_index(i)
.map_err(from_zip)?
.read_to_end(&mut bytes)?;
match String::from_utf8(bytes) {
Ok(text) => {
let result = transform(&text).map_err(|e| Error::Malformed {
entry: name.clone(),
source: e.into(),
})?;
if let Some(new_text) = result {
writer
.start_file(name.as_str(), deflated)
.map_err(from_zip)?;
writer.write_all(new_text.as_bytes())?;
}
}
Err(_) => writer
.raw_copy_file(archive.by_index_raw(i).map_err(from_zip)?)
.map_err(from_zip)?,
}
}
Action::Image(kind) => {
let mut bytes = Vec::new();
archive
.by_index(i)
.map_err(from_zip)?
.read_to_end(&mut bytes)?;
report.image_bytes_before += size;
match images::optimize(kind, &bytes, opts) {
Ok(Some(new_bytes)) => {
report.images_changed += 1;
report.image_bytes_after += new_bytes.len() as u64;
writer.start_file(name.as_str(), stored).map_err(from_zip)?;
writer.write_all(&new_bytes)?;
}
result => {
match result {
Err(e) => report
.warnings
.push(format!("{name}: {e:#}; copied unchanged")),
Ok(_) => report.images_kept += 1,
}
report.image_bytes_after += size;
writer
.raw_copy_file(archive.by_index_raw(i).map_err(from_zip)?)
.map_err(from_zip)?;
}
}
}
}
}
writer.finish().map_err(from_zip)?;
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use quick_xml::Reader;
use quick_xml::events::Event;
use std::io::Cursor;
fn escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
fn visible_text(xhtml: &str) -> String {
let mut reader = Reader::from_str(xhtml);
let mut out = String::new();
loop {
match reader.read_event().expect("valid XHTML") {
Event::Eof => break,
Event::Text(t) => out.push_str(&t.xml10_content()),
Event::GeneralRef(r) => out.push_str(&format!("&{};", r.xml10_content())),
_ => {}
}
}
out
}
fn build_epub(chapters: &[Vec<String>], font: Option<&[u8]>) -> anyhow::Result<Vec<u8>> {
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
zip.start_file("mimetype", stored)?;
zip.write_all(b"application/epub+zip")?;
zip.start_file("META-INF/container.xml", stored)?;
zip.write_all(br#"<?xml version="1.0"?><container><rootfiles><rootfile full-path="OEBPS/content.opf"/></rootfiles></container>"#)?;
let mut manifest =
String::from(r#"<item href="style.css" id="css" media-type="text/css"/>"#);
let mut css = String::from("p { margin: 0 }\n");
if let Some(bytes) = font {
manifest.push_str(r#"<item href="fonts/f.ttf" id="font" media-type="font/ttf"/>"#);
css.push_str("@font-face { font-family: \"F\"; src: url(fonts/f.ttf); }\n");
zip.start_file("OEBPS/fonts/f.ttf", stored)?;
zip.write_all(bytes)?;
zip.start_file("META-INF/encryption.xml", stored)?;
zip.write_all(br#"<encryption><EncryptedData><CipherReference URI="OEBPS/fonts/f.ttf"/></EncryptedData></encryption>"#)?;
}
for (i, paragraphs) in chapters.iter().enumerate() {
manifest.push_str(&format!(
r#"<item href="ch{i}.xhtml" id="ch{i}" media-type="application/xhtml+xml"/>"#
));
let body: String = paragraphs
.iter()
.map(|p| format!("<p>{}</p>", escape(p)))
.collect();
zip.start_file(format!("OEBPS/ch{i}.xhtml"), stored)?;
zip.write_all(format!(r#"<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><body>{body}</body></html>"#).as_bytes())?;
}
zip.start_file("OEBPS/style.css", stored)?;
zip.write_all(css.as_bytes())?;
zip.start_file("OEBPS/content.opf", stored)?;
zip.write_all(format!(r#"<?xml version="1.0"?><package version="3.0"><manifest>{manifest}</manifest></package>"#).as_bytes())?;
Ok(zip.finish()?.into_inner())
}
fn read_all(epub: &[u8]) -> Vec<(String, Vec<u8>)> {
let mut archive = ZipArchive::new(Cursor::new(epub)).unwrap();
(0..archive.len())
.map(|i| {
let mut entry = archive.by_index(i).unwrap();
let mut bytes = Vec::new();
entry.read_to_end(&mut bytes).unwrap();
(entry.name().unwrap().into_owned(), bytes)
})
.collect()
}
fn chapter_texts(entries: &[(String, Vec<u8>)]) -> Vec<String> {
entries
.iter()
.filter(|(name, _)| name.ends_with(".xhtml"))
.map(|(_, bytes)| visible_text(std::str::from_utf8(bytes).unwrap()))
.collect()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
#[test]
fn visible_text_is_unchanged(
chapters in prop::collection::vec(prop::collection::vec("\\PC{0,60}", 0..5), 1..4),
font in prop::option::of(prop::collection::vec(any::<u8>(), 1..64)),
) {
let input = build_epub(&chapters, font.as_deref()).unwrap();
let mut output = Cursor::new(Vec::new());
let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
let before = read_all(&input);
let after = read_all(output.get_ref());
prop_assert_eq!(chapter_texts(&before), chapter_texts(&after));
prop_assert_eq!(after[0].0.as_str(), "mimetype");
prop_assert!(after.iter().all(|(name, _)| !fonts::is_font(name)));
prop_assert!(after.iter().all(|(name, _)| name != "META-INF/encryption.xml"));
let opf = &after.iter().find(|(n, _)| n.ends_with(".opf")).unwrap().1;
prop_assert!(!String::from_utf8_lossy(opf).contains("f.ttf"));
prop_assert_eq!(report.fonts_removed, usize::from(font.is_some()));
}
}
#[test]
fn reports_progress_for_every_entry() {
let input = build_epub(&[vec!["a".into()], vec!["b".into()]], None).unwrap();
let mut seen = Vec::new();
let mut output = Cursor::new(Vec::new());
optimize_with_progress(Cursor::new(&input), &mut output, &Options::default(), |p| {
seen.push((p.done, p.total, p.entry.to_owned()));
})
.unwrap();
let names: Vec<String> = read_all(&input).into_iter().map(|(n, _)| n).collect();
let expected: Vec<_> = names
.iter()
.enumerate()
.map(|(i, n)| (i, names.len(), n.clone()))
.collect();
assert_eq!(seen, expected);
}
#[test]
fn sizes_are_as_stored_in_the_epub() {
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file("f.ttf", SimpleFileOptions::default())
.unwrap();
zip.write_all(&[0u8; 10_000]).unwrap();
let input = zip.finish().unwrap().into_inner();
let stored = ZipArchive::new(Cursor::new(&input))
.unwrap()
.by_index_raw(0)
.unwrap()
.compressed_size();
let mut output = Cursor::new(Vec::new());
let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
assert!(stored < 10_000);
assert_eq!(report.font_bytes, stored);
}
#[test]
fn rejects_non_zip_input() {
let mut output = Cursor::new(Vec::new());
let err = optimize(Cursor::new(b"not a zip"), &mut output, &Options::default());
assert!(matches!(err, Err(Error::InvalidZip(_))));
}
#[test]
fn broken_opf_names_the_entry() {
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file("OEBPS/content.opf", SimpleFileOptions::default())
.unwrap();
zip.write_all(b"<package><manifest></package>").unwrap();
let input = zip.finish().unwrap().into_inner();
let mut output = Cursor::new(Vec::new());
match optimize(Cursor::new(input), &mut output, &Options::default()) {
Err(Error::Malformed { entry, .. }) => assert_eq!(entry, "OEBPS/content.opf"),
other => panic!("expected Malformed, got {other:?}"),
}
}
}