Skip to main content

prensa/
lib.rs

1//! Optimize EPUBs for e-ink readers.
2//!
3//! The engine works on any reader/writer pair, so it does not care whether the
4//! book comes from a file, memory or (later) a browser. Front ends such as the
5//! `prensa` CLI handle paths, atomic writes and printing.
6//!
7//! ```no_run
8//! use std::fs::File;
9//!
10//! let input = File::open("book.epub")?;
11//! let output = File::create("book-optimized.epub")?;
12//! let report = prensa::optimize(input, output, &prensa::Options::default())?;
13//! println!("{} image(s) optimized", report.images_changed);
14//! # Ok::<(), Box<dyn std::error::Error>>(())
15//! ```
16//!
17//! # Features
18//!
19//! - `parallel` (off by default): optimize images on all cores with
20//!   [rayon](https://docs.rs/rayon). The output is identical either way. Off
21//!   by default so the library adds no threads where they are unavailable,
22//!   such as WebAssembly in the browser.
23
24mod error;
25mod fonts;
26mod images;
27mod inline;
28mod options;
29mod passes;
30mod refs;
31mod report;
32
33pub use error::{Error, Source};
34pub use options::{Device, InvalidOptions, Options, OptionsBuilder, Rotation};
35pub use report::{Progress, Report, Warning};
36
37use error::from_zip;
38use images::Optimized;
39use passes::{Action, Book, Fallback, Outcome, decide};
40use std::collections::{HashMap, HashSet};
41use std::io::{Read, Seek, Write};
42use zip::write::SimpleFileOptions;
43use zip::{CompressionMethod, ZipArchive, ZipWriter};
44
45/// Largest entry read into memory to be rewritten (CSS, OPF, images).
46///
47/// Real books stay far below this; a bigger entry is a zip bomb or a broken
48/// archive, and reading it would exhaust memory. Small in tests so the limit
49/// can be hit without writing hundreds of megabytes.
50const MAX_ENTRY_SIZE: u64 = if cfg!(test) {
51    64 * 1024
52} else {
53    128 * 1024 * 1024
54};
55
56/// Read entry `i` fully, or `None` if it is larger than [`MAX_ENTRY_SIZE`].
57///
58/// The declared size is checked first, but it comes from the archive and can
59/// lie, so the read itself is capped too.
60fn read_entry<R: Read + Seek>(
61    archive: &mut ZipArchive<R>,
62    i: usize,
63) -> Result<Option<Vec<u8>>, Error> {
64    let entry = archive.by_index(i).map_err(from_zip)?;
65    if entry.size() > MAX_ENTRY_SIZE {
66        return Ok(None);
67    }
68    let mut bytes = Vec::new();
69    entry.take(MAX_ENTRY_SIZE + 1).read_to_end(&mut bytes)?;
70    Ok((bytes.len() as u64 <= MAX_ENTRY_SIZE).then_some(bytes))
71}
72
73fn too_large() -> String {
74    format!(
75        "entry is larger than {} MiB",
76        MAX_ENTRY_SIZE / (1024 * 1024)
77    )
78}
79
80/// Copy entry `i` as stored in the input, without decompressing and
81/// recompressing it.
82fn copy_raw<R, W>(
83    archive: &mut ZipArchive<R>,
84    writer: &mut ZipWriter<W>,
85    i: usize,
86) -> Result<(), Error>
87where
88    R: Read + Seek,
89    W: Write + Seek,
90{
91    let entry = archive.by_index_raw(i).map_err(from_zip)?;
92    writer.raw_copy_file(entry).map_err(from_zip)
93}
94
95fn malformed(entry: &str, source: Source) -> Error {
96    Error::Malformed {
97        entry: entry.to_owned(),
98        source,
99    }
100}
101
102/// What became of an image: rewritten (`Some`), kept because rewriting
103/// gained nothing (`None`), or not readable as an image (`Err`, a warning).
104type ImageResult = anyhow::Result<Option<Optimized>>;
105
106/// An image entry to optimize: its index, kind and bytes (`None` when it is
107/// larger than [`MAX_ENTRY_SIZE`]).
108type ImageJob = (usize, images::Kind, Option<Vec<u8>>);
109
110/// Read image entries for [`optimize_images`]. The archive needs `&mut`, so
111/// reads stay sequential.
112fn read_images<R: Read + Seek>(
113    archive: &mut ZipArchive<R>,
114    images: impl IntoIterator<Item = (usize, images::Kind)>,
115) -> Result<Vec<ImageJob>, Error> {
116    images
117        .into_iter()
118        .map(|(i, kind)| Ok((i, kind, read_entry(archive, i)?)))
119        .collect()
120}
121
122/// Run the images pass on each job, in parallel with the `parallel` feature.
123/// Results come back in the jobs' order.
124fn optimize_images(jobs: Vec<ImageJob>, opts: &Options) -> Vec<(usize, ImageResult)> {
125    let run = |(i, kind, bytes): ImageJob| {
126        let result = match bytes {
127            Some(bytes) => images::optimize(kind, &bytes, opts),
128            None => Err(anyhow::anyhow!(too_large())),
129        };
130        (i, result)
131    };
132    #[cfg(feature = "parallel")]
133    {
134        use rayon::iter::{IntoParallelIterator, ParallelIterator};
135        jobs.into_par_iter().map(run).collect()
136    }
137    #[cfg(not(feature = "parallel"))]
138    {
139        jobs.into_iter().map(run).collect()
140    }
141}
142
143/// How many images are read and optimized together. Twice the threads keeps
144/// every core busy when images differ in size, while holding only a few
145/// images in memory at once.
146fn batch_size() -> usize {
147    #[cfg(feature = "parallel")]
148    {
149        rayon::current_num_threads() * 2
150    }
151    #[cfg(not(feature = "parallel"))]
152    {
153        1
154    }
155}
156
157/// A warning for an entry copied unchanged.
158fn copied_unchanged(entry: &str, reason: impl std::fmt::Display) -> Warning {
159    Warning {
160        entry: entry.to_owned(),
161        // `{reason}`, not `{reason:#}`: `image` errors already include their
162        // cause in the message, so the chain would repeat it. Some decoders
163        // end it with a newline; a warning is one line.
164        message: format!("{}; copied unchanged", reason.to_string().trim_end()),
165    }
166}
167
168/// Read an EPUB from `input` and write an optimized copy to `output`.
169///
170/// Both are taken by value; pass `&mut file` to keep using it afterwards
171/// (`&mut T` is `Read`/`Write` + `Seek` whenever `T` is).
172///
173/// The output follows the EPUB container (OCF) rules: `mimetype` is the first
174/// entry and is stored uncompressed. On error, `output` may hold a partial
175/// file; callers writing to disk should write to a temporary file and rename it.
176pub fn optimize<R, W>(input: R, output: W, opts: &Options) -> Result<Report, Error>
177where
178    R: Read + Seek,
179    W: Write + Seek,
180{
181    optimize_with_progress(input, output, opts, |_| {})
182}
183
184/// Like [`optimize`], calling `on_progress` before each entry is processed.
185///
186/// On success it is called exactly once per entry (directories included), in
187/// archive order, with `done` equal to the entry's index. Nothing is called
188/// after the last entry; treat the return of this function as completion.
189///
190/// The library never prints; front ends use this to draw a progress bar.
191/// Images take most of the time, so progress is not linear in entries; with
192/// the `parallel` feature, it pauses at an image while that image and the
193/// next ones are optimized together, then moves past them at once.
194pub fn optimize_with_progress<R, W, F>(
195    input: R,
196    output: W,
197    opts: &Options,
198    on_progress: F,
199) -> Result<Report, Error>
200where
201    R: Read + Seek,
202    W: Write + Seek,
203    F: FnMut(Progress<'_>),
204{
205    optimize_in_batches(input, output, opts, on_progress, batch_size())
206}
207
208/// [`optimize_with_progress`] with images optimized `batch` at a time.
209fn optimize_in_batches<R, W, F>(
210    input: R,
211    output: W,
212    opts: &Options,
213    mut on_progress: F,
214    batch: usize,
215) -> Result<Report, Error>
216where
217    R: Read + Seek,
218    W: Write + Seek,
219    F: FnMut(Progress<'_>),
220{
221    let mut archive = ZipArchive::new(input).map_err(from_zip)?;
222    let mut writer = ZipWriter::new(output);
223
224    let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
225    let deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
226    writer.start_file("mimetype", stored).map_err(from_zip)?;
227    writer.write_all(b"application/epub+zip")?;
228
229    // Name and size of every entry. Sizes in the report are as stored in the
230    // EPUB (compressed), so they add up with the file size on disk.
231    let entries = (0..archive.len())
232        .map(|i| {
233            let entry = archive.by_index_raw(i).map_err(from_zip)?;
234            let name = entry.name().map_err(from_zip)?.into_owned();
235            Ok((name, entry.compressed_size()))
236        })
237        .collect::<Result<Vec<(String, u64)>, Error>>()?;
238
239    // Fonts declared in the manifest, so a font without a font extension is
240    // removed together with its manifest item and `encryption.xml` entry.
241    let mut book = Book::default();
242    for (i, (name, _)) in entries.iter().enumerate() {
243        if !name.to_ascii_lowercase().ends_with(".opf") {
244            continue;
245        }
246        let bytes =
247            read_entry(&mut archive, i)?.ok_or_else(|| malformed(name, too_large().into()))?;
248        let opf = std::str::from_utf8(&bytes).map_err(|e| malformed(name, Box::new(e)))?;
249        book.fonts
250            .add_manifest(opf, name)
251            .map_err(|e| malformed(name, e.into()))?;
252    }
253
254    let mut report = Report::default();
255
256    // What happens to each image must be known before anything is written:
257    // chapters that refer to an image can come earlier in the archive, and a
258    // renamed image (WebP, BMP, GIF) or a turned one changes them. Images that
259    // may change format are converted here; for JPEG and PNG, which keep their
260    // name, the header is enough to know whether they will be turned.
261    let mut taken: HashSet<String> = entries.iter().map(|(n, _)| n.to_lowercase()).collect();
262    let mut to_convert = Vec::new();
263    for (i, (name, _)) in entries.iter().enumerate() {
264        let Some(kind) = images::kind_of(name) else {
265            continue;
266        };
267        if !kind.may_change_format() {
268            if opts.rotate().is_some()
269                && let Some(bytes) = read_entry(&mut archive, i)?
270                && let Some((w, h)) = images::dimensions(kind, &bytes)
271                && images::rotation_for(w, h, opts).is_some()
272            {
273                book.rotated.insert(name.clone());
274            }
275            continue;
276        }
277        to_convert.push((i, kind));
278    }
279    // All at once: renames are needed before anything is written, and books
280    // rarely have many of these formats. Renames are then chosen in archive
281    // order, as if converted one by one.
282    let mut converted: HashMap<usize, ImageResult> = HashMap::new();
283    let jobs = read_images(&mut archive, to_convert)?;
284    for (i, result) in optimize_images(jobs, opts) {
285        let name = &entries[i].0;
286        if let Ok(Some(image)) = &result {
287            let format = image.format;
288            book.renames
289                .add(name, format.extension(), format.media_type(), &mut taken);
290            if image.rotated {
291                book.rotated.insert(name.clone());
292            }
293        }
294        converted.insert(i, result);
295    }
296
297    // Images embedded in chapters as `data:` URIs become entries of their own,
298    // listed in the manifest (which may come before the chapters).
299    for (i, (name, _)) in entries.iter().enumerate() {
300        if !passes::is_document(name) {
301            continue;
302        }
303        let Some(bytes) = read_entry(&mut archive, i)? else {
304            continue;
305        };
306        // Chapters that are not UTF-8 or not XML are reported by their
307        // rewrite, if they have anything to rewrite.
308        let Ok(text) = std::str::from_utf8(&bytes) else {
309            continue;
310        };
311        if !text.contains("data:image/") {
312            continue;
313        }
314        let Ok(uris) = refs::data_uris(text) else {
315            continue;
316        };
317        book.inline
318            .extract(name, uris, opts, &mut taken, &mut report.warnings);
319    }
320
321    // Files that survive the passes, used to drop directory entries left empty
322    // (e.g. `fonts/` after removing the fonts inside it).
323    let kept_files: Vec<&str> = entries
324        .iter()
325        .map(|(name, _)| name.as_str())
326        .filter(|n| {
327            !n.ends_with('/') && !matches!(decide(n, &book), Action::Skip | Action::RemoveFont)
328        })
329        .collect();
330
331    // JPEG and PNG images left, in archive order. Reaching the first one not
332    // yet optimized reads it and the next ones, and optimizes them together.
333    let pending: Vec<(usize, images::Kind)> = entries
334        .iter()
335        .enumerate()
336        .filter(|(i, _)| !converted.contains_key(i))
337        .filter_map(|(i, (name, _))| match decide(name, &book) {
338            Action::Image(kind) => Some((i, kind)),
339            _ => None,
340        })
341        .collect();
342    let mut pending = pending.chunks(batch.max(1));
343
344    let total = entries.len();
345    for (i, (name, size)) in entries.iter().enumerate() {
346        on_progress(Progress {
347            done: i,
348            total,
349            entry: name,
350        });
351
352        if name.ends_with('/') {
353            if kept_files.iter().any(|f| f.starts_with(name.as_str())) {
354                copy_raw(&mut archive, &mut writer, i)?;
355            }
356            continue;
357        }
358
359        match decide(name, &book) {
360            Action::Skip => {}
361            Action::RemoveFont => {
362                report.fonts_removed += 1;
363                report.font_bytes += size;
364            }
365            Action::CopyRaw => copy_raw(&mut archive, &mut writer, i)?,
366            Action::Rewrite(transform, fallback) => {
367                let bytes = read_entry(&mut archive, i)?
368                    .ok_or_else(|| malformed(name, too_large().into()))?;
369                let outcome = match String::from_utf8(bytes) {
370                    Ok(text) => transform(&text, name, &book).map_err(Source::from),
371                    Err(e) => Err(Box::new(e.utf8_error()) as Source),
372                };
373                match (outcome, fallback) {
374                    (Ok(Outcome::Keep), _) => copy_raw(&mut archive, &mut writer, i)?,
375                    (Ok(Outcome::Replace(new_text)), _) => {
376                        writer
377                            .start_file(name.as_str(), deflated)
378                            .map_err(from_zip)?;
379                        writer.write_all(new_text.as_bytes())?;
380                    }
381                    (Ok(Outcome::Drop), _) => {}
382                    (Err(_), Fallback::Copy) => copy_raw(&mut archive, &mut writer, i)?,
383                    (Err(e), Fallback::CopyWithWarning) => {
384                        report.warnings.push(copied_unchanged(
385                            name,
386                            format_args!("{e}; image references in it not updated"),
387                        ));
388                        copy_raw(&mut archive, &mut writer, i)?;
389                    }
390                    // Broken XML aborts everything: no output beats an inconsistent EPUB
391                    // (font removed but still listed in the manifest).
392                    (Err(e), Fallback::Reject) => return Err(malformed(name, e)),
393                }
394            }
395            Action::Image(kind) => {
396                report.image_bytes_before += size;
397                if !converted.contains_key(&i) {
398                    let next = pending.next().unwrap_or_default();
399                    debug_assert_eq!(next.first(), Some(&(i, kind)));
400                    let jobs = read_images(&mut archive, next.iter().copied())?;
401                    converted.extend(optimize_images(jobs, opts));
402                }
403                let result = converted
404                    .remove(&i)
405                    .expect("optimized with its batch, in archive order");
406                match result {
407                    Ok(Some(image)) => {
408                        report.images_changed += 1;
409                        report.image_bytes_after += image.bytes.len() as u64;
410                        let new_name = book.renames.new_path(name).unwrap_or(name);
411                        if new_name != name {
412                            report.images_converted += 1;
413                        }
414                        if image.rotated {
415                            report.images_rotated += 1;
416                        }
417                        // JPEG/PNG are already compressed: deflating them again only costs CPU.
418                        writer.start_file(new_name, stored).map_err(from_zip)?;
419                        writer.write_all(&image.bytes)?;
420                        continue;
421                    }
422                    // Rewriting gained nothing.
423                    Ok(None) => report.images_kept += 1,
424                    // An image that fails to decode does not fail the book: it stays as it was.
425                    Err(e) => {
426                        report.images_failed += 1;
427                        report.warnings.push(copied_unchanged(name, e));
428                    }
429                }
430                report.image_bytes_after += size;
431                copy_raw(&mut archive, &mut writer, i)?;
432            }
433        }
434    }
435
436    for file in &book.inline.files {
437        report.images_extracted += 1;
438        if file.changed {
439            report.images_changed += 1;
440        } else {
441            report.images_kept += 1;
442        }
443        if file.rotated {
444            report.images_rotated += 1;
445        }
446        // Inside the chapter the image was base64 text, compressed with it;
447        // its decoded size is the closest to an image entry's size.
448        report.image_bytes_before += file.original_len as u64;
449        report.image_bytes_after += file.bytes.len() as u64;
450        writer
451            .start_file(file.path.as_str(), stored)
452            .map_err(from_zip)?;
453        writer.write_all(&file.bytes)?;
454    }
455
456    writer.finish().map_err(from_zip)?;
457    Ok(report)
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use proptest::prelude::*;
464    use quick_xml::Reader;
465    use quick_xml::events::Event;
466    use std::io::Cursor;
467
468    fn escape(text: &str) -> String {
469        text.replace('&', "&amp;")
470            .replace('<', "&lt;")
471            .replace('>', "&gt;")
472    }
473
474    /// Text a reader would show: XHTML text nodes and entity references, in order.
475    fn visible_text(xhtml: &str) -> String {
476        let mut reader = Reader::from_str(xhtml);
477        let mut out = String::new();
478        loop {
479            match reader.read_event().expect("valid XHTML") {
480                Event::Eof => break,
481                Event::Text(t) => out.push_str(&t.xml10_content()),
482                Event::GeneralRef(r) => out.push_str(&format!("&{};", r.xml10_content())),
483                _ => {}
484            }
485        }
486        out
487    }
488
489    /// Element structure: start, end and empty tags by name, in order.
490    /// Attributes are left out on purpose: prensa may rewrite image
491    /// attributes (`src`, `width`), never the tree. Reading positions in sync
492    /// services (KOReader's XPath) depend on this tree and on the text.
493    fn tags(xhtml: &str) -> Vec<String> {
494        let mut reader = Reader::from_str(xhtml);
495        let mut out = Vec::new();
496        loop {
497            let tag = match reader.read_event().expect("valid XHTML") {
498                Event::Eof => break,
499                Event::Start(e) => format!("<{}>", e.name().as_ref()),
500                Event::Empty(e) => format!("<{}/>", e.name().as_ref()),
501                Event::End(e) => format!("</{}>", e.name().as_ref()),
502                _ => continue,
503            };
504            out.push(tag);
505        }
506        out
507    }
508
509    /// Build a minimal EPUB in memory: chapters, optional embedded font + @font-face,
510    /// optional obfuscation entry. Every chapter shows `images/figure.webp`,
511    /// also used as a CSS background; the file exists only if `figure` is given.
512    fn build_epub(
513        chapters: &[Vec<String>],
514        font: Option<&[u8]>,
515        figure: Option<&[u8]>,
516    ) -> anyhow::Result<Vec<u8>> {
517        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
518        let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
519        zip.start_file("mimetype", stored)?;
520        zip.write_all(b"application/epub+zip")?;
521        zip.start_file("META-INF/container.xml", stored)?;
522        zip.write_all(br#"<?xml version="1.0"?><container><rootfiles><rootfile full-path="OEBPS/content.opf"/></rootfiles></container>"#)?;
523
524        let mut manifest =
525            String::from(r#"<item href="style.css" id="css" media-type="text/css"/>"#);
526        let mut css = String::from("p { margin: 0 }\nh1 { background: url(images/figure.webp) }\n");
527        if let Some(bytes) = figure {
528            manifest
529                .push_str(r#"<item href="images/figure.webp" id="fig" media-type="image/webp"/>"#);
530            zip.start_file("OEBPS/images/figure.webp", stored)?;
531            zip.write_all(bytes)?;
532        }
533        if let Some(bytes) = font {
534            manifest.push_str(r#"<item href="fonts/f.ttf" id="font" media-type="font/ttf"/>"#);
535            css.push_str("@font-face { font-family: \"F\"; src: url(fonts/f.ttf); }\n");
536            zip.start_file("OEBPS/fonts/f.ttf", stored)?;
537            zip.write_all(bytes)?;
538            zip.start_file("META-INF/encryption.xml", stored)?;
539            zip.write_all(br#"<encryption><EncryptedData><CipherReference URI="OEBPS/fonts/f.ttf"/></EncryptedData></encryption>"#)?;
540        }
541        for (i, paragraphs) in chapters.iter().enumerate() {
542            manifest.push_str(&format!(
543                r#"<item href="ch{i}.xhtml" id="ch{i}" media-type="application/xhtml+xml"/>"#
544            ));
545            let body: String = paragraphs
546                .iter()
547                .map(|p| format!("<p>{}</p>", escape(p)))
548                .collect();
549            zip.start_file(format!("OEBPS/ch{i}.xhtml"), stored)?;
550            zip.write_all(format!(r#"<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><body><div><h1>Chapter {i}</h1>{body}<img src="images/figure.webp" alt=""/></div></body></html>"#).as_bytes())?;
551        }
552        zip.start_file("OEBPS/style.css", stored)?;
553        zip.write_all(css.as_bytes())?;
554        zip.start_file("OEBPS/content.opf", stored)?;
555        zip.write_all(format!(r#"<?xml version="1.0"?><package version="3.0"><manifest>{manifest}</manifest></package>"#).as_bytes())?;
556        Ok(zip.finish()?.into_inner())
557    }
558
559    fn read_all(epub: &[u8]) -> Vec<(String, Vec<u8>)> {
560        let mut archive = ZipArchive::new(Cursor::new(epub)).unwrap();
561        (0..archive.len())
562            .map(|i| {
563                let mut entry = archive.by_index(i).unwrap();
564                let mut bytes = Vec::new();
565                entry.read_to_end(&mut bytes).unwrap();
566                (entry.name().unwrap().into_owned(), bytes)
567            })
568            .collect()
569    }
570
571    /// `f` applied to every chapter, in archive order.
572    fn per_chapter<T>(entries: &[(String, Vec<u8>)], f: fn(&str) -> T) -> Vec<T> {
573        entries
574            .iter()
575            .filter(|(name, _)| name.ends_with(".xhtml"))
576            .map(|(_, bytes)| f(std::str::from_utf8(bytes).unwrap()))
577            .collect()
578    }
579
580    /// Zip with one deflated entry per `(name, bytes)`, in order.
581    fn zip_of(entries: &[(&str, &[u8])]) -> Vec<u8> {
582        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
583        for (name, bytes) in entries {
584            zip.start_file(*name, SimpleFileOptions::default()).unwrap();
585            zip.write_all(bytes).unwrap();
586        }
587        zip.finish().unwrap().into_inner()
588    }
589
590    proptest! {
591        #![proptest_config(ProptestConfig::with_cases(64))]
592
593        /// The core promise: whatever the book contains, the text a reader sees
594        /// and the element structure around it are identical before and after,
595        /// and the output is a valid EPUB container.
596        #[test]
597        fn visible_text_and_structure_are_unchanged(
598            chapters in prop::collection::vec(prop::collection::vec("\\PC{0,60}", 0..5), 1..4),
599            font in prop::option::of(prop::collection::vec(any::<u8>(), 1..64)),
600            has_figure in any::<bool>(),
601        ) {
602            let figure = has_figure.then(|| webp(8, 8));
603            let input = build_epub(&chapters, font.as_deref(), figure.as_deref()).unwrap();
604            let mut output = Cursor::new(Vec::new());
605
606            let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
607
608            let before = read_all(&input);
609            let after = read_all(output.get_ref());
610            prop_assert_eq!(per_chapter(&before, visible_text), per_chapter(&after, visible_text));
611            prop_assert_eq!(per_chapter(&before, tags), per_chapter(&after, tags));
612
613            // Container rules and the fonts pass, checked on every case.
614            prop_assert_eq!(after[0].0.as_str(), "mimetype");
615            prop_assert!(after.iter().all(|(name, _)| !fonts::is_font(name)));
616            prop_assert!(after.iter().all(|(name, _)| name != "META-INF/encryption.xml"));
617            let opf = &after.iter().find(|(n, _)| n.ends_with(".opf")).unwrap().1;
618            prop_assert!(!String::from_utf8_lossy(opf).contains("f.ttf"));
619            prop_assert_eq!(report.fonts_removed, usize::from(font.is_some()));
620
621            // The images pass: a WebP figure becomes PNG (it is lossless) and
622            // every reference follows it.
623            if has_figure {
624                prop_assert_eq!(report.images_converted, 1);
625                prop_assert!(after.iter().all(|(name, _)| !name.ends_with(".webp")));
626                prop_assert!(after.iter().any(|(name, _)| name == "OEBPS/images/figure.png"));
627                for (name, bytes) in &after {
628                    let text = String::from_utf8_lossy(bytes);
629                    if name.ends_with(".xhtml") || name.ends_with(".css") || name.ends_with(".opf") {
630                        prop_assert!(!text.contains("figure.webp"), "{}", name);
631                        prop_assert!(text.contains("images/figure.png"), "{}", name);
632                    }
633                }
634                prop_assert!(String::from_utf8_lossy(opf).contains(r#"media-type="image/png""#));
635            }
636        }
637    }
638
639    /// A lossless WebP (the only kind the `image` crate encodes).
640    fn webp(w: u32, h: u32) -> Vec<u8> {
641        let img =
642            image::RgbImage::from_fn(w, h, |x, y| image::Rgb([x as u8 * 20, y as u8 * 20, 90]));
643        let mut out = Vec::new();
644        image::DynamicImage::ImageRgb8(img)
645            .write_to(&mut Cursor::new(&mut out), image::ImageFormat::WebP)
646            .unwrap();
647        out
648    }
649
650    #[test]
651    fn structure_ignores_attributes_but_not_elements() {
652        let original = r#"<p>A. B.<img src="a.png" width="900"/></p>"#;
653        let new_attributes = r#"<p>A. B.<img src="a.jpg"/></p>"#;
654        // Same text, one paragraph split in two: what a "split long
655        // paragraphs" pass would do, and what this check exists to catch.
656        let split = r#"<p>A. </p><p>B.<img src="a.png" width="900"/></p>"#;
657
658        assert_eq!(tags(original), tags(new_attributes));
659        assert_eq!(visible_text(original), visible_text(split));
660        assert_ne!(tags(original), tags(split));
661    }
662
663    #[test]
664    fn reports_progress_for_every_entry() {
665        let input = build_epub(&[vec!["a".into()], vec!["b".into()]], None, None).unwrap();
666        let mut seen = Vec::new();
667        let mut output = Cursor::new(Vec::new());
668        optimize_with_progress(Cursor::new(&input), &mut output, &Options::default(), |p| {
669            seen.push((p.done, p.total, p.entry.to_owned()));
670        })
671        .unwrap();
672
673        let names: Vec<String> = read_all(&input).into_iter().map(|(n, _)| n).collect();
674        let expected: Vec<_> = names
675            .iter()
676            .enumerate()
677            .map(|(i, n)| (i, names.len(), n.clone()))
678            .collect();
679        assert_eq!(seen, expected);
680    }
681
682    #[test]
683    fn sizes_are_as_stored_in_the_epub() {
684        // A deflated font that compresses well: stored size << real size.
685        let input = zip_of(&[("f.ttf", &[0; 10_000])]);
686        let stored = ZipArchive::new(Cursor::new(&input))
687            .unwrap()
688            .by_index_raw(0)
689            .unwrap()
690            .compressed_size();
691
692        let mut output = Cursor::new(Vec::new());
693        let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
694        assert!(stored < 10_000);
695        assert_eq!(report.font_bytes, stored);
696    }
697
698    #[test]
699    fn rejects_non_zip_input() {
700        let mut output = Cursor::new(Vec::new());
701        let err = optimize(Cursor::new(b"not a zip"), &mut output, &Options::default());
702        assert!(matches!(err, Err(Error::InvalidZip(_))));
703    }
704
705    fn utf16(text: &str) -> Vec<u8> {
706        [0xFF, 0xFE]
707            .into_iter()
708            .chain(text.encode_utf16().flat_map(u16::to_le_bytes))
709            .collect()
710    }
711
712    #[test]
713    fn rejects_opf_and_encryption_that_are_not_utf8() {
714        let opf = utf16(r#"<package><manifest><item href="f.ttf" id="f"/></manifest></package>"#);
715        let enc = utf16(
716            r#"<encryption><EncryptedData><CipherReference URI="OEBPS/f.ttf"/></EncryptedData></encryption>"#,
717        );
718        for (name, bytes) in [
719            ("OEBPS/content.opf", &opf),
720            ("META-INF/encryption.xml", &enc),
721        ] {
722            let input = zip_of(&[(name, bytes), ("OEBPS/f.ttf", b"font")]);
723            let mut output = Cursor::new(Vec::new());
724            match optimize(Cursor::new(input), &mut output, &Options::default()) {
725                Err(Error::Malformed { entry, .. }) => assert_eq!(entry, name),
726                other => panic!("{name}: expected Malformed, got {other:?}"),
727            }
728        }
729    }
730
731    #[test]
732    fn unchanged_text_entries_are_copied_as_stored() {
733        // No @font-face, no font items: nothing to rewrite. Stored (not
734        // deflated) in the input, so a rewrite would show up as deflated.
735        let css: &[u8] = b"p { margin: 0 }";
736        let opf: &[u8] =
737            br#"<package><manifest><item href="ch.xhtml" id="c"/></manifest></package>"#;
738        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
739        let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
740        for (name, bytes) in [("OEBPS/style.css", css), ("OEBPS/content.opf", opf)] {
741            zip.start_file(name, stored).unwrap();
742            zip.write_all(bytes).unwrap();
743        }
744        let input = zip.finish().unwrap().into_inner();
745
746        let mut output = Cursor::new(Vec::new());
747        optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
748
749        let mut archive = ZipArchive::new(Cursor::new(output.into_inner())).unwrap();
750        for (name, bytes) in [("OEBPS/style.css", css), ("OEBPS/content.opf", opf)] {
751            let mut entry = archive.by_name(name).unwrap();
752            assert_eq!(entry.compression(), CompressionMethod::Stored, "{name}");
753            let mut out = Vec::new();
754            entry.read_to_end(&mut out).unwrap();
755            assert_eq!(out, bytes, "{name}");
756        }
757    }
758
759    #[test]
760    fn copies_css_that_is_not_utf8() {
761        // Latin-1 `é` in a comment: invalid UTF-8.
762        let css = b"/* caf\xe9 */ @font-face { src: url(f.ttf) }";
763        let input = zip_of(&[("OEBPS/style.css", css)]);
764        let mut output = Cursor::new(Vec::new());
765        optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
766        let after = read_all(output.get_ref());
767        let (_, bytes) = after.iter().find(|(n, _)| n == "OEBPS/style.css").unwrap();
768        assert_eq!(bytes, css);
769    }
770
771    #[test]
772    fn read_errors_are_io_errors() {
773        /// A reader whose disk fails: not a malformed book.
774        struct FailingReader;
775        impl Read for FailingReader {
776            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
777                Err(std::io::Error::other("disk failed"))
778            }
779        }
780        impl Seek for FailingReader {
781            fn seek(&mut self, _: std::io::SeekFrom) -> std::io::Result<u64> {
782                Ok(100)
783            }
784        }
785
786        let mut output = Cursor::new(Vec::new());
787        let err = optimize(FailingReader, &mut output, &Options::default());
788        assert!(matches!(err, Err(Error::Io(_))), "got {err:?}");
789    }
790
791    /// Zip with a single entry of `size` zero bytes.
792    fn zip_with_zeros(name: &str, size: u64) -> Vec<u8> {
793        zip_of(&[(name, &vec![0; size as usize])])
794    }
795
796    #[test]
797    fn oversized_text_entry_fails_the_book() {
798        let input = zip_with_zeros("OEBPS/style.css", MAX_ENTRY_SIZE + 1);
799        let mut output = Cursor::new(Vec::new());
800        match optimize(Cursor::new(input), &mut output, &Options::default()) {
801            Err(Error::Malformed { entry, source }) => {
802                assert_eq!(entry, "OEBPS/style.css");
803                assert!(source.to_string().contains("larger than"), "{source}");
804            }
805            other => panic!("expected Malformed, got {other:?}"),
806        }
807    }
808
809    #[test]
810    fn batch_size_does_not_change_the_output() {
811        let image = |w: u32, format: image::ImageFormat| {
812            let img = image::RgbImage::from_fn(w, 300, |x, y| {
813                image::Rgb([(x % 256) as u8, (y % 256) as u8, 90])
814            });
815            let mut out = Vec::new();
816            image::DynamicImage::ImageRgb8(img)
817                .write_to(&mut Cursor::new(&mut out), format)
818                .unwrap();
819            out
820        };
821        let (big_png, small_png) = (
822            image(900, image::ImageFormat::Png),
823            image(40, image::ImageFormat::Png),
824        );
825        let (big_jpg, small_jpg) = (
826            image(900, image::ImageFormat::Jpeg),
827            image(40, image::ImageFormat::Jpeg),
828        );
829        let figure = webp(4, 4);
830        // Images (changed, kept, failed, converted) between other entries.
831        let input = zip_of(&[
832            ("OEBPS/a.png", &big_png),
833            (
834                "OEBPS/ch1.xhtml",
835                br#"<html><body><img src="e.webp"/></body></html>"#,
836            ),
837            ("OEBPS/b.jpg", &big_jpg),
838            ("OEBPS/c.png", &small_png),
839            ("OEBPS/broken.png", b"not a png"),
840            ("OEBPS/style.css", b"p { margin: 0 }"),
841            ("OEBPS/d.jpg", &small_jpg),
842            ("OEBPS/e.webp", &figure),
843            ("OEBPS/f.png", &big_png),
844        ]);
845
846        let run = |batch| {
847            let mut output = Cursor::new(Vec::new());
848            let mut progress = Vec::new();
849            let report = optimize_in_batches(
850                Cursor::new(&input),
851                &mut output,
852                &Options::default(),
853                |p| progress.push((p.done, p.entry.to_owned())),
854                batch,
855            )
856            .unwrap();
857            (output.into_inner(), report, progress)
858        };
859        let one_by_one = run(1);
860        assert_eq!(one_by_one.1.images_failed, 1);
861        assert_eq!(one_by_one.1.images_converted, 1);
862        for batch in [2, 3, 100] {
863            assert_eq!(run(batch), one_by_one, "batch {batch}");
864        }
865    }
866
867    #[test]
868    fn oversized_image_is_copied_unchanged() {
869        let input = zip_with_zeros("OEBPS/a.png", MAX_ENTRY_SIZE + 1);
870        let mut output = Cursor::new(Vec::new());
871        let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
872        let [warning] = report.warnings.as_slice() else {
873            panic!("expected one warning, got {:?}", report.warnings);
874        };
875        assert_eq!(warning.entry, "OEBPS/a.png");
876        assert!(warning.message.contains("larger than"), "{warning}");
877        assert_eq!(report.images_failed, 1);
878        let after = read_all(output.get_ref());
879        assert_eq!(after[1].0, "OEBPS/a.png");
880        assert_eq!(after[1].1.len() as u64, MAX_ENTRY_SIZE + 1);
881    }
882
883    #[test]
884    fn entry_at_the_limit_is_read() {
885        let input = zip_with_zeros("OEBPS/style.css", MAX_ENTRY_SIZE);
886        let mut archive = ZipArchive::new(Cursor::new(input)).unwrap();
887        let bytes = read_entry(&mut archive, 0)
888            .unwrap()
889            .expect("within the limit");
890        assert_eq!(bytes.len() as u64, MAX_ENTRY_SIZE);
891    }
892
893    #[test]
894    fn removes_fonts_declared_only_by_media_type() {
895        let files: [(&str, &[u8]); 4] = [
896            (
897                "OEBPS/content.opf",
898                br#"<package><manifest><item href="fonts/f0001" id="f" media-type="font/ttf"/><item href="ch.xhtml" id="c" media-type="application/xhtml+xml"/></manifest></package>"#,
899            ),
900            ("OEBPS/fonts/f0001", b"font bytes"),
901            ("OEBPS/ch.xhtml", b"<html/>"),
902            (
903                "META-INF/encryption.xml",
904                br#"<encryption><EncryptedData><CipherReference URI="OEBPS/fonts/f0001"/></EncryptedData></encryption>"#,
905            ),
906        ];
907        let input = zip_of(&files);
908
909        let mut output = Cursor::new(Vec::new());
910        let report = optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
911        let names: Vec<String> = read_all(output.get_ref())
912            .into_iter()
913            .map(|(n, _)| n)
914            .collect();
915        assert_eq!(names, ["mimetype", "OEBPS/content.opf", "OEBPS/ch.xhtml"]);
916        assert_eq!(report.fonts_removed, 1);
917    }
918
919    #[test]
920    fn undecodable_image_is_a_warning_naming_the_entry() {
921        let input = zip_of(&[("OEBPS/a.png", b"not a png")]);
922
923        let mut output = Cursor::new(Vec::new());
924        let report = optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
925        let [warning] = report.warnings.as_slice() else {
926            panic!("expected one warning, got {:?}", report.warnings);
927        };
928        assert_eq!(warning.entry, "OEBPS/a.png");
929        assert!(warning.message.ends_with("; copied unchanged"), "{warning}");
930        assert!(warning.to_string().starts_with("OEBPS/a.png: "));
931        assert_eq!(
932            warning.message.matches("Invalid PNG signature").count(),
933            1,
934            "{warning}"
935        );
936        assert_eq!(report.images_failed, 1);
937        assert_eq!(report.images_kept, 0);
938    }
939
940    #[test]
941    fn truncated_jpeg_warning_is_one_line() {
942        let input = zip_of(&[("OEBPS/a.jpg", b"\xff\xd8\xff\xe0\x00\x10JFIF\x00")]);
943        let mut output = Cursor::new(Vec::new());
944        let report = optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
945        let [warning] = report.warnings.as_slice() else {
946            panic!("expected one warning, got {:?}", report.warnings);
947        };
948        assert!(!warning.message.contains('\n'), "{warning:?}");
949        assert!(
950            warning.message.ends_with("; copied unchanged"),
951            "{warning:?}"
952        );
953    }
954
955    #[test]
956    fn broken_opf_names_the_entry() {
957        let input = zip_of(&[("OEBPS/content.opf", b"<package><manifest></package>")]);
958
959        let mut output = Cursor::new(Vec::new());
960        match optimize(Cursor::new(input), &mut output, &Options::default()) {
961            Err(Error::Malformed { entry, .. }) => assert_eq!(entry, "OEBPS/content.opf"),
962            other => panic!("expected Malformed, got {other:?}"),
963        }
964    }
965
966    #[test]
967    fn converted_image_does_not_overwrite_an_existing_file() {
968        // `fig.webp` is lossless, so it becomes PNG, but `fig.png` exists.
969        let mut png = Vec::new();
970        image::DynamicImage::ImageLuma8(image::GrayImage::new(2, 2))
971            .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
972            .unwrap();
973        let figure = webp(4, 4);
974        let input = zip_of(&[
975            (
976                "OEBPS/content.opf",
977                br#"<package><manifest><item href="fig.png" id="a" media-type="image/png"/><item href="fig.webp" id="b" media-type="image/webp"/></manifest></package>"#,
978            ),
979            ("OEBPS/fig.png", &png),
980            ("OEBPS/fig.webp", &figure),
981            (
982                "OEBPS/ch.xhtml",
983                br#"<html><body><img src="fig.png"/><img src="fig.webp"/></body></html>"#,
984            ),
985        ]);
986
987        let mut output = Cursor::new(Vec::new());
988        let report = optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
989        let after = read_all(output.get_ref());
990        let get = |n: &str| {
991            after
992                .iter()
993                .find(|(name, _)| name == n)
994                .map(|(_, b)| String::from_utf8_lossy(b).into_owned())
995        };
996
997        assert_eq!(report.images_converted, 1);
998        assert!(get("OEBPS/fig.png").is_some());
999        assert!(get("OEBPS/fig-1.png").is_some());
1000        assert!(get("OEBPS/fig.webp").is_none());
1001        assert_eq!(
1002            get("OEBPS/ch.xhtml").unwrap(),
1003            r#"<html><body><img src="fig.png"/><img src="fig-1.png"/></body></html>"#
1004        );
1005        let opf = get("OEBPS/content.opf").unwrap();
1006        assert!(
1007            opf.contains(r#"<item href="fig.png" id="a" media-type="image/png"/>"#),
1008            "{opf}"
1009        );
1010        assert!(
1011            opf.contains(r#"<item href="fig-1.png" id="b" media-type="image/png"/>"#),
1012            "{opf}"
1013        );
1014    }
1015
1016    #[test]
1017    fn undecodable_webp_keeps_its_name_and_references() {
1018        let xhtml: &[u8] = br#"<html><body><img src="a.webp"/></body></html>"#;
1019        let input = zip_of(&[("OEBPS/a.webp", b"not a webp"), ("OEBPS/ch.xhtml", xhtml)]);
1020        let mut output = Cursor::new(Vec::new());
1021        let report = optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
1022        let after = read_all(output.get_ref());
1023        assert_eq!(report.images_failed, 1);
1024        assert_eq!(report.images_converted, 0);
1025        assert!(after.iter().any(|(n, _)| n == "OEBPS/a.webp"));
1026        assert!(
1027            after
1028                .iter()
1029                .any(|(n, b)| n == "OEBPS/ch.xhtml" && b == xhtml)
1030        );
1031    }
1032
1033    #[test]
1034    fn broken_chapter_is_copied_with_a_warning() {
1035        // An unterminated tag: not even attributes can be read.
1036        let broken: &[u8] = br#"<html><body><p><img src="a.webp"</p></body></html>"#;
1037        let figure = webp(4, 4);
1038        let input = zip_of(&[("OEBPS/a.webp", &figure), ("OEBPS/ch.xhtml", broken)]);
1039        let mut output = Cursor::new(Vec::new());
1040        let report = optimize(Cursor::new(input), &mut output, &Options::default()).unwrap();
1041        let after = read_all(output.get_ref());
1042
1043        assert!(
1044            after
1045                .iter()
1046                .any(|(n, b)| n == "OEBPS/ch.xhtml" && b == broken)
1047        );
1048        let [warning] = report.warnings.as_slice() else {
1049            panic!("expected one warning, got {:?}", report.warnings);
1050        };
1051        assert_eq!(warning.entry, "OEBPS/ch.xhtml");
1052        assert!(
1053            warning
1054                .message
1055                .ends_with("image references in it not updated; copied unchanged"),
1056            "{warning}"
1057        );
1058    }
1059
1060    #[test]
1061    fn wide_image_is_turned_and_loses_its_sizes() {
1062        let mut png = Vec::new();
1063        image::DynamicImage::ImageLuma8(image::GrayImage::new(2000, 800))
1064            .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
1065            .unwrap();
1066        let chapter = br#"<html><body><p>Figure 1</p><img src="../img/wide.png" width="2000" height="800" alt="Figure 1"/></body></html>"#;
1067        let input = zip_of(&[
1068            ("OEBPS/img/wide.png", &png),
1069            ("OEBPS/text/ch.xhtml", chapter),
1070        ]);
1071
1072        let cw = Options::builder()
1073            .rotate(Rotation::Clockwise)
1074            .build()
1075            .unwrap();
1076        let mut output = Cursor::new(Vec::new());
1077        let report = optimize(Cursor::new(&input), &mut output, &cw).unwrap();
1078        let after = read_all(output.get_ref());
1079        let get = |n: &str| &after.iter().find(|(name, _)| name == n).unwrap().1;
1080
1081        assert_eq!(report.images_rotated, 1);
1082        let img = image::load_from_memory(get("OEBPS/img/wide.png")).unwrap();
1083        assert!(img.height() > img.width(), "turned to portrait");
1084        assert_eq!(
1085            String::from_utf8_lossy(get("OEBPS/text/ch.xhtml")),
1086            r#"<html><body><p>Figure 1</p><img src="../img/wide.png" alt="Figure 1"/></body></html>"#
1087        );
1088
1089        // Off (the default): the chapter stays as it was.
1090        let mut output = Cursor::new(Vec::new());
1091        let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
1092        assert_eq!(report.images_rotated, 0);
1093        let after = read_all(output.get_ref());
1094        assert!(
1095            after
1096                .iter()
1097                .any(|(n, b)| n == "OEBPS/text/ch.xhtml" && b == chapter)
1098        );
1099    }
1100
1101    #[test]
1102    fn embedded_image_moves_to_its_own_entry() {
1103        use base64::Engine;
1104        let mut png = Vec::new();
1105        image::DynamicImage::ImageLuma8(image::GrayImage::new(900, 300))
1106            .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
1107            .unwrap();
1108        let uri = format!(
1109            "data:image/png;base64,{}",
1110            base64::engine::general_purpose::STANDARD.encode(&png)
1111        );
1112        let chapter = format!(
1113            r#"<html><body><p>A</p><img src="{uri}" alt="a"/><p>B</p><img src="{uri}"/></body></html>"#
1114        );
1115        let other = format!(r#"<html><body><img src="{uri}"/></body></html>"#);
1116        let opf: &[u8] = br#"<package><manifest><item id="c" href="text/ch.xhtml" media-type="application/xhtml+xml"/></manifest></package>"#;
1117        let input = zip_of(&[
1118            ("OEBPS/content.opf", opf),
1119            ("OEBPS/text/ch.xhtml", chapter.as_bytes()),
1120            ("OEBPS/other/end.xhtml", other.as_bytes()),
1121        ]);
1122
1123        let mut output = Cursor::new(Vec::new());
1124        let report = optimize(Cursor::new(&input), &mut output, &Options::default()).unwrap();
1125        let after = read_all(output.get_ref());
1126        let text = |n: &str| {
1127            String::from_utf8_lossy(&after.iter().find(|(name, _)| name == n).unwrap().1)
1128                .into_owned()
1129        };
1130
1131        assert_eq!(report.images_extracted, 1);
1132        assert_eq!(report.images_changed, 1);
1133        let new_chapter = text("OEBPS/text/ch.xhtml");
1134        assert_eq!(
1135            new_chapter,
1136            r#"<html><body><p>A</p><img src="ch-image-1.png" alt="a"/><p>B</p><img src="ch-image-1.png"/></body></html>"#
1137        );
1138        assert_eq!(visible_text(&chapter), visible_text(&new_chapter));
1139        assert_eq!(tags(&chapter), tags(&new_chapter));
1140        // The same image in another chapter: the same file.
1141        assert_eq!(
1142            text("OEBPS/other/end.xhtml"),
1143            r#"<html><body><img src="../text/ch-image-1.png"/></body></html>"#
1144        );
1145        let image = &after
1146            .iter()
1147            .find(|(n, _)| n == "OEBPS/text/ch-image-1.png")
1148            .unwrap()
1149            .1;
1150        assert_eq!(image::load_from_memory(image).unwrap().width(), 440);
1151        assert!(text("OEBPS/content.opf").contains(
1152            r#"<item id="prensa-ch-image-1-png" href="text/ch-image-1.png" media-type="image/png"/></manifest>"#
1153        ));
1154    }
1155}