Skip to main content

aylis_docview/
office.rs

1//! Leitura de planilhas (XLSX, XLSM, XLS, XLSB, ODS pelo `calamine`; CSV) e de textos
2//! (DOCX, ODT: o XML de dentro do zip) para o que o visualizador mostra.
3
4use std::io::{Cursor, Read};
5
6/// Uma planilha: nome e células (linhas de colunas, já em texto).
7#[derive(Clone, Debug, Default, PartialEq)]
8pub struct Sheet {
9    pub name: String,
10    pub rows: Vec<Vec<String>>,
11}
12
13/// Um bloco de texto do documento.
14#[derive(Clone, Debug, PartialEq)]
15pub enum Block {
16    /// Parágrafo; `level` > 0 é título (1 = o maior).
17    Paragraph { text: String, level: u8 },
18    /// Tabela: linhas de células.
19    Table(Vec<Vec<String>>),
20}
21
22/// Lê uma planilha pela extensão.
23pub fn read_sheets(bytes: &[u8], extension: &str) -> Result<Vec<Sheet>, String> {
24    read_sheets_with(bytes, extension, MAX_SHEETS)
25}
26
27/// Como [`read_sheets`], com o maior conteúdo descompactado (`max` bytes). O `calamine` não
28/// aceita limite: o índice do ZIP é conferido antes (XLSX, XLSM, XLSB, ODS); o XLS antigo e o
29/// CSV, pelo tamanho do arquivo.
30pub fn read_sheets_with(bytes: &[u8], extension: &str, max: usize) -> Result<Vec<Sheet>, String> {
31    if bytes.starts_with(b"PK") {
32        check_zip(bytes, max)?;
33    } else if bytes.len() > max {
34        return Err(too_big());
35    }
36    if extension == "csv" || extension == "tsv" {
37        return Ok(vec![Sheet { name: "CSV".into(), rows: parse_csv(&String::from_utf8_lossy(bytes)) }]);
38    }
39    use calamine::{Data, Reader};
40    let mut book = calamine::open_workbook_auto_from_rs(Cursor::new(bytes)).map_err(|e| e.to_string())?;
41    let names = book.sheet_names().to_vec();
42    let mut out = Vec::new();
43    for name in names {
44        let range = book.worksheet_range(&name).map_err(|e| e.to_string())?;
45        let rows = range
46            .rows()
47            .map(|r| {
48                r.iter()
49                    .map(|c| match c {
50                        Data::Empty => String::new(),
51                        Data::String(s) => s.clone(),
52                        Data::Float(f) => {
53                            if f.fract() == 0.0 && f.abs() < 1e15 { format!("{}", *f as i64) } else { format!("{f}") }
54                        }
55                        Data::Int(i) => i.to_string(),
56                        Data::Bool(b) => if *b { "VERDADEIRO" } else { "FALSO" }.to_string(),
57                        Data::DateTime(d) => excel_date(d.as_f64()),
58                        Data::DateTimeIso(s) | Data::DurationIso(s) => s.clone(),
59                        Data::Error(e) => format!("#{e:?}"),
60                    })
61                    .collect()
62            })
63            .collect();
64        out.push(Sheet { name, rows });
65    }
66    Ok(out)
67}
68
69/// Número de série do Excel (dias desde 30/12/1899) em `dd/mm/aaaa` (e `hh:mm`, se tiver).
70fn excel_date(serial: f64) -> String {
71    let days = serial.floor() as i64;
72    let minutes = ((serial - serial.floor()) * 1440.0).round() as i64;
73    // Dias desde 1970-01-01, depois o calendário civil (Howard Hinnant).
74    let z = days - 25569 + 719_468;
75    let era = z.div_euclid(146_097);
76    let doe = z - era * 146_097;
77    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
78    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
79    let mp = (5 * doy + 2) / 153;
80    let d = doy - (153 * mp + 2) / 5 + 1;
81    let m = if mp < 10 { mp + 3 } else { mp - 9 };
82    let y = yoe + era * 400 + i64::from(m <= 2);
83    if minutes == 0 { format!("{d:02}/{m:02}/{y}") } else { format!("{d:02}/{m:02}/{y} {:02}:{:02}", minutes / 60, minutes % 60) }
84}
85
86/// CSV com `;`, `,` ou tabulação (a que aparecer mais na primeira linha), com aspas.
87pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
88    let first = text.lines().next().unwrap_or("");
89    let sep = [';', ',', '\t'].into_iter().max_by_key(|s| first.matches(*s).count()).unwrap_or(',');
90    let mut rows = Vec::new();
91    let mut row = Vec::new();
92    let mut cell = String::new();
93    let mut quoted = false;
94    let mut chars = text.chars().peekable();
95    while let Some(c) = chars.next() {
96        match c {
97            '"' if quoted && chars.peek() == Some(&'"') => {
98                cell.push('"');
99                chars.next();
100            }
101            '"' => quoted = !quoted,
102            c if c == sep && !quoted => row.push(std::mem::take(&mut cell)),
103            '\n' if !quoted => {
104                row.push(std::mem::take(&mut cell).trim_end_matches('\r').to_string());
105                rows.push(std::mem::take(&mut row));
106            }
107            c => cell.push(c),
108        }
109    }
110    if !cell.is_empty() || !row.is_empty() {
111        row.push(cell);
112        rows.push(row);
113    }
114    rows
115}
116
117/// O padrão do maior texto descompactado de um DOCX ou ODT.
118pub const MAX_DOCUMENT: usize = 64 * 1024 * 1024;
119/// O padrão do maior conteúdo descompactado de uma planilha (todas as entradas do ZIP).
120pub const MAX_SHEETS: usize = 256 * 1024 * 1024;
121/// Acima desta razão entre descompactado e compactado, o ZIP é tratado como bomba.
122pub const MAX_RATIO: u64 = 100;
123
124fn too_big() -> String {
125    "documento grande demais ou corrompido".into()
126}
127
128fn zip_entry(bytes: &[u8], name: &str, max: usize) -> Result<String, String> {
129    let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| e.to_string())?;
130    let file = archive.by_name(name).map_err(|_| format!("{name} não encontrado no arquivo"))?;
131    // O tamanho declarado pode mentir: a leitura também para no limite.
132    if file.size() > max as u64 {
133        return Err(too_big());
134    }
135    let mut xml = String::new();
136    file.take(max as u64 + 1).read_to_string(&mut xml).map_err(|e| e.to_string())?;
137    if xml.len() > max {
138        return Err(too_big());
139    }
140    Ok(xml)
141}
142
143/// Uma bomba de ZIP é recusada pelo índice (sem descompactar nada): o total descompactado
144/// acima de `max` ou uma razão absurda de compressão.
145fn check_zip(bytes: &[u8], max: usize) -> Result<(), String> {
146    let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| e.to_string())?;
147    let (mut total, mut packed) = (0u64, 0u64);
148    for i in 0..archive.len() {
149        let entry = archive.by_index_raw(i).map_err(|e| e.to_string())?;
150        total = total.saturating_add(entry.size());
151        packed = packed.saturating_add(entry.compressed_size());
152    }
153    if total > max as u64 || total > packed.max(1).saturating_mul(MAX_RATIO).max(1024 * 1024) {
154        return Err(too_big());
155    }
156    Ok(())
157}
158
159/// Lê um texto (DOCX ou ODT) em blocos.
160pub fn read_document(bytes: &[u8], extension: &str) -> Result<Vec<Block>, String> {
161    read_document_with(bytes, extension, MAX_DOCUMENT)
162}
163
164/// Como [`read_document`], com o maior texto descompactado (`max` bytes).
165pub fn read_document_with(bytes: &[u8], extension: &str, max: usize) -> Result<Vec<Block>, String> {
166    if extension == "odt" { odt(&zip_entry(bytes, "content.xml", max)?) } else { docx(&zip_entry(bytes, "word/document.xml", max)?) }
167}
168
169fn local(name: &str) -> &str {
170    name.split_once(':').map_or(name, |(_, local)| local)
171}
172
173fn attr(e: &quick_xml::events::BytesStart, key: &str) -> Option<String> {
174    e.attributes().flatten().find(|a| local(a.key.as_ref()) == key).and_then(|a| a.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(|v| v.into_owned()))
175}
176
177/// Uma referência no texto (`&amp;`, `&#233;`): o quick-xml entrega à parte.
178fn push_ref(out: &mut String, r: &quick_xml::events::BytesRef) {
179    if let Ok(s) = quick_xml::escape::unescape(&format!("&{};", r.xml10_content())) {
180        out.push_str(&s);
181    }
182}
183
184/// Nível de título pelo estilo (`Heading1`, `Ttulo1`, `Title`...).
185fn heading_level(style: &str) -> u8 {
186    let lower = style.to_lowercase();
187    if lower == "title" || lower == "titulo" || lower == "ttulo" {
188        return 1;
189    }
190    if lower.starts_with("heading") || lower.starts_with("ttulo") || lower.starts_with("titulo") {
191        return lower.chars().filter(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(1).clamp(1, 6);
192    }
193    0
194}
195
196fn docx(xml: &str) -> Result<Vec<Block>, String> {
197    use quick_xml::events::Event;
198    let mut reader = quick_xml::Reader::from_str(xml);
199    let mut blocks = Vec::new();
200    let (mut text, mut level) = (String::new(), 0u8);
201    let mut in_text = false;
202    // Tabelas: pilha de (linhas, linha atual, célula atual).
203    let mut tables: Vec<(Vec<Vec<String>>, Vec<String>, String)> = Vec::new();
204    loop {
205        match reader.read_event().map_err(|e| e.to_string())? {
206            Event::Start(e) | Event::Empty(e) if local(e.name().as_ref()) == "pStyle" => {
207                level = attr(&e, "val").map_or(0, |s| heading_level(&s));
208            }
209            Event::Start(e) => match local(e.name().as_ref()) {
210                "t" => in_text = true,
211                "tbl" => tables.push((Vec::new(), Vec::new(), String::new())),
212                "p" => {
213                    text.clear();
214                    level = 0;
215                }
216                _ => {}
217            },
218            Event::Empty(e) => match local(e.name().as_ref()) {
219                "tab" => text.push('\t'),
220                "br" => text.push('\n'),
221                _ => {}
222            },
223            Event::Text(t) if in_text => text.push_str(&t.xml10_content()),
224            Event::GeneralRef(r) if in_text => push_ref(&mut text, &r),
225            Event::End(e) => match local(e.name().as_ref()) {
226                "t" => in_text = false,
227                "p" => {
228                    if let Some((_, _, cell)) = tables.last_mut() {
229                        if !cell.is_empty() {
230                            cell.push('\n');
231                        }
232                        cell.push_str(&text);
233                    } else {
234                        blocks.push(Block::Paragraph { text: std::mem::take(&mut text), level });
235                    }
236                }
237                "tc" => {
238                    if let Some((_, row, cell)) = tables.last_mut() {
239                        row.push(std::mem::take(cell));
240                    }
241                }
242                "tr" => {
243                    if let Some((rows, row, _)) = tables.last_mut() {
244                        rows.push(std::mem::take(row));
245                    }
246                }
247                "tbl" => {
248                    if let Some((rows, _, _)) = tables.pop() {
249                        blocks.push(Block::Table(rows));
250                    }
251                }
252                _ => {}
253            },
254            Event::Eof => break,
255            _ => {}
256        }
257    }
258    Ok(blocks)
259}
260
261fn odt(xml: &str) -> Result<Vec<Block>, String> {
262    use quick_xml::events::Event;
263    let mut reader = quick_xml::Reader::from_str(xml);
264    let mut blocks = Vec::new();
265    let mut stack: Vec<(String, u8)> = Vec::new();
266    let mut tables: Vec<(Vec<Vec<String>>, Vec<String>)> = Vec::new();
267    loop {
268        match reader.read_event().map_err(|e| e.to_string())? {
269            Event::Start(e) => match local(e.name().as_ref()) {
270                "p" => stack.push((String::new(), 0)),
271                "h" => stack.push((String::new(), attr(&e, "outline-level").and_then(|l| l.parse().ok()).unwrap_or(1))),
272                "table" => tables.push((Vec::new(), Vec::new())),
273                _ => {}
274            },
275            Event::Empty(e) => {
276                if let Some((t, _)) = stack.last_mut() {
277                    match local(e.name().as_ref()) {
278                        "tab" => t.push('\t'),
279                        "line-break" => t.push('\n'),
280                        "s" => t.push(' '),
281                        _ => {}
282                    }
283                }
284            }
285            Event::Text(t) => {
286                if let Some((text, _)) = stack.last_mut() {
287                    text.push_str(&t.xml10_content());
288                }
289            }
290            Event::GeneralRef(r) => {
291                if let Some((text, _)) = stack.last_mut() {
292                    push_ref(text, &r);
293                }
294            }
295            Event::End(e) => match local(e.name().as_ref()) {
296                "p" | "h" => {
297                    if let Some((text, level)) = stack.pop() {
298                        if let Some((_, row)) = tables.last_mut() {
299                            row.push(text);
300                        } else {
301                            blocks.push(Block::Paragraph { text, level });
302                        }
303                    }
304                }
305                "table-row" => {
306                    if let Some((rows, row)) = tables.last_mut() {
307                        rows.push(std::mem::take(row));
308                    }
309                }
310                "table" => {
311                    if let Some((rows, _)) = tables.pop() {
312                        blocks.push(Block::Table(rows));
313                    }
314                }
315                _ => {}
316            },
317            Event::Eof => break,
318            _ => {}
319        }
320    }
321    Ok(blocks)
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn entities_in_the_text_and_in_attributes_are_resolved() {
330        let docx_xml = r#"<w:document xmlns:w="w"><w:body><w:p><w:pPr><w:pStyle w:val="Heading&#50;"/></w:pPr><w:r><w:t>Caf&#233; &amp; p&#xE3;o &lt;3</w:t></w:r></w:p></w:body></w:document>"#;
331        let blocks = docx(docx_xml).unwrap();
332        assert!(matches!(&blocks[..], [Block::Paragraph { text, level: 2 }] if text == "Café & pão <3"), "{blocks:?}");
333        let odt_xml = r#"<office:text xmlns:office="o" xmlns:text="t"><text:p>A &amp; B&#33;</text:p></office:text>"#;
334        assert!(matches!(&odt(odt_xml).unwrap()[..], [Block::Paragraph { text, .. }] if text == "A & B!"));
335    }
336
337    #[test]
338    fn excel_serial_dates() {
339        assert_eq!(excel_date(45000.0), "15/03/2023");
340        assert_eq!(excel_date(45000.5), "15/03/2023 12:00");
341        assert_eq!(excel_date(1.0), "31/12/1899");
342    }
343
344    #[test]
345    fn csv_with_quotes_and_semicolons() {
346        let rows = parse_csv("nome;valor\n\"Silva; João\";10\n\"diz \"\"oi\"\"\";2\n");
347        assert_eq!(rows, vec![vec!["nome", "valor"], vec!["Silva; João", "10"], vec!["diz \"oi\"", "2"]]);
348    }
349
350    #[test]
351    fn docx_paragraphs_headings_and_tables() {
352        let xml = r#"<w:document xmlns:w="x"><w:body>
353            <w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Relatório</w:t></w:r></w:p>
354            <w:p><w:r><w:t xml:space="preserve">Olá </w:t></w:r><w:r><w:t>mundo &amp; cia</w:t></w:r></w:p>
355            <w:tbl><w:tr><w:tc><w:p><w:r><w:t>A</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B</w:t></w:r></w:p></w:tc></w:tr></w:tbl>
356        </w:body></w:document>"#;
357        let blocks = docx(xml).unwrap();
358        assert_eq!(
359            blocks,
360            vec![
361                Block::Paragraph { text: "Relatório".into(), level: 1 },
362                Block::Paragraph { text: "Olá mundo & cia".into(), level: 0 },
363                Block::Table(vec![vec!["A".into(), "B".into()]]),
364            ]
365        );
366    }
367
368    #[test]
369    fn odt_paragraphs_and_headings() {
370        let xml = r#"<office:document-content xmlns:office="o" xmlns:text="t"><office:body><office:text>
371            <text:h text:outline-level="2">Seção</text:h><text:p>Linha<text:s/>um</text:p>
372        </office:text></office:body></office:document-content>"#;
373        assert_eq!(odt(xml).unwrap(), vec![Block::Paragraph { text: "Seção".into(), level: 2 }, Block::Paragraph { text: "Linha um".into(), level: 0 }]);
374    }
375}