receipts.rs

 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(Option<String>),
19}
20
21impl TryFrom<Element> for Receipt {
22    type Error = Error;
23
24    fn try_from(elem: 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            for _ in elem.attrs() {
30                return Err(Error::ParseError("Unknown attribute in request element."));
31            }
32            Ok(Receipt::Request)
33        } else if elem.is("received", ns::RECEIPTS) {
34            for (attr, _) in elem.attrs() {
35                if attr != "id" {
36                    return Err(Error::ParseError("Unknown attribute in received element."));
37                }
38            }
39            let id = get_attr!(elem, "id", optional);
40            Ok(Receipt::Received(id))
41        } else {
42            Err(Error::ParseError("This is not a receipt element."))
43        }
44    }
45}
46
47impl Into<Element> for Receipt {
48    fn into(self) -> Element {
49        match self {
50            Receipt::Request => Element::builder("request")
51                                        .ns(ns::RECEIPTS),
52            Receipt::Received(id) => Element::builder("received")
53                                             .ns(ns::RECEIPTS)
54                                             .attr("id", id),
55        }.build()
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn test_simple() {
65        let elem: Element = "<request xmlns='urn:xmpp:receipts'/>".parse().unwrap();
66        Receipt::try_from(elem).unwrap();
67
68        let elem: Element = "<received xmlns='urn:xmpp:receipts'/>".parse().unwrap();
69        Receipt::try_from(elem).unwrap();
70
71        let elem: Element = "<received xmlns='urn:xmpp:receipts' id='coucou'/>".parse().unwrap();
72        Receipt::try_from(elem).unwrap();
73    }
74
75    #[test]
76    fn test_serialise() {
77        let receipt = Receipt::Request;
78        let elem: Element = receipt.into();
79        assert!(elem.is("request", ns::RECEIPTS));
80
81        let receipt = Receipt::Received(Some(String::from("coucou")));
82        let elem: Element = receipt.into();
83        assert!(elem.is("received", ns::RECEIPTS));
84        assert_eq!(elem.attr("id"), Some("coucou"));
85    }
86}