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