Skip to main content

deepdoc_core/extract/ooxml/
mod.rs

1//! OOXML extractors — docx and pptx, plus the parts they share.
2//!
3//! Both are ZIP + XML: the document body lives in one part, its hyperlink
4//! targets in a `_rels` part next to it, and the document properties split
5//! across `docProps/core.xml` (who and when) and `docProps/app.xml` (how big).
6
7pub mod docx;
8pub mod pptx;
9
10use std::collections::HashMap;
11
12use crate::extract::container::Container;
13use crate::extract::xml;
14use crate::model::Metadata;
15
16/// Read the OOXML metadata parts shared by every flavour.
17///
18/// The two parts are read independently: a document can ship one without the
19/// other, and losing the page count because `core.xml` is absent would be a
20/// silly way to lose it.
21pub fn core_properties(container: &mut Container) -> Metadata {
22    let mut meta = Metadata {
23        page_count: page_count(container),
24        ..Metadata::default()
25    };
26
27    let Some(source) = container.read_optional("docProps/core.xml") else {
28        return meta;
29    };
30    let Ok(root) = xml::parse(&source) else {
31        return meta;
32    };
33
34    let text_of = |name: &str| {
35        root.find(name)
36            .map(|element| element.text().trim().to_string())
37            .filter(|text| !text.is_empty())
38    };
39
40    meta.title = text_of("title");
41    meta.author = text_of("creator");
42    meta.created = text_of("created");
43    meta.language = text_of("language");
44    meta
45}
46
47/// Page count from `docProps/app.xml`.
48///
49/// It is the writing application's own count — the only page number an
50/// extractor can honestly report, since laying the document out again is not
51/// something DeepDoc does. `Slides` covers pptx, `Pages` the rest.
52fn page_count(container: &mut Container) -> Option<u32> {
53    let source = container.read_optional("docProps/app.xml")?;
54    let root = xml::parse(&source).ok()?;
55
56    ["Pages", "Slides"]
57        .iter()
58        .find_map(|name| root.find(name))
59        .and_then(|element| element.text().trim().parse().ok())
60        .filter(|count| *count > 0)
61}
62
63/// Relationship id → target, from a `_rels` part.
64///
65/// Hyperlinks in OOXML carry a relationship id (`r:id="rId7"`); the URL itself
66/// lives in the part's relationships file.
67pub fn relationships(source: Option<&str>) -> HashMap<String, String> {
68    let mut targets = HashMap::new();
69
70    let Some(root) = source.and_then(|source| xml::parse(source).ok()) else {
71        return targets;
72    };
73    for relationship in root.find_all("Relationship") {
74        if let (Some(id), Some(target)) = (relationship.attr("Id"), relationship.attr("Target")) {
75            targets.insert(id.to_string(), target.to_string());
76        }
77    }
78
79    targets
80}
81
82/// An OOXML boolean attribute: present means on unless it says otherwise.
83pub fn toggle(element: Option<&xml::Element>) -> bool {
84    match element {
85        None => false,
86        Some(element) => !matches!(element.attr("val"), Some("0" | "false" | "off")),
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn reads_core_properties() {
96        let bytes = crate::extract::container::tests::zip_bytes(&[(
97            "docProps/core.xml",
98            r#"<cp:coreProperties xmlns:cp="c" xmlns:dc="d" xmlns:dcterms="t">
99                 <dc:title>A title</dc:title>
100                 <dc:creator>Ada</dc:creator>
101                 <dcterms:created>2026-07-24T10:00:00Z</dcterms:created>
102               </cp:coreProperties>"#,
103        )]);
104        let mut container = Container::from_bytes(&bytes).unwrap();
105        let meta = core_properties(&mut container);
106
107        assert_eq!(meta.title.as_deref(), Some("A title"));
108        assert_eq!(meta.author.as_deref(), Some("Ada"));
109        assert_eq!(meta.created.as_deref(), Some("2026-07-24T10:00:00Z"));
110    }
111
112    #[test]
113    fn page_count_comes_from_the_app_properties() {
114        let word = crate::extract::container::tests::zip_bytes(&[(
115            "docProps/app.xml",
116            r#"<Properties><Pages>12</Pages><Words>3400</Words></Properties>"#,
117        )]);
118        let mut container = Container::from_bytes(&word).unwrap();
119        assert_eq!(core_properties(&mut container).page_count, Some(12));
120
121        let deck = crate::extract::container::tests::zip_bytes(&[(
122            "docProps/app.xml",
123            r#"<Properties><Slides>7</Slides></Properties>"#,
124        )]);
125        let mut container = Container::from_bytes(&deck).unwrap();
126        assert_eq!(core_properties(&mut container).page_count, Some(7));
127    }
128
129    #[test]
130    fn a_zero_page_count_is_no_count_at_all() {
131        let bytes = crate::extract::container::tests::zip_bytes(&[(
132            "docProps/app.xml",
133            r#"<Properties><Pages>0</Pages></Properties>"#,
134        )]);
135        let mut container = Container::from_bytes(&bytes).unwrap();
136        assert_eq!(core_properties(&mut container).page_count, None);
137    }
138
139    #[test]
140    fn missing_properties_are_not_an_error() {
141        let bytes = crate::extract::container::tests::zip_bytes(&[("word/document.xml", "<w:x/>")]);
142        let mut container = Container::from_bytes(&bytes).unwrap();
143        assert_eq!(core_properties(&mut container), Metadata::default());
144    }
145
146    #[test]
147    fn reads_relationship_targets() {
148        let targets = relationships(Some(
149            r#"<Relationships><Relationship Id="rId1" Target="https://example.com"/></Relationships>"#,
150        ));
151        assert_eq!(
152            targets.get("rId1").map(String::as_str),
153            Some("https://example.com")
154        );
155        assert!(relationships(None).is_empty());
156    }
157
158    #[test]
159    fn toggle_reads_ooxml_booleans() {
160        let on = xml::parse("<b/>").unwrap();
161        let off = xml::parse(r#"<b val="0"/>"#).unwrap();
162        assert!(toggle(Some(&on)));
163        assert!(!toggle(Some(&off)));
164        assert!(!toggle(None));
165    }
166}