1// Copyright (c) 2017 Maxime “pep” Buquet <pep+code@bouah.net>
2// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8use try_from::TryFrom;
9
10use minidom::Element;
11
12use error::Error;
13
14use ns;
15
16#[derive(Debug, Clone)]
17pub struct Muc {
18 pub password: Option<String>,
19}
20
21impl TryFrom<Element> for Muc {
22 type Err = Error;
23
24 fn try_from(elem: Element) -> Result<Muc, Error> {
25 if !elem.is("x", ns::MUC) {
26 return Err(Error::ParseError("This is not an x element."));
27 }
28
29 let mut password = None;
30 for child in elem.children() {
31 if child.is("password", ns::MUC) {
32 password = Some(child.text());
33 } else {
34 return Err(Error::ParseError("Unknown child in x element."));
35 }
36 }
37
38 for _ in elem.attrs() {
39 return Err(Error::ParseError("Unknown attribute in x element."));
40 }
41
42 Ok(Muc {
43 password: password,
44 })
45 }
46}
47
48impl From<Muc> for Element {
49 fn from(muc: Muc) -> Element {
50 Element::builder("x")
51 .ns(ns::MUC)
52 .append(muc.password)
53 .build()
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn test_muc_simple() {
63 let elem: Element = "<x xmlns='http://jabber.org/protocol/muc'/>".parse().unwrap();
64 Muc::try_from(elem).unwrap();
65 }
66
67 #[test]
68 fn test_muc_invalid_child() {
69 let elem: Element = "<x xmlns='http://jabber.org/protocol/muc'><coucou/></x>".parse().unwrap();
70 let error = Muc::try_from(elem).unwrap_err();
71 let message = match error {
72 Error::ParseError(string) => string,
73 _ => panic!(),
74 };
75 assert_eq!(message, "Unknown child in x element.");
76 }
77
78 #[test]
79 fn test_muc_serialise() {
80 let elem: Element = "<x xmlns='http://jabber.org/protocol/muc'/>".parse().unwrap();
81 let muc = Muc {
82 password: None,
83 };
84 let elem2 = muc.into();
85 assert_eq!(elem, elem2);
86 }
87
88 #[test]
89 fn test_muc_invalid_attribute() {
90 let elem: Element = "<x xmlns='http://jabber.org/protocol/muc' coucou=''/>".parse().unwrap();
91 let error = Muc::try_from(elem).unwrap_err();
92 let message = match error {
93 Error::ParseError(string) => string,
94 _ => panic!(),
95 };
96 assert_eq!(message, "Unknown attribute in x element.");
97 }
98
99 #[test]
100 fn test_muc_simple_password() {
101 let elem: Element = "
102 <x xmlns='http://jabber.org/protocol/muc'>
103 <password>coucou</password>
104 </x>"
105 .parse().unwrap();
106 let muc = Muc::try_from(elem).unwrap();
107 assert_eq!(muc.password, Some("coucou".to_owned()));
108 }
109}