changxi 0.3.0

TUI EPUB Reader
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
use crate::core::models::{ContentElement, StyledText, TextStyle};
use crate::core::parser::{ChapterInfo, Parser};
use crate::error::EpubError;
use quick_xml::XmlVersion;
use quick_xml::events::Event;
use quick_xml::reader::Reader;
use std::collections::HashMap;
use std::io::{Read, Seek};
use std::path::Path;
use zip::ZipArchive;

pub struct EpubParser;

impl EpubParser {
    pub fn normalize_path(path: &str) -> String {
        let mut components = Vec::new();
        for component in path.split('/') {
            match component {
                "." | "" => {}
                ".." => {
                    components.pop();
                }
                _ => components.push(component),
            }
        }
        components.join("/")
    }

    fn parse_ncx(&self, content: &str, ncx_path: &str) -> Vec<ChapterInfo> {
        let mut reader = Reader::from_str(content);
        let mut chapters = Vec::new();
        let mut buf = Vec::new();
        let mut level = 0;
        let mut tag_stack = Vec::new();
        let mut titles: HashMap<String, String> = HashMap::new();

        let base_path = Path::new(ncx_path).parent().unwrap_or(Path::new(""));

        loop {
            if let Ok(event) = reader.read_event_into(&mut buf) {
                match event {
                    Event::Start(ref e) | Event::Empty(ref e) => {
                        let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
                        let is_empty = matches!(event, Event::Empty(_));
                        match name.as_str() {
                            "navPoint" => {
                                let mut id = String::new();
                                for attr in e.attributes().flatten() {
                                    if attr.key.local_name().as_ref() == b"id" {
                                        id = attr
                                            .normalized_value(XmlVersion::Implicit1_0)
                                            .unwrap_or_default()
                                            .into_owned();
                                    }
                                }
                                if !is_empty {
                                    tag_stack.push(("navPoint".to_string(), id));
                                    level += 1;
                                }
                            }
                            "navLabel" => {
                                if !is_empty {
                                    tag_stack.push(("navLabel".to_string(), String::new()));
                                }
                            }
                            "text" => {
                                if !is_empty {
                                    tag_stack.push(("text".to_string(), String::new()));
                                }
                            }
                            "content" => {
                                let mut src = String::new();
                                for attr in e.attributes().flatten() {
                                    if attr.key.local_name().as_ref() == b"src" {
                                        src = attr
                                            .normalized_value(XmlVersion::Implicit1_0)
                                            .unwrap_or_default()
                                            .into_owned();
                                    }
                                }
                                if let Some((_tag, id)) =
                                    tag_stack.iter().rev().find(|(t, _)| t == "navPoint")
                                {
                                    let full_href = if base_path.as_os_str().is_empty() {
                                        src
                                    } else {
                                        base_path.join(src).to_string_lossy().into_owned()
                                    };
                                    let title = titles.get(id).cloned().unwrap_or_default();
                                    chapters.push(ChapterInfo {
                                        href: full_href,
                                        id: id.clone(),
                                        title,
                                        level: level - 1,
                                    });
                                }
                                if !is_empty {
                                    tag_stack.push(("content".to_string(), String::new()));
                                }
                            }
                            _ => {
                                if !is_empty {
                                    tag_stack.push((name, String::new()));
                                }
                            }
                        }
                    }
                    Event::Text(ref e) => {
                        if let Some(("text", _)) = tag_stack.last().map(|(t, i)| (t.as_str(), i)) {
                            let text = reader.decoder().decode(e).unwrap_or_default().into_owned();
                            if let Some((_tag, id)) =
                                tag_stack.iter().rev().find(|(t, _)| t == "navPoint")
                            {
                                titles.entry(id.clone()).or_default().push_str(&text);

                                // Update title for chapters already pushed with this ID
                                for chapter in chapters.iter_mut().rev() {
                                    if &chapter.id == id {
                                        chapter.title.push_str(&text);
                                    }
                                }
                            }
                        }
                    }
                    event => match event {
                        Event::End(ref e) => {
                            let name =
                                String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
                            if name == "text"
                                && let Some((_tag, id)) =
                                    tag_stack.iter().rev().find(|(t, _)| t == "navPoint")
                                    && let Some(title) = titles.get_mut(id) {
                                        let trimmed = title.trim().to_owned();
                                        *title = trimmed.clone();
                                        for chapter in chapters.iter_mut().rev() {
                                            if &chapter.id == id {
                                                chapter.title = trimmed.clone();
                                            }
                                        }
                                    }
                            tag_stack.pop();
                            if name == "navPoint" {
                                level -= 1;
                            }
                        }
                        Event::Eof => break,
                        _ => (),
                    },
                }
            } else {
                break;
            }
            buf.clear();
        }
        chapters
    }

    fn parse_nav(&self, content: &str, nav_path: &str) -> Vec<ChapterInfo> {
        let mut reader = Reader::from_str(content);
        reader.config_mut().trim_text(true);
        let mut chapters = Vec::new();
        let mut buf = Vec::new();
        let mut level = 0;
        let mut tag_stack = Vec::new();
        let mut in_nav_toc = false;

        let base_path = Path::new(nav_path).parent().unwrap_or(Path::new(""));

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(event) => match event {
                    Event::Start(ref e) | Event::Empty(ref e) => {
                        let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
                        let is_empty = matches!(event, Event::Empty(_));
                        match name.as_str() {
                            "nav" => {
                                for attr in e.attributes().flatten() {
                                    let attr_name = String::from_utf8_lossy(attr.key.as_ref());
                                    if (attr_name == "epub:type" || attr_name == "type")
                                        && attr
                                            .normalized_value(XmlVersion::Implicit1_0)
                                            .unwrap_or_default()
                                            == "toc"
                                    {
                                        in_nav_toc = true;
                                    }
                                }
                            }
                            "ol" if in_nav_toc => level += 1,
                            "a" if in_nav_toc => {
                                let mut href = String::new();
                                for attr in e.attributes().flatten() {
                                    if attr.key.local_name().as_ref() == b"href" {
                                        href = attr
                                            .normalized_value(XmlVersion::Implicit1_0)
                                            .unwrap_or_default()
                                            .into_owned();
                                    }
                                }
                                let full_href = if base_path.as_os_str().is_empty() {
                                    href
                                } else {
                                    base_path.join(href).to_string_lossy().into_owned()
                                };
                                chapters.push(ChapterInfo {
                                    href: full_href,
                                    id: format!("nav-{}", chapters.len()),
                                    title: String::new(),
                                    level: level - 1,
                                });
                            }
                            _ => (),
                        }
                        if !is_empty {
                            tag_stack.push(name);
                        } else if name == "nav" {
                            in_nav_toc = false;
                        } else if name == "ol" && in_nav_toc {
                            level -= 1;
                        }
                    }
                    Event::Text(ref e)
                        if in_nav_toc && tag_stack.last().map(|s| s.as_str()) == Some("a") =>
                    {
                        let text = reader.decoder().decode(e).unwrap_or_default().into_owned();
                        if let Some(last_chapter) = chapters.last_mut() {
                            last_chapter.title.push_str(&text);
                        }
                    }
                    Event::End(ref e) => {
                        let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
                        tag_stack.pop();
                        match name.as_str() {
                            "nav" => in_nav_toc = false,
                            "ol" if in_nav_toc => level -= 1,
                            _ => (),
                        }
                    }
                    Event::Eof => break,
                    _ => (),
                },
                Err(_) => break,
            }
            buf.clear();
        }
        chapters
    }
}

impl Parser for EpubParser {
    fn find_opf_path<R: Read + Seek>(
        &self,
        archive: &mut ZipArchive<R>,
    ) -> 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
                                .normalized_value(XmlVersion::Implicit1_0)?
                                .into_owned());
                        }
                    }
                }
                Event::Eof => break,
                _ => (),
            }
            buf.clear();
        }

        Err(EpubError::OpfNotFound)
    }

    fn parse_opf<R: Read + Seek>(
        &self,
        archive: &mut ZipArchive<R>,
        opf_path: &str,
    ) -> Result<
        (
            String,
            String,
            Vec<ChapterInfo>,
            HashMap<String, String>,
            Option<String>,
        ),
        EpubError,
    > {
        let content = {
            let mut opf_file = archive.by_name(opf_path)?;
            let mut content = String::new();
            opf_file.read_to_string(&mut content)?;
            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 ncx_id = None;
        let mut nav_path = 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
                                            .normalized_value(XmlVersion::Implicit1_0)?
                                            .into_owned()
                                    }
                                    b"content" => {
                                        content_attr = attr
                                            .normalized_value(XmlVersion::Implicit1_0)?
                                            .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();
                            let mut properties = String::new();
                            for attr in e.attributes() {
                                let attr = attr?;
                                match attr.key.local_name().as_ref() {
                                    b"id" => {
                                        id = attr
                                            .normalized_value(XmlVersion::Implicit1_0)?
                                            .into_owned()
                                    }
                                    b"href" => {
                                        href = attr
                                            .normalized_value(XmlVersion::Implicit1_0)?
                                            .into_owned()
                                    }
                                    b"media-type" => {
                                        media_type = attr
                                            .normalized_value(XmlVersion::Implicit1_0)?
                                            .into_owned()
                                    }
                                    b"properties" => {
                                        properties = attr
                                            .normalized_value(XmlVersion::Implicit1_0)?
                                            .into_owned()
                                    }
                                    _ => (),
                                }
                            }
                            if !id.is_empty() && !href.is_empty() {
                                if media_type.starts_with("image/") {
                                    images.insert(id.clone(), href.clone());
                                }
                                if properties.contains("nav") {
                                    nav_path = Some(href.clone());
                                }
                                manifest.insert(id, href);
                            }
                        }
                        "spine" => {
                            for attr in e.attributes() {
                                let attr = attr?;
                                if attr.key.local_name().as_ref() == b"toc" {
                                    ncx_id = Some(
                                        attr.normalized_value(XmlVersion::Implicit1_0)?
                                            .into_owned(),
                                    );
                                }
                            }
                        }
                        "itemref" => {
                            for attr in e.attributes() {
                                let attr = attr?;
                                if attr.key.local_name().as_ref() == b"idref" {
                                    spine.push(
                                        attr.normalized_value(XmlVersion::Implicit1_0)?
                                            .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 mut chapter_info = Vec::new();

        if let Some(nav_href) = nav_path {
            let full_nav_path = if base_path.as_os_str().is_empty() {
                nav_href
            } else {
                base_path.join(nav_href).to_string_lossy().into_owned()
            };

            if let Ok(mut nav_file) = archive.by_name(&full_nav_path) {
                let mut nav_content = String::new();
                if nav_file.read_to_string(&mut nav_content).is_ok() {
                    chapter_info = self.parse_nav(&nav_content, &full_nav_path);
                }
            }
        }

        if chapter_info.is_empty()
            && let Some(id) = ncx_id
            && let Some(href) = manifest.get(&id)
        {
            let full_ncx_path = if base_path.as_os_str().is_empty() {
                href.clone()
            } else {
                base_path.join(href).to_string_lossy().into_owned()
            };

            if let Ok(mut ncx_file) = archive.by_name(&full_ncx_path) {
                let mut ncx_content = String::new();
                if ncx_file.read_to_string(&mut ncx_content).is_ok() {
                    chapter_info = self.parse_ncx(&ncx_content, &full_ncx_path);
                }
            }
        }

        // Fallback to spine if TOC is missing or empty
        if chapter_info.is_empty() {
            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(),
                            level: 0,
                        }
                    })
                })
                .collect();
        }

        Ok((title, author, chapter_info, images, cover_id))
    }

    fn parse_chapter_content(
        &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) => match event {
                    Event::Start(ref e) | Event::Empty(ref e) => {
                        let name = String::from_utf8_lossy(e.local_name().as_ref()).to_lowercase();
                        let is_empty = matches!(event, Event::Empty(_));

                        match name.as_str() {
                            "title" | "h1" | "style" | "script" => {
                                if !is_empty {
                                    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));
                                    }
                                });
                                if !is_empty {
                                    tag_stack.push(name);
                                }
                            }
                            "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();
                                }
                                if !is_empty {
                                    tag_stack.push(name);
                                }
                            }
                            "br" => {
                                if !current_text_spans.is_empty() {
                                    elements.push(ContentElement::Text(current_text_spans.clone()));
                                    current_text_spans.clear();
                                }
                                if !is_empty {
                                    tag_stack.push(name);
                                }
                            }
                            "b" | "strong" => {
                                if !is_empty {
                                    style_stack.push(current_style.clone());
                                    current_style.bold = true;
                                    tag_stack.push(name);
                                }
                            }
                            "i" | "em" => {
                                if !is_empty {
                                    style_stack.push(current_style.clone());
                                    current_style.italic = true;
                                    tag_stack.push(name);
                                }
                            }
                            "u" | "ins" => {
                                if !is_empty {
                                    style_stack.push(current_style.clone());
                                    current_style.underline = true;
                                    tag_stack.push(name);
                                }
                            }
                            "s" | "strike" | "del" => {
                                if !is_empty {
                                    style_stack.push(current_style.clone());
                                    current_style.strikethrough = true;
                                    tag_stack.push(name);
                                }
                            }
                            _ => {
                                if !is_empty {
                                    tag_stack.push(name);
                                }
                            }
                        }
                    }
                    Event::Text(ref 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(),
                                    });
                                }
                            }
                        }
                    }
                    Event::End(ref 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();
                                }

                                // Add a blank line (whitespace) after paragraph elements
                                if name.as_str() == "p" && !elements.is_empty() {
                                    elements.push(ContentElement::BlankLine);
                                }
                            }
                            _ => {}
                        }
                    }
                    Event::Eof => break,
                    _ => (),
                },
                Err(_) => 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()
                && 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)
    }
}