1use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event};
9use quick_xml::Reader;
10use quick_xml::Writer;
11use serde::{Deserialize, Serialize};
12
13use crate::namespaces;
14
15#[derive(Debug, Clone, Default, PartialEq)]
21pub struct CoreProperties {
22 pub title: Option<String>,
23 pub subject: Option<String>,
24 pub creator: Option<String>,
25 pub keywords: Option<String>,
26 pub description: Option<String>,
27 pub last_modified_by: Option<String>,
28 pub revision: Option<String>,
29 pub created: Option<String>,
30 pub modified: Option<String>,
31 pub category: Option<String>,
32 pub content_status: Option<String>,
33}
34
35pub fn serialize_core_properties(props: &CoreProperties) -> String {
37 let mut writer = Writer::new(Vec::new());
38
39 writer
41 .write_event(Event::Decl(BytesDecl::new(
42 "1.0",
43 Some("UTF-8"),
44 Some("yes"),
45 )))
46 .unwrap();
47
48 let mut root = BytesStart::new("cp:coreProperties");
50 root.push_attribute(("xmlns:cp", namespaces::CORE_PROPERTIES));
51 root.push_attribute(("xmlns:dc", namespaces::DC));
52 root.push_attribute(("xmlns:dcterms", namespaces::DC_TERMS));
53 root.push_attribute(("xmlns:dcmitype", DC_MITYPE));
54 root.push_attribute(("xmlns:xsi", namespaces::XSI));
55 writer.write_event(Event::Start(root)).unwrap();
56
57 fn write_element(writer: &mut Writer<Vec<u8>>, tag: &str, value: &str) {
59 writer
60 .write_event(Event::Start(BytesStart::new(tag)))
61 .unwrap();
62 writer
63 .write_event(Event::Text(BytesText::new(value)))
64 .unwrap();
65 writer.write_event(Event::End(BytesEnd::new(tag))).unwrap();
66 }
67
68 fn write_dcterms_element(writer: &mut Writer<Vec<u8>>, tag: &str, value: &str) {
70 let mut start = BytesStart::new(tag);
71 start.push_attribute(("xsi:type", "dcterms:W3CDTF"));
72 writer.write_event(Event::Start(start)).unwrap();
73 writer
74 .write_event(Event::Text(BytesText::new(value)))
75 .unwrap();
76 writer.write_event(Event::End(BytesEnd::new(tag))).unwrap();
77 }
78
79 if let Some(ref v) = props.title {
80 write_element(&mut writer, "dc:title", v);
81 }
82 if let Some(ref v) = props.subject {
83 write_element(&mut writer, "dc:subject", v);
84 }
85 if let Some(ref v) = props.creator {
86 write_element(&mut writer, "dc:creator", v);
87 }
88 if let Some(ref v) = props.keywords {
89 write_element(&mut writer, "cp:keywords", v);
90 }
91 if let Some(ref v) = props.description {
92 write_element(&mut writer, "dc:description", v);
93 }
94 if let Some(ref v) = props.last_modified_by {
95 write_element(&mut writer, "cp:lastModifiedBy", v);
96 }
97 if let Some(ref v) = props.revision {
98 write_element(&mut writer, "cp:revision", v);
99 }
100 if let Some(ref v) = props.created {
101 write_dcterms_element(&mut writer, "dcterms:created", v);
102 }
103 if let Some(ref v) = props.modified {
104 write_dcterms_element(&mut writer, "dcterms:modified", v);
105 }
106 if let Some(ref v) = props.category {
107 write_element(&mut writer, "cp:category", v);
108 }
109 if let Some(ref v) = props.content_status {
110 write_element(&mut writer, "cp:contentStatus", v);
111 }
112
113 writer
114 .write_event(Event::End(BytesEnd::new("cp:coreProperties")))
115 .unwrap();
116
117 String::from_utf8(writer.into_inner()).unwrap()
118}
119
120fn xml_error(e: impl std::fmt::Display) -> String {
121 format!("XML parse error: {e}")
122}
123
124fn append_text(buf: &mut String, event: &Event<'_>) -> Result<(), String> {
129 match event {
130 Event::Text(t) => buf.push_str(&t.unescape().map_err(xml_error)?),
131 Event::CData(c) => buf.push_str(std::str::from_utf8(c).map_err(xml_error)?),
132 _ => {}
133 }
134 Ok(())
135}
136
137fn set_core_field(props: &mut CoreProperties, tag: &[u8], text: String) {
139 let slot = match tag {
140 b"title" => &mut props.title,
141 b"subject" => &mut props.subject,
142 b"creator" => &mut props.creator,
143 b"keywords" => &mut props.keywords,
144 b"description" => &mut props.description,
145 b"lastModifiedBy" => &mut props.last_modified_by,
146 b"revision" => &mut props.revision,
147 b"created" => &mut props.created,
148 b"modified" => &mut props.modified,
149 b"category" => &mut props.category,
150 b"contentStatus" => &mut props.content_status,
151 _ => return,
152 };
153 *slot = Some(text);
154}
155
156pub fn deserialize_core_properties(xml: &str) -> Result<CoreProperties, String> {
162 let mut reader = Reader::from_str(xml);
163
164 let mut props = CoreProperties::default();
165 let mut depth = 0usize;
166 let mut current: Option<(Vec<u8>, String)> = None;
168
169 loop {
170 let event = reader.read_event().map_err(xml_error)?;
171 match &event {
172 Event::Start(e) => {
173 depth += 1;
174 if depth == 2 {
175 current = Some((e.local_name().as_ref().to_vec(), String::new()));
176 }
177 }
178 Event::Empty(e) => {
179 if depth == 1 {
180 set_core_field(&mut props, e.local_name().as_ref(), String::new());
181 }
182 }
183 Event::Text(_) | Event::CData(_) => {
184 if depth == 2 {
185 if let Some((_, buf)) = current.as_mut() {
186 append_text(buf, &event)?;
187 }
188 }
189 }
190 Event::End(_) => {
191 if depth == 2 {
192 if let Some((tag, text)) = current.take() {
193 set_core_field(&mut props, &tag, text);
194 }
195 }
196 depth = depth.saturating_sub(1);
197 }
198 Event::Eof => break,
199 _ => {}
200 }
201 }
202
203 Ok(props)
204}
205
206const DC_MITYPE: &str = "http://purl.org/dc/dcmitype/";
208
209#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
211#[serde(rename = "Properties")]
212pub struct ExtendedProperties {
213 #[serde(rename = "@xmlns", default = "default_extended_properties_ns")]
214 pub xmlns: String,
215 #[serde(rename = "@xmlns:vt", skip_serializing_if = "Option::is_none")]
216 pub xmlns_vt: Option<String>,
217
218 #[serde(rename = "Application", skip_serializing_if = "Option::is_none")]
219 pub application: Option<String>,
220 #[serde(rename = "DocSecurity", skip_serializing_if = "Option::is_none")]
221 pub doc_security: Option<u32>,
222 #[serde(rename = "ScaleCrop", skip_serializing_if = "Option::is_none")]
223 pub scale_crop: Option<bool>,
224 #[serde(rename = "Company", skip_serializing_if = "Option::is_none")]
225 pub company: Option<String>,
226 #[serde(rename = "LinksUpToDate", skip_serializing_if = "Option::is_none")]
227 pub links_up_to_date: Option<bool>,
228 #[serde(rename = "SharedDoc", skip_serializing_if = "Option::is_none")]
229 pub shared_doc: Option<bool>,
230 #[serde(rename = "HyperlinksChanged", skip_serializing_if = "Option::is_none")]
231 pub hyperlinks_changed: Option<bool>,
232 #[serde(rename = "AppVersion", skip_serializing_if = "Option::is_none")]
233 pub app_version: Option<String>,
234 #[serde(rename = "Template", skip_serializing_if = "Option::is_none")]
235 pub template: Option<String>,
236 #[serde(rename = "Manager", skip_serializing_if = "Option::is_none")]
237 pub manager: Option<String>,
238}
239
240impl ExtendedProperties {
241 pub fn with_defaults() -> Self {
243 Self {
244 xmlns: namespaces::EXTENDED_PROPERTIES.to_string(),
245 xmlns_vt: Some(namespaces::VT.to_string()),
246 ..Default::default()
247 }
248 }
249}
250
251#[derive(Debug, Clone, Default, PartialEq)]
256pub struct CustomProperties {
257 pub properties: Vec<CustomProperty>,
258}
259
260#[derive(Debug, Clone, PartialEq)]
262pub struct CustomProperty {
263 pub fmtid: String,
264 pub pid: u32,
265 pub name: String,
266 pub value: CustomPropertyValue,
267}
268
269#[derive(Debug, Clone, PartialEq)]
271pub enum CustomPropertyValue {
272 String(String),
273 Int(i32),
274 Float(f64),
275 Bool(bool),
276 DateTime(String),
277}
278
279pub const CUSTOM_PROPERTY_FMTID: &str = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
281
282pub fn serialize_custom_properties(props: &CustomProperties) -> String {
284 let mut writer = Writer::new(Vec::new());
285
286 writer
288 .write_event(Event::Decl(BytesDecl::new(
289 "1.0",
290 Some("UTF-8"),
291 Some("yes"),
292 )))
293 .unwrap();
294
295 let mut root = BytesStart::new("Properties");
296 root.push_attribute(("xmlns", namespaces::CUSTOM_PROPERTIES));
297 root.push_attribute(("xmlns:vt", namespaces::VT));
298 writer.write_event(Event::Start(root)).unwrap();
299
300 for prop in &props.properties {
301 let mut elem = BytesStart::new("property");
302 elem.push_attribute(("fmtid", prop.fmtid.as_str()));
303 elem.push_attribute(("pid", prop.pid.to_string().as_str()));
304 elem.push_attribute(("name", prop.name.as_str()));
305 writer.write_event(Event::Start(elem)).unwrap();
306
307 match &prop.value {
308 CustomPropertyValue::String(s) => {
309 writer
310 .write_event(Event::Start(BytesStart::new("vt:lpwstr")))
311 .unwrap();
312 writer.write_event(Event::Text(BytesText::new(s))).unwrap();
313 writer
314 .write_event(Event::End(BytesEnd::new("vt:lpwstr")))
315 .unwrap();
316 }
317 CustomPropertyValue::Int(n) => {
318 writer
319 .write_event(Event::Start(BytesStart::new("vt:i4")))
320 .unwrap();
321 writer
322 .write_event(Event::Text(BytesText::new(&n.to_string())))
323 .unwrap();
324 writer
325 .write_event(Event::End(BytesEnd::new("vt:i4")))
326 .unwrap();
327 }
328 CustomPropertyValue::Float(f) => {
329 writer
330 .write_event(Event::Start(BytesStart::new("vt:r8")))
331 .unwrap();
332 writer
333 .write_event(Event::Text(BytesText::new(&f.to_string())))
334 .unwrap();
335 writer
336 .write_event(Event::End(BytesEnd::new("vt:r8")))
337 .unwrap();
338 }
339 CustomPropertyValue::Bool(b) => {
340 writer
341 .write_event(Event::Start(BytesStart::new("vt:bool")))
342 .unwrap();
343 writer
344 .write_event(Event::Text(BytesText::new(if *b {
345 "true"
346 } else {
347 "false"
348 })))
349 .unwrap();
350 writer
351 .write_event(Event::End(BytesEnd::new("vt:bool")))
352 .unwrap();
353 }
354 CustomPropertyValue::DateTime(dt) => {
355 writer
356 .write_event(Event::Start(BytesStart::new("vt:filetime")))
357 .unwrap();
358 writer.write_event(Event::Text(BytesText::new(dt))).unwrap();
359 writer
360 .write_event(Event::End(BytesEnd::new("vt:filetime")))
361 .unwrap();
362 }
363 }
364
365 writer
366 .write_event(Event::End(BytesEnd::new("property")))
367 .unwrap();
368 }
369
370 writer
371 .write_event(Event::End(BytesEnd::new("Properties")))
372 .unwrap();
373
374 String::from_utf8(writer.into_inner()).unwrap()
375}
376
377struct PendingProperty {
379 fmtid: Option<String>,
380 pid: Option<u32>,
381 name: Option<String>,
382 depth: usize,
384 value_children: usize,
386 value_tag: Option<Vec<u8>>,
387 value_text: String,
388}
389
390impl PendingProperty {
391 fn from_start(e: &BytesStart<'_>, depth: usize) -> Result<Self, String> {
392 let mut pending = Self {
393 fmtid: None,
394 pid: None,
395 name: None,
396 depth,
397 value_children: 0,
398 value_tag: None,
399 value_text: String::new(),
400 };
401 for attr in e.attributes().flatten() {
402 let slot = match attr.key.as_ref() {
403 b"fmtid" => &mut pending.fmtid,
404 b"name" => &mut pending.name,
405 b"pid" => {
406 let raw = attr.unescape_value().map_err(xml_error)?;
407 pending.pid = raw.trim().parse().ok();
408 continue;
409 }
410 _ => continue,
411 };
412 *slot = Some(attr.unescape_value().map_err(xml_error)?.into_owned());
413 }
414 Ok(pending)
415 }
416
417 fn start_value(&mut self, local_name: &[u8]) {
418 self.value_children += 1;
419 if self.value_children == 1 {
420 self.value_tag = Some(local_name.to_vec());
421 }
422 }
423
424 fn finish(self) -> Option<CustomProperty> {
425 let text = self.value_text;
426 let value = match self.value_tag.as_deref()? {
427 b"lpwstr" => CustomPropertyValue::String(text),
428 b"i4" => CustomPropertyValue::Int(text.trim().parse().ok()?),
429 b"r8" => CustomPropertyValue::Float(text.trim().parse().ok()?),
430 b"bool" => {
431 let t = text.trim();
432 CustomPropertyValue::Bool(t == "true" || t == "1")
433 }
434 b"filetime" => CustomPropertyValue::DateTime(text.trim().to_string()),
435 _ => return None,
436 };
437 Some(CustomProperty {
438 fmtid: self.fmtid?,
439 pid: self.pid?,
440 name: self.name?,
441 value,
442 })
443 }
444}
445
446pub fn deserialize_custom_properties(xml: &str) -> Result<CustomProperties, String> {
454 let mut reader = Reader::from_str(xml);
455
456 let mut props = CustomProperties::default();
457 let mut depth = 0usize;
458 let mut pending: Option<PendingProperty> = None;
459
460 loop {
461 let event = reader.read_event().map_err(xml_error)?;
462 match &event {
463 Event::Start(e) => {
464 depth += 1;
465 match pending.as_mut() {
466 None if e.local_name().as_ref() == b"property" => {
467 pending = Some(PendingProperty::from_start(e, depth)?);
468 }
469 Some(p) if depth == p.depth + 1 => p.start_value(e.local_name().as_ref()),
470 _ => {}
471 }
472 }
473 Event::Empty(e) => {
474 if let Some(p) = pending.as_mut() {
475 if depth == p.depth {
476 p.start_value(e.local_name().as_ref());
477 }
478 }
479 }
480 Event::Text(_) | Event::CData(_) => {
481 if let Some(p) = pending.as_mut() {
482 if depth == p.depth + 1 && p.value_children == 1 {
483 append_text(&mut p.value_text, &event)?;
484 }
485 }
486 }
487 Event::End(_) => {
488 if pending.as_ref().is_some_and(|p| p.depth == depth) {
489 if let Some(prop) = pending.take().and_then(PendingProperty::finish) {
490 props.properties.push(prop);
491 }
492 }
493 depth = depth.saturating_sub(1);
494 }
495 Event::Eof => break,
496 _ => {}
497 }
498 }
499
500 Ok(props)
501}
502
503fn default_extended_properties_ns() -> String {
504 namespaces::EXTENDED_PROPERTIES.to_string()
505}
506
507#[cfg(test)]
508mod tests {
509 use super::*;
510
511 #[test]
512 fn test_core_properties_roundtrip() {
513 let props = CoreProperties {
514 title: Some("Test Title".to_string()),
515 subject: Some("Test Subject".to_string()),
516 creator: Some("Test Author".to_string()),
517 keywords: Some("key1, key2".to_string()),
518 description: Some("A description".to_string()),
519 last_modified_by: Some("Editor".to_string()),
520 revision: Some("3".to_string()),
521 created: Some("2024-01-01T00:00:00Z".to_string()),
522 modified: Some("2024-06-15T12:30:00Z".to_string()),
523 category: Some("Reports".to_string()),
524 content_status: Some("Draft".to_string()),
525 };
526
527 let xml = serialize_core_properties(&props);
528 let parsed = deserialize_core_properties(&xml).unwrap();
529 assert_eq!(props, parsed);
530 }
531
532 #[test]
533 fn test_core_properties_empty_fields() {
534 let props = CoreProperties::default();
535 let xml = serialize_core_properties(&props);
536 let parsed = deserialize_core_properties(&xml).unwrap();
537 assert_eq!(props, parsed);
538 }
539
540 #[test]
541 fn test_core_properties_partial_fields() {
542 let props = CoreProperties {
543 title: Some("Only Title".to_string()),
544 creator: Some("Only Author".to_string()),
545 ..Default::default()
546 };
547
548 let xml = serialize_core_properties(&props);
549 let parsed = deserialize_core_properties(&xml).unwrap();
550 assert_eq!(props, parsed);
551 }
552
553 #[test]
554 fn test_core_properties_serialized_format() {
555 let props = CoreProperties {
556 title: Some("My Title".to_string()),
557 creator: Some("Author Name".to_string()),
558 created: Some("2024-01-01T00:00:00Z".to_string()),
559 ..Default::default()
560 };
561
562 let xml = serialize_core_properties(&props);
563 assert!(xml.contains("<cp:coreProperties"));
564 assert!(xml.contains("xmlns:cp="));
565 assert!(xml.contains("xmlns:dc="));
566 assert!(xml.contains("xmlns:dcterms="));
567 assert!(xml.contains("<dc:title>My Title</dc:title>"));
568 assert!(xml.contains("<dc:creator>Author Name</dc:creator>"));
569 assert!(xml.contains("xsi:type=\"dcterms:W3CDTF\""));
570 assert!(xml.contains("<dcterms:created"));
571 assert!(xml.contains("2024-01-01T00:00:00Z</dcterms:created>"));
572 }
573
574 #[test]
575 fn test_parse_real_excel_core_xml() {
576 let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
577<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">
578 <dc:title>Budget Report</dc:title>
579 <dc:subject>Finance</dc:subject>
580 <dc:creator>John Doe</dc:creator>
581 <cp:keywords>budget, 2024</cp:keywords>
582 <dc:description>Annual budget report</dc:description>
583 <cp:lastModifiedBy>Jane Smith</cp:lastModifiedBy>
584 <cp:revision>5</cp:revision>
585 <dcterms:created xsi:type="dcterms:W3CDTF">2024-01-15T08:00:00Z</dcterms:created>
586 <dcterms:modified xsi:type="dcterms:W3CDTF">2024-06-20T16:45:00Z</dcterms:modified>
587 <cp:category>Financial</cp:category>
588 <cp:contentStatus>Final</cp:contentStatus>
589</cp:coreProperties>"#;
590
591 let props = deserialize_core_properties(xml).unwrap();
592 assert_eq!(props.title.as_deref(), Some("Budget Report"));
593 assert_eq!(props.subject.as_deref(), Some("Finance"));
594 assert_eq!(props.creator.as_deref(), Some("John Doe"));
595 assert_eq!(props.keywords.as_deref(), Some("budget, 2024"));
596 assert_eq!(props.description.as_deref(), Some("Annual budget report"));
597 assert_eq!(props.last_modified_by.as_deref(), Some("Jane Smith"));
598 assert_eq!(props.revision.as_deref(), Some("5"));
599 assert_eq!(props.created.as_deref(), Some("2024-01-15T08:00:00Z"));
600 assert_eq!(props.modified.as_deref(), Some("2024-06-20T16:45:00Z"));
601 assert_eq!(props.category.as_deref(), Some("Financial"));
602 assert_eq!(props.content_status.as_deref(), Some("Final"));
603 }
604
605 #[test]
606 fn test_extended_properties_serde_roundtrip() {
607 let props = ExtendedProperties {
608 xmlns: namespaces::EXTENDED_PROPERTIES.to_string(),
609 xmlns_vt: Some(namespaces::VT.to_string()),
610 application: Some("SheetKit".to_string()),
611 doc_security: Some(0),
612 scale_crop: Some(false),
613 company: Some("Acme Corp".to_string()),
614 links_up_to_date: Some(false),
615 shared_doc: Some(false),
616 hyperlinks_changed: Some(false),
617 app_version: Some("1.0.0".to_string()),
618 template: None,
619 manager: Some("Boss".to_string()),
620 };
621
622 let xml = quick_xml::se::to_string(&props).unwrap();
623 let parsed: ExtendedProperties = quick_xml::de::from_str(&xml).unwrap();
624 assert_eq!(props, parsed);
625 }
626
627 #[test]
628 fn test_extended_properties_with_defaults() {
629 let props = ExtendedProperties::with_defaults();
630 assert_eq!(props.xmlns, namespaces::EXTENDED_PROPERTIES);
631 assert_eq!(props.xmlns_vt.as_deref(), Some(namespaces::VT));
632 assert!(props.application.is_none());
633 }
634
635 #[test]
636 fn test_extended_properties_skip_none_fields() {
637 let props = ExtendedProperties {
638 xmlns: namespaces::EXTENDED_PROPERTIES.to_string(),
639 xmlns_vt: None,
640 application: Some("Test".to_string()),
641 doc_security: None,
642 scale_crop: None,
643 company: None,
644 links_up_to_date: None,
645 shared_doc: None,
646 hyperlinks_changed: None,
647 app_version: None,
648 template: None,
649 manager: None,
650 };
651
652 let xml = quick_xml::se::to_string(&props).unwrap();
653 assert!(xml.contains("<Application>Test</Application>"));
654 assert!(!xml.contains("DocSecurity"));
655 assert!(!xml.contains("Company"));
656 }
657
658 #[test]
659 fn test_custom_properties_roundtrip() {
660 let props = CustomProperties {
661 properties: vec![
662 CustomProperty {
663 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
664 pid: 2,
665 name: "Project".to_string(),
666 value: CustomPropertyValue::String("SheetKit".to_string()),
667 },
668 CustomProperty {
669 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
670 pid: 3,
671 name: "Version".to_string(),
672 value: CustomPropertyValue::Int(42),
673 },
674 ],
675 };
676
677 let xml = serialize_custom_properties(&props);
678 let parsed = deserialize_custom_properties(&xml).unwrap();
679 assert_eq!(props, parsed);
680 }
681
682 #[test]
683 fn test_custom_properties_all_value_types() {
684 let props = CustomProperties {
685 properties: vec![
686 CustomProperty {
687 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
688 pid: 2,
689 name: "StringProp".to_string(),
690 value: CustomPropertyValue::String("hello".to_string()),
691 },
692 CustomProperty {
693 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
694 pid: 3,
695 name: "IntProp".to_string(),
696 value: CustomPropertyValue::Int(-7),
697 },
698 CustomProperty {
699 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
700 pid: 4,
701 name: "FloatProp".to_string(),
702 value: CustomPropertyValue::Float(3.15),
703 },
704 CustomProperty {
705 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
706 pid: 5,
707 name: "BoolProp".to_string(),
708 value: CustomPropertyValue::Bool(true),
709 },
710 CustomProperty {
711 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
712 pid: 6,
713 name: "DateProp".to_string(),
714 value: CustomPropertyValue::DateTime("2024-01-01T00:00:00Z".to_string()),
715 },
716 ],
717 };
718
719 let xml = serialize_custom_properties(&props);
720 let parsed = deserialize_custom_properties(&xml).unwrap();
721 assert_eq!(props.properties.len(), parsed.properties.len());
722 for (orig, p) in props.properties.iter().zip(parsed.properties.iter()) {
723 assert_eq!(orig.name, p.name);
724 assert_eq!(orig.value, p.value);
725 }
726 }
727
728 #[test]
729 fn test_custom_properties_empty() {
730 let props = CustomProperties::default();
731 let xml = serialize_custom_properties(&props);
732 let parsed = deserialize_custom_properties(&xml).unwrap();
733 assert!(parsed.properties.is_empty());
734 }
735
736 #[test]
737 fn test_custom_properties_serialized_format() {
738 let props = CustomProperties {
739 properties: vec![CustomProperty {
740 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
741 pid: 2,
742 name: "MyProp".to_string(),
743 value: CustomPropertyValue::String("MyValue".to_string()),
744 }],
745 };
746
747 let xml = serialize_custom_properties(&props);
748 assert!(xml.contains("<Properties"));
749 assert!(xml.contains("xmlns:vt="));
750 assert!(xml.contains("<property"));
751 assert!(xml.contains("fmtid="));
752 assert!(xml.contains("pid=\"2\""));
753 assert!(xml.contains("name=\"MyProp\""));
754 assert!(xml.contains("<vt:lpwstr>MyValue</vt:lpwstr>"));
755 }
756
757 #[test]
758 fn test_custom_properties_bool_false() {
759 let props = CustomProperties {
760 properties: vec![CustomProperty {
761 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
762 pid: 2,
763 name: "Flag".to_string(),
764 value: CustomPropertyValue::Bool(false),
765 }],
766 };
767
768 let xml = serialize_custom_properties(&props);
769 let parsed = deserialize_custom_properties(&xml).unwrap();
770 assert_eq!(parsed.properties[0].value, CustomPropertyValue::Bool(false));
771 }
772
773 fn string_prop(pid: u32, name: &str, value: &str) -> CustomProperty {
774 CustomProperty {
775 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
776 pid,
777 name: name.to_string(),
778 value: CustomPropertyValue::String(value.to_string()),
779 }
780 }
781
782 #[test]
783 fn test_custom_properties_special_chars_and_empty_values_multi_cycle() {
784 let props = CustomProperties {
785 properties: vec![
786 string_prop(2, "A&B", "x&y"),
787 string_prop(3, "<lt>", "<v>"),
788 string_prop(4, "q\"uote'apos", "\"'"),
789 string_prop(5, "Empty", ""),
790 string_prop(6, "Spaces", " "),
791 string_prop(7, "Padded", " a "),
792 CustomProperty {
793 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
794 pid: 8,
795 name: "Count&Co".to_string(),
796 value: CustomPropertyValue::Int(3),
797 },
798 ],
799 };
800
801 let mut current = props.clone();
802 for _ in 0..3 {
803 let xml = serialize_custom_properties(¤t);
804 current = deserialize_custom_properties(&xml).unwrap();
805 assert_eq!(current, props);
806 }
807 }
808
809 #[test]
810 fn test_custom_properties_cdata_and_pretty_printed_values() {
811 let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
812<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
813 <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name='Cd&ata'>
814 <vt:lpwstr><![CDATA[a<b>&]]></vt:lpwstr>
815 </property>
816 <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="Mixed"><vt:lpwstr>x & <![CDATA[<y>]]></vt:lpwstr></property>
817 <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="4" name="SelfClosed"><vt:lpwstr/></property>
818 <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="5" name="Num">
819 <vt:i4> 7 </vt:i4>
820 </property>
821</Properties>"#;
822
823 let parsed = deserialize_custom_properties(xml).unwrap();
824 assert_eq!(
825 parsed.properties,
826 vec![
827 string_prop(2, "Cd&ata", "a<b>&"),
828 string_prop(3, "Mixed", "x & <y>"),
829 string_prop(4, "SelfClosed", ""),
830 CustomProperty {
831 fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
832 pid: 5,
833 name: "Num".to_string(),
834 value: CustomPropertyValue::Int(7),
835 },
836 ]
837 );
838
839 let again = deserialize_custom_properties(&serialize_custom_properties(&parsed)).unwrap();
840 assert_eq!(again, parsed);
841 }
842
843 #[test]
844 fn test_custom_properties_vector_value_does_not_leak_inner_items() {
845 let xml = r#"<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
846<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Vec"><vt:vector size="1" baseType="lpwstr"><vt:lpwstr>inner</vt:lpwstr></vt:vector></property>
847<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="After"><vt:lpwstr>ok</vt:lpwstr></property>
848</Properties>"#;
849
850 let parsed = deserialize_custom_properties(xml).unwrap();
851 assert_eq!(parsed.properties, vec![string_prop(3, "After", "ok")]);
852 }
853
854 #[test]
855 fn test_core_properties_special_chars_and_empty_values_multi_cycle() {
856 let props = CoreProperties {
857 title: Some("A&B <c> \"d\" 'e'".to_string()),
858 subject: Some(String::new()),
859 creator: Some(" ".to_string()),
860 keywords: Some(" k1, k2 ".to_string()),
861 ..Default::default()
862 };
863
864 let mut current = props.clone();
865 for _ in 0..3 {
866 let xml = serialize_core_properties(¤t);
867 current = deserialize_core_properties(&xml).unwrap();
868 assert_eq!(current, props);
869 }
870 }
871
872 #[test]
873 fn test_core_properties_cdata_and_alternate_prefixes() {
874 let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
875<core:coreProperties xmlns:core="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:d="http://purl.org/dc/elements/1.1/">
876 <d:title><![CDATA[T<1>&]]></d:title>
877 <d:creator/>
878 <core:keywords>a & b</core:keywords>
879</core:coreProperties>"#;
880
881 let props = deserialize_core_properties(xml).unwrap();
882 assert_eq!(props.title.as_deref(), Some("T<1>&"));
883 assert_eq!(props.creator.as_deref(), Some(""));
884 assert_eq!(props.keywords.as_deref(), Some("a & b"));
885 assert_eq!(props.subject, None);
886 }
887
888 #[test]
889 fn test_extended_properties_special_chars_and_empty_values() {
890 let mut props = ExtendedProperties::with_defaults();
891 props.company = Some("A&B <c> \"d\" 'e'".to_string());
892 props.manager = Some(String::new());
893
894 let mut current = props.clone();
895 for _ in 0..3 {
896 let xml = quick_xml::se::to_string(¤t).unwrap();
897 current = quick_xml::de::from_str(&xml).unwrap();
898 assert_eq!(current, props);
899 }
900 }
901}