Skip to main content

ragfs_extract/
office.rs

1//! Office document extractor (OOXML and ODT).
2//!
3//! Reads ZIP containers and pulls visible text from XML parts.
4//! Supported: `.docx`, `.xlsx`, `.pptx`, `.odt`.
5//! Not supported: legacy binary `.doc` / `.xls` / `.ppt`, RTF, EPUB.
6
7use async_trait::async_trait;
8use ragfs_core::{
9    ContentElement, ContentExtractor, ContentMetadataInfo, ExtractError, ExtractedContent,
10};
11use std::cmp::Ordering;
12use std::io::{Cursor, Read};
13use std::path::Path;
14use tracing::debug;
15use zip::ZipArchive;
16
17const DOCX_MIME: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
18const XLSX_MIME: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
19const PPTX_MIME: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
20const ODT_MIME: &str = "application/vnd.oasis.opendocument.text";
21
22/// Per-entry uncompressed cap (zip-bomb guard).
23const MAX_ENTRY_UNCOMPRESSED: u64 = 8 * 1024 * 1024;
24/// Aggregate uncompressed cap across extracted XML parts.
25const MAX_TOTAL_UNCOMPRESSED: u64 = 32 * 1024 * 1024;
26/// Upper bound on spaces expanded from one ODT `text:c` count.
27const MAX_ODT_SPACES: usize = 255;
28
29/// Office/OpenDocument text extractor.
30pub struct OfficeExtractor;
31
32impl OfficeExtractor {
33    /// Create a new office extractor.
34    #[must_use]
35    pub fn new() -> Self {
36        Self
37    }
38}
39
40impl Default for OfficeExtractor {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47enum OfficeKind {
48    Docx,
49    Xlsx,
50    Pptx,
51    Odt,
52}
53
54impl OfficeKind {
55    fn from_ext(ext: &str) -> Option<Self> {
56        match ext.to_ascii_lowercase().as_str() {
57            "docx" => Some(Self::Docx),
58            "xlsx" => Some(Self::Xlsx),
59            "pptx" => Some(Self::Pptx),
60            "odt" => Some(Self::Odt),
61            _ => None,
62        }
63    }
64
65    fn from_mime(mime: &str) -> Option<Self> {
66        match mime {
67            DOCX_MIME => Some(Self::Docx),
68            XLSX_MIME => Some(Self::Xlsx),
69            PPTX_MIME => Some(Self::Pptx),
70            ODT_MIME => Some(Self::Odt),
71            _ => None,
72        }
73    }
74
75    fn mime(self) -> &'static str {
76        match self {
77            Self::Docx => DOCX_MIME,
78            Self::Xlsx => XLSX_MIME,
79            Self::Pptx => PPTX_MIME,
80            Self::Odt => ODT_MIME,
81        }
82    }
83}
84
85#[async_trait]
86impl ContentExtractor for OfficeExtractor {
87    fn supported_types(&self) -> &[&str] {
88        &[DOCX_MIME, XLSX_MIME, PPTX_MIME, ODT_MIME]
89    }
90
91    fn can_extract_by_extension(&self, path: &Path) -> bool {
92        path.extension()
93            .and_then(|ext| ext.to_str())
94            .and_then(OfficeKind::from_ext)
95            .is_some()
96    }
97
98    async fn extract(&self, path: &Path) -> Result<ExtractedContent, ExtractError> {
99        debug!("Extracting office document: {:?}", path);
100        let bytes = tokio::fs::read(path).await?;
101        let kind = path
102            .extension()
103            .and_then(|ext| ext.to_str())
104            .and_then(OfficeKind::from_ext)
105            .ok_or_else(|| ExtractError::UnsupportedType(path.display().to_string()))?;
106        extract_kind(&bytes, kind)
107    }
108
109    async fn extract_bytes(
110        &self,
111        data: &[u8],
112        mime_type: &str,
113    ) -> Result<ExtractedContent, ExtractError> {
114        let kind = OfficeKind::from_mime(mime_type)
115            .ok_or_else(|| ExtractError::UnsupportedType(mime_type.to_string()))?;
116        extract_kind(data, kind)
117    }
118}
119
120fn extract_kind(bytes: &[u8], kind: OfficeKind) -> Result<ExtractedContent, ExtractError> {
121    let text = match kind {
122        OfficeKind::Docx => extract_named_parts(bytes, |name| {
123            name == "word/document.xml"
124                || name.starts_with("word/header")
125                || name.starts_with("word/footer")
126        })?,
127        OfficeKind::Xlsx => extract_xlsx(bytes)?,
128        OfficeKind::Pptx => extract_named_parts(bytes, |name| {
129            name.starts_with("ppt/slides/slide")
130                && Path::new(name)
131                    .extension()
132                    .is_some_and(|ext| ext.eq_ignore_ascii_case("xml"))
133        })?,
134        OfficeKind::Odt => extract_named_parts(bytes, |name| name == "content.xml")?,
135    };
136
137    if text.trim().is_empty() {
138        return Err(ExtractError::Failed(format!(
139            "no text extracted from {}",
140            kind.mime()
141        )));
142    }
143
144    let elements = text
145        .split('\n')
146        .filter(|line| !line.trim().is_empty())
147        .scan(0u64, |offset, line| {
148            let element = ContentElement::Paragraph {
149                text: line.to_string(),
150                byte_offset: *offset,
151            };
152            *offset += line.len() as u64 + 1;
153            Some(element)
154        })
155        .collect();
156
157    Ok(ExtractedContent {
158        text,
159        elements,
160        images: vec![],
161        metadata: ContentMetadataInfo::default(),
162    })
163}
164
165fn open_zip(bytes: &[u8]) -> Result<ZipArchive<Cursor<&[u8]>>, ExtractError> {
166    ZipArchive::new(Cursor::new(bytes))
167        .map_err(|e| ExtractError::Parse(format!("not a ZIP office document: {e}")))
168}
169
170fn collect_part_names(
171    archive: &mut ZipArchive<Cursor<&[u8]>>,
172    include: impl Fn(&str) -> bool,
173) -> Vec<String> {
174    let mut names: Vec<String> = (0..archive.len())
175        .filter_map(|i| {
176            let file = archive.by_index(i).ok()?;
177            let name = file.name().ok()?.into_owned();
178            include(&name).then_some(name)
179        })
180        .collect();
181    names.sort_by(|a, b| natural_cmp(a, b));
182    names
183}
184
185fn extract_named_parts(
186    bytes: &[u8],
187    include: impl Fn(&str) -> bool,
188) -> Result<String, ExtractError> {
189    let mut archive = open_zip(bytes)?;
190    let names = collect_part_names(&mut archive, include);
191    let mut remaining = MAX_TOTAL_UNCOMPRESSED;
192    let mut parts = Vec::new();
193    for name in names {
194        let mut file = archive
195            .by_name(&name)
196            .map_err(|e| ExtractError::Parse(format!("missing {name}: {e}")))?;
197        let xml = read_xml_part(&mut file, &mut remaining, MAX_ENTRY_UNCOMPRESSED)?;
198        let part = xml_to_text(&xml);
199        if !part.is_empty() {
200            parts.push(part);
201        }
202    }
203    Ok(parts.join("\n"))
204}
205
206fn extract_xlsx(bytes: &[u8]) -> Result<String, ExtractError> {
207    let mut archive = open_zip(bytes)?;
208    let mut remaining = MAX_TOTAL_UNCOMPRESSED;
209
210    let sst = if archive.by_name("xl/sharedStrings.xml").is_ok() {
211        let mut file = archive
212            .by_name("xl/sharedStrings.xml")
213            .map_err(|e| ExtractError::Parse(format!("missing sharedStrings: {e}")))?;
214        let xml = read_xml_part(&mut file, &mut remaining, MAX_ENTRY_UNCOMPRESSED)?;
215        drop(file);
216        parse_shared_strings(&xml)
217    } else {
218        Vec::new()
219    };
220
221    let sheets = collect_part_names(&mut archive, |name| {
222        name.starts_with("xl/worksheets/")
223            && Path::new(name)
224                .extension()
225                .is_some_and(|ext| ext.eq_ignore_ascii_case("xml"))
226    });
227
228    let mut parts = Vec::new();
229    for name in sheets {
230        let mut file = archive
231            .by_name(&name)
232            .map_err(|e| ExtractError::Parse(format!("missing {name}: {e}")))?;
233        let xml = read_xml_part(&mut file, &mut remaining, MAX_ENTRY_UNCOMPRESSED)?;
234        drop(file);
235        let part = xlsx_sheet_to_text(&xml, &sst);
236        if !part.is_empty() {
237            parts.push(part);
238        }
239    }
240    Ok(parts.join("\n"))
241}
242
243fn read_xml_part<R: Read + ?Sized>(
244    file: &mut zip::read::ZipFile<'_, R>,
245    remaining: &mut u64,
246    max_entry: u64,
247) -> Result<String, ExtractError> {
248    let bytes = read_entry_bytes(file, remaining, max_entry)?;
249    decode_xml_part(&bytes)
250}
251
252fn read_entry_bytes<R: Read + ?Sized>(
253    file: &mut zip::read::ZipFile<'_, R>,
254    remaining: &mut u64,
255    max_entry: u64,
256) -> Result<Vec<u8>, ExtractError> {
257    let name = file
258        .name()
259        .map_err(|e| ExtractError::Parse(format!("invalid ZIP entry name: {e}")))?
260        .into_owned();
261    let declared = file.size();
262    if declared > max_entry {
263        return Err(ExtractError::Failed(format!(
264            "office ZIP entry {name} exceeds {max_entry} uncompressed bytes"
265        )));
266    }
267    if declared > *remaining {
268        return Err(ExtractError::Failed(format!(
269            "office ZIP aggregate uncompressed limit exceeded at {name}"
270        )));
271    }
272
273    let mut buf = Vec::new();
274    let mut limited = file.take(max_entry.saturating_add(1));
275    limited
276        .read_to_end(&mut buf)
277        .map_err(|e| ExtractError::Parse(format!("failed to read {name}: {e}")))?;
278    let len = buf.len() as u64;
279    if len > max_entry {
280        return Err(ExtractError::Failed(format!(
281            "office ZIP entry {name} exceeds {max_entry} uncompressed bytes"
282        )));
283    }
284    if len > *remaining {
285        return Err(ExtractError::Failed(format!(
286            "office ZIP aggregate uncompressed limit exceeded at {name}"
287        )));
288    }
289    *remaining -= len;
290    Ok(buf)
291}
292
293fn decode_xml_part(bytes: &[u8]) -> Result<String, ExtractError> {
294    if bytes.starts_with(&[0xFF, 0xFE]) {
295        return decode_utf16(&bytes[2..], true);
296    }
297    if bytes.starts_with(&[0xFE, 0xFF]) {
298        return decode_utf16(&bytes[2..], false);
299    }
300    match std::str::from_utf8(bytes) {
301        Ok(s) => Ok(s.to_string()),
302        Err(_) => decode_utf16(bytes, true).or_else(|_| decode_utf16(bytes, false)),
303    }
304}
305
306fn decode_utf16(bytes: &[u8], little_endian: bool) -> Result<String, ExtractError> {
307    if !bytes.len().is_multiple_of(2) {
308        return Err(ExtractError::Parse(
309            "UTF-16 XML part has an odd number of bytes".into(),
310        ));
311    }
312    let units: Vec<u16> = bytes
313        .as_chunks::<2>()
314        .0
315        .iter()
316        .map(|&c| {
317            if little_endian {
318                u16::from_le_bytes(c)
319            } else {
320                u16::from_be_bytes(c)
321            }
322        })
323        .collect();
324    String::from_utf16(&units)
325        .map_err(|e| ExtractError::Parse(format!("invalid UTF-16 XML part: {e}")))
326}
327
328fn natural_cmp(a: &str, b: &str) -> Ordering {
329    let mut ai = a.chars().peekable();
330    let mut bi = b.chars().peekable();
331    loop {
332        match (ai.peek(), bi.peek()) {
333            (None, None) => return Ordering::Equal,
334            (None, Some(_)) => return Ordering::Less,
335            (Some(_), None) => return Ordering::Greater,
336            (Some(ac), Some(bc)) if ac.is_ascii_digit() && bc.is_ascii_digit() => {
337                let mut an = 0u64;
338                while matches!(ai.peek(), Some(c) if c.is_ascii_digit()) {
339                    let d = ai.next().expect("digit") as u32 - u32::from(b'0');
340                    an = an.saturating_mul(10).saturating_add(u64::from(d));
341                }
342                let mut bn = 0u64;
343                while matches!(bi.peek(), Some(c) if c.is_ascii_digit()) {
344                    let d = bi.next().expect("digit") as u32 - u32::from(b'0');
345                    bn = bn.saturating_mul(10).saturating_add(u64::from(d));
346                }
347                match an.cmp(&bn) {
348                    Ordering::Equal => {}
349                    other => return other,
350                }
351            }
352            (Some(_), Some(_)) => {
353                let ac = ai.next().expect("char");
354                let bc = bi.next().expect("char");
355                match ac.cmp(&bc) {
356                    Ordering::Equal => {}
357                    other => return other,
358                }
359            }
360        }
361    }
362}
363
364fn parse_shared_strings(xml: &str) -> Vec<String> {
365    inner_elements(xml, "si")
366        .into_iter()
367        .map(xml_to_text)
368        .collect()
369}
370
371fn xlsx_sheet_to_text(xml: &str, sst: &[String]) -> String {
372    let mut out = String::new();
373    let mut rest = xml;
374    let mut shared = false;
375    let mut in_v = false;
376    let mut in_f = false;
377    let mut index_buf = String::new();
378
379    while let Some(start) = rest.find('<') {
380        if start > 0 {
381            if shared && in_v {
382                index_buf.push_str(&rest[..start]);
383            } else if !shared && !in_f {
384                push_decoded(&mut out, &rest[..start]);
385            }
386        }
387        let after = &rest[start + 1..];
388        let Some(end_rel) = after.find('>') else {
389            break;
390        };
391        let tag = &after[..end_rel];
392        let local = local_name(tag_name(tag));
393        let is_end = tag.starts_with('/');
394
395        if !is_end && local == "c" {
396            shared = cell_is_shared_string(tag);
397            in_f = false;
398            index_buf.clear();
399        } else if is_end && local == "c" {
400            shared = false;
401            in_v = false;
402            in_f = false;
403            index_buf.clear();
404            out.push('\n');
405        } else if !is_end && local == "f" {
406            in_f = true;
407        } else if is_end && local == "f" {
408            in_f = false;
409        } else if !is_end && local == "v" {
410            in_v = true;
411            index_buf.clear();
412        } else if is_end && local == "v" {
413            if shared {
414                if let Ok(i) = index_buf.trim().parse::<usize>()
415                    && let Some(s) = sst.get(i)
416                {
417                    if !out.is_empty() && !out.ends_with(['\n', ' ']) {
418                        out.push(' ');
419                    }
420                    out.push_str(s);
421                }
422                index_buf.clear();
423            }
424            in_v = false;
425        } else if is_end && is_block_local(local) {
426            out.push('\n');
427        }
428        rest = &after[end_rel + 1..];
429    }
430    if !rest.is_empty() && !shared && !in_f {
431        push_decoded(&mut out, rest);
432    }
433    normalize_ws(&out)
434}
435
436fn cell_is_shared_string(tag: &str) -> bool {
437    tag.contains("t=\"s\"") || tag.contains("t='s'")
438}
439
440fn inner_elements<'a>(xml: &'a str, local: &str) -> Vec<&'a str> {
441    let mut rest = xml;
442    let mut out = Vec::new();
443    while let Some(i) = rest.find('<') {
444        let after = &rest[i + 1..];
445        let Some(gt) = after.find('>') else {
446            break;
447        };
448        let tag = &after[..gt];
449        let is_end = tag.starts_with('/');
450        let is_empty = tag.ends_with('/');
451        if !is_end && !is_empty && local_name(tag_name(tag)) == local {
452            let inner = &after[gt + 1..];
453            if let Some(end) = find_close_local(inner, local) {
454                out.push(&inner[..end]);
455                rest = &inner[end..];
456                continue;
457            }
458        }
459        rest = &after[gt + 1..];
460    }
461    out
462}
463
464fn find_close_local(inner: &str, local: &str) -> Option<usize> {
465    let mut offset = 0;
466    let mut rest = inner;
467    while let Some(i) = rest.find("</") {
468        let after = &rest[i + 2..];
469        let gt = after.find('>')?;
470        if local_name(tag_name(&after[..gt])) == local {
471            return Some(offset + i);
472        }
473        offset += i + 2 + gt + 1;
474        rest = &inner[offset..];
475    }
476    None
477}
478
479fn xml_to_text(xml: &str) -> String {
480    let mut out = String::new();
481    let mut rest = xml;
482    let mut skip_depth = 0u32;
483    let mut vanish_run = false;
484    while let Some(start) = rest.find('<') {
485        if start > 0 && skip_depth == 0 && !vanish_run {
486            push_decoded(&mut out, &rest[..start]);
487        }
488        let after = &rest[start + 1..];
489        let Some(end_rel) = after.find('>') else {
490            break;
491        };
492        let tag = &after[..end_rel];
493        let local = local_name(tag_name(tag));
494        let is_end = tag.starts_with('/');
495        let is_empty = tag.ends_with('/');
496
497        if !is_end && matches!(local, "delText" | "del") {
498            if !is_empty {
499                skip_depth = skip_depth.saturating_add(1);
500            }
501        } else if is_end && matches!(local, "delText" | "del") {
502            skip_depth = skip_depth.saturating_sub(1);
503        }
504
505        if !is_end && local == "vanish" && !vanish_disabled(tag) {
506            vanish_run = true;
507        }
508        if is_end && local == "r" {
509            vanish_run = false;
510        }
511
512        if skip_depth == 0 && !vanish_run {
513            if is_end && is_block_local(local) {
514                out.push('\n');
515            } else if !is_end && local == "s" {
516                for _ in 0..odt_space_count(tag) {
517                    out.push(' ');
518                }
519            } else if matches!(local, "tab" | "br") {
520                out.push(' ');
521            } else if local == "line-break" {
522                out.push('\n');
523            }
524        }
525        rest = &after[end_rel + 1..];
526    }
527    if !rest.is_empty() && skip_depth == 0 && !vanish_run {
528        push_decoded(&mut out, rest);
529    }
530    normalize_ws(&out)
531}
532
533fn vanish_disabled(tag: &str) -> bool {
534    tag.contains("val=\"0\"")
535        || tag.contains("val='0'")
536        || tag.contains("val=\"false\"")
537        || tag.contains("val='false'")
538}
539
540fn tag_name(tag: &str) -> &str {
541    let trimmed = tag.trim_start_matches('/').trim_start_matches('?');
542    trimmed
543        .split(|c: char| c.is_whitespace() || c == '/')
544        .next()
545        .unwrap_or("")
546}
547
548fn local_name(qname: &str) -> &str {
549    qname.rsplit_once(':').map_or(qname, |(_, local)| local)
550}
551
552fn is_block_local(local: &str) -> bool {
553    matches!(local, "p" | "h" | "tr" | "si" | "c")
554}
555
556fn odt_space_count(tag: &str) -> usize {
557    for key in ["text:c=", "c="] {
558        for quote in ['"', '\''] {
559            let pat = format!("{key}{quote}");
560            if let Some(i) = tag.find(&pat) {
561                let rest = &tag[i + pat.len()..];
562                if let Some(end) = rest.find(quote)
563                    && let Ok(n) = rest[..end].parse::<usize>()
564                {
565                    return n.clamp(1, MAX_ODT_SPACES);
566                }
567            }
568        }
569    }
570    1
571}
572
573fn push_decoded(out: &mut String, raw: &str) {
574    let mut chars = raw.chars().peekable();
575    while let Some(c) = chars.next() {
576        if c == '&' {
577            let mut entity = String::new();
578            while let Some(&next) = chars.peek() {
579                chars.next();
580                if next == ';' {
581                    break;
582                }
583                entity.push(next);
584                if entity.len() > 10 {
585                    break;
586                }
587            }
588            match entity.as_str() {
589                "amp" => out.push('&'),
590                "lt" => out.push('<'),
591                "gt" => out.push('>'),
592                "quot" => out.push('"'),
593                "apos" => out.push('\''),
594                "nbsp" => out.push(' '),
595                other if other.starts_with('#') => {
596                    let code = if let Some(hex) = other.strip_prefix("#x") {
597                        u32::from_str_radix(hex, 16).ok()
598                    } else {
599                        other.strip_prefix('#').and_then(|n| n.parse().ok())
600                    };
601                    if let Some(ch) = code.and_then(char::from_u32) {
602                        out.push(ch);
603                    }
604                }
605                _ => {
606                    out.push('&');
607                    out.push_str(&entity);
608                }
609            }
610        } else {
611            out.push(c);
612        }
613    }
614}
615
616fn normalize_ws(text: &str) -> String {
617    text.lines()
618        .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
619        .filter(|line| !line.is_empty())
620        .collect::<Vec<_>>()
621        .join("\n")
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627    use std::io::{Cursor, Write};
628    use zip::ZipWriter;
629    use zip::write::SimpleFileOptions;
630
631    fn zip_with(files: &[(&str, &str)]) -> Vec<u8> {
632        let owned: Vec<(&str, Vec<u8>)> = files
633            .iter()
634            .map(|(n, b)| (*n, b.as_bytes().to_vec()))
635            .collect();
636        let refs: Vec<(&str, &[u8])> = owned.iter().map(|(n, b)| (*n, b.as_slice())).collect();
637        zip_with_bytes(&refs)
638    }
639
640    fn zip_with_bytes(files: &[(&str, &[u8])]) -> Vec<u8> {
641        let mut cursor = Cursor::new(Vec::new());
642        {
643            let mut zip = ZipWriter::new(&mut cursor);
644            let opts = SimpleFileOptions::default();
645            for (name, body) in files {
646                zip.start_file(*name, opts).unwrap();
647                zip.write_all(body).unwrap();
648            }
649            zip.finish().unwrap();
650        }
651        cursor.into_inner()
652    }
653
654    fn utf16_le_bom(s: &str) -> Vec<u8> {
655        let mut out = vec![0xFF, 0xFE];
656        for unit in s.encode_utf16() {
657            out.extend_from_slice(&unit.to_le_bytes());
658        }
659        out
660    }
661
662    #[test]
663    fn xml_to_text_strips_tags_and_entities() {
664        let xml = r"<w:p><w:r><w:t>Hello &amp; world</w:t></w:r></w:p>";
665        assert_eq!(xml_to_text(xml), "Hello & world");
666    }
667
668    #[test]
669    fn xml_to_text_emits_odt_whitespace() {
670        assert_eq!(xml_to_text("A<text:s/>B"), "A B");
671        assert_eq!(xml_to_text(r#"A<text:s text:c="3"/>B"#), "A B");
672        assert_eq!(xml_to_text("A<text:tab/>B"), "A B");
673        assert_eq!(xml_to_text("A<text:line-break/>B"), "A\nB");
674    }
675
676    #[test]
677    fn odt_space_count_honors_text_c_but_clamps() {
678        assert_eq!(odt_space_count(r#"text:s text:c="3""#), 3);
679        assert_eq!(odt_space_count(r#"text:s text:c="0""#), 1);
680        assert_eq!(
681            odt_space_count(r#"text:s text:c="18446744073709551615""#),
682            255
683        );
684        assert_eq!(
685            xml_to_text(r#"A<text:s text:c="18446744073709551615"/>B"#),
686            "A B"
687        );
688    }
689
690    #[test]
691    fn xml_to_text_skips_deleted_and_vanished() {
692        let xml = r"<w:p><w:r><w:t>Keep</w:t></w:r><w:del><w:r><w:delText>Gone</w:delText></w:r></w:del><w:r><w:rPr><w:vanish/></w:rPr><w:t>Hidden</w:t></w:r><w:r><w:t>Visible</w:t></w:r></w:p>";
693        let text = xml_to_text(xml);
694        assert!(text.contains("Keep"));
695        assert!(text.contains("Visible"));
696        assert!(!text.contains("Gone"));
697        assert!(!text.contains("Hidden"));
698    }
699
700    #[test]
701    fn natural_cmp_orders_slide10_after_slide2() {
702        assert_eq!(
703            natural_cmp("ppt/slides/slide2.xml", "ppt/slides/slide10.xml"),
704            Ordering::Less
705        );
706        let mut names = vec![
707            "ppt/slides/slide10.xml".to_string(),
708            "ppt/slides/slide2.xml".to_string(),
709        ];
710        names.sort_by(|a, b| natural_cmp(a, b));
711        assert_eq!(
712            names,
713            vec![
714                "ppt/slides/slide2.xml".to_string(),
715                "ppt/slides/slide10.xml".to_string()
716            ]
717        );
718    }
719
720    #[test]
721    fn rejects_legacy_doc_extension() {
722        let extractor = OfficeExtractor::new();
723        assert!(!extractor.can_extract_by_extension(Path::new("report.doc")));
724        assert!(extractor.can_extract_by_extension(Path::new("report.docx")));
725    }
726
727    #[tokio::test]
728    async fn extracts_docx_paragraph() {
729        let xml = r#"<?xml version="1.0"?>
730<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
731  <w:body>
732    <w:p><w:r><w:t>Indexed from DOCX</w:t></w:r></w:p>
733  </w:body>
734</w:document>"#;
735        let bytes = zip_with(&[("word/document.xml", xml)]);
736        let extractor = OfficeExtractor::new();
737        let content = extractor.extract_bytes(&bytes, DOCX_MIME).await.unwrap();
738        assert!(content.text.contains("Indexed from DOCX"));
739    }
740
741    #[tokio::test]
742    async fn extracts_xlsx_skips_formula_keeps_cached_value() {
743        let sheet = r#"<?xml version="1.0"?>
744<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
745  <sheetData>
746    <row><c><f>SUM(A1:A2)</f><v>3</v></c></row>
747  </sheetData>
748</worksheet>"#;
749        let bytes = zip_with(&[("xl/worksheets/sheet1.xml", sheet)]);
750        let extractor = OfficeExtractor::new();
751        let content = extractor.extract_bytes(&bytes, XLSX_MIME).await.unwrap();
752        assert!(content.text.contains('3'));
753        assert!(!content.text.contains("SUM"));
754    }
755
756    #[tokio::test]
757    async fn extracts_xlsx_prefixed_shared_string_cells() {
758        let sst = r#"<?xml version="1.0"?>
759<x:sst xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
760  <x:si><x:t>Prefixed</x:t></x:si>
761</x:sst>"#;
762        let sheet = r#"<?xml version="1.0"?>
763<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
764  <x:sheetData>
765    <x:row><x:c t="s"><x:v>0</x:v></x:c></x:row>
766  </x:sheetData>
767</x:worksheet>"#;
768        let bytes = zip_with(&[
769            ("xl/sharedStrings.xml", sst),
770            ("xl/worksheets/sheet1.xml", sheet),
771        ]);
772        let extractor = OfficeExtractor::new();
773        let content = extractor.extract_bytes(&bytes, XLSX_MIME).await.unwrap();
774        assert!(content.text.contains("Prefixed"));
775        assert!(!content.text.split_whitespace().any(|w| w == "0"));
776    }
777
778    #[test]
779    fn xml_to_text_skips_prefixed_deleted_text() {
780        let xml = r"<ns:p><ns:r><ns:t>Keep</ns:t></ns:r><ns:del><ns:r><ns:delText>Gone</ns:delText></ns:r></ns:del></ns:p>";
781        let text = xml_to_text(xml);
782        assert!(text.contains("Keep"));
783        assert!(!text.contains("Gone"));
784    }
785
786    #[tokio::test]
787    async fn extracts_xlsx_shared_strings_in_sheet_order() {
788        let sst = r#"<?xml version="1.0"?>
789<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
790  <si><t>Revenue</t></si>
791  <si><t>Q1 actuals</t></si>
792</sst>"#;
793        let sheet = r#"<?xml version="1.0"?>
794<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
795  <sheetData>
796    <row>
797      <c t="s"><v>1</v></c>
798      <c t="s"><v>0</v></c>
799    </row>
800  </sheetData>
801</worksheet>"#;
802        let bytes = zip_with(&[
803            ("xl/sharedStrings.xml", sst),
804            ("xl/worksheets/sheet1.xml", sheet),
805        ]);
806        let extractor = OfficeExtractor::new();
807        let content = extractor.extract_bytes(&bytes, XLSX_MIME).await.unwrap();
808        assert!(content.text.contains("Q1 actuals"));
809        assert!(content.text.contains("Revenue"));
810        let q1 = content.text.find("Q1 actuals").unwrap();
811        let rev = content.text.find("Revenue").unwrap();
812        assert!(q1 < rev, "worksheet order should resolve index 1 then 0");
813        assert!(
814            !content
815                .text
816                .split_whitespace()
817                .any(|w| w == "0" || w == "1")
818        );
819    }
820
821    #[tokio::test]
822    async fn extracts_pptx_slides_in_numeric_order() {
823        let slide = |title: &str| {
824            format!(
825                r#"<?xml version="1.0"?>
826<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
827  <a:p><a:r><a:t>{title}</a:t></a:r></a:p>
828</p:sld>"#
829            )
830        };
831        let s10 = slide("Slide ten");
832        let s2 = slide("Slide two");
833        let bytes = zip_with(&[
834            ("ppt/slides/slide10.xml", s10.as_str()),
835            ("ppt/slides/slide2.xml", s2.as_str()),
836        ]);
837        let extractor = OfficeExtractor::new();
838        let content = extractor.extract_bytes(&bytes, PPTX_MIME).await.unwrap();
839        let two = content.text.find("Slide two").unwrap();
840        let ten = content.text.find("Slide ten").unwrap();
841        assert!(two < ten);
842    }
843
844    #[tokio::test]
845    async fn extracts_pptx_slide() {
846        let xml = r#"<?xml version="1.0"?>
847<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
848  <a:p><a:r><a:t>Slide title</a:t></a:r></a:p>
849</p:sld>"#;
850        let bytes = zip_with(&[("ppt/slides/slide1.xml", xml)]);
851        let extractor = OfficeExtractor::new();
852        let content = extractor.extract_bytes(&bytes, PPTX_MIME).await.unwrap();
853        assert!(content.text.contains("Slide title"));
854    }
855
856    #[tokio::test]
857    async fn extracts_odt_content() {
858        let xml = r#"<?xml version="1.0"?>
859<office:document-content xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
860  <text:p>OpenDocument text</text:p>
861</office:document-content>"#;
862        let bytes = zip_with(&[("content.xml", xml)]);
863        let extractor = OfficeExtractor::new();
864        let content = extractor.extract_bytes(&bytes, ODT_MIME).await.unwrap();
865        assert!(content.text.contains("OpenDocument text"));
866    }
867
868    #[tokio::test]
869    async fn extracts_utf16_docx_part() {
870        let xml = r#"<?xml version="1.0" encoding="UTF-16"?>
871<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
872  <w:body>
873    <w:p><w:r><w:t>UTF16 body</w:t></w:r></w:p>
874  </w:body>
875</w:document>"#;
876        let encoded = utf16_le_bom(xml);
877        let bytes = zip_with_bytes(&[("word/document.xml", encoded.as_slice())]);
878        let extractor = OfficeExtractor::new();
879        let content = extractor.extract_bytes(&bytes, DOCX_MIME).await.unwrap();
880        assert!(content.text.contains("UTF16 body"));
881    }
882
883    #[test]
884    fn rejects_oversized_zip_entry() {
885        let bytes = zip_with(&[("word/document.xml", "hello")]);
886        let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
887        let mut file = archive.by_name("word/document.xml").unwrap();
888        let mut remaining = 1024u64;
889        let err = read_entry_bytes(&mut file, &mut remaining, 2).unwrap_err();
890        assert!(matches!(err, ExtractError::Failed(_)));
891    }
892
893    #[tokio::test]
894    async fn extract_bytes_rejects_unknown_mime() {
895        let extractor = OfficeExtractor::new();
896        let err = extractor
897            .extract_bytes(b"not zip", "application/msword")
898            .await
899            .unwrap_err();
900        assert!(matches!(err, ExtractError::UnsupportedType(_)));
901    }
902}