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