1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
use crate::error::EpubError;
use quick_xml::events::Event;
use quick_xml::reader::Reader;
use std::collections::HashMap;
use std::io::Read;
use std::{
fs::File,
path::Path,
sync::{Arc, Mutex},
};
use zip::ZipArchive;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextStyle {
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strikethrough: bool,
}
#[derive(Clone, Debug)]
pub struct StyledText {
pub text: String,
pub style: TextStyle,
}
#[derive(Clone, Debug)]
pub enum ContentElement {
Text(Vec<StyledText>),
Image(String),
}
#[derive(Clone, Debug)]
pub struct Chapter {
pub id: String,
pub title: String,
pub elements: Vec<ContentElement>,
}
impl Chapter {
pub fn new(id: String, title: String, elements: Vec<ContentElement>) -> Self {
Chapter {
id,
title,
elements,
}
}
pub fn content_as_text(&self) -> String {
self.elements
.iter()
.map(|e| match e {
ContentElement::Text(spans) => {
spans.iter().map(|s| s.text.as_str()).collect::<String>()
}
ContentElement::Image(_) => String::new(),
})
.collect::<Vec<_>>()
.join("\n\n")
}
}
pub struct SearchResult {
pub chapter_id: String,
pub chapter_title: String,
pub context_before: String,
pub match_text: String,
pub context_after: String,
pub position: usize,
}
impl SearchResult {
pub fn new(
chapter_id: String,
chapter_title: String,
context_before: String,
match_text: String,
context_after: String,
position: usize,
) -> Self {
SearchResult {
chapter_id,
chapter_title,
context_before,
match_text,
context_after,
position,
}
}
}
#[derive(Clone)]
struct ChapterInfo {
href: String,
id: String,
title: String,
}
pub struct EpubReader {
archive: Arc<Mutex<ZipArchive<File>>>,
chapter_info: Vec<ChapterInfo>,
images: HashMap<String, String>,
opf_path: String,
title: String,
author: String,
cover_id: Option<String>,
}
impl EpubReader {
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, EpubError> {
let file = File::open(path)?;
let mut archive = ZipArchive::new(file)?;
let opf_path = Self::find_opf_path(&mut archive)?;
let (title, author, chapter_info, images, cover_id) =
Self::parse_opf(&mut archive, &opf_path)?;
Ok(EpubReader {
archive: Arc::new(Mutex::new(archive)),
chapter_info,
images,
opf_path,
title,
author,
cover_id,
})
}
fn find_opf_path(archive: &mut ZipArchive<File>) -> Result<String, EpubError> {
let mut container_file = archive.by_name("META-INF/container.xml")?;
let mut content = String::new();
container_file.read_to_string(&mut content)?;
let mut reader = Reader::from_str(&content);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
loop {
match reader.read_event_into(&mut buf)? {
Event::Start(ref e) | Event::Empty(ref e)
if e.local_name().as_ref() == b"rootfile" =>
{
for attr in e.attributes() {
let attr = attr?;
if attr.key.local_name().as_ref() == b"full-path" {
return Ok(attr.unescape_value()?.into_owned());
}
}
}
Event::Eof => break,
_ => (),
}
buf.clear();
}
Err(EpubError::OpfNotFound)
}
fn parse_opf(
archive: &mut ZipArchive<File>,
opf_path: &str,
) -> Result<
(
String,
String,
Vec<ChapterInfo>,
HashMap<String, String>,
Option<String>,
),
EpubError,
> {
let mut opf_file = archive.by_name(opf_path)?;
let mut content = String::new();
opf_file.read_to_string(&mut content)?;
let mut reader = Reader::from_str(&content);
reader.config_mut().trim_text(true);
let mut title = String::from("Unknown Title");
let mut author = String::from("Unknown Author");
let mut manifest = std::collections::HashMap::new();
let mut images = std::collections::HashMap::new();
let mut spine = Vec::new();
let mut cover_id = None;
let mut buf = Vec::new();
let mut in_metadata = false;
let mut current_tag = String::new();
loop {
match reader.read_event_into(&mut buf)? {
Event::Start(ref e) | Event::Empty(ref e) => {
let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
match name.as_str() {
"metadata" => in_metadata = true,
"title" if in_metadata => current_tag = "title".to_string(),
"creator" if in_metadata => current_tag = "creator".to_string(),
"meta" if in_metadata => {
let mut name_attr = String::new();
let mut content_attr = String::new();
for attr in e.attributes() {
let attr = attr?;
match attr.key.local_name().as_ref() {
b"name" => name_attr = attr.unescape_value()?.into_owned(),
b"content" => {
content_attr = attr.unescape_value()?.into_owned()
}
_ => (),
}
}
if name_attr == "cover" {
cover_id = Some(content_attr);
}
}
"item" => {
let mut id = String::new();
let mut href = String::new();
let mut media_type = String::new();
for attr in e.attributes() {
let attr = attr?;
match attr.key.local_name().as_ref() {
b"id" => id = attr.unescape_value()?.into_owned(),
b"href" => href = attr.unescape_value()?.into_owned(),
b"media-type" => {
media_type = attr.unescape_value()?.into_owned()
}
_ => (),
}
}
if !id.is_empty() && !href.is_empty() {
if media_type.starts_with("image/") {
images.insert(id.clone(), href.clone());
}
manifest.insert(id, href);
}
}
"itemref" => {
for attr in e.attributes() {
let attr = attr?;
if attr.key.local_name().as_ref() == b"idref" {
spine.push(attr.unescape_value()?.into_owned());
}
}
}
_ => (),
}
}
Event::End(ref e) => {
let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
if name == "metadata" {
in_metadata = false;
}
current_tag.clear();
}
Event::Text(ref e) if in_metadata => match current_tag.as_str() {
"title" => title = reader.decoder().decode(e)?.into_owned(),
"creator" => author = reader.decoder().decode(e)?.into_owned(),
_ => (),
},
Event::Text(_) => {}
Event::Eof => break,
_ => (),
}
buf.clear();
}
let base_path = Path::new(opf_path).parent().unwrap_or(Path::new(""));
// Resolve image paths
let images = images
.into_iter()
.map(|(id, href)| {
let full_href = if base_path.as_os_str().is_empty() {
href
} else {
base_path.join(href).to_string_lossy().into_owned()
};
(id, full_href)
})
.collect();
let chapter_info = spine
.into_iter()
.filter_map(|id| {
manifest.get(&id).map(|href| {
let full_href = if base_path.as_os_str().is_empty() {
href.clone()
} else {
base_path.join(href).to_string_lossy().into_owned()
};
ChapterInfo {
href: full_href,
id,
title: String::new(),
}
})
})
.collect();
Ok((title, author, chapter_info, images, cover_id))
}
pub fn title(&self) -> &str {
&self.title
}
pub fn author(&self) -> &str {
&self.author
}
pub fn chapter_count(&self) -> usize {
self.chapter_info.len()
}
pub fn get_image_by_path(&self, path: &str) -> Result<Vec<u8>, EpubError> {
let mut archive = self.archive.lock().map_err(|_| EpubError::CacheLockError)?;
let mut file = archive.by_name(path)?;
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(data)
}
pub fn get_image(&self, id: &str) -> Result<Vec<u8>, EpubError> {
let href = self
.images
.get(id)
.ok_or_else(|| EpubError::ChapterNotFound(format!("Image not found: {}", id)))?;
let mut archive = self.archive.lock().map_err(|_| EpubError::CacheLockError)?;
let mut file = archive.by_name(href)?;
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(data)
}
pub fn cover_image(&self) -> Result<Option<Vec<u8>>, EpubError> {
if let Some(ref id) = self.cover_id {
Ok(Some(self.get_image(id)?))
} else {
Ok(None)
}
}
pub fn get_chapter(&self, index: usize) -> Result<Chapter, EpubError> {
if index >= self.chapter_info.len() {
return Err(EpubError::InvalidChapterIndex(index));
}
let info = &self.chapter_info[index];
let mut archive = self.archive.lock().map_err(|_| EpubError::CacheLockError)?;
let mut file = archive.by_name(&info.href)?;
let mut html = String::new();
file.read_to_string(&mut html)?;
let (title, elements) = self.parse_chapter_html(&html, index, &info.href);
Ok(Chapter::new(info.id.clone(), title, elements))
}
fn parse_chapter_html(
&self,
html: &str,
index: usize,
chapter_href: &str,
) -> (String, Vec<ContentElement>) {
let mut reader = Reader::from_str(html);
let mut elements = Vec::new();
let mut buf = Vec::new();
let mut html_title = String::new();
let mut first_h1 = String::new();
let mut style_stack: Vec<TextStyle> = Vec::new();
let mut current_style = TextStyle::default();
let mut current_text_spans: Vec<StyledText> = Vec::new();
let mut tag_stack: Vec<String> = Vec::new();
let base_path = Path::new(chapter_href).parent().unwrap_or(Path::new(""));
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
let name = String::from_utf8_lossy(e.local_name().as_ref()).to_lowercase();
match name.as_str() {
"title" | "h1" | "style" | "script" => {
tag_stack.push(name.clone());
}
"img" => {
if !current_text_spans.is_empty() {
elements.push(ContentElement::Text(current_text_spans.clone()));
current_text_spans.clear();
}
e.attributes().for_each(|attr| {
if let Ok(attr) = attr
&& attr.key.local_name().as_ref() == b"src"
&& let Ok(src) = reader.decoder().decode(attr.value.as_ref())
{
let full_path = if base_path.as_os_str().is_empty() {
src.into_owned()
} else {
base_path.join(src.as_ref()).to_string_lossy().into_owned()
};
let clean_path = self.normalize_path(&full_path);
elements.push(ContentElement::Image(clean_path));
}
});
}
"p" | "div" | "blockquote" | "li" | "h2" | "h3" | "h4" | "h5" | "h6" => {
if !current_text_spans.is_empty() {
elements.push(ContentElement::Text(current_text_spans.clone()));
current_text_spans.clear();
}
tag_stack.push(name);
}
"br" => {
if !current_text_spans.is_empty() {
elements.push(ContentElement::Text(current_text_spans.clone()));
current_text_spans.clear();
}
}
"b" | "strong" => {
style_stack.push(current_style.clone());
current_style.bold = true;
tag_stack.push(name);
}
"i" | "em" => {
style_stack.push(current_style.clone());
current_style.italic = true;
tag_stack.push(name);
}
"u" | "ins" => {
style_stack.push(current_style.clone());
current_style.underline = true;
tag_stack.push(name);
}
"s" | "strike" | "del" => {
style_stack.push(current_style.clone());
current_style.strikethrough = true;
tag_stack.push(name);
}
_ => {
tag_stack.push(name);
}
}
}
Ok(Event::Text(e)) => {
let decoded = reader.decoder().decode(&e).unwrap_or_default();
let current_tag = tag_stack.last().map(|s| s.as_str()).unwrap_or("");
match current_tag {
"title" => html_title = decoded.trim().to_owned(),
"h1" if first_h1.is_empty() => first_h1 = decoded.trim().to_owned(),
"style" | "script" => {}
_ => {
let text = decoded;
if !text.trim().is_empty()
|| (!text.is_empty() && !current_text_spans.is_empty())
{
current_text_spans.push(StyledText {
text: text.into_owned(),
style: current_style.clone(),
});
}
}
}
}
Ok(Event::End(e)) => {
let name = String::from_utf8_lossy(e.local_name().as_ref()).to_lowercase();
tag_stack.pop();
match name.as_str() {
"b" | "strong" | "i" | "em" | "u" | "ins" | "s" | "strike" | "del" => {
if let Some(s) = style_stack.pop() {
current_style = s;
}
}
"p" | "div" | "blockquote" | "li" | "h1" | "h2" | "h3" | "h4" | "h5"
| "h6" => {
if !current_text_spans.is_empty() {
elements.push(ContentElement::Text(current_text_spans.clone()));
current_text_spans.clear();
}
}
_ => {}
}
}
Ok(Event::Eof) => break,
_ => (),
}
buf.clear();
}
if !current_text_spans.is_empty() {
elements.push(ContentElement::Text(current_text_spans));
}
let title = if !first_h1.is_empty() {
first_h1
} else if !html_title.is_empty() {
html_title
} else {
format!("Chapter {}", index + 1)
};
if let Some(ContentElement::Text(spans)) = elements.first_mut() {
if let Some(first_span) = spans.first_mut() {
if first_span.text.trim_start().starts_with(&title) {
let trimmed = first_span.text.trim_start();
first_span.text = trimmed[title.len()..].trim_start().to_string();
}
}
spans.retain(|s| !s.text.is_empty());
}
// Remove empty text elements
elements.retain(|e| {
if let ContentElement::Text(spans) = e {
!spans.is_empty()
} else {
true
}
});
(title, elements)
}
fn normalize_path(&self, path: &str) -> String {
let mut components = Vec::new();
for component in path.split('/') {
match component {
"." | "" => {}
".." => {
components.pop();
}
_ => components.push(component),
}
}
components.join("/")
}
// fn strip_html(&self, html: &str) -> String {
// let (_, elements) = self.parse_chapter_html(html, 0, "");
// elements
// .iter()
// .filter_map(|e| {
// if let ContentElement::Text(t) = e {
// Some(t.as_str())
// } else {
// None
// }
// })
// .collect::<Vec<_>>()
// .join("\n\n")
// }
// pub fn get_chapter_by_id(&self, id: &str) -> Result<Chapter, EpubError> {
// let index = self
// .chapter_info
// .iter()
// .position(|info| info.id == id)
// .ok_or_else(|| EpubError::ChapterNotFound(id.to_string()))?;
// self.get_chapter(index)
// }
// pub fn search(&self, query: &str) -> Result<Vec<SearchResult>, EpubError> {
// self.search_case_sensitive(query, false)
// }
// pub fn search_case_sensitive(
// &self,
// query: &str,
// case_sensitive: bool,
// ) -> Result<Vec<SearchResult>, EpubError> {
// let mut results = Vec::new();
// let query = if case_sensitive {
// query.to_string()
// } else {
// query.to_lowercase()
// };
// for (i, _info) in self.chapter_info.iter().enumerate() {
// let chapter = self.get_chapter(i)?;
// let full_content = chapter.content_as_text();
// let content = if case_sensitive {
// full_content.clone()
// } else {
// full_content.to_lowercase()
// };
// let mut start = 0;
// while let Some(pos) = content[start..].find(&query) {
// let actual_pos = start + pos;
// let before_start = actual_pos.saturating_sub(30);
// let after_end = (actual_pos + query.len() + 30).min(content.len());
// results.push(SearchResult::new(
// chapter.id.clone(),
// chapter.title.clone(),
// full_content[before_start..actual_pos].to_string(),
// full_content[actual_pos..actual_pos + query.len()].to_string(),
// full_content[actual_pos + query.len()..after_end].to_string(),
// actual_pos,
// ));
// start = actual_pos + query.len();
// }
// }
// Ok(results)
// }
}