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::Element;
9use jid::Jid;
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
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use std::str::FromStr;
337
338 #[cfg(target_pointer_width = "32")]
339 #[test]
340 fn test_size() {
341 assert_size!(MessageType, 1);
342 assert_size!(Body, 12);
343 assert_size!(Subject, 12);
344 assert_size!(Thread, 12);
345 assert_size!(Message, 96);
346 }
347
348 #[cfg(target_pointer_width = "64")]
349 #[test]
350 fn test_size() {
351 assert_size!(MessageType, 1);
352 assert_size!(Body, 24);
353 assert_size!(Subject, 24);
354 assert_size!(Thread, 24);
355 assert_size!(Message, 192);
356 }
357
358 #[test]
359 fn test_simple() {
360 #[cfg(not(feature = "component"))]
361 let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
362 #[cfg(feature = "component")]
363 let elem: Element = "<message xmlns='jabber:component:accept'/>"
364 .parse()
365 .unwrap();
366 let message = Message::try_from(elem).unwrap();
367 assert_eq!(message.from, None);
368 assert_eq!(message.to, None);
369 assert_eq!(message.id, None);
370 assert_eq!(message.type_, MessageType::Normal);
371 assert!(message.payloads.is_empty());
372 }
373
374 #[test]
375 fn test_serialise() {
376 #[cfg(not(feature = "component"))]
377 let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
378 #[cfg(feature = "component")]
379 let elem: Element = "<message xmlns='jabber:component:accept'/>"
380 .parse()
381 .unwrap();
382 let mut message = Message::new(None);
383 message.type_ = MessageType::Normal;
384 let elem2 = message.into();
385 assert_eq!(elem, elem2);
386 }
387
388 #[test]
389 fn test_body() {
390 #[cfg(not(feature = "component"))]
391 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
392 #[cfg(feature = "component")]
393 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
394 let elem1 = elem.clone();
395 let message = Message::try_from(elem).unwrap();
396 assert_eq!(message.bodies[""], Body::from_str("Hello world!").unwrap());
397
398 {
399 let (lang, body) = message.get_best_body(vec!["en"]).unwrap();
400 assert_eq!(lang, "");
401 assert_eq!(body, &Body::from_str("Hello world!").unwrap());
402 }
403
404 let elem2 = message.into();
405 assert_eq!(elem1, elem2);
406 }
407
408 #[test]
409 fn test_serialise_body() {
410 #[cfg(not(feature = "component"))]
411 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
412 #[cfg(feature = "component")]
413 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
414 let mut message = Message::new(Jid::new("coucou@example.org").unwrap());
415 message
416 .bodies
417 .insert(String::from(""), Body::from_str("Hello world!").unwrap());
418 let elem2 = message.into();
419 assert_eq!(elem, elem2);
420 }
421
422 #[test]
423 fn test_subject() {
424 #[cfg(not(feature = "component"))]
425 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
426 #[cfg(feature = "component")]
427 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
428 let elem1 = elem.clone();
429 let message = Message::try_from(elem).unwrap();
430 assert_eq!(
431 message.subjects[""],
432 Subject::from_str("Hello world!").unwrap()
433 );
434
435 {
436 let (lang, subject) = message.get_best_subject(vec!["en"]).unwrap();
437 assert_eq!(lang, "");
438 assert_eq!(subject, &Subject::from_str("Hello world!").unwrap());
439 }
440
441 let elem2 = message.into();
442 assert_eq!(elem1, elem2);
443 }
444
445 #[test]
446 fn get_best_body() {
447 #[cfg(not(feature = "component"))]
448 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();
449 #[cfg(feature = "component")]
450 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
451 let message = Message::try_from(elem).unwrap();
452
453 // Tests basic feature.
454 {
455 let (lang, body) = message.get_best_body(vec!["fr"]).unwrap();
456 assert_eq!(lang, "fr");
457 assert_eq!(body, &Body::from_str("Salut le monde !").unwrap());
458 }
459
460 // Tests order.
461 {
462 let (lang, body) = message.get_best_body(vec!["en", "de"]).unwrap();
463 assert_eq!(lang, "de");
464 assert_eq!(body, &Body::from_str("Hallo Welt!").unwrap());
465 }
466
467 // Tests fallback.
468 {
469 let (lang, body) = message.get_best_body(vec![]).unwrap();
470 assert_eq!(lang, "");
471 assert_eq!(body, &Body::from_str("Hello world!").unwrap());
472 }
473
474 // Tests fallback.
475 {
476 let (lang, body) = message.get_best_body(vec!["ja"]).unwrap();
477 assert_eq!(lang, "");
478 assert_eq!(body, &Body::from_str("Hello world!").unwrap());
479 }
480
481 let message = Message::new(None);
482
483 // Tests without a body.
484 assert_eq!(message.get_best_body(vec!("ja")), None);
485 }
486
487 #[test]
488 fn test_attention() {
489 #[cfg(not(feature = "component"))]
490 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
491 #[cfg(feature = "component")]
492 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
493 let elem1 = elem.clone();
494 let message = Message::try_from(elem).unwrap();
495 let elem2 = message.into();
496 assert_eq!(elem1, elem2);
497 }
498
499 #[test]
500 fn test_extract_payload() {
501 use super::super::attention::Attention;
502 use super::super::pubsub::event::PubSubEvent;
503
504 #[cfg(not(feature = "component"))]
505 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
506 #[cfg(feature = "component")]
507 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
508 let mut message = Message::try_from(elem).unwrap();
509 assert_eq!(message.payloads.len(), 1);
510 match message.extract_payload::<PubSubEvent>() {
511 Ok(None) => (),
512 other => panic!("unexpected result: {:?}", other),
513 };
514 assert_eq!(message.payloads.len(), 1);
515 match message.extract_payload::<Attention>() {
516 Ok(Some(_)) => (),
517 other => panic!("unexpected result: {:?}", other),
518 };
519 assert_eq!(message.payloads.len(), 0);
520 }
521}