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 crate::ns;
  8use crate::util::error::Error;
  9use crate::Element;
 10use jid::Jid;
 11use std::collections::BTreeMap;
 12
 13/// Should be implemented on every known payload of a `<message/>`.
 14pub trait MessagePayload: TryFrom<Element> + Into<Element> {}
 15
 16generate_attribute!(
 17    /// The type of a message.
 18    MessageType, "type", {
 19        /// Standard instant messaging message.
 20        Chat => "chat",
 21
 22        /// Notifies that an error happened.
 23        Error => "error",
 24
 25        /// Standard group instant messaging message.
 26        Groupchat => "groupchat",
 27
 28        /// Used by servers to notify users when things happen.
 29        Headline => "headline",
 30
 31        /// This is an email-like message, it usually contains a
 32        /// [subject](struct.Subject.html).
 33        Normal => "normal",
 34    }, Default = Normal
 35);
 36
 37type Lang = String;
 38
 39generate_elem_id!(
 40    /// Represents one `<body/>` element, that is the free form text content of
 41    /// a message.
 42    Body,
 43    "body",
 44    DEFAULT_NS
 45);
 46
 47generate_elem_id!(
 48    /// Defines the subject of a room, or of an email-like normal message.
 49    Subject,
 50    "subject",
 51    DEFAULT_NS
 52);
 53
 54generate_elem_id!(
 55    /// A thread identifier, so that other people can specify to which message
 56    /// they are replying.
 57    Thread,
 58    "thread",
 59    DEFAULT_NS
 60);
 61
 62/// The main structure representing the `<message/>` stanza.
 63#[derive(Debug, Clone, PartialEq)]
 64pub struct Message {
 65    /// The JID emitting this stanza.
 66    pub from: Option<Jid>,
 67
 68    /// The recipient of this stanza.
 69    pub to: Option<Jid>,
 70
 71    /// The @id attribute of this stanza, which is required in order to match a
 72    /// request with its response.
 73    pub id: Option<String>,
 74
 75    /// The type of this message.
 76    pub type_: MessageType,
 77
 78    /// A list of bodies, sorted per language.  Use
 79    /// [get_best_body()](#method.get_best_body) to access them on reception.
 80    pub bodies: BTreeMap<Lang, Body>,
 81
 82    /// A list of subjects, sorted per language.  Use
 83    /// [get_best_subject()](#method.get_best_subject) to access them on
 84    /// reception.
 85    pub subjects: BTreeMap<Lang, Subject>,
 86
 87    /// An optional thread identifier, so that other people can reply directly
 88    /// to this message.
 89    pub thread: Option<Thread>,
 90
 91    /// A list of the extension payloads contained in this stanza.
 92    pub payloads: Vec<Element>,
 93}
 94
 95impl Message {
 96    /// Creates a new `<message/>` stanza of type Chat for the given recipient.
 97    /// This is equivalent to the [`Message::chat`] method.
 98    pub fn new<J: Into<Option<Jid>>>(to: J) -> Message {
 99        Message {
100            from: None,
101            to: to.into(),
102            id: None,
103            type_: MessageType::Chat,
104            bodies: BTreeMap::new(),
105            subjects: BTreeMap::new(),
106            thread: None,
107            payloads: vec![],
108        }
109    }
110
111    /// Creates a new `<message/>` stanza of a certain type for the given recipient.
112    pub fn new_with_type<J: Into<Option<Jid>>>(type_: MessageType, to: J) -> Message {
113        Message {
114            from: None,
115            to: to.into(),
116            id: None,
117            type_,
118            bodies: BTreeMap::new(),
119            subjects: BTreeMap::new(),
120            thread: None,
121            payloads: vec![],
122        }
123    }
124
125    /// Creates a Message of type Chat
126    pub fn chat<J: Into<Option<Jid>>>(to: J) -> Message {
127        Self::new_with_type(MessageType::Chat, to)
128    }
129
130    /// Creates a Message of type Error
131    pub fn error<J: Into<Option<Jid>>>(to: J) -> Message {
132        Self::new_with_type(MessageType::Error, to)
133    }
134
135    /// Creates a Message of type Groupchat
136    pub fn groupchat<J: Into<Option<Jid>>>(to: J) -> Message {
137        Self::new_with_type(MessageType::Groupchat, to)
138    }
139
140    /// Creates a Message of type Headline
141    pub fn headline<J: Into<Option<Jid>>>(to: J) -> Message {
142        Self::new_with_type(MessageType::Headline, to)
143    }
144
145    /// Creates a Message of type Normal
146    pub fn normal<J: Into<Option<Jid>>>(to: J) -> Message {
147        Self::new_with_type(MessageType::Normal, to)
148    }
149
150    /// Appends a body in given lang to the Message
151    pub fn with_body(mut self, lang: Lang, body: String) -> Message {
152        self.bodies.insert(lang, Body(body));
153        self
154    }
155
156    /// Set a payload inside this message.
157    pub fn with_payload<P: MessagePayload>(mut self, payload: P) -> Message {
158        self.payloads.push(payload.into());
159        self
160    }
161
162    /// Set the payloads of this message.
163    pub fn with_payloads(mut self, payloads: Vec<Element>) -> Message {
164        self.payloads = payloads;
165        self
166    }
167
168    fn get_best<'a, T>(
169        map: &'a BTreeMap<Lang, T>,
170        preferred_langs: Vec<&str>,
171    ) -> Option<(Lang, &'a T)> {
172        if map.is_empty() {
173            return None;
174        }
175        for lang in preferred_langs {
176            if let Some(value) = map.get(lang) {
177                return Some((Lang::from(lang), value));
178            }
179        }
180        if let Some(value) = map.get("") {
181            return Some((Lang::new(), value));
182        }
183        map.iter().map(|(lang, value)| (lang.clone(), value)).next()
184    }
185
186    /// Returns the best matching body from a list of languages.
187    ///
188    /// For instance, if a message contains both an xml:lang='de', an xml:lang='fr' and an English
189    /// body without an xml:lang attribute, and you pass ["fr", "en"] as your preferred languages,
190    /// `Some(("fr", the_second_body))` will be returned.
191    ///
192    /// If no body matches, an undefined body will be returned.
193    pub fn get_best_body(&self, preferred_langs: Vec<&str>) -> Option<(Lang, &Body)> {
194        Message::get_best::<Body>(&self.bodies, preferred_langs)
195    }
196
197    /// Returns the best matching subject from a list of languages.
198    ///
199    /// For instance, if a message contains both an xml:lang='de', an xml:lang='fr' and an English
200    /// subject without an xml:lang attribute, and you pass ["fr", "en"] as your preferred
201    /// languages, `Some(("fr", the_second_subject))` will be returned.
202    ///
203    /// If no subject matches, an undefined subject will be returned.
204    pub fn get_best_subject(&self, preferred_langs: Vec<&str>) -> Option<(Lang, &Subject)> {
205        Message::get_best::<Subject>(&self.subjects, preferred_langs)
206    }
207
208    /// Try to extract the given payload type from the message's payloads.
209    ///
210    /// Returns the first matching payload element as parsed struct or its
211    /// parse error. If no element matches, `Ok(None)` is returned. If an
212    /// element matches, but fails to parse, it is nonetheless removed from
213    /// the message.
214    ///
215    /// Elements which do not match the given type are not removed.
216    pub fn extract_payload<T: TryFrom<Element, Error = Error>>(
217        &mut self,
218    ) -> Result<Option<T>, Error> {
219        let mut buf = Vec::with_capacity(self.payloads.len());
220        let mut iter = self.payloads.drain(..);
221        let mut result = Ok(None);
222        for item in &mut iter {
223            match T::try_from(item) {
224                Ok(v) => {
225                    result = Ok(Some(v));
226                    break;
227                }
228                Err(Error::TypeMismatch(_, _, residual)) => {
229                    buf.push(residual);
230                }
231                Err(other) => {
232                    result = Err(other);
233                    break;
234                }
235            }
236        }
237        buf.extend(iter);
238        std::mem::swap(&mut buf, &mut self.payloads);
239        result
240    }
241}
242
243impl TryFrom<Element> for Message {
244    type Error = Error;
245
246    fn try_from(root: Element) -> Result<Message, Error> {
247        check_self!(root, "message", DEFAULT_NS);
248        let from = get_attr!(root, "from", Option);
249        let to = get_attr!(root, "to", Option);
250        let id = get_attr!(root, "id", Option);
251        let type_ = get_attr!(root, "type", Default);
252        let mut bodies = BTreeMap::new();
253        let mut subjects = BTreeMap::new();
254        let mut thread = None;
255        let mut payloads = vec![];
256        for elem in root.children() {
257            if elem.is("body", ns::DEFAULT_NS) {
258                check_no_children!(elem, "body");
259                let lang = get_attr!(elem, "xml:lang", Default);
260                let body = Body(elem.text());
261                if bodies.insert(lang, body).is_some() {
262                    return Err(Error::ParseError(
263                        "Body element present twice for the same xml:lang.",
264                    ));
265                }
266            } else if elem.is("subject", ns::DEFAULT_NS) {
267                check_no_children!(elem, "subject");
268                let lang = get_attr!(elem, "xml:lang", Default);
269                let subject = Subject(elem.text());
270                if subjects.insert(lang, subject).is_some() {
271                    return Err(Error::ParseError(
272                        "Subject element present twice for the same xml:lang.",
273                    ));
274                }
275            } else if elem.is("thread", ns::DEFAULT_NS) {
276                if thread.is_some() {
277                    return Err(Error::ParseError("Thread element present twice."));
278                }
279                check_no_children!(elem, "thread");
280                thread = Some(Thread(elem.text()));
281            } else {
282                payloads.push(elem.clone())
283            }
284        }
285        Ok(Message {
286            from,
287            to,
288            id,
289            type_,
290            bodies,
291            subjects,
292            thread,
293            payloads,
294        })
295    }
296}
297
298impl From<Message> for Element {
299    fn from(message: Message) -> Element {
300        Element::builder("message", ns::DEFAULT_NS)
301            .attr("from", message.from)
302            .attr("to", message.to)
303            .attr("id", message.id)
304            .attr("type", message.type_)
305            .append_all(message.subjects.into_iter().map(|(lang, subject)| {
306                let mut subject = Element::from(subject);
307                subject.set_attr(
308                    "xml:lang",
309                    match lang.as_ref() {
310                        "" => None,
311                        lang => Some(lang),
312                    },
313                );
314                subject
315            }))
316            .append_all(message.bodies.into_iter().map(|(lang, body)| {
317                let mut body = Element::from(body);
318                body.set_attr(
319                    "xml:lang",
320                    match lang.as_ref() {
321                        "" => None,
322                        lang => Some(lang),
323                    },
324                );
325                body
326            }))
327            .append_all(message.payloads)
328            .build()
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use std::str::FromStr;
336
337    #[cfg(target_pointer_width = "32")]
338    #[test]
339    fn test_size() {
340        assert_size!(MessageType, 1);
341        assert_size!(Body, 12);
342        assert_size!(Subject, 12);
343        assert_size!(Thread, 12);
344        assert_size!(Message, 96);
345    }
346
347    #[cfg(target_pointer_width = "64")]
348    #[test]
349    fn test_size() {
350        assert_size!(MessageType, 1);
351        assert_size!(Body, 24);
352        assert_size!(Subject, 24);
353        assert_size!(Thread, 24);
354        assert_size!(Message, 192);
355    }
356
357    #[test]
358    fn test_simple() {
359        #[cfg(not(feature = "component"))]
360        let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
361        #[cfg(feature = "component")]
362        let elem: Element = "<message xmlns='jabber:component:accept'/>"
363            .parse()
364            .unwrap();
365        let message = Message::try_from(elem).unwrap();
366        assert_eq!(message.from, None);
367        assert_eq!(message.to, None);
368        assert_eq!(message.id, None);
369        assert_eq!(message.type_, MessageType::Normal);
370        assert!(message.payloads.is_empty());
371    }
372
373    #[test]
374    fn test_serialise() {
375        #[cfg(not(feature = "component"))]
376        let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
377        #[cfg(feature = "component")]
378        let elem: Element = "<message xmlns='jabber:component:accept'/>"
379            .parse()
380            .unwrap();
381        let mut message = Message::new(None);
382        message.type_ = MessageType::Normal;
383        let elem2 = message.into();
384        assert_eq!(elem, elem2);
385    }
386
387    #[test]
388    fn test_body() {
389        #[cfg(not(feature = "component"))]
390        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
391        #[cfg(feature = "component")]
392        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
393        let elem1 = elem.clone();
394        let message = Message::try_from(elem).unwrap();
395        assert_eq!(message.bodies[""], Body::from_str("Hello world!").unwrap());
396
397        {
398            let (lang, body) = message.get_best_body(vec!["en"]).unwrap();
399            assert_eq!(lang, "");
400            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
401        }
402
403        let elem2 = message.into();
404        assert_eq!(elem1, elem2);
405    }
406
407    #[test]
408    fn test_serialise_body() {
409        #[cfg(not(feature = "component"))]
410        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
411        #[cfg(feature = "component")]
412        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
413        let mut message = Message::new(Jid::new("coucou@example.org").unwrap());
414        message
415            .bodies
416            .insert(String::from(""), Body::from_str("Hello world!").unwrap());
417        let elem2 = message.into();
418        assert_eq!(elem, elem2);
419    }
420
421    #[test]
422    fn test_subject() {
423        #[cfg(not(feature = "component"))]
424        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
425        #[cfg(feature = "component")]
426        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
427        let elem1 = elem.clone();
428        let message = Message::try_from(elem).unwrap();
429        assert_eq!(
430            message.subjects[""],
431            Subject::from_str("Hello world!").unwrap()
432        );
433
434        {
435            let (lang, subject) = message.get_best_subject(vec!["en"]).unwrap();
436            assert_eq!(lang, "");
437            assert_eq!(subject, &Subject::from_str("Hello world!").unwrap());
438        }
439
440        let elem2 = message.into();
441        assert_eq!(elem1, elem2);
442    }
443
444    #[test]
445    fn get_best_body() {
446        #[cfg(not(feature = "component"))]
447        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();
448        #[cfg(feature = "component")]
449        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
450        let message = Message::try_from(elem).unwrap();
451
452        // Tests basic feature.
453        {
454            let (lang, body) = message.get_best_body(vec!["fr"]).unwrap();
455            assert_eq!(lang, "fr");
456            assert_eq!(body, &Body::from_str("Salut le monde !").unwrap());
457        }
458
459        // Tests order.
460        {
461            let (lang, body) = message.get_best_body(vec!["en", "de"]).unwrap();
462            assert_eq!(lang, "de");
463            assert_eq!(body, &Body::from_str("Hallo Welt!").unwrap());
464        }
465
466        // Tests fallback.
467        {
468            let (lang, body) = message.get_best_body(vec![]).unwrap();
469            assert_eq!(lang, "");
470            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
471        }
472
473        // Tests fallback.
474        {
475            let (lang, body) = message.get_best_body(vec!["ja"]).unwrap();
476            assert_eq!(lang, "");
477            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
478        }
479
480        let message = Message::new(None);
481
482        // Tests without a body.
483        assert_eq!(message.get_best_body(vec!("ja")), None);
484    }
485
486    #[test]
487    fn test_attention() {
488        #[cfg(not(feature = "component"))]
489        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
490        #[cfg(feature = "component")]
491        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
492        let elem1 = elem.clone();
493        let message = Message::try_from(elem).unwrap();
494        let elem2 = message.into();
495        assert_eq!(elem1, elem2);
496    }
497
498    #[test]
499    fn test_extract_payload() {
500        use super::super::attention::Attention;
501        use super::super::pubsub::event::PubSubEvent;
502
503        #[cfg(not(feature = "component"))]
504        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
505        #[cfg(feature = "component")]
506        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
507        let mut message = Message::try_from(elem).unwrap();
508        assert_eq!(message.payloads.len(), 1);
509        match message.extract_payload::<PubSubEvent>() {
510            Ok(None) => (),
511            other => panic!("unexpected result: {:?}", other),
512        };
513        assert_eq!(message.payloads.len(), 1);
514        match message.extract_payload::<Attention>() {
515            Ok(Some(_)) => (),
516            other => panic!("unexpected result: {:?}", other),
517        };
518        assert_eq!(message.payloads.len(), 0);
519    }
520}