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 jid::Jid;
  9use minidom::Element;
 10use std::collections::BTreeMap;
 11use xso::error::{Error, FromElementError};
 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 = FromElementError>>(
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(FromElementError::Mismatch(residual)) => {
229                    buf.push(residual);
230                }
231                Err(FromElementError::Invalid(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 = FromElementError;
245
246    fn try_from(root: Element) -> Result<Message, FromElementError> {
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(
263                        Error::Other("Body element present twice for the same xml:lang.").into(),
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::Other(
272                        "Subject element present twice for the same xml:lang.",
273                    )
274                    .into());
275                }
276            } else if elem.is("thread", ns::DEFAULT_NS) {
277                if thread.is_some() {
278                    return Err(Error::Other("Thread element present twice.").into());
279                }
280                check_no_children!(elem, "thread");
281                thread = Some(Thread(elem.text()));
282            } else {
283                payloads.push(elem.clone())
284            }
285        }
286        Ok(Message {
287            from,
288            to,
289            id,
290            type_,
291            bodies,
292            subjects,
293            thread,
294            payloads,
295        })
296    }
297}
298
299impl From<Message> for Element {
300    fn from(message: Message) -> Element {
301        Element::builder("message", ns::DEFAULT_NS)
302            .attr("from", message.from)
303            .attr("to", message.to)
304            .attr("id", message.id)
305            .attr("type", message.type_)
306            .append_all(message.subjects.into_iter().map(|(lang, subject)| {
307                let mut subject = Element::from(subject);
308                subject.set_attr(
309                    "xml:lang",
310                    match lang.as_ref() {
311                        "" => None,
312                        lang => Some(lang),
313                    },
314                );
315                subject
316            }))
317            .append_all(message.bodies.into_iter().map(|(lang, body)| {
318                let mut body = Element::from(body);
319                body.set_attr(
320                    "xml:lang",
321                    match lang.as_ref() {
322                        "" => None,
323                        lang => Some(lang),
324                    },
325                );
326                body
327            }))
328            .append_all(message.payloads)
329            .build()
330    }
331}
332
333impl ::xso::FromXml for Message {
334    type Builder = ::xso::minidom_compat::FromEventsViaElement<Message>;
335
336    fn from_events(
337        qname: ::xso::exports::rxml::QName,
338        attrs: ::xso::exports::rxml::AttrMap,
339    ) -> Result<Self::Builder, ::xso::error::FromEventsError> {
340        if qname.0 != crate::ns::DEFAULT_NS || qname.1 != "message" {
341            return Err(::xso::error::FromEventsError::Mismatch { name: qname, attrs });
342        }
343        Self::Builder::new(qname, attrs)
344    }
345}
346
347impl ::xso::AsXml for Message {
348    type ItemIter<'x> = ::xso::minidom_compat::AsItemsViaElement<'x>;
349
350    fn as_xml_iter(&self) -> Result<Self::ItemIter<'_>, ::xso::error::Error> {
351        ::xso::minidom_compat::AsItemsViaElement::new(self.clone())
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use std::str::FromStr;
359
360    #[cfg(target_pointer_width = "32")]
361    #[test]
362    fn test_size() {
363        assert_size!(MessageType, 1);
364        assert_size!(Body, 12);
365        assert_size!(Subject, 12);
366        assert_size!(Thread, 12);
367        assert_size!(Message, 96);
368    }
369
370    #[cfg(target_pointer_width = "64")]
371    #[test]
372    fn test_size() {
373        assert_size!(MessageType, 1);
374        assert_size!(Body, 24);
375        assert_size!(Subject, 24);
376        assert_size!(Thread, 24);
377        assert_size!(Message, 192);
378    }
379
380    #[test]
381    fn test_simple() {
382        #[cfg(not(feature = "component"))]
383        let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
384        #[cfg(feature = "component")]
385        let elem: Element = "<message xmlns='jabber:component:accept'/>"
386            .parse()
387            .unwrap();
388        let message = Message::try_from(elem).unwrap();
389        assert_eq!(message.from, None);
390        assert_eq!(message.to, None);
391        assert_eq!(message.id, None);
392        assert_eq!(message.type_, MessageType::Normal);
393        assert!(message.payloads.is_empty());
394    }
395
396    #[test]
397    fn test_serialise() {
398        #[cfg(not(feature = "component"))]
399        let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
400        #[cfg(feature = "component")]
401        let elem: Element = "<message xmlns='jabber:component:accept'/>"
402            .parse()
403            .unwrap();
404        let mut message = Message::new(None);
405        message.type_ = MessageType::Normal;
406        let elem2 = message.into();
407        assert_eq!(elem, elem2);
408    }
409
410    #[test]
411    fn test_body() {
412        #[cfg(not(feature = "component"))]
413        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
414        #[cfg(feature = "component")]
415        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
416        let elem1 = elem.clone();
417        let message = Message::try_from(elem).unwrap();
418        assert_eq!(message.bodies[""], Body::from_str("Hello world!").unwrap());
419
420        {
421            let (lang, body) = message.get_best_body(vec!["en"]).unwrap();
422            assert_eq!(lang, "");
423            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
424        }
425
426        let elem2 = message.into();
427        assert_eq!(elem1, elem2);
428    }
429
430    #[test]
431    fn test_serialise_body() {
432        #[cfg(not(feature = "component"))]
433        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
434        #[cfg(feature = "component")]
435        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
436        let mut message = Message::new(Jid::new("coucou@example.org").unwrap());
437        message
438            .bodies
439            .insert(String::from(""), Body::from_str("Hello world!").unwrap());
440        let elem2 = message.into();
441        assert_eq!(elem, elem2);
442    }
443
444    #[test]
445    fn test_subject() {
446        #[cfg(not(feature = "component"))]
447        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
448        #[cfg(feature = "component")]
449        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
450        let elem1 = elem.clone();
451        let message = Message::try_from(elem).unwrap();
452        assert_eq!(
453            message.subjects[""],
454            Subject::from_str("Hello world!").unwrap()
455        );
456
457        {
458            let (lang, subject) = message.get_best_subject(vec!["en"]).unwrap();
459            assert_eq!(lang, "");
460            assert_eq!(subject, &Subject::from_str("Hello world!").unwrap());
461        }
462
463        let elem2 = message.into();
464        assert_eq!(elem1, elem2);
465    }
466
467    #[test]
468    fn get_best_body() {
469        #[cfg(not(feature = "component"))]
470        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();
471        #[cfg(feature = "component")]
472        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
473        let message = Message::try_from(elem).unwrap();
474
475        // Tests basic feature.
476        {
477            let (lang, body) = message.get_best_body(vec!["fr"]).unwrap();
478            assert_eq!(lang, "fr");
479            assert_eq!(body, &Body::from_str("Salut le monde !").unwrap());
480        }
481
482        // Tests order.
483        {
484            let (lang, body) = message.get_best_body(vec!["en", "de"]).unwrap();
485            assert_eq!(lang, "de");
486            assert_eq!(body, &Body::from_str("Hallo Welt!").unwrap());
487        }
488
489        // Tests fallback.
490        {
491            let (lang, body) = message.get_best_body(vec![]).unwrap();
492            assert_eq!(lang, "");
493            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
494        }
495
496        // Tests fallback.
497        {
498            let (lang, body) = message.get_best_body(vec!["ja"]).unwrap();
499            assert_eq!(lang, "");
500            assert_eq!(body, &Body::from_str("Hello world!").unwrap());
501        }
502
503        let message = Message::new(None);
504
505        // Tests without a body.
506        assert_eq!(message.get_best_body(vec!("ja")), None);
507    }
508
509    #[test]
510    fn test_attention() {
511        #[cfg(not(feature = "component"))]
512        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
513        #[cfg(feature = "component")]
514        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
515        let elem1 = elem.clone();
516        let message = Message::try_from(elem).unwrap();
517        let elem2 = message.into();
518        assert_eq!(elem1, elem2);
519    }
520
521    #[test]
522    fn test_extract_payload() {
523        use super::super::attention::Attention;
524        use super::super::pubsub::event::PubSubEvent;
525
526        #[cfg(not(feature = "component"))]
527        let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
528        #[cfg(feature = "component")]
529        let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
530        let mut message = Message::try_from(elem).unwrap();
531        assert_eq!(message.payloads.len(), 1);
532        match message.extract_payload::<PubSubEvent>() {
533            Ok(None) => (),
534            other => panic!("unexpected result: {:?}", other),
535        };
536        assert_eq!(message.payloads.len(), 1);
537        match message.extract_payload::<Attention>() {
538            Ok(Some(_)) => (),
539            other => panic!("unexpected result: {:?}", other),
540        };
541        assert_eq!(message.payloads.len(), 0);
542    }
543}