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 minidom::Element;
 8
 9use error::Error;
10
11use ns;
12
13#[derive(Debug, Clone)]
14pub enum Receipt {
15    Request,
16    Received(String),
17}
18
19pub fn parse_receipt(root: &Element) -> Result<Receipt, Error> {
20    for _ in root.children() {
21        return Err(Error::ParseError("Unknown child in receipt element."));
22    }
23    if root.is("request", ns::RECEIPTS) {
24        Ok(Receipt::Request)
25    } else if root.is("received", ns::RECEIPTS) {
26        let id = root.attr("id").unwrap_or("").to_owned();
27        Ok(Receipt::Received(id))
28    } else {
29        Err(Error::ParseError("This is not a receipt element."))
30    }
31}
32
33pub fn serialise(receipt: &Receipt) -> Element {
34    match *receipt {
35        Receipt::Request => Element::builder("request")
36                                    .ns(ns::RECEIPTS)
37                                    .build(),
38        Receipt::Received(ref id) => Element::builder("received")
39                                             .ns(ns::RECEIPTS)
40                                             .attr("id", id.clone())
41                                             .build(),
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use minidom::Element;
48    //use error::Error;
49    use receipts;
50    use ns;
51
52    #[test]
53    fn test_simple() {
54        let elem: Element = "<request xmlns='urn:xmpp:receipts'/>".parse().unwrap();
55        receipts::parse_receipt(&elem).unwrap();
56
57        let elem: Element = "<received xmlns='urn:xmpp:receipts'/>".parse().unwrap();
58        receipts::parse_receipt(&elem).unwrap();
59
60        let elem: Element = "<received xmlns='urn:xmpp:receipts' id='coucou'/>".parse().unwrap();
61        receipts::parse_receipt(&elem).unwrap();
62    }
63
64    #[test]
65    fn test_serialise() {
66        let receipt = receipts::Receipt::Request;
67        let elem = receipts::serialise(&receipt);
68        assert!(elem.is("request", ns::RECEIPTS));
69
70        let receipt = receipts::Receipt::Received("coucou".to_owned());
71        let elem = receipts::serialise(&receipt);
72        assert!(elem.is("received", ns::RECEIPTS));
73        assert_eq!(elem.attr("id"), Some("coucou"));
74    }
75}