Skip to main content

jikji_parser/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::collections::BTreeMap;
4use std::fs;
5use std::path::{Path, PathBuf};
6
7mod archive;
8mod binary;
9mod container;
10mod legacy_office;
11mod media;
12mod rtf;
13mod structured;
14mod text;
15mod utils;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct ArchiveLimits {
19    pub max_entries: usize,
20    pub max_entry_bytes: u64,
21    pub max_total_bytes: u64,
22}
23
24impl Default for ArchiveLimits {
25    fn default() -> Self {
26        Self {
27            max_entries: 1_000,
28            max_entry_bytes: 16 * 1024 * 1024,
29            max_total_bytes: 128 * 1024 * 1024,
30        }
31    }
32}
33
34#[derive(Debug, Clone, Copy)]
35pub struct ParserInput<'a> {
36    pub path: &'a Path,
37    pub bytes: &'a [u8],
38    pub max_chars: usize,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ParseStatus {
43    Success,
44    ArchiveListing,
45    MetadataOnly,
46    Failed,
47    Unsupported,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct ParsedDocument {
52    pub text: String,
53    pub metadata: BTreeMap<String, String>,
54    pub status: ParseStatus,
55    pub parser_name: &'static str,
56}
57
58impl ParsedDocument {
59    pub fn new(text: String, status: ParseStatus, parser_name: &'static str) -> Self {
60        Self {
61            text,
62            metadata: BTreeMap::new(),
63            status,
64            parser_name,
65        }
66    }
67
68    pub fn unsupported() -> Self {
69        Self::new(String::new(), ParseStatus::Unsupported, "unsupported")
70    }
71
72    pub fn failed(parser_name: &'static str) -> Self {
73        Self::new(String::new(), ParseStatus::Failed, parser_name)
74    }
75}
76
77pub trait DocumentParser: Send + Sync {
78    fn name(&self) -> &'static str;
79    fn supports_extension(&self, extension: &str) -> bool;
80    fn parse(&self, input: ParserInput<'_>) -> ParsedDocument;
81}
82
83#[derive(Default)]
84pub struct ParserRegistry {
85    parsers: Vec<Box<dyn DocumentParser>>,
86}
87
88impl ParserRegistry {
89    pub fn with_defaults() -> Self {
90        Self {
91            parsers: vec![
92                Box::<text::PlainTextParser>::default(),
93                Box::<text::SubtitleParser>::default(),
94                Box::<text::HtmlParser>::default(),
95                Box::<text::RtfParser>::default(),
96                Box::<archive::ArchiveParser>::default(),
97                Box::<structured::EmailParser>::default(),
98                Box::<structured::CalendarParser>::default(),
99                Box::<structured::SqliteParser>::default(),
100                Box::<container::EpubParser>::default(),
101                Box::<container::OfficeOpenXmlParser>::default(),
102                Box::<container::OpenDocumentParser>::default(),
103                Box::<container::HwpxParser>::default(),
104                Box::<binary::PdfParser>::default(),
105                Box::<binary::LegacyOfficeParser>::default(),
106                Box::<binary::BinaryHwpParser>::default(),
107                Box::<media::MediaMetadataParser>::default(),
108            ],
109        }
110    }
111
112    pub fn with_default_stubs() -> Self {
113        Self::with_defaults()
114    }
115
116    pub fn parser_for_extension(&self, extension: &str) -> Option<&dyn DocumentParser> {
117        let normalized = normalize_extension(extension);
118        self.parsers
119            .iter()
120            .map(Box::as_ref)
121            .find(|parser| parser.supports_extension(normalized.as_str()))
122    }
123
124    pub fn parse_path(&self, path: &Path, max_chars: usize) -> ParsedDocument {
125        let bytes = match fs::read(path) {
126            Ok(bytes) => bytes,
127            Err(_) => return ParsedDocument::failed("filesystem"),
128        };
129        self.parse_path_with_bytes(path, &bytes, max_chars)
130    }
131
132    pub fn parse_bytes(&self, name: &str, bytes: &[u8], max_chars: usize) -> ParsedDocument {
133        let path = PathBuf::from(name);
134        self.parse_path_with_bytes(path.as_path(), bytes, max_chars)
135    }
136
137    pub fn parse_path_deep(
138        &self,
139        path: &Path,
140        max_chars: usize,
141        limits: ArchiveLimits,
142    ) -> ParsedDocument {
143        let bytes = match fs::read(path) {
144            Ok(bytes) => bytes,
145            Err(_) => return ParsedDocument::failed("filesystem"),
146        };
147        archive::parse_deep(self, path, &bytes, max_chars, limits)
148    }
149
150    pub fn parse_bytes_deep(
151        &self,
152        name: &str,
153        bytes: &[u8],
154        max_chars: usize,
155        limits: ArchiveLimits,
156    ) -> ParsedDocument {
157        let path = PathBuf::from(name);
158        archive::parse_deep(self, &path, bytes, max_chars, limits)
159    }
160
161    fn parse_path_with_bytes(&self, path: &Path, bytes: &[u8], max_chars: usize) -> ParsedDocument {
162        let extension = extension_for_path(path);
163        // Legacy Office names are often reused for other formats: Word saves RTF, HTML or a
164        // renamed .docx as ".doc". Pick the parser from the content in that case.
165        let effective = match (extension.as_str(), sniff_document_format(bytes)) {
166            ("doc" | "dot" | "xls" | "ppt" | "pps", Some(sniffed)) => sniffed,
167            _ => extension.as_str(),
168        };
169        let Some(parser) = self.parser_for_extension(effective) else {
170            return ParsedDocument::unsupported();
171        };
172        parser.parse(ParserInput {
173            path,
174            bytes,
175            max_chars,
176        })
177    }
178}
179
180/// Document format recognised from the leading bytes, for files whose extension lies.
181/// `None` for compound (OLE) files and anything unrecognised, which keep their extension.
182fn sniff_document_format(bytes: &[u8]) -> Option<&'static str> {
183    let head = bytes.get(..bytes.len().min(512)).unwrap_or_default();
184    if head.starts_with(b"{\\rtf") {
185        return Some("rtf");
186    }
187    if head.starts_with(b"PK\x03\x04") {
188        return Some("docx");
189    }
190    let text = String::from_utf8_lossy(head)
191        .trim_start_matches('\u{feff}')
192        .trim_start()
193        .to_ascii_lowercase();
194    if text.starts_with("<html")
195        || text.starts_with("<!doctype html")
196        || (text.starts_with("<?xml") && text.contains("<html"))
197    {
198        return Some("html");
199    }
200    if text.starts_with("mime-version:") {
201        return Some("eml");
202    }
203    None
204}
205
206fn normalize_extension(extension: &str) -> String {
207    extension.trim_start_matches('.').to_ascii_lowercase()
208}
209
210fn extension_for_path(path: &Path) -> String {
211    let name = path
212        .file_name()
213        .and_then(|part| part.to_str())
214        .unwrap_or_default()
215        .to_ascii_lowercase();
216    for compound in ["tar.gz", "tar.bz2", "tar.xz"] {
217        if name.ends_with(compound) {
218            return compound.to_owned();
219        }
220    }
221    path.extension()
222        .and_then(|extension| extension.to_str())
223        .map(normalize_extension)
224        .unwrap_or_default()
225}
226
227#[cfg(test)]
228mod tests {
229    use super::{ParseStatus, ParserRegistry};
230
231    #[test]
232    fn registry_resolves_plain_text_when_extension_is_text() {
233        let registry = ParserRegistry::with_defaults();
234
235        let parsed = registry.parse_bytes("note.txt", b"hello", 1_000);
236
237        assert_eq!(parsed.text, "hello");
238        assert_eq!(parsed.status, ParseStatus::Success);
239    }
240}