### Accessing Metadata Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Example of retrieving a specific metadata item from the document. ```rust let title = doc.metadata.iter().find(|d| d.property == "title"); assert_eq!(title.unwrap().value, "Todo es mío"); ``` -------------------------------- ### Get Container File Content Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Retrieves the content of the "META-INF/container.xml" file from the EPUB archive. Returns an error if the file is missing. ```rust pub fn get_container_file(&mut self) -> Result, ArchiveError> ``` -------------------------------- ### Get Total Number of Chapters in EPUB Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the total number of chapters within the EPUB document. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let mut doc = doc.unwrap(); assert_eq!(17, doc.get_num_chapters()); ``` -------------------------------- ### Get EPUB Root File Path Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Parses the container XML to find the 'rootfile' element and extracts its 'full-path' attribute, which specifies the main OPF or XPF file. ```rust let root = xmlutils::XMLReader::parse(container)?; let el = root.borrow(); let element = el .find("rootfile") .ok_or_else(|| XMLError::AttrNotFound("rootfile".into()))?; let el2 = element.borrow(); let attr = el2 .get_attr("full-path") .ok_or_else(|| XMLError::AttrNotFound("full-path".into()))?; Ok(PathBuf::from(attr)) ``` -------------------------------- ### Get EPUB Entry as String Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Retrieves the content of a specific file within the EPUB archive as a String. Returns an error if the file does not exist or cannot be decoded as UTF-8. ```rust pub fn get_entry_as_str>( &mut self, name: P, ) -> Result ``` -------------------------------- ### Get Resource by Path Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the raw content of a resource from the EPUB archive using its full path. Returns None if the path does not exist. ```APIDOC ## GET /api/epub/resource/path/{path} ### Description Retrieves the raw content of a resource specified by its full path within the EPUB archive. ### Method GET ### Endpoint /api/epub/resource/path/{path} ### Parameters #### Path Parameters - **path** (string) - Required - The full path to the resource within the EPUB archive. ### Request Example None ### Response #### Success Response (200) - **content** (bytes) - The binary content of the resource. #### Response Example { "content": "...binary resource data..." } ``` -------------------------------- ### Retrieve current chapter with URI rewriting Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Get the current chapter content with internal resource URIs updated to use the epub:// prefix for rendering. ```rust let current = doc.get_current_with_epub_uris().unwrap(); let text = String::from_utf8(current).unwrap(); assert!(text.contains("epub://OEBPS/Images/portada.png")); doc.go_next(); let current = doc.get_current_with_epub_uris().unwrap(); let text = String::from_utf8(current).unwrap(); assert!(text.contains("epub://OEBPS/Styles/stylesheet.css")); assert!(text.contains("http://creativecommons.org/licenses/by-sa/3.0/")); ``` -------------------------------- ### Get EPUB Metadata Source: https://docs.rs/epub/latest/src/epub/lib.rs.html Retrieves specific metadata from an opened EPUB document using its key. Asserts that the 'language' metadata is 'es'. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let doc = doc.unwrap(); let language = doc.mdata("language"); assert_eq!(language.unwrap().value, "es"); ``` -------------------------------- ### Get Resource as String by Path Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the content of a resource as a String, using its full path. Returns None if the path does not exist or cannot be decoded as a string. ```APIDOC ## GET /api/epub/resource/string/path/{path} ### Description Retrieves the content of a resource as a String, specified by its full path within the EPUB archive. Assumes UTF-8 encoding. ### Method GET ### Endpoint /api/epub/resource/string/path/{path} ### Parameters #### Path Parameters - **path** (string) - Required - The full path to the resource within the EPUB archive. ### Request Example None ### Response #### Success Response (200) - **content** (string) - The content of the resource as a string. #### Response Example { "content": "

Title

" } ``` -------------------------------- ### Get Current Chapter Number in EPUB Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Returns the index of the currently active chapter, starting from 0. ```rust pub fn get_current_chapter(&self) -> usize { self.current } ``` -------------------------------- ### Getting the Cover ID Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Retrieve the identifier for the document's cover image. ```rust use epub::doc::EpubDoc; let doc = EpubDoc::new("test.epub"); assert!(doc.is_ok()); let mut doc = doc.unwrap(); let cover_id = doc.get_cover_id(); ``` -------------------------------- ### Get Resource MIME Type by Path Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Searches for and returns the MIME type of a resource using its full path. Returns None if the resource is not found. ```rust pub fn get_resource_mime_by_path>(&self, path: P) -> Option { let path = path.as_ref(); self.resources.iter().find_map(|(_, r)| { if r.path == path { Some(r.mime.clone()) } else { None } }) } ``` -------------------------------- ### Get EPUB Entry as Bytes Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Retrieves the content of a specific file within the EPUB archive as a byte vector. Returns an error if the file does not exist. ```rust pub fn get_entry>( &mut self, name: P, ) -> Result, ArchiveError> ``` -------------------------------- ### Get Entry Content as String Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Retrieves the content of a specific file within the EPUB archive and attempts to decode it as a UTF-8 String. Returns an error if the file is not found or if decoding fails. ```rust /// Returns the content of the file by the `name` as `String`. /// /// # Errors /// /// Returns an error if the name doesn't exists in the zip archive. pub fn get_entry_as_str>(&mut self, name: P) -> Result { let content = self.get_entry(name)?; String::from_utf8(content).map_err(ArchiveError::from) } ``` -------------------------------- ### Get Cover Information Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the cover image data and its MIME type. It first finds the cover ID and then fetches the corresponding resource. ```APIDOC ## GET /api/epub/cover ### Description Retrieves the cover image content and its MIME type from the EPUB document. ### Method GET ### Endpoint /api/epub/cover ### Parameters None ### Request Example None ### Response #### Success Response (200) - **content** (bytes) - The binary data of the cover image. - **mime_type** (string) - The MIME type of the cover image (e.g., 'image/jpeg'). #### Response Example { "content": "...binary image data...", "mime_type": "image/png" } ``` -------------------------------- ### Chapter Navigation and Information Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Provides methods for retrieving the current chapter ID, navigating to the next or previous chapter, and getting the total number of chapters. ```APIDOC ## GET /epub/current_id ### Description Returns the ID of the current chapter. ### Method GET ### Endpoint /epub/current_id ### Response #### Success Response (200) - **id** (string) - The ID of the current chapter. Can be None if the epub is broken. #### Response Example { "id": "titlepage.xhtml" } ## POST /epub/go_next ### Description Changes the current chapter to the next one in the sequence. ### Method POST ### Endpoint /epub/go_next ### Response #### Success Response (200) - **success** (boolean) - True if navigation was successful, false if the current chapter was the last one. #### Response Example { "success": true } ## POST /epub/go_prev ### Description Changes the current chapter to the previous one in the sequence. ### Method POST ### Endpoint /epub/go_prev ### Response #### Success Response (200) - **success** (boolean) - True if navigation was successful, false if the current chapter was the first one. #### Response Example { "success": true } ## GET /epub/num_chapters ### Description Returns the total number of chapters in the EPUB document. ### Method GET ### Endpoint /epub/num_chapters ### Response #### Success Response (200) - **count** (integer) - The total number of chapters. #### Response Example { "count": 17 } ## GET /epub/current_chapter ### Description Returns the index of the current chapter, starting from 0. ### Method GET ### Endpoint /epub/current_chapter ### Response #### Success Response (200) - **index** (integer) - The index of the current chapter. #### Response Example { "index": 0 } ## PUT /epub/set_chapter ### Description Changes the current chapter to a specified chapter index. ### Method PUT ### Endpoint /epub/set_chapter ### Parameters #### Query Parameters - **n** (integer) - Required - The index of the chapter to set as current. ### Response #### Success Response (200) - **success** (boolean) - True if the chapter was set successfully, false if the index was out of bounds. #### Response Example { "success": true } ``` -------------------------------- ### Get Current Chapter with EPUB URIs Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Returns the current chapter's content with local resource URIs transformed to the 'epub://' prefix. This is useful for rendering HTML content, as it allows the engine to correctly resolve relative paths. Errors if the EPUB is broken. ```rust pub fn get_current_with_epub_uris(&mut self) -> Result, DocError> { let path = self.get_current_path().ok_or(DocError::InvalidEpub)?; let (current, _mime) = self.get_current().ok_or(DocError::InvalidEpub)?; let resp = xmlutils::replace_attrs( current.as_slice(), |element, attr, value| match (element, attr) { ("link", "href") | ("image", "href") | ("a", "href") | ("img", "src") => { build_epub_uri(&path, value) } _ => String::from(value), }, &self.extra_css, ); resp.map_err(From::from) } ``` -------------------------------- ### Get Entry Content as Bytes Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Retrieves the content of a specific file within the EPUB archive as a byte vector. It handles potential percent-encoding in file names and returns an error if the file is not found or other zip errors occur. ```rust /// Returns the content of the file by the `name` as `Vec`. /// /// # Errors /// /// Returns an error if the name doesn't exists in the zip archive. pub fn get_entry>(&mut self, name: P) -> Result, ArchiveError> { let mut entry: Vec = vec![]; let name = name.as_ref().to_str().ok_or(ArchiveError::PathUtf8)?; match self.zip.by_name(name) { Ok(mut zipfile) => { zipfile.read_to_end(&mut entry)?; return Ok(entry); } Err(zip::result::ZipError::FileNotFound) => {} // Fall through to try percent encoding Err(e) => { return Err(e.into()); } }; // try percent encoding let name = percent_encoding::percent_decode(name.as_bytes()).decode_utf8()?; let mut zipfile = self.zip.by_name(&name)?; zipfile.read_to_end(&mut entry)?; Ok(entry) } ``` -------------------------------- ### Get Resource as String by ID Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the content and MIME type of a resource as a String, identified by its ID. Returns None if the ID is not found or cannot be decoded. ```APIDOC ## GET /api/epub/resource/string/id/{id} ### Description Retrieves the content and MIME type of a resource as a String, identified by its ID. Assumes UTF-8 encoding. ### Method GET ### Endpoint /api/epub/resource/string/id/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the resource to retrieve. ### Request Example None ### Response #### Success Response (200) - **content** (string) - The content of the resource as a string. - **mime_type** (string) - The MIME type of the resource. #### Response Example { "content": "This is the content of the resource.", "mime_type": "text/plain" } ``` -------------------------------- ### Get Current Chapter Content as String Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the current chapter's content as a String and its MIME type. This is a convenience method for text-based content. Returns None if the EPUB is broken. ```rust pub fn get_current_str(&mut self) -> Option<(String, String)> { let current_id = self.get_current_id()?; self.get_resource_str(¤t_id) } ``` -------------------------------- ### Get Resource by ID Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the content and MIME type of a resource identified by its ID, typically defined in the EPUB spine. Returns None if the ID is not found. ```APIDOC ## GET /api/epub/resource/id/{id} ### Description Retrieves the content and MIME type of a resource identified by its ID. This ID is usually defined within the EPUB's spine or manifest. ### Method GET ### Endpoint /api/epub/resource/id/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the resource to retrieve. ### Request Example None ### Response #### Success Response (200) - **content** (bytes) - The binary content of the resource. - **mime_type** (string) - The MIME type of the resource. #### Response Example { "content": "...binary resource data...", "mime_type": "application/xhtml+xml" } ``` -------------------------------- ### Get Current Chapter Path Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the full file path of the current chapter within the EPUB structure. Returns None if the EPUB is broken or the current chapter cannot be determined. ```rust pub fn get_current_path(&self) -> Option { let current_id = self.get_current_id()?; ``` -------------------------------- ### Opening an EPUB file Source: https://docs.rs/epub/latest/epub Initialize an EpubDoc instance from a file path. ```rust use epub::doc::EpubDoc; let doc = EpubDoc::new("test.epub"); assert!(doc.is_ok()); let doc = doc.unwrap(); ``` -------------------------------- ### Create EpubArchive from File Path Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Constructor for EpubArchive that opens an EPUB file from a given path. Requires a file to exist and be a valid zip archive. Uses BufReader for efficient file handling. ```rust impl EpubArchive> { /// Opens the epub file in `path`. /// /// # Errors /// /// Returns an error if the zip is broken or if the file doesn't /// exists. pub fn new>(path: P) -> Result { let path = path.as_ref(); let file = File::open(path)?; let mut archive = Self::from_reader(BufReader::new(file))?; archive.path = path.to_path_buf(); Ok(archive) } } ``` -------------------------------- ### EpubDoc::new Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Constructor for EpubDoc that opens an EPUB file from a given path. ```APIDOC ## EpubDoc::new ### Description Opens the epub file in `path`. Initializes some internal variables to be able to access the epub spine definition and to navigate through the epub. ### Method `pub fn new>(path: P) -> Result` ### Endpoint N/A (This is a constructor) ### Parameters #### Path Parameters - **path** (P: AsRef) - Required - The path to the EPUB file. ### Request Body N/A ### Response #### Success Response (Result) - **Self** - An initialized `EpubDoc` instance if successful. #### Errors - **DocError** - Returned if the epub is broken or if the file doesn’t exist. ### Examples ```rust use epub::doc::EpubDoc; let doc = EpubDoc::new("test.epub"); assert!(doc.is_ok()); ``` ``` -------------------------------- ### Open EpubArchive from File Path Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Opens an EPUB file from a given path. Returns an error if the file is not found or the archive is corrupted. ```rust pub fn new>(path: P) -> Result ``` -------------------------------- ### EpubArchive::new Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Opens an EPUB file from a given path. ```APIDOC ## EpubArchive::new ### Description Opens the epub file in `path`. ### Method `pub fn new>(path: P) -> Result` ### Endpoint N/A (File System Operation) ### Parameters #### Path Parameters - **path** (P: AsRef) - Required - The path to the EPUB file. ### Request Body N/A ### Response #### Success Response (Self) - **EpubArchive>** - An instance of EpubArchive opened from the specified file. #### Errors - **ArchiveError::IO** - If there is an I/O error opening the file. - **ArchiveError::Zip** - If the zip archive is corrupted. - **ArchiveError::PathUtf8** - If the provided path is not valid UTF-8. ### Request Example ```rust let archive = EpubArchive::>::new("path/to/your/epub.epub"); ``` ### Response Example ```rust // On success: // Ok(EpubArchive { ... }) // On error: // Err(ArchiveError::IO(std::io::Error)) // Err(ArchiveError::Zip(zip::result::ZipError)) ``` ``` -------------------------------- ### Get Current Chapter ID in EPUB Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the ID of the current chapter. Returns `None` if the EPUB is malformed. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let doc = doc.unwrap(); let id = doc.get_current_id(); assert_eq!("titlepage.xhtml", id.unwrap()); ``` -------------------------------- ### Get Navigation Document ID Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the ID of the navigation document, which is specific to EPUB3. Returns None for EPUB2 documents. ```APIDOC ## GET /api/epub/nav/id ### Description Retrieves the ID of the navigation document. This is a feature specific to EPUB3. For EPUB2, this will return null. ### Method GET ### Endpoint /api/epub/nav/id ### Parameters None ### Request Example None ### Response #### Success Response (200) - **nav_id** (string) - The ID of the navigation document, if found. #### Response Example { "nav_id": "nav" } ``` -------------------------------- ### Navigate between chapters Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Move forward or backward through the EPUB spine. ```rust doc.go_next(); assert_eq!("000.xhtml", doc.get_current_id().unwrap()); let len = doc.spine.len(); for i in 1..len { doc.go_next(); } assert!(!doc.go_next()); ``` ```rust assert!(!doc.go_prev()); doc.go_next(); // 000.xhtml doc.go_next(); // 001.xhtml doc.go_next(); // 002.xhtml doc.go_prev(); // 001.xhtml assert_eq!("001.xhtml", doc.get_current_id().unwrap()); ``` -------------------------------- ### Parse EPUB Root File Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Initializes the EPUB structure by parsing the root file and populating manifest, spine, and metadata fields. ```rust fn fill_resources(&mut self) -> Result<(), DocError> { let container = self.archive.get_entry(&self.root_file)?; let root = xmlutils::XMLReader::parse(container.as_slice())?; self.version = match root.borrow().get_attr("version") { Some(v) if v == "2.0" => EpubVersion::Version2_0, Some(v) if v == "3.0" => EpubVersion::Version3_0, Some(v) => EpubVersion::Unknown(String::from(v)), _ => EpubVersion::Unknown(String::from("Unknown")), }; let unique_identifier_id = &root.borrow().get_attr("unique-identifier"); // resources from manifest // This should be run before everything else, because other functions relies on // self.resources and should be filled before calling `fill_toc` let manifest = root .borrow() .find("manifest") .ok_or(DocError::InvalidEpub)?; for r in &manifest.borrow().children { let item = r.borrow(); let _ = self.insert_resource(&item); } // items from spine let spine = root.borrow().find("spine").ok_or(DocError::InvalidEpub)?; for r in &spine.borrow().children { let item = r.borrow(); let _ = self.insert_spine(&item); } // toc.ncx if let Some(toc) = spine.borrow().get_attr("toc") { let _ = self.fill_toc(&toc); } // metadata let metadata_elem = root .borrow() .find("metadata") .ok_or(DocError::InvalidEpub)?; self.fill_metadata(&metadata_elem.borrow()); let identifier = if let Some(uid) = unique_identifier_id { // find identifier with id self.metadata .iter() .find(|d| d.property == "identifier" && d.id.as_ref().is_some_and(|id| id == uid)) } else { // fallback with the first identifier. self.metadata.iter().find(|d| d.property == "identifier") }; self.unique_identifier = identifier.map(|data| data.value.clone()); Ok(()) } ``` -------------------------------- ### Get Owned Version of EpubArchive Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Creates an owned version of the EpubArchive, typically by cloning. This is part of the `ToOwned` trait implementation. ```rust type Owned = T ``` ```rust fn to_owned(&self) -> T ``` -------------------------------- ### Manage chapter count and selection Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Retrieve the total number of chapters or jump to a specific chapter index. ```rust assert_eq!(17, doc.get_num_chapters()); ``` ```rust assert_eq!(0, doc.get_current_chapter()); doc.set_current_chapter(2); assert_eq!("001.xhtml", doc.get_current_id().unwrap()); assert_eq!(2, doc.get_current_chapter()); assert!(!doc.set_current_chapter(50)); ``` -------------------------------- ### Get Resource MIME Type by ID Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the MIME type of a resource using its ID. Returns None if the resource cannot be found. ```rust pub fn get_resource_mime(&self, id: &str) -> Option { self.resources.get(id).map(|r| r.mime.clone()) } ``` -------------------------------- ### Opening an EPUB from a Reader Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Initialize an EpubDoc instance from a type implementing Read and Seek. ```rust use epub::doc::EpubDoc; use std::fs::File; use std::io::{Cursor, Read}; let mut file = File::open("test.epub").unwrap(); let mut buffer = Vec::new(); file.read_to_end(&mut buffer).unwrap(); let cursor = Cursor::new(buffer); let doc = EpubDoc::from_reader(cursor); assert!(doc.is_ok()); ``` -------------------------------- ### Get Release Identifier Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the Release Identifier for the EPUB, formatted as 'unique_identifier@dcterms:modified'. This is based on EPUB 3.2 specifications. ```APIDOC ## GET /api/epub/release-identifier ### Description Retrieves the Release Identifier defined for the EPUB document. This identifier is constructed using the unique identifier and the dcterms:modified date. ### Method GET ### Endpoint /api/epub/release-identifier ### Parameters None ### Request Example None ### Response #### Success Response (200) - **release_identifier** (string) - The formatted release identifier (e.g., "urn:uuid:12345@2023-10-27T10:00:00Z"). #### Response Example { "release_identifier": "urn:uuid:12345@2023-10-27T10:00:00Z" } ``` -------------------------------- ### EpubArchive> Implementations Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Methods for creating an EpubArchive from a file path. ```APIDOC ## impl EpubArchive> ### `new` #### `pub fn new>(path: P) -> Result` Opens the epub file in `path`. ##### Errors Returns an error if the zip is broken or if the file doesn’t exists. ``` -------------------------------- ### EpubDoc::mock Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Creates a mock EpubDoc instance for testing purposes. It uses a minimal binary data representing an empty zip file. ```APIDOC ## GET /api/products/{id} ### Description Retrieves the details of a specific product by its ID. ### Method GET ### Endpoint /api/products/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the product to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the product. - **name** (string) - The name of the product. - **price** (number) - The price of the product. - **category** (string) - The category the product belongs to. - **description** (string) - A detailed description of the product. #### Response Example ```json { "id": "prod-001", "name": "Laptop", "price": 1200.00, "category": "Electronics", "description": "A high-performance laptop with a 15-inch display." } ``` ``` -------------------------------- ### Create EpubArchive from Reader Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Initializes an EpubArchive from any reader that implements Read and Seek. It populates the files list by iterating over the zip archive's file names. ```rust impl EpubArchive { /// Opens the epub contained in `reader`. /// /// # Errors /// /// Returns an error if the zip is broken. pub fn from_reader(reader: R) -> Result { let zip = zip::ZipArchive::new(reader)?; let files: Vec = zip.file_names().map(String::from).collect(); Ok(Self { zip, path: PathBuf::new(), files, }) } ``` -------------------------------- ### Managing internal navigation state Source: https://docs.rs/epub/latest/epub Use methods like go_next, go_prev, and set_current_chapter to traverse the document structure. ```rust use epub::doc::EpubDoc; let doc = EpubDoc::new("test.epub"); let mut doc = doc.unwrap(); assert_eq!(0, doc.get_current_chapter()); assert_eq!("application/xhtml+xml", doc.get_current_mime().unwrap()); doc.go_next(); assert_eq!("000.xhtml", doc.get_current_id().unwrap()); doc.go_next(); assert_eq!("001.xhtml", doc.get_current_id().unwrap()); doc.go_prev(); assert_eq!("000.xhtml", doc.get_current_id().unwrap()); doc.set_current_chapter(2); assert_eq!("001.xhtml", doc.get_current_id().unwrap()); assert_eq!(2, doc.get_current_chapter()); assert!(!doc.set_current_chapter(50)); ``` -------------------------------- ### Get Current Chapter MIME Type Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the MIME type of the current chapter. Returns None if the EPUB is broken or the current chapter cannot be determined. ```rust pub fn get_current_mime(&self) -> Option { let current_id = self.get_current_id()?; self.get_resource_mime(¤t_id) } ``` -------------------------------- ### EpubArchive Implementations Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html General methods for EpubArchive, applicable when reading from any compatible reader. ```APIDOC ## impl EpubArchive ### `from_reader` #### `pub fn from_reader(reader: R) -> Result` Opens the epub contained in `reader`. ##### Errors Returns an error if the zip is broken. ### `get_entry` #### `pub fn get_entry>( &mut self, name: P, ) -> Result, ArchiveError>` Returns the content of the file by the `name` as `Vec`. ##### Errors Returns an error if the name doesn’t exists in the zip archive. ### `get_entry_as_str` #### `pub fn get_entry_as_str>( &mut self, name: P, ) -> Result` Returns the content of the file by the `name` as `String`. ##### Errors Returns an error if the name doesn’t exists in the zip archive. ### `get_container_file` #### `pub fn get_container_file(&mut self) -> Result, ArchiveError>` Returns the content of container file “META-INF/container.xml”. ##### Errors Returns an error if the epub doesn’t have the container file. ``` -------------------------------- ### Build EPUB URI Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Constructs a URI string for EPUB internal resources. Handles external HTTP links directly and resolves relative paths within the EPUB structure. ```rust if append.starts_with("http") { return String::from(append); } let path = path.as_ref(); let mut cpath = path.to_path_buf(); // current file base dir cpath.pop(); for p in Path::new(append).components() { match p { Component::ParentDir => { cpath.pop(); } Component::Normal(s) => { cpath.push(s); } _ => {} // Ignore other component types like Prefix,RootDir, etc. }; } // If on Windows, replace all Windows path separators with Unix path separators let path = if cfg!(windows) { cpath.to_string_lossy().replace('\\', "/") } else { cpath.to_string_lossy().to_string() }; format!("epub://{}", path) ``` -------------------------------- ### Accessing EPUB resources Source: https://docs.rs/epub/latest/epub Query the resources HashMap to retrieve file paths and MIME types by resource ID. ```rust assert_eq!(23, doc.resources.len()); let tpage = doc.resources.get("titlepage.xhtml"); assert_eq!(tpage.unwrap().path, Path::new("OEBPS/Text/titlepage.xhtml")); assert_eq!(tpage.unwrap().mime, "application/xhtml+xml"); ``` -------------------------------- ### Implement From Trait Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataRefinement.html Allows conversion into MetadataRefinement from itself. This is a standard blanket implementation. ```rust fn from(t: T) -> T ``` -------------------------------- ### Open EpubArchive from Reader Source: https://docs.rs/epub/latest/epub/archive/struct.EpubArchive.html Opens an EPUB contained within a reader. Returns an error if the archive is corrupted. ```rust pub fn from_reader(reader: R) -> Result ``` -------------------------------- ### Accessing EPUB Metadata Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Demonstrates how to retrieve a specific metadata item, such as the document title, from the metadata collection. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let doc = doc.unwrap(); let title = doc.metadata.iter().find(|d| d.property == "title"); assert_eq!(title.unwrap().value, "Todo es mío"); ``` -------------------------------- ### Navigate EPUB Document State Source: https://docs.rs/epub/latest/epub/index.html Manages the internal state of the EPUB document, including current chapter, MIME type, and navigation using go_next, go_prev, and set_current_chapter. ```rust use epub::doc::EpubDoc; let doc = EpubDoc::new("test.epub"); let mut doc = doc.unwrap(); assert_eq!(0, doc.get_current_chapter()); assert_eq!("application/xhtml+xml", doc.get_current_mime().unwrap()); doc.go_next(); assert_eq!("000.xhtml", doc.get_current_id().unwrap()); doc.go_next(); assert_eq!("001.xhtml", doc.get_current_id().unwrap()); doc.go_prev(); assert_eq!("000.xhtml", doc.get_current_id().unwrap()); doc.set_current_chapter(2); assert_eq!("001.xhtml", doc.get_current_id().unwrap()); assert_eq!(2, doc.get_current_chapter()); assert!(!doc.set_current_chapter(50)); // doc.get_current() will return a Vec with the current chapter content // doc.get_current_str() will return a String with the current chapter content ``` -------------------------------- ### Access EPUB Resources Source: https://docs.rs/epub/latest/src/epub/lib.rs.html Shows how to access the resources within an EPUB file, which are stored in a HashMap. It checks the total number of resources and verifies the path and MIME type for a specific resource ('titlepage.xhtml'). ```rust # use epub::doc::EpubDoc; # use std::path::Path; # let doc = EpubDoc::new("test.epub"); # let doc = doc.unwrap(); assert_eq!(23, doc.resources.len()); let tpage = doc.resources.get("titlepage.xhtml"); assert_eq!(tpage.unwrap().path, Path::new("OEBPS/Text/titlepage.xhtml")); assert_eq!(tpage.unwrap().mime, "application/xhtml+xml"); ``` -------------------------------- ### Get Current Chapter Content Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Retrieves the byte content and MIME type of the current chapter. The current chapter is determined by the EPUB spine order and can be changed using navigation methods. Returns None if the EPUB is broken. ```rust pub fn get_current(&mut self) -> Option<(Vec, String)> { let current_id = self.get_current_id()?; self.get_resource(¤t_id) } ``` -------------------------------- ### Implement CloneToUninit Trait (Nightly) Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataRefinement.html Experimental nightly feature for copying MetadataRefinement to uninitialized memory. Use with caution. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Implement Any Trait Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataRefinement.html Provides runtime type information for MetadataRefinement. This is a blanket implementation for any type that is 'static and Send + Sync + Unpin. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Navigate EPUB Spine Source: https://docs.rs/epub/latest/src/epub/lib.rs.html Demonstrates accessing the spine of an EPUB document, which is a list of resource IDs representing the reading order. It asserts the total number of items in the spine and the ID of the first item. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let doc = doc.unwrap(); assert_eq!(17, doc.spine.len()); assert_eq!("titlepage.xhtml", doc.spine[0].idref); ``` -------------------------------- ### Navigate to Next Chapter in EPUB Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Advances to the next chapter in the EPUB. Returns `false` if the current chapter is the last one. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let mut doc = doc.unwrap(); doc.go_next(); assert_eq!("000.xhtml", doc.get_current_id().unwrap()); let len = doc.spine.len(); for i in 1..len { doc.go_next(); } assert!(!doc.go_next()); ``` -------------------------------- ### Navigate to Previous Chapter in EPUB Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Reverts to the previous chapter in the EPUB. Returns `false` if the current chapter is the first one. ```rust # use epub::doc::EpubDoc; # let doc = EpubDoc::new("test.epub"); # let mut doc = doc.unwrap(); assert!(!doc.go_prev()); doc.go_next(); // 000.xhtml doc.go_next(); // 001.xhtml doc.go_next(); // 002.xhtml doc.go_prev(); // 001.xhtml assert_eq!("001.xhtml", doc.get_current_id().unwrap()); ``` -------------------------------- ### Implement Into Trait Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataRefinement.html Allows conversion from MetadataRefinement to itself. This relies on the From trait implementation. ```rust fn into(self) -> U ``` -------------------------------- ### EPUB Structs Source: https://docs.rs/epub/latest/epub/all.html Lists the available structs for representing EPUB data. ```APIDOC ## EPUB Structs ### Structs - **archive::EpubArchive**: Represents an EPUB archive. - **doc::EpubDoc**: Represents an EPUB document. - **doc::MetadataItem**: Represents a metadata item within an EPUB. - **doc::MetadataRefinement**: Represents a refinement of metadata. - **doc::NavPoint**: Represents a navigation point in the EPUB. - **doc::ResourceItem**: Represents a resource item within an EPUB. - **doc::SpineItem**: Represents an item in the EPUB spine. ``` -------------------------------- ### Convert File Path Separators on Windows Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Converts Windows-style backslashes in a file path to forward slashes for compatibility with ZipArchive on Windows. ```rust let mut path = self.root_base.join(href); if cfg!(windows) { path = PathBuf::from(path.to_string_lossy().replace('\\', "/")); } ``` -------------------------------- ### Retrieve Resource Path from EPUB Source: https://docs.rs/epub/latest/src/epub/doc.rs.html Fetches the file path of a resource within the EPUB using its ID. ```rust self.resources.get(¤t_id).map(|r| r.path.clone()) ``` -------------------------------- ### EpubArchive::get_container_file Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Retrieves the content of the 'META-INF/container.xml' file. ```APIDOC ## EpubArchive::get_container_file ### Description Returns the content of container file "META-INF/container.xml". ### Method `pub fn get_container_file(&mut self) -> Result, ArchiveError>` ### Endpoint N/A (Archive Internal Operation) ### Parameters N/A ### Request Body N/A ### Response #### Success Response (Vec) - **Vec** - A vector of bytes representing the content of the container.xml file. #### Errors - **ArchiveError::Zip** - If the container.xml file is not found in the archive or if there's a zip-related error. ### Request Example ```rust let mut archive = EpubArchive::new("path/to/your/epub.epub")?; let container_content = archive.get_container_file()?; ``` ### Response Example ```rust // On success: // Ok(vec![... bytes of container.xml ...]) // On error: // Err(ArchiveError::Zip(zip::result::ZipError::FileNotFound)) ``` ``` -------------------------------- ### Implement Clone for MetadataRefinement Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataRefinement.html Provides functionality to duplicate MetadataRefinement values. This allows creating a copy of an existing metadata refinement. ```rust fn clone(&self) -> MetadataRefinement ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Chapter Navigation API Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Methods for retrieving current chapter information and navigating through the EPUB spine. ```APIDOC ## GET /current ### Description Returns the current chapter content and mime-type based on the epub spine order. ### Response #### Success Response (200) - **content** (Vec) - The chapter content. - **mime-type** (String) - The chapter mime-type. --- ## POST /navigation/next ### Description Changes the current chapter to the next one in the spine. ### Response #### Success Response (200) - **result** (bool) - Returns true if successful, false if the current chapter is the last one. --- ## POST /navigation/chapter/{n} ### Description Sets the current chapter by index. ### Parameters #### Path Parameters - **n** (usize) - Required - The chapter index starting from 0. ### Response #### Success Response (200) - **result** (bool) - Returns true if successful, false if the index is out of bounds. ``` -------------------------------- ### Implement Debug for MetadataRefinement Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataRefinement.html Enables debugging output for MetadataRefinement. This allows the struct to be formatted for debugging purposes. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Define EpubVersion Enum Source: https://docs.rs/epub/latest/epub/doc/enum.EpubVersion.html Represents the supported EPUB versions within the epub crate. ```rust pub enum EpubVersion { Version2_0, Version3_0, Unknown(String), } ``` -------------------------------- ### EpubArchive::from_reader Source: https://docs.rs/epub/latest/src/epub/archive.rs.html Opens an EPUB from a reader. ```APIDOC ## EpubArchive::from_reader ### Description Opens the epub contained in `reader`. ### Method `pub fn from_reader(reader: R) -> Result` where R: Read + Seek ### Endpoint N/A (Reader Operation) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```rust use std::fs::File; use std::io::BufReader; let file = File::open("path/to/your/epub.epub")?; let reader = BufReader::new(file); let archive = EpubArchive::from_reader(reader); ``` ### Response #### Success Response (Self) - **EpubArchive** - An instance of EpubArchive created from the provided reader. #### Errors - **ArchiveError::Zip** - If the zip archive is broken. ### Response Example ```rust // On success: // Ok(EpubArchive { ... }) // On error: // Err(ArchiveError::Zip(zip::result::ZipError)) ``` ``` -------------------------------- ### Navigating via spine Source: https://docs.rs/epub/latest/epub Access the spine vector to retrieve resource IDs in reading order. ```rust assert_eq!(17, doc.spine.len()); assert_eq!("titlepage.xhtml", doc.spine[0].idref); ``` -------------------------------- ### MetadataItem Implementations Source: https://docs.rs/epub/latest/epub/doc/struct.MetadataItem.html Available implementations and methods for the MetadataItem struct. ```APIDOC ## impl MetadataItem ### `refinement(&self, property: &str) -> Option<&MetadataRefinement>` Returns a reference to a `MetadataRefinement` if it matches the given property, otherwise returns `None`. ``` -------------------------------- ### Extracting the cover image Source: https://docs.rs/epub/latest/epub Retrieve the cover data as a byte vector and write it to a file. ```rust use std::fs; use std::io::Write; use epub::doc::EpubDoc; let doc = EpubDoc::new("test.epub"); assert!(doc.is_ok()); let mut doc = doc.unwrap(); let cover_data = doc.get_cover().unwrap(); let f = fs::File::create("/tmp/cover.png"); assert!(f.is_ok()); let mut f = f.unwrap(); let resp = f.write_all(&cover_data); ``` -------------------------------- ### NavPoint Trait Implementations Source: https://docs.rs/epub/latest/epub/doc/struct.NavPoint.html Details the various trait implementations for the NavPoint struct, such as Clone, Debug, Ord, PartialEq, and PartialOrd. ```APIDOC ### Trait Implementations for NavPoint #### Clone - `clone(&self) -> NavPoint`: Returns a duplicate of the value. - `clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. #### Debug - `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. #### Ord - `cmp(&self, other: &Self) -> Ordering`: Compares `self` and `other` and returns an `Ordering`. - `max(self, other: Self) -> Self`: Compares and returns the maximum of two values. - `min(self, other: Self) -> Self`: Compares and returns the minimum of two values. - `clamp(self, min: Self, max: Self) -> Self`: Restricts a value to a certain interval. #### PartialEq - `eq(&self, other: &Self) -> bool`: Tests if `self` and `other` values are equal. - `ne(&self, other: &Rhs) -> bool`: Tests for inequality (`!=`). #### PartialOrd - `partial_cmp(&self, other: &Self) -> Option`: Returns an ordering between `self` and `other` if one exists. - `lt(&self, other: &Rhs) -> bool`: Tests less than (`<`). - `le(&self, other: &Rhs) -> bool`: Tests less than or equal to (`<=`). - `gt(&self, other: &Rhs) -> bool`: Tests greater than (`>`). - `ge(&self, other: &Rhs) -> bool`: Tests greater than or equal to (`>=`). #### Eq - Implemented for NavPoint. ``` -------------------------------- ### EPUB Enums Source: https://docs.rs/epub/latest/epub/doc/index.html This section describes the enumerations used within the epub crate. ```APIDOC ## Enums ### DocError ### EpubVersion ``` -------------------------------- ### Resource Access Methods Source: https://docs.rs/epub/latest/epub/doc/struct.EpubDoc.html Methods for retrieving content and metadata for specific resources within the EPUB archive. ```APIDOC ## GET /resource/{id} ### Description Returns the resource content and mime-type by the id defined in the spine. ### Parameters #### Path Parameters - **id** (str) - Required - The resource identifier defined in the spine. ### Response #### Success Response (200) - **content** (Vec) - The resource content. - **mime-type** (String) - The resource mime-type. --- ## GET /resource/path/{path} ### Description Returns the resource content by full path in the epub archive. ### Parameters #### Path Parameters - **path** (Path) - Required - The full path of the resource in the epub archive. ### Response #### Success Response (200) - **content** (String) - The resource content as a string. ```