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 check_self!(root, "message", ns::DEFAULT_NS);
193 let from = get_attr!(root, "from", optional);
194 let to = get_attr!(root, "to", optional);
195 let id = get_attr!(root, "id", optional);
196 let type_ = get_attr!(root, "type", default);
197 let mut bodies = BTreeMap::new();
198 let mut subjects = BTreeMap::new();
199 let mut thread = None;
200 let mut payloads = vec!();
201 for elem in root.children() {
202 if elem.is("body", ns::DEFAULT_NS) {
203 for _ in elem.children() {
204 return Err(Error::ParseError("Unknown child in body element."));
205 }
206 let lang = get_attr!(elem, "xml:lang", default);
207 let body = Body(elem.text());
208 if bodies.insert(lang, body).is_some() {
209 return Err(Error::ParseError("Body element present twice for the same xml:lang."));
210 }
211 } else if elem.is("subject", ns::DEFAULT_NS) {
212 for _ in elem.children() {
213 return Err(Error::ParseError("Unknown child in subject element."));
214 }
215 let lang = get_attr!(elem, "xml:lang", default);
216 let subject = Subject(elem.text());
217 if subjects.insert(lang, subject).is_some() {
218 return Err(Error::ParseError("Subject element present twice for the same xml:lang."));
219 }
220 } else if elem.is("thread", ns::DEFAULT_NS) {
221 if thread.is_some() {
222 return Err(Error::ParseError("Thread element present twice."));
223 }
224 for _ in elem.children() {
225 return Err(Error::ParseError("Unknown child in thread element."));
226 }
227 thread = Some(Thread(elem.text()));
228 } else {
229 payloads.push(elem.clone())
230 }
231 }
232 Ok(Message {
233 from: from,
234 to: to,
235 id: id,
236 type_: type_,
237 bodies: bodies,
238 subjects: subjects,
239 thread: thread,
240 payloads: payloads,
241 })
242 }
243}
244
245impl From<Message> for Element {
246 fn from(message: Message) -> Element {
247 Element::builder("message")
248 .ns(ns::DEFAULT_NS)
249 .attr("from", message.from)
250 .attr("to", message.to)
251 .attr("id", message.id)
252 .attr("type", message.type_)
253 .append(message.subjects.into_iter()
254 .map(|(lang, subject)| {
255 let mut subject = Element::from(subject);
256 subject.set_attr("xml:lang", match lang.as_ref() {
257 "" => None,
258 lang => Some(lang),
259 });
260 subject
261 })
262 .collect::<Vec<_>>())
263 .append(message.bodies.into_iter()
264 .map(|(lang, body)| {
265 let mut body = Element::from(body);
266 body.set_attr("xml:lang", match lang.as_ref() {
267 "" => None,
268 lang => Some(lang),
269 });
270 body
271 })
272 .collect::<Vec<_>>())
273 .append(message.payloads)
274 .build()
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
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}