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