1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use std::convert::TryFrom;
8
9use minidom::Element;
10
11use error::Error;
12
13use ns;
14
15#[derive(Debug, Clone)]
16pub enum Receipt {
17 Request,
18 Received(String),
19}
20
21impl<'a> TryFrom<&'a Element> for Receipt {
22 type Error = Error;
23
24 fn try_from(elem: &'a Element) -> Result<Receipt, Error> {
25 for _ in elem.children() {
26 return Err(Error::ParseError("Unknown child in receipt element."));
27 }
28 if elem.is("request", ns::RECEIPTS) {
29 Ok(Receipt::Request)
30 } else if elem.is("received", ns::RECEIPTS) {
31 let id = elem.attr("id").unwrap_or("").to_owned();
32 Ok(Receipt::Received(id))
33 } else {
34 Err(Error::ParseError("This is not a receipt element."))
35 }
36 }
37}
38
39impl<'a> Into<Element> for &'a Receipt {
40 fn into(self) -> Element {
41 match *self {
42 Receipt::Request => Element::builder("request")
43 .ns(ns::RECEIPTS)
44 .build(),
45 Receipt::Received(ref id) => Element::builder("received")
46 .ns(ns::RECEIPTS)
47 .attr("id", id.clone())
48 .build(),
49 }
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn test_simple() {
59 let elem: Element = "<request xmlns='urn:xmpp:receipts'/>".parse().unwrap();
60 Receipt::try_from(&elem).unwrap();
61
62 let elem: Element = "<received xmlns='urn:xmpp:receipts'/>".parse().unwrap();
63 Receipt::try_from(&elem).unwrap();
64
65 let elem: Element = "<received xmlns='urn:xmpp:receipts' id='coucou'/>".parse().unwrap();
66 Receipt::try_from(&elem).unwrap();
67 }
68
69 #[test]
70 fn test_serialise() {
71 let receipt = Receipt::Request;
72 let elem: Element = (&receipt).into();
73 assert!(elem.is("request", ns::RECEIPTS));
74
75 let receipt = Receipt::Received("coucou".to_owned());
76 let elem: Element = (&receipt).into();
77 assert!(elem.is("received", ns::RECEIPTS));
78 assert_eq!(elem.attr("id"), Some("coucou"));
79 }
80}