docparser-epub 0.1.0

docparser EPUB 后端:container/OPF/spine 结构解析,每章复用 HTML 块解析(标题/段落/列表/表格)
Documentation
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! `docparser-epub`:EPUB2/EPUB3 后端。
//!
//! 结构(对齐 Python `book.read_epub`):
//! `META-INF/container.xml` → rootfile(OPF 路径)→ `metadata` / `manifest` / `spine`,
//! 章节标题优先取 EPUB3 `nav`,其次 EPUB2 `toc.ncx`,取不到回落到文档内首个标题;
//! 封面取 `properties="cover-image"`,其次 `<meta name="cover">`。
//!
//! 正文:每个 spine 文档用 `docparser_core::plugins::html` 解析成**结构化块**
//! (标题/段落/列表/引用/代码/表格),再按文档内标题切节(层级自适应 h2→h3→h4,
//! 单节超过 [`BIG_SECTION_CHARS`] 才往深一层切)——与 Python 的分章口径一致,
//! 区别是这里保留块结构而不是压平成一段文本。
//!
//! 不做的事:DRM(`META-INF/encryption.xml`)不解密,加密书会在读取正文时报 `corrupt`;
//! 图片/字体等资源不解包(只记录封面路径)。

use std::collections::BTreeMap;
use std::io::Read;
use std::sync::Arc;

use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::Reader;

use docparser_core::error::{DocError, Result};
use docparser_core::model::{Block, BlockKind, Document, Page};
use docparser_core::plugin::{FormatPlugin, ParseCapability, RawDoc, RawPage, RawTextItem};
use docparser_core::plugins::html::parse_blocks;
use docparser_core::registry::Registry;

/// 单节超过该字符数就尝试按更深层标题再切(与 Python `BIG_SECTION_CHARS` 一致)。
pub const BIG_SECTION_CHARS: usize = 8000;
const SECTION_LEVELS: [u8; 3] = [2, 3, 4];

/// 书籍元数据(取不到的字段为空串 / None)。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EpubMeta {
    pub title: String,
    pub authors: Vec<String>,
    pub language: String,
    pub publisher: String,
    /// 从 `dc:date` 里取的四位年份。
    pub year: String,
    /// 封面在包内的路径(POSIX,相对包根)。
    pub cover_href: Option<String>,
}

/// 一章(= 一个 spine 文档,或文档内按标题切出的一节)。
#[derive(Debug, Clone, Default, PartialEq)]
pub struct EpubChapter {
    pub title: String,
    pub blocks: Vec<Block>,
    /// `blocks` 的非空 content 以空行连接(与 Python 章文本口径一致)。
    pub text: String,
}

/// 整本书的解析结果。
#[derive(Debug, Clone, Default)]
pub struct EpubBook {
    pub meta: EpubMeta,
    pub chapters: Vec<EpubChapter>,
}

// ── XML 小工具 ───────────────────────────────────────────────────────

fn local_name(e: &BytesStart<'_>) -> String {
    e.local_name().as_ref().to_string()
}

fn end_name(e: &BytesEnd<'_>) -> String {
    e.local_name().as_ref().to_string()
}

fn attrs(e: &BytesStart<'_>) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    for a in e.attributes().flatten() {
        let key = a.key.local_name().as_ref().to_string();
        let val = quick_xml::escape::unescape(&a.value)
            .map(|v| v.into_owned())
            .unwrap_or_else(|_| a.value.to_string());
        out.insert(key, val);
    }
    out
}

/// quick-xml 0.42:`&amp;` / `&#65;` 是独立的 `Event::GeneralRef`,按 0.37 语义就地解码。
fn push_ref(buf: &mut String, e: &quick_xml::events::BytesRef<'_>) {
    match e.resolve_char_ref() {
        Ok(Some(ch)) => buf.push(ch),
        _ => {
            let entity = format!("&{};", e.xml10_content());
            if let Ok(t) = quick_xml::escape::unescape(&entity) {
                buf.push_str(&t);
            }
        }
    }
}

/// Text 事件取内容并解实体(0.38+ 不再自动 unescape)。
fn text_of(e: &quick_xml::events::BytesText<'_>) -> Option<String> {
    let raw = e.xml10_content();
    quick_xml::escape::unescape(&raw)
        .ok()
        .map(|v| v.into_owned())
}

fn xml_err(what: &str, e: impl std::fmt::Display) -> DocError {
    DocError::corrupt(format!("{what} 解析失败: {e}"))
}

// ── 容器 / OPF ──────────────────────────────────────────────────────

#[derive(Debug, Clone, Default)]
struct Item {
    id: String,
    href: String,
    props: String,
}

#[derive(Debug, Clone, Default)]
struct Opf {
    title: String,
    authors: Vec<String>,
    language: String,
    publisher: String,
    date: String,
    items: Vec<Item>,
    spine: Vec<String>,
    toc: Option<String>,
    cover_id: Option<String>,
}

/// `container.xml` → OPF 包内路径。
fn find_rootfile(xml: &str) -> Result<Option<String>> {
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                if local_name(&e) == "rootfile" {
                    if let Some(p) = attrs(&e).get("full-path") {
                        return Ok(Some(p.clone()));
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(xml_err("container.xml", e)),
            _ => {}
        }
        buf.clear();
    }
    Ok(None)
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Field {
    Title,
    Creator,
    Language,
    Publisher,
    Date,
}

/// OPF 单元素处理:元数据字段登记 + `manifest` / `spine` / 封面收集。
///
/// `is_empty`(自闭合元素)不登记文本字段——没有正文可收。
fn on_opf_element(
    opf: &mut Opf,
    e: &BytesStart<'_>,
    stack: &[String],
    field: &mut Option<Field>,
    acc: &mut String,
    is_empty: bool,
) {
    let name = local_name(e);
    let a = attrs(e);
    let in_metadata = stack.iter().any(|s| s == "metadata");
    if in_metadata && field.is_none() && !is_empty {
        let f = match name.as_str() {
            "title" => Some(Field::Title),
            "creator" => Some(Field::Creator),
            "language" => Some(Field::Language),
            "publisher" => Some(Field::Publisher),
            "date" => Some(Field::Date),
            _ => None,
        };
        if f.is_some() {
            *field = f;
            acc.clear();
        }
    }
    match name.as_str() {
        "item" => opf.items.push(Item {
            id: a.get("id").cloned().unwrap_or_default(),
            href: a.get("href").cloned().unwrap_or_default(),
            props: a.get("properties").cloned().unwrap_or_default(),
        }),
        "itemref" => {
            if let Some(id) = a.get("idref") {
                opf.spine.push(id.clone());
            }
        }
        "spine" => {
            if let Some(t) = a.get("toc") {
                opf.toc = Some(t.clone());
            }
        }
        "meta" if a.get("name").map(|n| n == "cover").unwrap_or(false) => {
            opf.cover_id = a.get("content").cloned();
        }
        _ => {}
    }
}

fn parse_opf(xml: &str) -> Result<Opf> {
    let mut opf = Opf::default();
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();
    let mut stack: Vec<String> = Vec::new();
    let mut field: Option<Field> = None;
    let mut acc = String::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                on_opf_element(&mut opf, &e, &stack, &mut field, &mut acc, false);
                stack.push(local_name(&e));
            }
            Ok(Event::Empty(e)) => {
                on_opf_element(&mut opf, &e, &stack, &mut field, &mut acc, true);
            }
            Ok(Event::Text(t)) => {
                if field.is_some() {
                    if let Some(v) = text_of(&t) {
                        acc.push_str(&v);
                    }
                }
            }
            Ok(Event::GeneralRef(ref e)) => {
                if field.is_some() {
                    push_ref(&mut acc, e);
                }
            }
            Ok(Event::End(e)) => {
                let name = end_name(&e);
                if let Some(f) = field {
                    let matched = matches!(
                        (f, name.as_str()),
                        (Field::Title, "title")
                            | (Field::Creator, "creator")
                            | (Field::Language, "language")
                            | (Field::Publisher, "publisher")
                            | (Field::Date, "date")
                    );
                    if matched {
                        let v = acc.trim().to_string();
                        match f {
                            Field::Title => {
                                if opf.title.is_empty() {
                                    opf.title = v;
                                }
                            }
                            Field::Creator => {
                                if !v.is_empty() {
                                    opf.authors.push(v);
                                }
                            }
                            Field::Language => {
                                if opf.language.is_empty() {
                                    opf.language = v;
                                }
                            }
                            Field::Publisher => {
                                if opf.publisher.is_empty() {
                                    opf.publisher = v;
                                }
                            }
                            Field::Date => {
                                if opf.date.is_empty() {
                                    opf.date = v;
                                }
                            }
                        }
                        field = None;
                        acc.clear();
                    }
                }
                if stack.last().map(|s| s == &name).unwrap_or(false) {
                    stack.pop();
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(xml_err("OPF", e)),
            _ => {}
        }
        buf.clear();
    }
    Ok(opf)
}

/// EPUB3 nav.xhtml → {href(去 fragment): 标题}。
fn nav_titles(xml: &str) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();
    let mut href: Option<String> = None;
    let mut acc = String::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                if local_name(&e) == "a" {
                    href = attrs(&e).get("href").cloned();
                    acc.clear();
                }
            }
            Ok(Event::Text(t)) => {
                if href.is_some() {
                    if let Some(v) = text_of(&t) {
                        acc.push_str(&v);
                    }
                }
            }
            Ok(Event::GeneralRef(ref e)) => {
                if href.is_some() {
                    push_ref(&mut acc, e);
                }
            }
            Ok(Event::End(e)) => {
                if end_name(&e) == "a" {
                    if let Some(h) = href.take() {
                        let h = h.split('#').next().unwrap_or("").to_string();
                        let title = acc.trim().to_string();
                        if !h.is_empty() && !title.is_empty() {
                            out.entry(h).or_insert(title);
                        }
                    }
                    acc.clear();
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buf.clear();
    }
    out
}

/// EPUB2 toc.ncx → {href(去 fragment): 标题}(`navLabel/text` + `content@src` 配对)。
fn ncx_titles(xml: &str) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();
    let mut last_label = String::new();
    let mut in_text = false;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                let name = local_name(&e);
                match name.as_str() {
                    "text" => {
                        in_text = true;
                        last_label.clear();
                    }
                    "content" => {
                        if let Some(src) = attrs(&e).get("src") {
                            let h = src.split('#').next().unwrap_or("").to_string();
                            if !h.is_empty() && !last_label.is_empty() {
                                out.entry(h).or_insert_with(|| last_label.clone());
                            }
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Text(t)) => {
                if in_text {
                    if let Some(v) = text_of(&t) {
                        last_label.push_str(&v);
                    }
                }
            }
            Ok(Event::GeneralRef(ref e)) => {
                if in_text {
                    push_ref(&mut last_label, e);
                }
            }
            Ok(Event::End(e)) => {
                if end_name(&e) == "text" {
                    last_label = last_label.trim().to_string();
                    in_text = false;
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buf.clear();
    }
    out
}

// ── 路径 / ZIP ──────────────────────────────────────────────────────

/// manifest href(可含 `./` `../`)→ 包内 POSIX 路径。
fn resolve(base: &str, href: &str) -> String {
    let href = href.split('#').next().unwrap_or("");
    let joined = if base.is_empty() {
        href.to_string()
    } else {
        format!("{base}/{href}")
    };
    let mut parts: Vec<&str> = Vec::new();
    for seg in joined.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            s => parts.push(s),
        }
    }
    parts.join("/")
}

fn open_zip(path: &str) -> Result<zip::ZipArchive<std::fs::File>> {
    let f =
        std::fs::File::open(path).map_err(|e| DocError::corrupt(format!("EPUB 打不开: {e}")))?;
    zip::ZipArchive::new(f).map_err(|e| DocError::corrupt(format!("EPUB 打不开: {e}")))
}

fn read_entry(zip: &mut zip::ZipArchive<std::fs::File>, name: &str) -> Result<Option<String>> {
    match zip.by_name(name) {
        Ok(mut f) => {
            let mut buf = Vec::new();
            f.read_to_end(&mut buf)
                .map_err(|e| DocError::corrupt(format!("读取 {name} 失败: {e}")))?;
            // EPUB 正文常含非法字节:解码失败按替换字符处理,不整体失败
            Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
        }
        Err(zip::result::ZipError::FileNotFound) => Ok(None),
        Err(e) => Err(DocError::corrupt(format!("ZIP 读取 {name} 失败: {e}"))),
    }
}

fn year_of(date: &str) -> String {
    let bytes: Vec<char> = date.chars().collect();
    for w in bytes.windows(4) {
        if w.iter().all(|c| c.is_ascii_digit()) {
            return w.iter().collect();
        }
    }
    String::new()
}

// ── 分章 ────────────────────────────────────────────────────────────

/// 按标题切节:返回 (标题, 该节块下标)。
fn cut_indices(blocks: &[Block], max_level: u8) -> Vec<(String, Vec<usize>)> {
    let mut out: Vec<(String, Vec<usize>)> = Vec::new();
    let mut title = String::new();
    let mut cur: Vec<usize> = Vec::new();
    for (i, b) in blocks.iter().enumerate() {
        if b.kind == BlockKind::Heading && b.level.unwrap_or(1) <= max_level {
            if !cur.is_empty() {
                out.push((std::mem::take(&mut title), std::mem::take(&mut cur)));
            }
            title = b.content.trim().to_string();
            continue;
        }
        if !b.content.is_empty() {
            cur.push(i);
        }
    }
    if !cur.is_empty() {
        out.push((title, cur));
    }
    out.retain(|(_, idx)| !idx.is_empty());
    out
}

/// 层级自适应切节:单节仍过大就试更深一层(h2 → h3 → h4)。
fn sections(blocks: &[Block]) -> Vec<(String, Vec<usize>)> {
    let mut best = Vec::new();
    for max_level in SECTION_LEVELS {
        best = cut_indices(blocks, max_level);
        let max_chars = best
            .iter()
            .map(|(_, idx)| {
                idx.iter()
                    .map(|&i| blocks[i].content.chars().count())
                    .sum::<usize>()
            })
            .max()
            .unwrap_or(0);
        if best.is_empty() || max_chars <= BIG_SECTION_CHARS {
            break;
        }
    }
    best
}

fn page_text(blocks: &[Block]) -> String {
    blocks
        .iter()
        .filter(|b| !b.content.is_empty())
        .map(|b| b.content.as_str())
        .collect::<Vec<_>>()
        .join("\n\n")
}

fn build_page(title: &str, blocks: Vec<Block>) -> Page {
    let text = page_text(&blocks);
    Page {
        name: if title.trim().is_empty() {
            None
        } else {
            Some(title.trim().to_string())
        },
        blocks,
        text,
        ..Default::default()
    }
}

// ── 能力 / 插件 ─────────────────────────────────────────────────────

/// 原始读取:把 spine 顺序的 XHTML 原文放进 `RawPage.items[0]`,书籍元数据进 `RawDoc.meta`。
pub struct EpubRawBackend;

impl ParseCapability for EpubRawBackend {
    fn id(&self) -> &str {
        "epub.read"
    }
    fn formats(&self) -> &[&str] {
        &["epub"]
    }
    fn parse(&self, path: &str) -> Result<RawDoc> {
        let mut zip = open_zip(path)?;

        let container = read_entry(&mut zip, "META-INF/container.xml")?
            .ok_or_else(|| DocError::corrupt("EPUB 缺 META-INF/container.xml"))?;
        let opf_path = find_rootfile(&container)?
            .ok_or_else(|| DocError::corrupt("container.xml 缺 rootfile"))?;
        let opf_xml = read_entry(&mut zip, &opf_path)?
            .ok_or_else(|| DocError::corrupt(format!("EPUB 缺 OPF: {opf_path}")))?;
        let opf = parse_opf(&opf_xml)?;
        let opf_dir = opf_path
            .rsplit_once('/')
            .map(|(d, _)| d.to_string())
            .unwrap_or_default();

        // 章节标题:EPUB3 nav 优先,其次 NCX
        let mut titles = BTreeMap::new();
        if let Some(nav) = opf
            .items
            .iter()
            .find(|it| it.props.split_whitespace().any(|p| p == "nav"))
            .map(|it| resolve(&opf_dir, &it.href))
        {
            if let Some(xml) = read_entry(&mut zip, &nav)? {
                titles = nav_titles(&xml);
            }
        }
        if titles.is_empty() {
            let ncx_path = opf
                .toc
                .as_ref()
                .and_then(|id| {
                    opf.items
                        .iter()
                        .find(|it| &it.id == id)
                        .map(|it| resolve(&opf_dir, &it.href))
                })
                .or_else(|| {
                    opf.items
                        .iter()
                        .find(|it| it.href.ends_with(".ncx"))
                        .map(|it| resolve(&opf_dir, &it.href))
                });
            if let Some(p) = ncx_path {
                if let Some(xml) = read_entry(&mut zip, &p)? {
                    titles = ncx_titles(&xml);
                }
            }
        }

        // 封面:properties="cover-image" 优先,其次 <meta name="cover">
        let cover = opf
            .items
            .iter()
            .find(|it| it.props.split_whitespace().any(|p| p == "cover-image"))
            .map(|it| resolve(&opf_dir, &it.href))
            .or_else(|| {
                opf.cover_id.as_ref().and_then(|id| {
                    opf.items
                        .iter()
                        .find(|it| &it.id == id)
                        .map(|it| resolve(&opf_dir, &it.href))
                })
            });

        let mut pages = Vec::new();
        for idref in &opf.spine {
            let Some(item) = opf.items.iter().find(|it| &it.id == idref) else {
                continue;
            };
            let full = resolve(&opf_dir, &item.href);
            if full.ends_with(".ncx") {
                continue;
            }
            let Some(xhtml) = read_entry(&mut zip, &full)? else {
                continue;
            };
            let title = titles
                .get(&item.href)
                .or_else(|| titles.get(&full))
                .cloned()
                .unwrap_or_default();
            pages.push(RawPage {
                name: if title.is_empty() { None } else { Some(title) },
                items: vec![RawTextItem {
                    text: xhtml,
                    bbox: None,
                }],
                ..Default::default()
            });
        }

        let mut meta: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        if !opf.title.is_empty() {
            meta.insert("epub.title".to_string(), opf.title.clone());
        }
        if !opf.authors.is_empty() {
            meta.insert("epub.authors".to_string(), opf.authors.join("; "));
        }
        if !opf.language.is_empty() {
            meta.insert("epub.language".to_string(), opf.language.clone());
        }
        if !opf.publisher.is_empty() {
            meta.insert("epub.publisher".to_string(), opf.publisher.clone());
        }
        let year = year_of(&opf.date);
        if !year.is_empty() {
            meta.insert("epub.year".to_string(), year);
        }
        if let Some(c) = &cover {
            meta.insert("epub.cover_href".to_string(), c.clone());
        }

        Ok(RawDoc {
            pages,
            meta,
            needs_ocr: false,
        })
    }
}

/// EPUB 插件:XHTML → 结构化块 → 按标题分章。
pub struct EpubPlugin;

impl FormatPlugin for EpubPlugin {
    fn id(&self) -> &str {
        "epub"
    }
    fn formats(&self) -> &[&str] {
        &["epub"]
    }
    fn default_parse_chain(&self) -> Vec<&'static str> {
        vec!["epub.read"]
    }
    fn default_process_chain(&self) -> Vec<&'static str> {
        vec![]
    }
    fn assemble(&self, raw: &RawDoc) -> Document {
        let mut pages: Vec<Page> = Vec::new();

        for (idx, rp) in raw.pages.iter().enumerate() {
            let Some(xhtml) = rp.items.first().map(|i| i.text.as_str()) else {
                continue;
            };
            let blocks = parse_blocks(xhtml);
            if blocks.iter().all(|b| b.content.is_empty()) {
                continue; // 纯图/空白页(封面页等)不成为章
            }

            let secs = sections(&blocks);
            if secs.len() > 1 {
                for (title, idxs) in secs {
                    let sec_blocks: Vec<Block> = idxs.iter().map(|&i| blocks[i].clone()).collect();
                    pages.push(build_page(&title, sec_blocks));
                }
                continue;
            }

            // 单节:保留完整块(含首个标题),标题回落到 toc → 文档内首个标题 → 第 N 章
            let first_heading = blocks
                .iter()
                .find(|b| b.kind == BlockKind::Heading && !b.content.trim().is_empty())
                .map(|b| b.content.trim().to_string());
            let title = rp
                .name
                .clone()
                .filter(|s| !s.trim().is_empty())
                .or(first_heading)
                .unwrap_or_else(|| format!("第{}章", idx + 1));
            pages.push(build_page(&title, blocks));
        }

        let mut doc = Document {
            pages,
            ..Default::default()
        };
        for key in [
            "epub.title",
            "epub.authors",
            "epub.language",
            "epub.publisher",
            "epub.year",
            "epub.cover_href",
        ] {
            if let Some(v) = raw.meta.get(key) {
                doc.meta.extra.insert(key.to_string(), v.clone());
            }
        }
        doc
    }
}

/// 注册 EPUB 后端与插件。
pub fn register_defaults(reg: &mut Registry) {
    let _ = reg.register_parse(Arc::new(EpubRawBackend), None);
    reg.register_plugin(Arc::new(EpubPlugin));
}

// ── 便捷 API ────────────────────────────────────────────────────────

/// 一次读完:元数据 + 分章(含结构化块)。
pub fn read_epub(path: &str) -> Result<EpubBook> {
    let raw = EpubRawBackend.parse(path)?;
    let doc = EpubPlugin.assemble(&raw);
    let get = |k: &str| raw.meta.get(k).cloned().unwrap_or_default();
    let meta = EpubMeta {
        title: get("epub.title"),
        authors: raw
            .meta
            .get("epub.authors")
            .map(|a| a.split("; ").map(|s| s.to_string()).collect())
            .unwrap_or_default(),
        language: get("epub.language"),
        publisher: get("epub.publisher"),
        year: get("epub.year"),
        cover_href: raw.meta.get("epub.cover_href").cloned(),
    };
    let chapters = doc
        .pages
        .iter()
        .map(|p| EpubChapter {
            title: p.name.clone().unwrap_or_default(),
            blocks: p.blocks.clone(),
            text: p.text.clone(),
        })
        .collect();
    Ok(EpubBook { meta, chapters })
}

/// 只取封面路径与书名(不解析正文),供书库/缩略图场景使用。
pub fn epub_cover_href(path: &str) -> (Option<String>, String) {
    match EpubRawBackend.parse(path) {
        Ok(raw) => (
            raw.meta.get("epub.cover_href").cloned(),
            raw.meta.get("epub.title").cloned().unwrap_or_default(),
        ),
        Err(_) => (None, String::new()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    const CONTAINER: &str = r#"<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
  <rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>
</container>"#;

    const OPF: &str = r#"<?xml version="1.0"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:title>测试书</dc:title>
    <dc:creator>作者甲</dc:creator>
    <dc:creator>作者乙</dc:creator>
    <dc:language>zh</dc:language>
    <dc:publisher>某社</dc:publisher>
    <dc:date>2021-05-01</dc:date>
  </metadata>
  <manifest>
    <item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
    <item id="ch1" href="text/ch1.xhtml" media-type="application/xhtml+xml"/>
    <item id="ch2" href="text/ch2.xhtml" media-type="application/xhtml+xml"/>
    <item id="cover" href="img/cover.jpg" media-type="image/jpeg" properties="cover-image"/>
  </manifest>
  <spine>
    <itemref idref="ch1"/>
    <itemref idref="ch2"/>
  </spine>
</package>"#;

    const NAV: &str = r#"<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml"><body>
<nav epub:type="toc" xmlns:epub="http://www.idpf.org/2007/ops">
  <ol>
    <li><a href="text/ch1.xhtml">第一章</a></li>
    <li><a href="text/ch2.xhtml#sec1">第二章</a></li>
  </ol>
</nav></body></html>"#;

    const CH1: &str = r#"<html><body><h1>第一章</h1><p>正文一</p></body></html>"#;
    /// 单文档内两个 h2:应切成两章。
    const CH2: &str = r#"<html><body><h2>甲节</h2><p>甲正文</p><h2>乙节</h2><ul><li>要点</li></ul></body></html>"#;

    fn write_epub(dir_name: &str, title_opts: Option<&str>) -> std::path::PathBuf {
        let dir = std::env::temp_dir()
            .join("docparser_epub_test")
            .join(dir_name);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("book.epub");
        let f = std::fs::File::create(&path).unwrap();
        let mut zw = zip::ZipWriter::new(f);
        let opts = zip::write::SimpleFileOptions::default();
        let mut put = |name: &str, body: &str| {
            zw.start_file(name, opts).unwrap();
            zw.write_all(body.as_bytes()).unwrap();
        };
        put("mimetype", "application/epub+zip");
        put("META-INF/container.xml", CONTAINER);
        put("OEBPS/content.opf", title_opts.unwrap_or(OPF));
        put("OEBPS/nav.xhtml", NAV);
        put("OEBPS/text/ch1.xhtml", CH1);
        put("OEBPS/text/ch2.xhtml", CH2);
        zw.finish().unwrap();
        path
    }

    #[test]
    fn reads_metadata_and_split_chapters() {
        let p = write_epub("ok", None);
        let book = read_epub(p.to_str().unwrap()).unwrap();
        std::fs::remove_file(&p).ok();

        assert_eq!(book.meta.title, "测试书");
        assert_eq!(book.meta.authors, vec!["作者甲", "作者乙"]);
        assert_eq!(book.meta.language, "zh");
        assert_eq!(book.meta.publisher, "某社");
        assert_eq!(book.meta.year, "2021");
        assert_eq!(book.meta.cover_href.as_deref(), Some("OEBPS/img/cover.jpg"));

        // ch1 单节(保留 h1 块),ch2 按 h2 切成两节
        let titles: Vec<&str> = book.chapters.iter().map(|c| c.title.as_str()).collect();
        assert_eq!(titles, vec!["第一章", "甲节", "乙节"]);
        assert_eq!(book.chapters[0].blocks[0].kind, BlockKind::Heading);
        assert_eq!(book.chapters[1].text, "甲正文");
        assert_eq!(book.chapters[2].blocks[0].kind, BlockKind::List);
    }

    #[test]
    fn engine_route_and_meta_extra() {
        let p = write_epub("engine", None);
        let mut reg = Registry::new();
        docparser_core::plugins::text::register_defaults(&mut reg);
        register_defaults(&mut reg);
        let doc = docparser_core::DocumentEngine::new(reg)
            .parse(p.to_str().unwrap())
            .unwrap();
        std::fs::remove_file(&p).ok();

        assert_eq!(doc.meta.file_type, "epub");
        assert_eq!(doc.meta.page_count, 3);
        assert_eq!(
            doc.meta.extra.get("epub.title").map(|s| s.as_str()),
            Some("测试书")
        );
        assert!(doc.pages.iter().all(|p| p.name.is_some()));
    }

    #[test]
    fn broken_container_is_corrupt() {
        let dir = std::env::temp_dir()
            .join("docparser_epub_test")
            .join("broken");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("bad.epub");
        let f = std::fs::File::create(&path).unwrap();
        let mut zw = zip::ZipWriter::new(f);
        let opts = zip::write::SimpleFileOptions::default();
        zw.start_file("mimetype", opts).unwrap();
        zw.write_all(b"application/epub+zip").unwrap();
        zw.finish().unwrap();

        let err = read_epub(path.to_str().unwrap()).unwrap_err();
        std::fs::remove_file(&path).ok();
        assert_eq!(err.code.as_str(), "corrupt");
        assert!(err.message.contains("container.xml"));
    }

    #[test]
    fn non_zip_is_corrupt() {
        let dir = std::env::temp_dir()
            .join("docparser_epub_test")
            .join("notzip");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("x.epub");
        std::fs::write(&path, b"not a zip").unwrap();
        let err = read_epub(path.to_str().unwrap()).unwrap_err();
        std::fs::remove_file(&path).ok();
        assert_eq!(err.code.as_str(), "corrupt");
    }

    #[test]
    fn resolve_normalizes_dot_segments() {
        assert_eq!(resolve("OEBPS", "text/ch1.xhtml"), "OEBPS/text/ch1.xhtml");
        assert_eq!(resolve("OEBPS/text", "../img/a.png"), "OEBPS/img/a.png");
        assert_eq!(resolve("", "ch1.xhtml#frag"), "ch1.xhtml");
    }

    #[test]
    fn ncx_titles_pair_label_and_src() {
        let ncx = r#"<ncx><navMap>
            <navPoint id="n1"><navLabel><text>卷首</text></navLabel><content src="ch1.xhtml#top"/></navPoint>
            <navPoint id="n2"><navLabel><text>卷尾</text></navLabel><content src="ch2.xhtml"/></navPoint>
        </navMap></ncx>"#;
        let m = ncx_titles(ncx);
        assert_eq!(m.get("ch1.xhtml").map(|s| s.as_str()), Some("卷首"));
        assert_eq!(m.get("ch2.xhtml").map(|s| s.as_str()), Some("卷尾"));
    }
}