websocket.rs

 1// Copyright (c) 2018 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 jid::Jid;
 8
 9generate_element!(
10    /// The stream opening for WebSocket.
11    Open, "open", WEBSOCKET,
12    attributes: [
13        /// The JID of the entity opening this stream.
14        from: Option<Jid> = "from" => optional,
15
16        /// The JID of the entity receiving this stream opening.
17        to: Option<Jid> = "to" => optional,
18
19        /// The id of the stream, used for authentication challenges.
20        id: Option<String> = "id" => optional,
21
22        /// The XMPP version used during this stream.
23        version: Option<String> = "version" => optional,
24
25        /// The default human language for all subsequent stanzas, which will
26        /// be transmitted to other entities for better localisation.
27        xml_lang: Option<String> = "xml:lang" => optional,
28    ]
29);
30
31impl Open {
32    /// Creates a simple client→server `<open/>` element.
33    pub fn new(to: Jid) -> Open {
34        Open {
35            from: None,
36            to: Some(to),
37            id: None,
38            version: Some(String::from("1.0")),
39            xml_lang: None,
40        }
41    }
42
43    /// Sets the [@from](#structfield.from) attribute on this `<open/>`
44    /// element.
45    pub fn with_from(mut self, from: Jid) -> Open {
46        self.from = Some(from);
47        self
48    }
49
50    /// Sets the [@id](#structfield.id) attribute on this `<open/>` element.
51    pub fn with_id(mut self, id: String) -> Open {
52        self.id = Some(id);
53        self
54    }
55
56    /// Sets the [@xml:lang](#structfield.xml_lang) attribute on this `<open/>`
57    /// element.
58    pub fn with_lang(mut self, xml_lang: String) -> Open {
59        self.xml_lang = Some(xml_lang);
60        self
61    }
62
63    /// Checks whether the version matches the expected one.
64    pub fn is_version(&self, version: &str) -> bool {
65        match self.version {
66            None => false,
67            Some(ref self_version) => self_version == &String::from(version),
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use try_from::TryFrom;
76    use minidom::Element;
77
78    #[test]
79    fn test_simple() {
80        let elem: Element = "<open xmlns='urn:ietf:params:xml:ns:xmpp-framing'/>".parse().unwrap();
81        let open = Open::try_from(elem).unwrap();
82        assert_eq!(open.from, None);
83        assert_eq!(open.to, None);
84        assert_eq!(open.id, None);
85        assert_eq!(open.version, None);
86        assert_eq!(open.xml_lang, None);
87    }
88}