blocking.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 try_from::TryFrom;
  8
  9use jid::Jid;
 10use minidom::Element;
 11
 12use error::Error;
 13
 14use ns;
 15use iq::{IqGetPayload, IqSetPayload, IqResultPayload};
 16
 17generate_empty_element!(
 18    /// The element requesting the blocklist, the result iq will contain a
 19    /// [BlocklistResult].
 20    BlocklistRequest, "blocklist", BLOCKING
 21);
 22
 23impl IqGetPayload for BlocklistRequest {}
 24
 25macro_rules! generate_blocking_element {
 26    ($(#[$meta:meta])* $elem:ident, $name:tt) => (
 27        $(#[$meta])*
 28        #[derive(Debug, Clone)]
 29        pub struct $elem {
 30            /// List of JIDs affected by this command.
 31            pub items: Vec<Jid>,
 32        }
 33
 34        impl TryFrom<Element> for $elem {
 35            type Err = Error;
 36
 37            fn try_from(elem: Element) -> Result<$elem, Error> {
 38                check_self!(elem, $name, BLOCKING);
 39                check_no_attributes!(elem, $name);
 40                let mut items = vec!();
 41                for child in elem.children() {
 42                    check_self!(child, "item", BLOCKING);
 43                    check_no_unknown_attributes!(child, "item", ["jid"]);
 44                    check_no_children!(child, "item");
 45                    items.push(get_attr!(child, "jid", required));
 46                }
 47                Ok($elem { items })
 48            }
 49        }
 50
 51        impl From<$elem> for Element {
 52            fn from(elem: $elem) -> Element {
 53                Element::builder($name)
 54                        .ns(ns::BLOCKING)
 55                        .append(elem.items.into_iter().map(|jid| {
 56                             Element::builder("item")
 57                                     .ns(ns::BLOCKING)
 58                                     .attr("jid", jid)
 59                                     .build()
 60                         }).collect::<Vec<_>>())
 61                        .build()
 62            }
 63        }
 64    );
 65}
 66
 67generate_blocking_element!(
 68    /// The element containing the current blocklist, as a reply from
 69    /// [BlocklistRequest].
 70    BlocklistResult, "blocklist"
 71);
 72
 73impl IqResultPayload for BlocklistResult {}
 74
 75// TODO: Prevent zero elements from being allowed.
 76generate_blocking_element!(
 77    /// A query to block one or more JIDs.
 78    Block, "block"
 79);
 80
 81impl IqSetPayload for Block {}
 82
 83generate_blocking_element!(
 84    /// A query to unblock one or more JIDs, or all of them.
 85    ///
 86    /// Warning: not putting any JID there means clearing out the blocklist.
 87    Unblock, "unblock"
 88);
 89
 90impl IqSetPayload for Unblock {}
 91
 92generate_empty_element!(
 93    /// The application-specific error condition when a message is blocked.
 94    Blocked, "blocked", BLOCKING_ERRORS
 95);
 96
 97#[cfg(test)]
 98mod tests {
 99    use super::*;
100
101    #[test]
102    fn test_simple() {
103        let elem: Element = "<blocklist xmlns='urn:xmpp:blocking'/>".parse().unwrap();
104        let request_elem = elem.clone();
105        BlocklistRequest::try_from(request_elem).unwrap();
106
107        let result_elem = elem.clone();
108        let result = BlocklistResult::try_from(result_elem).unwrap();
109        assert_eq!(result.items, vec!());
110
111        let elem: Element = "<block xmlns='urn:xmpp:blocking'/>".parse().unwrap();
112        let block = Block::try_from(elem).unwrap();
113        assert_eq!(block.items, vec!());
114
115        let elem: Element = "<unblock xmlns='urn:xmpp:blocking'/>".parse().unwrap();
116        let unblock = Unblock::try_from(elem).unwrap();
117        assert_eq!(unblock.items, vec!());
118    }
119
120    #[test]
121    fn test_items() {
122        let elem: Element = "<blocklist xmlns='urn:xmpp:blocking'><item jid='coucou@coucou'/><item jid='domain'/></blocklist>".parse().unwrap();
123        let two_items = vec!(
124            Jid {
125                node: Some(String::from("coucou")),
126                domain: String::from("coucou"),
127                resource: None,
128            },
129            Jid {
130                node: None,
131                domain: String::from("domain"),
132                resource: None,
133            },
134        );
135
136        let request_elem = elem.clone();
137        let error = BlocklistRequest::try_from(request_elem).unwrap_err();
138        let message = match error {
139            Error::ParseError(string) => string,
140            _ => panic!(),
141        };
142        assert_eq!(message, "Unknown child in blocklist element.");
143
144        let result_elem = elem.clone();
145        let result = BlocklistResult::try_from(result_elem).unwrap();
146        assert_eq!(result.items, two_items);
147
148        let elem: Element = "<block xmlns='urn:xmpp:blocking'><item jid='coucou@coucou'/><item jid='domain'/></block>".parse().unwrap();
149        let block = Block::try_from(elem).unwrap();
150        assert_eq!(block.items, two_items);
151
152        let elem: Element = "<unblock xmlns='urn:xmpp:blocking'><item jid='coucou@coucou'/><item jid='domain'/></unblock>".parse().unwrap();
153        let unblock = Unblock::try_from(elem).unwrap();
154        assert_eq!(unblock.items, two_items);
155    }
156
157    #[test]
158    fn test_invalid() {
159        let elem: Element = "<blocklist xmlns='urn:xmpp:blocking' coucou=''/>".parse().unwrap();
160        let request_elem = elem.clone();
161        let error = BlocklistRequest::try_from(request_elem).unwrap_err();
162        let message = match error {
163            Error::ParseError(string) => string,
164            _ => panic!(),
165        };
166        assert_eq!(message, "Unknown attribute in blocklist element.");
167
168        let result_elem = elem.clone();
169        let error = BlocklistResult::try_from(result_elem).unwrap_err();
170        let message = match error {
171            Error::ParseError(string) => string,
172            _ => panic!(),
173        };
174        assert_eq!(message, "Unknown attribute in blocklist element.");
175
176        let elem: Element = "<block xmlns='urn:xmpp:blocking' coucou=''/>".parse().unwrap();
177        let error = Block::try_from(elem).unwrap_err();
178        let message = match error {
179            Error::ParseError(string) => string,
180            _ => panic!(),
181        };
182        assert_eq!(message, "Unknown attribute in block element.");
183
184        let elem: Element = "<unblock xmlns='urn:xmpp:blocking' coucou=''/>".parse().unwrap();
185        let error = Unblock::try_from(elem).unwrap_err();
186        let message = match error {
187            Error::ParseError(string) => string,
188            _ => panic!(),
189        };
190        assert_eq!(message, "Unknown attribute in unblock element.");
191    }
192}