1use crate::types::{Image, Metadata, Page, TocEntry};
2use crate::utils::ZipHandler;
3use ordered_hash_map::OrderedHashMap;
4use quick_xml::events::Event;
5use std::io::Cursor;
6use std::path::{Path, PathBuf};
7
8#[derive(Debug)]
40pub struct Epub {
41 pub metadata: Metadata,
43 pub toc: Vec<TocEntry>,
45 pub pages: Vec<Page>,
47 pub images: Vec<Image>,
49}
50
51#[derive(Debug)]
53pub enum Error {
54 InvalidEpub(String),
56 IoError(std::io::Error),
58 ZipError(zip::result::ZipError),
60 XmlError(String),
62 MissingContainer,
64 MissingOpf,
66 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 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 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 mut reader = quick_xml::Reader::from_str(content);
250 let mut metadata = Metadata::new();
251 let mut manifest: OrderedHashMap<String, ManifestItem> = OrderedHashMap::new();
252 let mut spine: Vec<String> = Vec::new();
253 let mut ncx_path: Option<String> = None;
254
255 let mut current_text_tag: Option<String> = None;
256
257 let mut buf = Vec::new();
258
259 loop {
260 match reader.read_event_into(&mut buf) {
261 Ok(Event::Start(ref e)) => {
262 let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
263 if name.contains("title") {
264 current_text_tag = Some("title".to_string());
265 } else if name.contains("creator") {
266 current_text_tag = Some("author".to_string());
267 } else if name.contains("publisher") {
268 current_text_tag = Some("publisher".to_string());
269 } else if name.contains("language") {
270 current_text_tag = Some("language".to_string());
271 } else if name.contains("identifier") {
272 current_text_tag = Some("identifier".to_string());
273 } else if name.contains("date") {
274 current_text_tag = Some("date".to_string());
275 } else if name.contains("rights") {
276 current_text_tag = Some("rights".to_string());
277 }
278 }
279 Ok(Event::Empty(ref e)) => {
280 let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
281 if name.contains("item") && !name.contains("itemref") {
282 let mut id = String::new();
283 let mut href = String::new();
284 let mut media_type = String::new();
285
286 for attr_result in e.attributes() {
287 if let Ok(attr) = attr_result {
288 let attr_name =
289 String::from_utf8_lossy(attr.key.as_ref()).to_string();
290 if attr_name == "id" || attr_name.ends_with(":id") {
291 if let Some(val) =
292 attr.decode_and_unescape_value(reader.decoder()).ok()
293 {
294 id = val.to_string();
295 }
296 } else if attr_name == "href" || attr_name.ends_with(":href") {
297 href = attr
298 .decode_and_unescape_value(reader.decoder())?
299 .to_string();
300 } else if attr_name == "media-type"
301 || attr_name.ends_with(":media-type")
302 {
303 media_type = attr
304 .decode_and_unescape_value(reader.decoder())?
305 .to_string();
306 }
307 }
308 }
309
310 if !id.is_empty() && !href.is_empty() {
311 if media_type == "application/x-dtbncx+xml" {
312 ncx_path = Some(href.clone());
313 }
314 manifest.insert(
315 id.clone(),
316 ManifestItem {
317 _id: id.clone(),
318 href,
319 _media_type: media_type,
320 },
321 );
322 }
323 } else if name.contains("itemref") {
324 let mut idref = String::new();
325
326 for attr_result in e.attributes() {
327 if let Ok(attr) = attr_result {
328 let attr_name =
329 String::from_utf8_lossy(attr.key.as_ref()).to_string();
330 if attr_name == "idref" || attr_name.ends_with(":idref") {
331 if let Some(val) =
332 attr.decode_and_unescape_value(reader.decoder()).ok()
333 {
334 idref = val.to_string();
335 }
336 break;
337 }
338 }
339 }
340
341 if !idref.is_empty() {
342 spine.push(idref);
343 }
344 }
345 }
346 Ok(Event::Text(e)) => {
347 if let Some(tag) = ¤t_text_tag {
348 let text = e.unescape()?.into_owned().trim().to_string();
349 if !text.is_empty() {
350 match tag.as_str() {
351 "title" => metadata.title = Some(text),
352 "author" => metadata.author = Some(text),
353 "publisher" => metadata.publisher = Some(text),
354 "language" => metadata.language = Some(text),
355 "identifier" => metadata.identifier = Some(text),
356 "date" => metadata.date = Some(text),
357 "rights" => metadata.rights = Some(text),
358 _ => {}
359 }
360 }
361 current_text_tag = None;
362 }
363 }
364 Ok(Event::End(_)) => {
365 current_text_tag = None;
366 }
367 Ok(Event::Eof) => break,
368 Err(e) => return Err(Error::XmlError(e.to_string())),
369 _ => {}
370 }
371 buf.clear();
372 }
373
374 Ok((metadata, manifest, spine, ncx_path))
375 }
376
377 fn parse_ncx(content: &str) -> Result<Vec<TocEntry>, Error> {
378 let mut reader = quick_xml::Reader::from_str(content);
379 let mut toc = Vec::new();
380 let mut stack: Vec<TocEntry> = Vec::new();
381
382 let mut buf = Vec::new();
383 let mut in_nav_label = false;
384 let mut in_text = false;
385
386 loop {
387 match reader.read_event_into(&mut buf) {
388 Ok(Event::Start(ref e)) => {
389 let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
390 if name == "navPoint" {
391 let entry = TocEntry {
392 label: String::new(),
393 href: String::new(),
394 children: Vec::new(),
395 };
396 stack.push(entry);
397 } else if name == "navLabel" {
398 in_nav_label = true;
399 } else if name == "text" && in_nav_label {
400 in_text = true;
401 }
402 }
403 Ok(Event::End(ref e)) => {
404 let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
405 if name == "navPoint" {
406 if let Some(entry) = stack.pop() {
407 if let Some(parent) = stack.last_mut() {
408 parent.children.push(entry);
409 } else {
410 toc.push(entry);
411 }
412 }
413 } else if name == "navLabel" {
414 in_nav_label = false;
415 } else if name == "text" && in_nav_label {
416 in_text = false;
417 }
418 }
419 Ok(Event::Text(e)) => {
420 if in_text {
421 if let Some(entry) = stack.last_mut() {
422 entry.label = e.unescape()?.into_owned();
423 }
424 }
425 }
426 Ok(Event::Empty(ref e)) => {
427 let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
428 if name == "content" {
429 if let Some(src) = e.try_get_attribute("src")? {
430 if let Some(entry) = stack.last_mut() {
431 entry.href =
432 src.decode_and_unescape_value(reader.decoder())?.to_string();
433 }
434 }
435 }
436 }
437 Ok(Event::Eof) => break,
438 Err(e) => return Err(Error::XmlError(e.to_string())),
439 _ => {}
440 }
441 buf.clear();
442 }
443
444 Ok(toc)
445 }
446
447 fn extract_text_from_html(content: &str) -> Result<String, Error> {
448 let mut reader = quick_xml::Reader::from_str(content);
449 let mut text = String::new();
450 let skip_tags: Vec<Vec<u8>> = vec![b"script".to_vec(), b"style".to_vec(), b"head".to_vec()];
451 let mut in_skip_tag = false;
452
453 let mut buf = Vec::new();
454
455 loop {
456 match reader.read_event_into(&mut buf) {
457 Ok(Event::Start(ref e)) => {
458 let tag = e.name().as_ref().to_vec();
459 if skip_tags.contains(&tag) {
460 in_skip_tag = true;
461 } else if tag.as_slice() == b"p"
462 || tag.as_slice() == b"div"
463 || tag.as_slice() == b"br"
464 || tag.as_slice() == b"li"
465 {
466 text.push('\n');
467 }
468 }
469 Ok(Event::End(ref e)) => {
470 let tag = e.name().as_ref().to_vec();
471 if skip_tags.contains(&tag) {
472 in_skip_tag = false;
473 }
474 }
475 Ok(Event::Text(e)) => {
476 if !in_skip_tag {
477 let t = e.unescape()?.into_owned();
478 let trimmed: String = t.chars().filter(|c| !c.is_control()).collect();
479 text.push_str(&trimmed);
480 text.push(' ');
481 }
482 }
483 Ok(Event::Eof) => break,
484 Err(e) => return Err(Error::XmlError(e.to_string())),
485 _ => {}
486 }
487 buf.clear();
488 }
489
490 Ok(text
491 .lines()
492 .map(|l| l.trim())
493 .filter(|l| !l.is_empty())
494 .collect::<Vec<_>>()
495 .join("\n"))
496 }
497
498 fn resolve_path(base_path: &str, href: &str) -> String {
499 let base = PathBuf::from(base_path);
500 let parent = base.parent().unwrap_or(base.as_path());
501 let resolved = parent.join(href);
502 resolved.to_string_lossy().to_string().replace('\\', "/")
503 }
504}
505
506#[derive(Debug, Clone)]
507struct ManifestItem {
508 _id: String,
509 href: String,
510 _media_type: String,
511}