message.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
  7#![allow(missing_docs)]
  8
  9use try_from::TryFrom;
 10use std::collections::BTreeMap;
 11
 12use minidom::Element;
 13
 14use jid::Jid;
 15
 16use error::Error;
 17
 18use ns;
 19
 20use stanza_error::StanzaError;
 21use chatstates::ChatState;
 22use receipts::{Request as ReceiptRequest, Received as ReceiptReceived};
 23use delay::Delay;
 24use attention::Attention;
 25use message_correct::Replace;
 26use eme::ExplicitMessageEncryption;
 27use stanza_id::{StanzaId, OriginId};
 28use mam::Result_ as MamResult;
 29
 30/// Lists every known payload of a `<message/>`.
 31#[derive(Debug, Clone)]
 32pub enum MessagePayload {
 33    StanzaError(StanzaError),
 34    ChatState(ChatState),
 35    ReceiptRequest(ReceiptRequest),
 36    ReceiptReceived(ReceiptReceived),
 37    Delay(Delay),
 38    Attention(Attention),
 39    MessageCorrect(Replace),
 40    ExplicitMessageEncryption(ExplicitMessageEncryption),
 41    StanzaId(StanzaId),
 42    OriginId(OriginId),
 43    MamResult(MamResult),
 44
 45    Unknown(Element),
 46}
 47
 48impl TryFrom<Element> for MessagePayload {
 49    type Err = Error;
 50
 51    fn try_from(elem: Element) -> Result<MessagePayload, Error> {
 52        Ok(match (elem.name().as_ref(), elem.ns().unwrap().as_ref()) {
 53            ("error", ns::DEFAULT_NS) => MessagePayload::StanzaError(StanzaError::try_from(elem)?),
 54
 55            // XEP-0085
 56            ("active", ns::CHATSTATES)
 57          | ("inactive", ns::CHATSTATES)
 58          | ("composing", ns::CHATSTATES)
 59          | ("paused", ns::CHATSTATES)
 60          | ("gone", ns::CHATSTATES) => MessagePayload::ChatState(ChatState::try_from(elem)?),
 61
 62            // XEP-0184
 63            ("request", ns::RECEIPTS) => MessagePayload::ReceiptRequest(ReceiptRequest::try_from(elem)?),
 64            ("received", ns::RECEIPTS) => MessagePayload::ReceiptReceived(ReceiptReceived::try_from(elem)?),
 65
 66            // XEP-0203
 67            ("delay", ns::DELAY) => MessagePayload::Delay(Delay::try_from(elem)?),
 68
 69            // XEP-0224
 70            ("attention", ns::ATTENTION) => MessagePayload::Attention(Attention::try_from(elem)?),
 71
 72            // XEP-0308
 73            ("replace", ns::MESSAGE_CORRECT) => MessagePayload::MessageCorrect(Replace::try_from(elem)?),
 74
 75            // XEP-0313
 76            ("result", ns::MAM) => MessagePayload::MamResult(MamResult::try_from(elem)?),
 77
 78            // XEP-0359
 79            ("stanza-id", ns::SID) => MessagePayload::StanzaId(StanzaId::try_from(elem)?),
 80            ("origin-id", ns::SID) => MessagePayload::OriginId(OriginId::try_from(elem)?),
 81
 82            // XEP-0380
 83            ("encryption", ns::EME) => MessagePayload::ExplicitMessageEncryption(ExplicitMessageEncryption::try_from(elem)?),
 84
 85            _ => MessagePayload::Unknown(elem),
 86        })
 87    }
 88}
 89
 90impl From<MessagePayload> for Element {
 91    fn from(payload: MessagePayload) -> Element {
 92        match payload {
 93            MessagePayload::StanzaError(stanza_error) => stanza_error.into(),
 94            MessagePayload::Attention(attention) => attention.into(),
 95            MessagePayload::ChatState(chatstate) => chatstate.into(),
 96            MessagePayload::ReceiptRequest(request) => request.into(),
 97            MessagePayload::ReceiptReceived(received) => received.into(),
 98            MessagePayload::Delay(delay) => delay.into(),
 99            MessagePayload::MessageCorrect(replace) => replace.into(),
100            MessagePayload::ExplicitMessageEncryption(eme) => eme.into(),
101            MessagePayload::StanzaId(stanza_id) => stanza_id.into(),
102            MessagePayload::OriginId(origin_id) => origin_id.into(),
103            MessagePayload::MamResult(result) => result.into(),
104
105            MessagePayload::Unknown(elem) => elem,
106        }
107    }
108}
109
110generate_attribute!(MessageType, "type", {
111    Chat => "chat",
112    Error => "error",
113    Groupchat => "groupchat",
114    Headline => "headline",
115    Normal => "normal",
116}, Default = Normal);
117
118type Lang = String;
119
120generate_elem_id!(Body, "body", DEFAULT_NS);
121generate_elem_id!(Subject, "subject", DEFAULT_NS);
122generate_elem_id!(Thread, "thread", DEFAULT_NS);
123
124/// The main structure representing the `<message/>` stanza.
125#[derive(Debug, Clone)]
126pub struct Message {
127    pub from: Option<Jid>,
128    pub to: Option<Jid>,
129    pub id: Option<String>,
130    pub type_: MessageType,
131    pub bodies: BTreeMap<Lang, Body>,
132    pub subjects: BTreeMap<Lang, Subject>,
133    pub thread: Option<Thread>,
134    pub payloads: Vec<Element>,
135}
136
137impl Message {
138    pub fn new(to: Option<Jid>) -> Message {
139        Message {
140            from: None,
141            to: to,
142            id: None,
143            type_: MessageType::Chat,
144            bodies: BTreeMap::new(),
145            subjects: BTreeMap::new(),
146            thread: None,
147            payloads: vec!(),
148        }
149    }
150
151    fn get_best<'a, T>(map: &'a BTreeMap<Lang, T>, preferred_langs: Vec<&str>) -> Option<(Lang, &'a T)> {
152        if map.is_empty() {
153            return None;
154        }
155        for lang in preferred_langs {
156            if let Some(value) = map.get(lang) {
157                return Some((Lang::from(lang), value));
158            }
159        }
160        if let Some(value) = map.get("") {
161            return Some((Lang::new(), value));
162        }
163        map.iter().map(|(lang, value)| (lang.clone(), value)).next()
164    }
165
166    /// Returns the best matching body from a list of languages.
167    ///
168    /// For instance, if a message contains both an xml:lang='de', an xml:lang='fr' and an English
169    /// body without an xml:lang attribute, and you pass ["fr", "en"] as your preferred languages,
170    /// `Some(("fr", the_second_body))` will be returned.
171    ///
172    /// If no body matches, an undefined body will be returned.
173    pub fn get_best_body(&self, preferred_langs: Vec<&str>) -> Option<(Lang, &Body)> {
174        Message::get_best::<Body>(&self.bodies, preferred_langs)
175    }
176
177    /// Returns the best matching subject from a list of languages.
178    ///
179    /// For instance, if a message contains both an xml:lang='de', an xml:lang='fr' and an English
180    /// subject without an xml:lang attribute, and you pass ["fr", "en"] as your preferred
181    /// languages, `Some(("fr", the_second_subject))` will be returned.
182    ///
183    /// If no subject matches, an undefined subject will be returned.
184    pub fn get_best_subject(&self, preferred_langs: Vec<&str>) -> Option<(Lang, &Subject)> {
185        Message::get_best::<Subject>(&self.subjects, preferred_langs)
186    }
187}
188
189impl TryFrom<Element> for Message {
190    type Err = Error;
191
192    fn try_from(root: Element) -> Result<Message, Error> {
193        check_self!(root, "message", DEFAULT_NS);
194        let from = get_attr!(root, "from", optional);
195        let to = get_attr!(root, "to", optional);
196        let id = get_attr!(root, "id", optional);
197        let type_ = get_attr!(root, "type", default);
198        let mut bodies = BTreeMap::new();
199        let mut subjects = BTreeMap::new();
200        let mut thread = None;
201        let mut payloads = vec!();
202        for elem in root.children() {
203            if elem.is("body", ns::DEFAULT_NS) {
204                check_no_children!(elem, "body");
205                let lang = get_attr!(elem, "xml:lang", default);
206                let body = Body(elem.text());
207                if bodies.insert(lang, body).is_some() {
208                    return Err(Error::ParseError("Body element present twice for the same xml:lang."));
209                }
210            } else if elem.is("subject", ns::DEFAULT_NS) {
211                check_no_children!(elem, "subject");
212                let lang = get_attr!(elem, "xml:lang", default);
213                let subject = Subject(elem.text());
214                if subjects.insert(lang, subject).is_some() {
215                    return Err(Error::ParseError("Subject element present twice for the same xml:lang."));
216                }
217            } else if elem.is("thread", ns::DEFAULT_NS) {
218                if thread.is_some() {
219                    return Err(Error::ParseError("Thread element present twice."));
220                }
221                check_no_children!(elem, "thread");
222                thread = Some(Thread(elem.text()));
223            } else {
224                payloads.push(elem.clone())
225            }
226        }
227        Ok(Message {
228            from: from,
229            to: to,
230            id: id,
231            type_: type_,
232            bodies: bodies,
233            subjects: subjects,
234            thread: thread,
235            payloads: payloads,
236        })
237    }
238}
239
240impl From<Message> for Element {
241    fn from(message: Message) -> Element {
242        Element::builder("message")
243                .ns(ns::DEFAULT_NS)
244                .attr("from", message.from)
245                .attr("to", message.to)
246                .attr("id", message.id)
247                .attr("type", message.type_)
248                .append(message.subjects.into_iter()
249                                        .map(|(lang, subject)| {
250                                                 let mut subject = Element::from(subject);
251                                                 subject.set_attr("xml:lang", match lang.as_ref() {
252                                                     "" => None,
253                                                     lang => Some(lang),
254                                                 });
255                                                 subject
256                                             })
257                                        .collect::<Vec<_>>())
258                .append(message.bodies.into_iter()
259                                      .map(|(lang, body)| {
260                                               let mut body = Element::from(body);
261                                               body.set_attr("xml:lang", match lang.as_ref() {
262                                                   "" => None,
263                                                   lang => Some(lang),
264                                               });
265                                               body
266                                           })
267                                      .collect::<Vec<_>>())
268                .append(message.payloads)
269                .build()
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276    use std::str::FromStr;
277    use compare_elements::NamespaceAwareCompare;
278
279    #[test]
280    fn test_simple() {
281        #[cfg(not(feature = "component"))]
282        let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
283        #[cfg(feature = "component")]
284        let elem: Element = "<message xmlns='jabber:component:accept'/>".parse().unwrap();
285        let message = Message::try_from(elem).unwrap();
286        assert_eq!(message.from, None);
287        assert_eq!(message.to, None);
288        assert_eq!(message.id, None);
289        assert_eq!(message.type_, MessageType::Normal);
290        assert!(message.payloads.is_empty());
291    }
292
293    #[test]
294    fn test_serialise() {
295        #[cfg(not(feature = "component"))]
296        let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
297        #[cfg(feature = "component")]
298        let elem: Element = "<message xmlns='jabber:component:accept'/>".parse().unwrap();
299        let mut message = Message::new(None);
300        message.type_ = MessageType::Normal;
301        let elem2 = message.into();
302        assert_eq!(elem, elem2);
303    }
304
305    #[test]
306    fn test_body() {
307        #[cfg(not(feature = "component"))]
308        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
309        #[cfg(feature = "component")]
310        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
311        let elem1 = elem.clone();
312        let message = Message::try_from(elem).unwrap();
313        assert_eq!(message.bodies[""], Body::from_str("Hello world!").unwrap());
314
315        {
316            let (lang, body) = message.get_best_body(vec!("en")).unwrap();
317            assert_eq!(lang, "");
318            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
319        }
320
321        let elem2 = message.into();
322        assert!(elem1.compare_to(&elem2));
323    }
324
325    #[test]
326    fn test_serialise_body() {
327        #[cfg(not(feature = "component"))]
328        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
329        #[cfg(feature = "component")]
330        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
331        let mut message = Message::new(Some(Jid::from_str("coucou@example.org").unwrap()));
332        message.bodies.insert(String::from(""), Body::from_str("Hello world!").unwrap());
333        let elem2 = message.into();
334        assert!(elem.compare_to(&elem2));
335    }
336
337    #[test]
338    fn test_subject() {
339        #[cfg(not(feature = "component"))]
340        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
341        #[cfg(feature = "component")]
342        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
343        let elem1 = elem.clone();
344        let message = Message::try_from(elem).unwrap();
345        assert_eq!(message.subjects[""], Subject::from_str("Hello world!").unwrap());
346
347        {
348            let (lang, subject) = message.get_best_subject(vec!("en")).unwrap();
349            assert_eq!(lang, "");
350            assert_eq!(subject, &Subject::from_str("Hello world!").unwrap());
351        }
352
353        let elem2 = message.into();
354        assert!(elem1.compare_to(&elem2));
355    }
356
357    #[test]
358    fn get_best_body() {
359        #[cfg(not(feature = "component"))]
360        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body xml:lang='de'>Hallo Welt!</body><body xml:lang='fr'>Salut le monde !</body><body>Hello world!</body></message>".parse().unwrap();
361        #[cfg(feature = "component")]
362        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
363        let message = Message::try_from(elem).unwrap();
364
365        // Tests basic feature.
366        {
367            let (lang, body) = message.get_best_body(vec!("fr")).unwrap();
368            assert_eq!(lang, "fr");
369            assert_eq!(body, &Body::from_str("Salut le monde !").unwrap());
370        }
371
372        // Tests order.
373        {
374            let (lang, body) = message.get_best_body(vec!("en", "de")).unwrap();
375            assert_eq!(lang, "de");
376            assert_eq!(body, &Body::from_str("Hallo Welt!").unwrap());
377        }
378
379        // Tests fallback.
380        {
381            let (lang, body) = message.get_best_body(vec!()).unwrap();
382            assert_eq!(lang, "");
383            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
384        }
385
386        // Tests fallback.
387        {
388            let (lang, body) = message.get_best_body(vec!("ja")).unwrap();
389            assert_eq!(lang, "");
390            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
391        }
392
393        let message = Message::new(None);
394
395        // Tests without a body.
396        assert_eq!(message.get_best_body(vec!("ja")), None);
397    }
398
399    #[test]
400    fn test_attention() {
401        #[cfg(not(feature = "component"))]
402        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
403        #[cfg(feature = "component")]
404        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
405        let elem1 = elem.clone();
406        let message = Message::try_from(elem).unwrap();
407        let elem2 = message.into();
408        assert_eq!(elem1, elem2);
409    }
410}