1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use crate::error::OoxmlError;
use crate::packaging::content_type::ContentType;

use serde::{Deserialize, Serialize};

use std::io::prelude::*;
use std::{fmt, fs::File, path::Path};

pub type DateTime = String;
pub const CORE_PROPERTIES_URI: &str = "docProps/core.xml";
pub const CORE_PROPERTIES_NAMESPACE: &str =
    "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
pub const DC_NAMESPACE: &str = "http://purl.org/dc/elements/1.1/";
pub const DCTERMS_NAMESPACE: &str = "http://purl.org/dc/terms/";
pub const DCMITYPE_NAMESPACE: &str = "http://purl.org/dc/dcmitype/";
pub const XSI_NAMESPACE: &str = "http://www.w3.org/2001/XMLSchema-instance";

pub const CORE_PROPERTIES_TAG: &str = "cp:coreProperties";
pub const CORE_PROPERTIES_NAMESPACE_ATTRIBUTE: &str = "xmlns:dc";
pub const DC_NAMESPACE_ATTRIBUTE: &str = "xmlns:dc";
pub const DCTERMS_NAMESPACE_ATTRIBUTE: &str = "xmlns:dcterms";
pub const DCMITYPE_NAMESPACE_ATTRIBUTE: &str = "xmlns:dcmitype";
pub const XSI_NAMESPACE_ATTRIBUTE: &str = "xmlns:xsi";

pub const PROPERTY_CATEGORY_TAG: &str = "dc:creator";
pub const PROPERTY_CONTENT_STATUS_TAG: &str = "dc:contentStatus";
pub const PROPERTY_CONTENT_TYPE_TAG: &str = "dc:contentType";
pub const PROPERTY_CREATED_TAG: &str = "dcterms:created";
pub const PROPERTY_CREATOR_TAG: &str = "dc:creator";
pub const PROPERTY_DESCRIPTION_TAG: &str = "dc:description";
pub const PROPERTY_IDENTIFIER_TAG: &str = "dc:identifier";
pub const PROPERTY_KEYWORDS_TAG: &str = "dc:keywords";
pub const PROPERTY_LANGUAGE_TAG: &str = "dc:language";
pub const PROPERTY_MODIFIED_TAG: &str = "dcterms:modified";
pub const PROPERTY_LAST_MODIFIED_BY_TAG: &str = "cp:lastModifiedBy";
pub const PROPERTY_LAST_PRINTED_TAG: &str = "cp:lastPrinted";
pub const PROPERTY_REVISION_TAG: &str = "cp:revision";
pub const PROPERTY_SUBJECT_TAG: &str = "cp:subject";
pub const PROPERTY_TITLE_TAG: &str = "cp:title";
pub const PROPERTY_VERSION_TAG: &str = "cp:version";
/// Package properties, all the terms came from OpenXML SDK.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all(deserialize = "camelCase"))]
pub struct Properties {
    pub category: Option<String>,
    pub content_status: Option<String>,
    pub content_type: Option<ContentType>,
    pub created: Option<DateTime>,
    pub creator: Option<String>,
    pub description: Option<String>,
    pub identifier: Option<String>,
    pub keywords: Option<String>,
    pub language: Option<String>,
    pub modified: Option<String>,
    pub last_modified_by: Option<String>,
    pub last_printed: Option<DateTime>,
    pub revision: Option<String>,
    pub subject: Option<String>,
    pub title: Option<String>,
    pub version: Option<String>,
}

impl fmt::Display for Properties {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut container = Vec::new();
        let mut cursor = std::io::Cursor::new(&mut container);
        self.write(&mut cursor).expect("write xml to memory error");
        let s = String::from_utf8_lossy(&container);
        write!(f, "{}", s)?;
        Ok(())
    }
}

impl Properties {
    /// Parse content types data from an xml reader.
    pub fn parse_from_xml_reader<R: BufRead>(reader: R) -> Self {
        quick_xml::de::from_reader(reader).unwrap()
    }

    /// Parse content types data from an xml str.
    pub fn parse_from_xml_str(reader: &str) -> Self {
        quick_xml::de::from_str(reader).unwrap()
    }

    /// Save to file path.
    pub fn save_as<P: AsRef<Path>>(&self, path: P) -> Result<(), OoxmlError> {
        let file = File::create(path)?;
        self.write(file)
    }

    /// Write to an writer
    pub fn write<W: std::io::Write>(&self, writer: W) -> Result<(), OoxmlError> {
        let mut xml = quick_xml::Writer::new(writer);
        use quick_xml::events::attributes::Attribute;
        use quick_xml::events::*;

        // 1. write decl
        xml.write_event(Event::Decl(BytesDecl::new(
            b"1.0",
            Some(b"UTF-8"),
            Some(b"yes"),
        )))?;

        // 2. start types element
        let mut elem = BytesStart::borrowed_name(CORE_PROPERTIES_TAG.as_bytes());

        macro_rules! nsattr {
            ($ns:ident) => {
                paste::paste! {
                    Attribute {
                        key: [<$ns _NAMESPACE_ATTRIBUTE>].as_bytes(),
                        value: [<$ns _NAMESPACE>].as_bytes().into(),
                    }
                }
            };
        }

        elem.extend_attributes(vec![
            nsattr!(CORE_PROPERTIES),
            nsattr!(DC),
            nsattr!(DCTERMS),
            nsattr!(DCMITYPE),
            nsattr!(XSI),
        ]);
        xml.write_event(Event::Start(elem))?;

        macro_rules! field {
                ($field:ident) => {
                    paste::paste! {
                        if let Some(field) = &self.$field {
                            let start = BytesStart::borrowed_name([<PROPERTY_ $field:upper _TAG>].as_bytes());
                            let text = BytesText::from_plain_str(&field);
                            let end = BytesEnd::borrowed([<PROPERTY_ $field:upper _TAG>].as_bytes());
                            xml.write_event(Event::Start(start))?;
                            xml.write_event(Event::Text(text))?;
                            xml.write_event(Event::End(end))?;

                        }
                    }
                };
                ($field:ident, $xsi:expr) => {
                    paste::paste! {
                        if let Some(field) = &self.$field {
                            let mut start = BytesStart::borrowed_name([<PROPERTY_ $field:upper _TAG>].as_bytes());
                            start.extend_attributes(vec![
                                Attribute {
                                    key: b"xsi:type",
                                    value: "dcterms:W3CDTF".as_bytes().into()
                                }
                            ]);
                            let text = BytesText::from_plain_str(&field);
                            let end = BytesEnd::borrowed([<PROPERTY_ $field:upper _TAG>].as_bytes());
                            xml.write_event(Event::Start(start))?;
                            xml.write_event(Event::Text(text))?;
                            xml.write_event(Event::End(end))?;

                        }
                    }
                }
            }
        // FIXME(@zitsen): add more field to xml.
        field!(created, "term");
        field!(creator);
        field!(last_modified_by);
        field!(modified, "term");
        field!(revision);

        // bellow may not right
        field!(category);
        field!(content_status);
        field!(content_type);
        field!(description);
        field!(identifier);
        field!(keywords);
        field!(language);
        field!(last_printed);
        field!(subject);
        field!(title);
        field!(version);

        // ends types element.
        let end = BytesEnd::borrowed(CORE_PROPERTIES_TAG.as_bytes());
        xml.write_event(Event::End(end))?;
        Ok(())
    }
}
#[test]
fn test_de() {
    let raw = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <dcterms:created xsi:type="dcterms:W3CDTF">1970-01-01T00:00:00Z</dcterms:created>
      <dc:creator>unknown</dc:creator>
      <cp:lastModifiedBy>unknown</cp:lastModifiedBy>
      <dcterms:modified xsi:type="dcterms:W3CDTF">1970-01-01T00:00:00Z</dcterms:modified>
      <cp:revision>1</cp:revision>
    </cp:coreProperties>"#;
    println!("{}", raw);
    let value: Properties = quick_xml::de::from_str(raw).unwrap();
    println!("{:?}", value);
    let display = format!("{}", value);
    println!("{}", display);
    // assert_eq!(raw, display);
}