use crate::ns;
use crate::util::error::Error;
use crate::Element;
use jid::Jid;
use std::collections::BTreeMap;
pub trait MessagePayload: TryFrom<Element> + Into<Element> {}
generate_attribute!(
MessageType, "type", {
Chat => "chat",
Error => "error",
Groupchat => "groupchat",
Headline => "headline",
Normal => "normal",
}, Default = Normal
);
type Lang = String;
generate_elem_id!(
Body,
"body",
DEFAULT_NS
);
generate_elem_id!(
Subject,
"subject",
DEFAULT_NS
);
generate_elem_id!(
Thread,
"thread",
DEFAULT_NS
);
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
pub from: Option<Jid>,
pub to: Option<Jid>,
pub id: Option<String>,
pub type_: MessageType,
pub bodies: BTreeMap<Lang, Body>,
pub subjects: BTreeMap<Lang, Subject>,
pub thread: Option<Thread>,
pub payloads: Vec<Element>,
}
impl Message {
pub fn new<J: Into<Option<Jid>>>(to: J) -> Message {
Message {
from: None,
to: to.into(),
id: None,
type_: MessageType::Chat,
bodies: BTreeMap::new(),
subjects: BTreeMap::new(),
thread: None,
payloads: vec![],
}
}
pub fn new_with_type<J: Into<Option<Jid>>>(type_: MessageType, to: J) -> Message {
Message {
from: None,
to: to.into(),
id: None,
type_,
bodies: BTreeMap::new(),
subjects: BTreeMap::new(),
thread: None,
payloads: vec![],
}
}
pub fn chat<J: Into<Option<Jid>>>(to: J) -> Message {
Self::new_with_type(MessageType::Chat, to)
}
pub fn error<J: Into<Option<Jid>>>(to: J) -> Message {
Self::new_with_type(MessageType::Error, to)
}
pub fn groupchat<J: Into<Option<Jid>>>(to: J) -> Message {
Self::new_with_type(MessageType::Groupchat, to)
}
pub fn headline<J: Into<Option<Jid>>>(to: J) -> Message {
Self::new_with_type(MessageType::Headline, to)
}
pub fn normal<J: Into<Option<Jid>>>(to: J) -> Message {
Self::new_with_type(MessageType::Normal, to)
}
pub fn with_body(mut self, lang: Lang, body: String) -> Message {
self.bodies.insert(lang, Body(body));
self
}
pub fn with_payload<P: MessagePayload>(mut self, payload: P) -> Message {
self.payloads.push(payload.into());
self
}
pub fn with_payloads(mut self, payloads: Vec<Element>) -> Message {
self.payloads = payloads;
self
}
fn get_best<'a, T>(
map: &'a BTreeMap<Lang, T>,
preferred_langs: Vec<&str>,
) -> Option<(Lang, &'a T)> {
if map.is_empty() {
return None;
}
for lang in preferred_langs {
if let Some(value) = map.get(lang) {
return Some((Lang::from(lang), value));
}
}
if let Some(value) = map.get("") {
return Some((Lang::new(), value));
}
map.iter().map(|(lang, value)| (lang.clone(), value)).next()
}
pub fn get_best_body(&self, preferred_langs: Vec<&str>) -> Option<(Lang, &Body)> {
Message::get_best::<Body>(&self.bodies, preferred_langs)
}
pub fn get_best_subject(&self, preferred_langs: Vec<&str>) -> Option<(Lang, &Subject)> {
Message::get_best::<Subject>(&self.subjects, preferred_langs)
}
pub fn extract_payload<T: TryFrom<Element, Error = Error>>(
&mut self,
) -> Result<Option<T>, Error> {
let mut buf = Vec::with_capacity(self.payloads.len());
let mut iter = self.payloads.drain(..);
let mut result = Ok(None);
for item in &mut iter {
match T::try_from(item) {
Ok(v) => {
result = Ok(Some(v));
break;
}
Err(Error::TypeMismatch(_, _, residual)) => {
buf.push(residual);
}
Err(other) => {
result = Err(other);
break;
}
}
}
buf.extend(iter);
std::mem::swap(&mut buf, &mut self.payloads);
result
}
}
impl TryFrom<Element> for Message {
type Error = Error;
fn try_from(root: Element) -> Result<Message, Error> {
check_self!(root, "message", DEFAULT_NS);
let from = get_attr!(root, "from", Option);
let to = get_attr!(root, "to", Option);
let id = get_attr!(root, "id", Option);
let type_ = get_attr!(root, "type", Default);
let mut bodies = BTreeMap::new();
let mut subjects = BTreeMap::new();
let mut thread = None;
let mut payloads = vec![];
for elem in root.children() {
if elem.is("body", ns::DEFAULT_NS) {
check_no_children!(elem, "body");
let lang = get_attr!(elem, "xml:lang", Default);
let body = Body(elem.text());
if bodies.insert(lang, body).is_some() {
return Err(Error::ParseError(
"Body element present twice for the same xml:lang.",
));
}
} else if elem.is("subject", ns::DEFAULT_NS) {
check_no_children!(elem, "subject");
let lang = get_attr!(elem, "xml:lang", Default);
let subject = Subject(elem.text());
if subjects.insert(lang, subject).is_some() {
return Err(Error::ParseError(
"Subject element present twice for the same xml:lang.",
));
}
} else if elem.is("thread", ns::DEFAULT_NS) {
if thread.is_some() {
return Err(Error::ParseError("Thread element present twice."));
}
check_no_children!(elem, "thread");
thread = Some(Thread(elem.text()));
} else {
payloads.push(elem.clone())
}
}
Ok(Message {
from,
to,
id,
type_,
bodies,
subjects,
thread,
payloads,
})
}
}
impl From<Message> for Element {
fn from(message: Message) -> Element {
Element::builder("message", ns::DEFAULT_NS)
.attr("from", message.from)
.attr("to", message.to)
.attr("id", message.id)
.attr("type", message.type_)
.append_all(message.subjects.into_iter().map(|(lang, subject)| {
let mut subject = Element::from(subject);
subject.set_attr(
"xml:lang",
match lang.as_ref() {
"" => None,
lang => Some(lang),
},
);
subject
}))
.append_all(message.bodies.into_iter().map(|(lang, body)| {
let mut body = Element::from(body);
body.set_attr(
"xml:lang",
match lang.as_ref() {
"" => None,
lang => Some(lang),
},
);
body
}))
.append_all(message.payloads)
.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[cfg(target_pointer_width = "32")]
#[test]
fn test_size() {
assert_size!(MessageType, 1);
assert_size!(Body, 12);
assert_size!(Subject, 12);
assert_size!(Thread, 12);
assert_size!(Message, 96);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_size() {
assert_size!(MessageType, 1);
assert_size!(Body, 24);
assert_size!(Subject, 24);
assert_size!(Thread, 24);
assert_size!(Message, 192);
}
#[test]
fn test_simple() {
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept'/>"
.parse()
.unwrap();
let message = Message::try_from(elem).unwrap();
assert_eq!(message.from, None);
assert_eq!(message.to, None);
assert_eq!(message.id, None);
assert_eq!(message.type_, MessageType::Normal);
assert!(message.payloads.is_empty());
}
#[test]
fn test_serialise() {
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept'/>"
.parse()
.unwrap();
let mut message = Message::new(None);
message.type_ = MessageType::Normal;
let elem2 = message.into();
assert_eq!(elem, elem2);
}
#[test]
fn test_body() {
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
let elem1 = elem.clone();
let message = Message::try_from(elem).unwrap();
assert_eq!(message.bodies[""], Body::from_str("Hello world!").unwrap());
{
let (lang, body) = message.get_best_body(vec!["en"]).unwrap();
assert_eq!(lang, "");
assert_eq!(body, &Body::from_str("Hello world!").unwrap());
}
let elem2 = message.into();
assert_eq!(elem1, elem2);
}
#[test]
fn test_serialise_body() {
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
let mut message = Message::new(Jid::new("coucou@example.org").unwrap());
message
.bodies
.insert(String::from(""), Body::from_str("Hello world!").unwrap());
let elem2 = message.into();
assert_eq!(elem, elem2);
}
#[test]
fn test_subject() {
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><subject>Hello world!</subject></message>".parse().unwrap();
let elem1 = elem.clone();
let message = Message::try_from(elem).unwrap();
assert_eq!(
message.subjects[""],
Subject::from_str("Hello world!").unwrap()
);
{
let (lang, subject) = message.get_best_subject(vec!["en"]).unwrap();
assert_eq!(lang, "");
assert_eq!(subject, &Subject::from_str("Hello world!").unwrap());
}
let elem2 = message.into();
assert_eq!(elem1, elem2);
}
#[test]
fn get_best_body() {
#[cfg(not(feature = "component"))]
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();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><body>Hello world!</body></message>".parse().unwrap();
let message = Message::try_from(elem).unwrap();
{
let (lang, body) = message.get_best_body(vec!["fr"]).unwrap();
assert_eq!(lang, "fr");
assert_eq!(body, &Body::from_str("Salut le monde !").unwrap());
}
{
let (lang, body) = message.get_best_body(vec!["en", "de"]).unwrap();
assert_eq!(lang, "de");
assert_eq!(body, &Body::from_str("Hallo Welt!").unwrap());
}
{
let (lang, body) = message.get_best_body(vec![]).unwrap();
assert_eq!(lang, "");
assert_eq!(body, &Body::from_str("Hello world!").unwrap());
}
{
let (lang, body) = message.get_best_body(vec!["ja"]).unwrap();
assert_eq!(lang, "");
assert_eq!(body, &Body::from_str("Hello world!").unwrap());
}
let message = Message::new(None);
assert_eq!(message.get_best_body(vec!("ja")), None);
}
#[test]
fn test_attention() {
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
let elem1 = elem.clone();
let message = Message::try_from(elem).unwrap();
let elem2 = message.into();
assert_eq!(elem1, elem2);
}
#[test]
fn test_extract_payload() {
use super::super::attention::Attention;
use super::super::pubsub::event::PubSubEvent;
#[cfg(not(feature = "component"))]
let elem: Element = "<message xmlns='jabber:client' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<message xmlns='jabber:component:accept' to='coucou@example.org' type='chat'><attention xmlns='urn:xmpp:attention:0'/></message>".parse().unwrap();
let mut message = Message::try_from(elem).unwrap();
assert_eq!(message.payloads.len(), 1);
match message.extract_payload::<PubSubEvent>() {
Ok(None) => (),
other => panic!("unexpected result: {:?}", other),
};
assert_eq!(message.payloads.len(), 1);
match message.extract_payload::<Attention>() {
Ok(Some(_)) => (),
other => panic!("unexpected result: {:?}", other),
};
assert_eq!(message.payloads.len(), 0);
}
}