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