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
209impl TryFrom<Element> for Message {
210 type Error = Error;
211
212 fn try_from(root: Element) -> Result<Message, Error> {
213 check_self!(root, "message", DEFAULT_NS);
214 let from = get_attr!(root, "from", Option);
215 let to = get_attr!(root, "to", Option);
216 let id = get_attr!(root, "id", Option);
217 let type_ = get_attr!(root, "type", Default);
218 let mut bodies = BTreeMap::new();
219 let mut subjects = BTreeMap::new();
220 let mut thread = None;
221 let mut payloads = vec![];
222 for elem in root.children() {
223 if elem.is("body", ns::DEFAULT_NS) {
224 check_no_children!(elem, "body");
225 let lang = get_attr!(elem, "xml:lang", Default);
226 let body = Body(elem.text());
227 if bodies.insert(lang, body).is_some() {
228 return Err(Error::ParseError(
229 "Body element present twice for the same xml:lang.",
230 ));
231 }
232 } else if elem.is("subject", ns::DEFAULT_NS) {
233 check_no_children!(elem, "subject");
234 let lang = get_attr!(elem, "xml:lang", Default);
235 let subject = Subject(elem.text());
236 if subjects.insert(lang, subject).is_some() {
237 return Err(Error::ParseError(
238 "Subject element present twice for the same xml:lang.",
239 ));
240 }
241 } else if elem.is("thread", ns::DEFAULT_NS) {
242 if thread.is_some() {
243 return Err(Error::ParseError("Thread element present twice."));
244 }
245 check_no_children!(elem, "thread");
246 thread = Some(Thread(elem.text()));
247 } else {
248 payloads.push(elem.clone())
249 }
250 }
251 Ok(Message {
252 from,
253 to,
254 id,
255 type_,
256 bodies,
257 subjects,
258 thread,
259 payloads,
260 })
261 }
262}
263
264impl From<Message> for Element {
265 fn from(message: Message) -> Element {
266 Element::builder("message", ns::DEFAULT_NS)
267 .attr("from", message.from)
268 .attr("to", message.to)
269 .attr("id", message.id)
270 .attr("type", message.type_)
271 .append_all(message.subjects.into_iter().map(|(lang, subject)| {
272 let mut subject = Element::from(subject);
273 subject.set_attr(
274 "xml:lang",
275 match lang.as_ref() {
276 "" => None,
277 lang => Some(lang),
278 },
279 );
280 subject
281 }))
282 .append_all(message.bodies.into_iter().map(|(lang, body)| {
283 let mut body = Element::from(body);
284 body.set_attr(
285 "xml:lang",
286 match lang.as_ref() {
287 "" => None,
288 lang => Some(lang),
289 },
290 );
291 body
292 }))
293 .append_all(message.payloads)
294 .build()
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301 use std::str::FromStr;
302
303 #[cfg(target_pointer_width = "32")]
304 #[test]
305 fn test_size() {
306 assert_size!(MessageType, 1);
307 assert_size!(Body, 12);
308 assert_size!(Subject, 12);
309 assert_size!(Thread, 12);
310 assert_size!(Message, 104);
311 }
312
313 #[cfg(target_pointer_width = "64")]
314 #[test]
315 fn test_size() {
316 assert_size!(MessageType, 1);
317 assert_size!(Body, 24);
318 assert_size!(Subject, 24);
319 assert_size!(Thread, 24);
320 assert_size!(Message, 208);
321 }
322
323 #[test]
324 fn test_simple() {
325 #[cfg(not(feature = "component"))]
326 let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
327 #[cfg(feature = "component")]
328 let elem: Element = "<message xmlns='jabber:component:accept'/>"
329 .parse()
330 .unwrap();
331 let message = Message::try_from(elem).unwrap();
332 assert_eq!(message.from, None);
333 assert_eq!(message.to, None);
334 assert_eq!(message.id, None);
335 assert_eq!(message.type_, MessageType::Normal);
336 assert!(message.payloads.is_empty());
337 }
338
339 #[test]
340 fn test_serialise() {
341 #[cfg(not(feature = "component"))]
342 let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
343 #[cfg(feature = "component")]
344 let elem: Element = "<message xmlns='jabber:component:accept'/>"
345 .parse()
346 .unwrap();
347 let mut message = Message::new(None);
348 message.type_ = MessageType::Normal;
349 let elem2 = message.into();
350 assert_eq!(elem, elem2);
351 }
352
353 #[test]
354 fn test_body() {
355 #[cfg(not(feature = "component"))]
356 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
357 #[cfg(feature = "component")]
358 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
359 let elem1 = elem.clone();
360 let message = Message::try_from(elem).unwrap();
361 assert_eq!(message.bodies[""], Body::from_str("Hello world!").unwrap());
362
363 {
364 let (lang, body) = message.get_best_body(vec!["en"]).unwrap();
365 assert_eq!(lang, "");
366 assert_eq!(body, &Body::from_str("Hello world!").unwrap());
367 }
368
369 let elem2 = message.into();
370 assert_eq!(elem1, elem2);
371 }
372
373 #[test]
374 fn test_serialise_body() {
375 #[cfg(not(feature = "component"))]
376 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
377 #[cfg(feature = "component")]
378 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
379 let mut message = Message::new(Jid::new("coucou@example.org").unwrap());
380 message
381 .bodies
382 .insert(String::from(""), Body::from_str("Hello world!").unwrap());
383 let elem2 = message.into();
384 assert_eq!(elem, elem2);
385 }
386
387 #[test]
388 fn test_subject() {
389 #[cfg(not(feature = "component"))]
390 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
391 #[cfg(feature = "component")]
392 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
393 let elem1 = elem.clone();
394 let message = Message::try_from(elem).unwrap();
395 assert_eq!(
396 message.subjects[""],
397 Subject::from_str("Hello world!").unwrap()
398 );
399
400 {
401 let (lang, subject) = message.get_best_subject(vec!["en"]).unwrap();
402 assert_eq!(lang, "");
403 assert_eq!(subject, &Subject::from_str("Hello world!").unwrap());
404 }
405
406 let elem2 = message.into();
407 assert_eq!(elem1, elem2);
408 }
409
410 #[test]
411 fn get_best_body() {
412 #[cfg(not(feature = "component"))]
413 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();
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 message = Message::try_from(elem).unwrap();
417
418 // Tests basic feature.
419 {
420 let (lang, body) = message.get_best_body(vec!["fr"]).unwrap();
421 assert_eq!(lang, "fr");
422 assert_eq!(body, &Body::from_str("Salut le monde !").unwrap());
423 }
424
425 // Tests order.
426 {
427 let (lang, body) = message.get_best_body(vec!["en", "de"]).unwrap();
428 assert_eq!(lang, "de");
429 assert_eq!(body, &Body::from_str("Hallo Welt!").unwrap());
430 }
431
432 // Tests fallback.
433 {
434 let (lang, body) = message.get_best_body(vec![]).unwrap();
435 assert_eq!(lang, "");
436 assert_eq!(body, &Body::from_str("Hello world!").unwrap());
437 }
438
439 // Tests fallback.
440 {
441 let (lang, body) = message.get_best_body(vec!["ja"]).unwrap();
442 assert_eq!(lang, "");
443 assert_eq!(body, &Body::from_str("Hello world!").unwrap());
444 }
445
446 let message = Message::new(None);
447
448 // Tests without a body.
449 assert_eq!(message.get_best_body(vec!("ja")), None);
450 }
451
452 #[test]
453 fn test_attention() {
454 #[cfg(not(feature = "component"))]
455 let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
456 #[cfg(feature = "component")]
457 let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
458 let elem1 = elem.clone();
459 let message = Message::try_from(elem).unwrap();
460 let elem2 = message.into();
461 assert_eq!(elem1, elem2);
462 }
463}