use std::collections::HashMap;
use f_office_xml::{Document, NodeId};
use crate::dates::DateTime;
use crate::ns::{CUSTOM_PROPERTIES, VT};
const TEXT_TYPES: [&str; 14] = [
"lpwstr", "lpstr", "bstr", "i1", "i2", "i4", "i8", "int", "ui1", "ui2", "ui4", "ui8", "uint",
"decimal",
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Property {
Text(String),
Date(DateTime),
}
pub type Properties = HashMap<String, Property>;
#[must_use]
pub fn read(doc: &Document, root: NodeId) -> Properties {
doc.child_elements(root)
.filter(|node| doc.is(*node, CUSTOM_PROPERTIES, "property"))
.filter_map(|property| {
let name = doc.attribute(property, None, "name")?;
doc.child_elements(property).find_map(|value| {
let text = || doc.text_content(value);
let found = if TEXT_TYPES.iter().any(|kind| doc.is(value, VT, kind)) {
Property::Text(text())
} else if doc.is(value, VT, "filetime") {
Property::Date(DateTime::parse_utc(&text())?)
} else {
return None;
};
Some((name.to_owned(), found))
})
})
.collect()
}
#[cfg(test)]
mod tests {
use f_office_xml::{Document, Limits};
use super::{Property, read};
use crate::dates::DateTime;
use crate::ns::{CUSTOM_PROPERTIES, VT};
#[test]
fn reads_text_number_and_date_properties() {
let xml = format!(
r#"<Properties xmlns="{CUSTOM_PROPERTIES}" xmlns:vt="{VT}"><property fmtid="x" pid="2" name="AsAtDate"><vt:lpwstr>04 Mar 1977</vt:lpwstr></property><property fmtid="x" pid="3" name="Count"><vt:i4>7</vt:i4></property><property fmtid="x" pid="4" name="Start"><vt:filetime>2018-12-28T13:00:00Z</vt:filetime></property><property fmtid="x" pid="5" name="Done"><vt:bool>false</vt:bool></property><property fmtid="x" pid="6" name="Bad"><vt:filetime>2018-12-28</vt:filetime></property></Properties>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let properties = read(&doc, doc.root().unwrap());
let text = |s: &str| Some(Property::Text(s.to_owned()));
assert_eq!(properties.get("AsAtDate").cloned(), text("04 Mar 1977"));
assert_eq!(properties.get("Count").cloned(), text("7"));
let start = DateTime {
year: 2018,
month: 12,
day: 28,
hour: 13,
minute: 0,
second: 0,
};
assert_eq!(
properties.get("Start").cloned(),
Some(Property::Date(start))
);
assert_eq!(
(properties.get("Done"), properties.get("Bad")),
(None, None)
);
}
}