Skip to main content

epub_parser/
epub.rs

1use crate::types::{Image, Metadata, Page, TocEntry};
2use crate::utils::{preprocess_html_entities, ZipHandler};
3use ordered_hash_map::OrderedHashMap;
4use quick_xml::events::Event;
5use std::io::Cursor;
6use std::path::{Path, PathBuf};
7
8/// A parsed EPUB e-book representation.
9///
10/// This struct contains all the extracted data from an EPUB file including:
11/// - Metadata (title, author, publisher, etc.)
12/// - Table of contents (hierarchical navigation)
13/// - Text content (pages in reading order)
14/// - Images (including cover image)
15///
16/// # Example
17///
18/// ```
19/// use epub_parser::Epub;
20/// use std::path::Path;
21///
22/// let epub = Epub::parse(Path::new("book.epub"))?;
23///
24/// // Access metadata
25/// if let Some(title) = &epub.metadata.title {
26///     println!("Title: {}", title);
27/// }
28///
29/// // Access all pages
30/// for page in &epub.pages {
31///     println!("Page {}: {} chars", page.index, page.content.len());
32/// }
33///
34/// // Access images
35/// for image in &epub.images {
36///     println!("Image: {} ({})", image.href, image.media_type);
37/// }
38/// ```
39#[derive(Debug)]
40pub struct Epub {
41    /// The Dublin Core metadata extracted from the EPUB.
42    pub metadata: Metadata,
43    /// The hierarchical table of contents from the NCX file.
44    pub toc: Vec<TocEntry>,
45    /// The text content of each page in reading order.
46    pub pages: Vec<Page>,
47    /// All images found in the EPUB (including cover).
48    pub images: Vec<Image>,
49}
50
51/// Errors that can occur while parsing an EPUB file.
52#[derive(Debug)]
53pub enum Error {
54    /// The EPUB file is invalid or corrupted.
55    InvalidEpub(String),
56    /// An I/O error occurred while reading the file.
57    IoError(std::io::Error),
58    /// An error occurred while reading the ZIP archive.
59    ZipError(zip::result::ZipError),
60    /// An error occurred while parsing XML.
61    XmlError(String),
62    /// The META-INF/container.xml file is missing.
63    MissingContainer,
64    /// The OPF package file is missing or not found.
65    MissingOpf,
66    /// The NCX table of contents file is missing.
67    MissingNcx,
68}
69
70impl std::fmt::Display for Error {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        match self {
73            Error::InvalidEpub(msg) => write!(f, "Invalid EPUB: {}", msg),
74            Error::IoError(e) => write!(f, "I/O error: {}", e),
75            Error::ZipError(e) => write!(f, "ZIP error: {}", e),
76            Error::XmlError(e) => write!(f, "XML error: {}", e),
77            Error::MissingContainer => write!(f, "Missing container.xml"),
78            Error::MissingOpf => write!(f, "Missing OPF file"),
79            Error::MissingNcx => write!(f, "Missing NCX file"),
80        }
81    }
82}
83
84impl std::error::Error for Error {
85    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
86        match self {
87            Error::IoError(e) => Some(e),
88            Error::ZipError(e) => Some(e),
89            _ => None,
90        }
91    }
92}
93
94impl From<std::io::Error> for Error {
95    fn from(err: std::io::Error) -> Self {
96        Error::IoError(err)
97    }
98}
99
100impl From<zip::result::ZipError> for Error {
101    fn from(err: zip::result::ZipError) -> Self {
102        Error::ZipError(err)
103    }
104}
105
106impl From<quick_xml::Error> for Error {
107    fn from(err: quick_xml::Error) -> Self {
108        Error::XmlError(err.to_string())
109    }
110}
111
112impl Epub {
113    /// Parse an EPUB file from a file path.
114    ///
115    /// # Arguments
116    ///
117    /// * `path` - The path to the EPUB file.
118    ///
119    /// # Returns
120    ///
121    /// Returns `Ok(Epub)` on success, or an `Error` if parsing fails.
122    ///
123    /// # Errors
124    ///
125    /// This function will return an error if:
126    /// - The file does not exist
127    /// - The file is not a valid ZIP archive
128    /// - The EPUB structure is invalid
129    ///
130    /// # Example
131    ///
132    /// ```
133    /// use epub_parser::Epub;
134    /// use std::path::Path;
135    ///
136    /// let epub = Epub::parse(Path::new("book.epub"))?;
137    /// println!("Parsed: {}", epub.metadata.title.unwrap_or_default());
138    /// # Ok::<(), Box<dyn std::error::Error>>(())
139    /// ```
140    pub fn parse(path: &Path) -> Result<Self, Error> {
141        let mut zip_handler = ZipHandler::new(path)?;
142        Self::parse_from_handler(&mut zip_handler)
143    }
144
145    /// Parse an EPUB file from a byte buffer.
146    ///
147    /// This is useful when you have the EPUB data in memory, for example
148    /// when downloading from a network or reading from a database.
149    ///
150    /// # Arguments
151    ///
152    /// * `buffer` - The raw bytes of the EPUB file.
153    ///
154    /// # Returns
155    ///
156    /// Returns `Ok(Epub)` on success, or an `Error` if parsing fails.
157    ///
158    /// # Example
159    ///
160    /// ```
161    /// use epub_parser::Epub;
162    ///
163    /// let bytes = std::fs::read("book.epub")?;
164    /// let epub = Epub::parse_from_buffer(&bytes)?;
165    /// println!("Parsed: {}", epub.metadata.title.unwrap_or_default());
166    /// # Ok::<(), Box<dyn std::error::Error>>(())
167    /// ```
168    pub fn parse_from_buffer(buffer: &[u8]) -> Result<Self, Error> {
169        let cursor = Cursor::new(buffer.to_vec());
170        let mut zip_handler = ZipHandler::new_from_reader(cursor)?;
171        Self::parse_from_handler(&mut zip_handler)
172    }
173
174    fn parse_from_handler<R: std::io::Read + std::io::Seek>(
175        zip_handler: &mut ZipHandler<R>,
176    ) -> Result<Self, Error> {
177        let opf_path = zip_handler.get_opf_path()?;
178        let opf_content = zip_handler.read_file(&opf_path)?;
179
180        let (metadata, manifest, spine, ncx_path) = Self::parse_opf(&opf_content)?;
181
182        let toc = if let Some(ncx_ref) = ncx_path {
183            let ncx_path_full = Self::resolve_path(&opf_path, &ncx_ref);
184            let ncx_content = zip_handler.read_file(&ncx_path_full)?;
185            Self::parse_ncx(&ncx_content)?
186        } else {
187            Vec::new()
188        };
189
190        let mut pages = Vec::new();
191        for itemref in spine {
192            if let Some(manifest_item) = manifest.get(&itemref) {
193                let content_path = Self::resolve_path(&opf_path, &manifest_item.href);
194                let content = zip_handler.read_file(&content_path)?;
195                let text = Self::extract_text_from_html(&content)?;
196                pages.push(Page {
197                    index: pages.len(),
198                    content: text,
199                });
200            }
201        }
202
203        let mut images = Vec::new();
204        for (id, item) in &manifest {
205            if item._media_type.to_lowercase().starts_with("image/") {
206                let image_path = Self::resolve_path(&opf_path, &item.href);
207                if let Ok(bytes) = zip_handler.read_file_as_bytes(&image_path) {
208                    if id.to_lowercase().contains("cover") {
209                        images.insert(
210                            0,
211                            Image {
212                                id: id.clone(),
213                                href: item.href.clone(),
214                                media_type: item._media_type.clone(),
215                                content: bytes,
216                            },
217                        );
218                    } else {
219                        images.push(Image {
220                            id: id.clone(),
221                            href: item.href.clone(),
222                            media_type: item._media_type.clone(),
223                            content: bytes,
224                        });
225                    }
226                }
227            }
228        }
229
230        Ok(Epub {
231            metadata,
232            toc,
233            pages,
234            images,
235        })
236    }
237
238    fn parse_opf(
239        content: &str,
240    ) -> Result<
241        (
242            Metadata,
243            OrderedHashMap<String, ManifestItem>,
244            Vec<String>,
245            Option<String>,
246        ),
247        Error,
248    > {
249        let content = preprocess_html_entities(content);
250        let mut reader = quick_xml::Reader::from_str(&content);
251        let mut metadata = Metadata::new();
252        let mut manifest: OrderedHashMap<String, ManifestItem> = OrderedHashMap::new();
253        let mut spine: Vec<String> = Vec::new();
254        let mut ncx_path: Option<String> = None;
255
256        let mut current_text_tag: Option<String> = None;
257
258        let mut buf = Vec::new();
259
260        loop {
261            match reader.read_event_into(&mut buf) {
262                Ok(Event::Start(ref e)) => {
263                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
264                    if name.contains("title") {
265                        current_text_tag = Some("title".to_string());
266                    } else if name.contains("creator") {
267                        current_text_tag = Some("author".to_string());
268                    } else if name.contains("publisher") {
269                        current_text_tag = Some("publisher".to_string());
270                    } else if name.contains("language") {
271                        current_text_tag = Some("language".to_string());
272                    } else if name.contains("identifier") {
273                        current_text_tag = Some("identifier".to_string());
274                    } else if name.contains("date") {
275                        current_text_tag = Some("date".to_string());
276                    } else if name.contains("rights") {
277                        current_text_tag = Some("rights".to_string());
278                    }
279                }
280                Ok(Event::Empty(ref e)) => {
281                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
282                    if name.contains("item") && !name.contains("itemref") {
283                        let mut id = String::new();
284                        let mut href = String::new();
285                        let mut media_type = String::new();
286
287                        for attr_result in e.attributes() {
288                            if let Ok(attr) = attr_result {
289                                let attr_name =
290                                    String::from_utf8_lossy(attr.key.as_ref()).to_string();
291                                if attr_name == "id" || attr_name.ends_with(":id") {
292                                    if let Some(val) =
293                                        attr.decode_and_unescape_value(reader.decoder()).ok()
294                                    {
295                                        id = val.to_string();
296                                    }
297                                } else if attr_name == "href" || attr_name.ends_with(":href") {
298                                    href = attr
299                                        .decode_and_unescape_value(reader.decoder())?
300                                        .to_string();
301                                } else if attr_name == "media-type"
302                                    || attr_name.ends_with(":media-type")
303                                {
304                                    media_type = attr
305                                        .decode_and_unescape_value(reader.decoder())?
306                                        .to_string();
307                                }
308                            }
309                        }
310
311                        if !id.is_empty() && !href.is_empty() {
312                            if media_type == "application/x-dtbncx+xml" {
313                                ncx_path = Some(href.clone());
314                            }
315                            manifest.insert(
316                                id.clone(),
317                                ManifestItem {
318                                    _id: id.clone(),
319                                    href,
320                                    _media_type: media_type,
321                                },
322                            );
323                        }
324                    } else if name.contains("itemref") {
325                        let mut idref = String::new();
326
327                        for attr_result in e.attributes() {
328                            if let Ok(attr) = attr_result {
329                                let attr_name =
330                                    String::from_utf8_lossy(attr.key.as_ref()).to_string();
331                                if attr_name == "idref" || attr_name.ends_with(":idref") {
332                                    if let Some(val) =
333                                        attr.decode_and_unescape_value(reader.decoder()).ok()
334                                    {
335                                        idref = val.to_string();
336                                    }
337                                    break;
338                                }
339                            }
340                        }
341
342                        if !idref.is_empty() {
343                            spine.push(idref);
344                        }
345                    }
346                }
347                Ok(Event::Text(e)) => {
348                    if let Some(tag) = &current_text_tag {
349                        let text = e.unescape()?.into_owned().trim().to_string();
350                        if !text.is_empty() {
351                            match tag.as_str() {
352                                "title" => metadata.title = Some(text),
353                                "author" => metadata.author = Some(text),
354                                "publisher" => metadata.publisher = Some(text),
355                                "language" => metadata.language = Some(text),
356                                "identifier" => metadata.identifier = Some(text),
357                                "date" => metadata.date = Some(text),
358                                "rights" => metadata.rights = Some(text),
359                                _ => {}
360                            }
361                        }
362                        current_text_tag = None;
363                    }
364                }
365                Ok(Event::End(_)) => {
366                    current_text_tag = None;
367                }
368                Ok(Event::Eof) => break,
369                Err(e) => return Err(Error::XmlError(e.to_string())),
370                _ => {}
371            }
372            buf.clear();
373        }
374
375        Ok((metadata, manifest, spine, ncx_path))
376    }
377
378    fn parse_ncx(content: &str) -> Result<Vec<TocEntry>, Error> {
379        let content = preprocess_html_entities(content);
380        let mut reader = quick_xml::Reader::from_str(&content);
381        let mut toc = Vec::new();
382        let mut stack: Vec<TocEntry> = Vec::new();
383
384        let mut buf = Vec::new();
385        let mut in_nav_label = false;
386        let mut in_text = false;
387
388        loop {
389            match reader.read_event_into(&mut buf) {
390                Ok(Event::Start(ref e)) => {
391                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
392                    if name == "navPoint" {
393                        let entry = TocEntry {
394                            label: String::new(),
395                            href: String::new(),
396                            children: Vec::new(),
397                        };
398                        stack.push(entry);
399                    } else if name == "navLabel" {
400                        in_nav_label = true;
401                    } else if name == "text" && in_nav_label {
402                        in_text = true;
403                    }
404                }
405                Ok(Event::End(ref e)) => {
406                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
407                    if name == "navPoint" {
408                        if let Some(entry) = stack.pop() {
409                            if let Some(parent) = stack.last_mut() {
410                                parent.children.push(entry);
411                            } else {
412                                toc.push(entry);
413                            }
414                        }
415                    } else if name == "navLabel" {
416                        in_nav_label = false;
417                    } else if name == "text" && in_nav_label {
418                        in_text = false;
419                    }
420                }
421                Ok(Event::Text(e)) => {
422                    if in_text {
423                        if let Some(entry) = stack.last_mut() {
424                            entry.label = e.unescape()?.into_owned();
425                        }
426                    }
427                }
428                Ok(Event::Empty(ref e)) => {
429                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
430                    if name == "content" {
431                        if let Some(src) = e.try_get_attribute("src")? {
432                            if let Some(entry) = stack.last_mut() {
433                                entry.href =
434                                    src.decode_and_unescape_value(reader.decoder())?.to_string();
435                            }
436                        }
437                    }
438                }
439                Ok(Event::Eof) => break,
440                Err(e) => return Err(Error::XmlError(e.to_string())),
441                _ => {}
442            }
443            buf.clear();
444        }
445
446        Ok(toc)
447    }
448
449    fn extract_text_from_html(content: &str) -> Result<String, Error> {
450        let content = preprocess_html_entities(content);
451        let mut reader = quick_xml::Reader::from_str(&content);
452        let mut text = String::new();
453        let skip_tags: Vec<Vec<u8>> = vec![b"script".to_vec(), b"style".to_vec(), b"head".to_vec()];
454        let mut in_skip_tag = false;
455
456        let mut buf = Vec::new();
457
458        loop {
459            match reader.read_event_into(&mut buf) {
460                Ok(Event::Start(ref e)) => {
461                    let tag = e.name().as_ref().to_vec();
462                    if skip_tags.contains(&tag) {
463                        in_skip_tag = true;
464                    } else if tag.as_slice() == b"p"
465                        || tag.as_slice() == b"div"
466                        || tag.as_slice() == b"br"
467                        || tag.as_slice() == b"li"
468                    {
469                        text.push('\n');
470                    }
471                }
472                Ok(Event::End(ref e)) => {
473                    let tag = e.name().as_ref().to_vec();
474                    if skip_tags.contains(&tag) {
475                        in_skip_tag = false;
476                    }
477                }
478                Ok(Event::Text(e)) => {
479                    if !in_skip_tag {
480                        let t = e.unescape()?.into_owned();
481                        let trimmed: String = t.chars().filter(|c| !c.is_control()).collect();
482                        text.push_str(&trimmed);
483                        text.push(' ');
484                    }
485                }
486                Ok(Event::Eof) => break,
487                Err(e) => return Err(Error::XmlError(e.to_string())),
488                _ => {}
489            }
490            buf.clear();
491        }
492
493        Ok(text
494            .lines()
495            .map(|l| l.trim())
496            .filter(|l| !l.is_empty())
497            .collect::<Vec<_>>()
498            .join("\n"))
499    }
500
501    fn resolve_path(base_path: &str, href: &str) -> String {
502        let base = PathBuf::from(base_path);
503        let parent = base.parent().unwrap_or(base.as_path());
504        let resolved = parent.join(href);
505        resolved.to_string_lossy().to_string().replace('\\', "/")
506    }
507}
508
509#[derive(Debug, Clone)]
510struct ManifestItem {
511    _id: String,
512    href: String,
513    _media_type: String,
514}