xmpp-rs/src/presence.rs

446 lines
15 KiB
Rust
Raw Normal View History

2017-04-29 21:14:34 +00:00
// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
2017-05-06 19:42:12 +00:00
use std::convert::TryFrom;
2017-04-23 16:30:23 +00:00
use std::str::FromStr;
use std::collections::BTreeMap;
2017-04-23 16:30:23 +00:00
2017-05-24 20:30:33 +00:00
use minidom::{Element, IntoAttributeValue};
2017-04-23 16:30:23 +00:00
use jid::Jid;
use error::Error;
use ns;
2017-05-06 20:13:53 +00:00
use stanza_error::StanzaError;
2017-05-27 11:21:32 +00:00
use caps::Caps;
2017-05-06 19:42:12 +00:00
use delay::Delay;
2017-05-21 19:30:42 +00:00
use idle::Idle;
2017-05-06 19:58:22 +00:00
use ecaps2::ECaps2;
2017-04-23 16:30:23 +00:00
2017-04-30 20:03:04 +00:00
#[derive(Debug, Clone, PartialEq)]
pub enum Show {
Away,
Chat,
Dnd,
Xa,
}
2017-05-24 20:30:33 +00:00
impl FromStr for Show {
type Err = Error;
fn from_str(s: &str) -> Result<Show, Error> {
Ok(match s {
"away" => Show::Away,
"chat" => Show::Chat,
"dnd" => Show::Dnd,
"xa" => Show::Xa,
_ => return Err(Error::ParseError("Invalid value for show.")),
})
}
}
impl Into<Element> for Show {
fn into(self) -> Element {
Element::builder("show")
.append(match self {
Show::Away => "away",
Show::Chat => "chat",
Show::Dnd => "dnd",
Show::Xa => "xa",
})
.build()
2017-04-30 20:03:04 +00:00
}
}
pub type Lang = String;
pub type Status = String;
2017-04-30 20:29:55 +00:00
pub type Priority = i8;
2017-04-23 16:30:23 +00:00
/// Lists every known payload of a `<presence/>`.
#[derive(Debug, Clone)]
pub enum PresencePayload {
2017-05-06 20:13:53 +00:00
StanzaError(StanzaError),
2017-05-27 11:21:32 +00:00
Caps(Caps),
2017-05-06 19:42:12 +00:00
Delay(Delay),
2017-05-21 19:30:42 +00:00
Idle(Idle),
2017-05-06 19:58:22 +00:00
ECaps2(ECaps2),
Unknown(Element),
2017-04-23 16:30:23 +00:00
}
impl TryFrom<Element> for PresencePayload {
type Error = Error;
fn try_from(elem: Element) -> Result<PresencePayload, Error> {
Ok(match (elem.name().as_ref(), elem.ns().unwrap().as_ref()) {
("error", ns::JABBER_CLIENT) => PresencePayload::StanzaError(StanzaError::try_from(elem)?),
2017-05-27 11:21:32 +00:00
// XEP-0115
("c", ns::CAPS) => PresencePayload::Caps(Caps::try_from(elem)?),
// XEP-0203
("delay", ns::DELAY) => PresencePayload::Delay(Delay::try_from(elem)?),
2017-05-21 19:30:42 +00:00
// XEP-0319
("idle", ns::IDLE) => PresencePayload::Idle(Idle::try_from(elem)?),
// XEP-0390
("c", ns::ECAPS2) => PresencePayload::ECaps2(ECaps2::try_from(elem)?),
_ => PresencePayload::Unknown(elem),
})
}
}
impl Into<Element> for PresencePayload {
fn into(self) -> Element {
match self {
PresencePayload::StanzaError(stanza_error) => stanza_error.into(),
2017-05-27 11:21:32 +00:00
PresencePayload::Caps(caps) => caps.into(),
PresencePayload::Delay(delay) => delay.into(),
PresencePayload::Idle(idle) => idle.into(),
PresencePayload::ECaps2(ecaps2) => ecaps2.into(),
2017-05-24 20:30:33 +00:00
PresencePayload::Unknown(elem) => elem,
}
}
}
2017-04-23 16:30:23 +00:00
#[derive(Debug, Clone, PartialEq)]
pub enum PresenceType {
/// This value is not an acceptable 'type' attribute, it is only used
/// internally to signal the absence of 'type'.
None,
2017-04-23 16:30:23 +00:00
Error,
Probe,
Subscribe,
Subscribed,
Unavailable,
Unsubscribe,
Unsubscribed,
}
impl Default for PresenceType {
fn default() -> PresenceType {
PresenceType::None
2017-04-23 16:30:23 +00:00
}
}
impl FromStr for PresenceType {
type Err = Error;
fn from_str(s: &str) -> Result<PresenceType, Error> {
Ok(match s {
"error" => PresenceType::Error,
"probe" => PresenceType::Probe,
"subscribe" => PresenceType::Subscribe,
"subscribed" => PresenceType::Subscribed,
"unavailable" => PresenceType::Unavailable,
"unsubscribe" => PresenceType::Unsubscribe,
"unsubscribed" => PresenceType::Unsubscribed,
_ => return Err(Error::ParseError("Invalid 'type' attribute on presence element.")),
})
}
}
impl IntoAttributeValue for PresenceType {
fn into_attribute_value(self) -> Option<String> {
Some(match self {
PresenceType::None => return None,
2017-04-23 16:30:23 +00:00
PresenceType::Error => "error",
PresenceType::Probe => "probe",
PresenceType::Subscribe => "subscribe",
PresenceType::Subscribed => "subscribed",
PresenceType::Unavailable => "unavailable",
PresenceType::Unsubscribe => "unsubscribe",
PresenceType::Unsubscribed => "unsubscribed",
}.to_owned())
}
}
#[derive(Debug, Clone)]
pub struct Presence {
pub from: Option<Jid>,
pub to: Option<Jid>,
pub id: Option<String>,
pub type_: PresenceType,
pub show: Option<Show>,
pub statuses: BTreeMap<Lang, Status>,
pub priority: Priority,
pub payloads: Vec<Element>,
2017-04-23 16:30:23 +00:00
}
impl TryFrom<Element> for Presence {
2017-05-06 20:24:17 +00:00
type Error = Error;
fn try_from(root: Element) -> Result<Presence, Error> {
2017-05-06 20:24:17 +00:00
if !root.is("presence", ns::JABBER_CLIENT) {
return Err(Error::ParseError("This is not a presence element."));
}
let mut priority = None;
2017-05-24 20:30:33 +00:00
let mut presence = Presence {
from: get_attr!(root, "from", optional),
to: get_attr!(root, "to", optional),
id: get_attr!(root, "id", optional),
type_: get_attr!(root, "type", default),
show: None,
statuses: BTreeMap::new(),
priority: 0i8,
payloads: vec!(),
};
2017-05-06 20:24:17 +00:00
for elem in root.children() {
if elem.is("show", ns::JABBER_CLIENT) {
2017-05-24 20:30:33 +00:00
if presence.show.is_some() {
2017-05-06 20:24:17 +00:00
return Err(Error::ParseError("More than one show element in a presence."));
}
for _ in elem.children() {
return Err(Error::ParseError("Unknown child in show element."));
}
for _ in elem.attrs() {
return Err(Error::ParseError("Unknown attribute in show element."));
}
2017-05-24 20:30:33 +00:00
presence.show = Some(Show::from_str(elem.text().as_ref())?);
2017-05-06 20:24:17 +00:00
} else if elem.is("status", ns::JABBER_CLIENT) {
for _ in elem.children() {
return Err(Error::ParseError("Unknown child in status element."));
}
for (attr, _) in elem.attrs() {
if attr != "xml:lang" {
return Err(Error::ParseError("Unknown attribute in status element."));
}
}
let lang = get_attr!(elem, "xml:lang", default);
2017-05-24 20:30:33 +00:00
if presence.statuses.insert(lang, elem.text()).is_some() {
2017-05-06 20:24:17 +00:00
return Err(Error::ParseError("Status element present twice for the same xml:lang."));
}
} else if elem.is("priority", ns::JABBER_CLIENT) {
if priority.is_some() {
return Err(Error::ParseError("More than one priority element in a presence."));
}
for _ in elem.children() {
return Err(Error::ParseError("Unknown child in priority element."));
}
for _ in elem.attrs() {
return Err(Error::ParseError("Unknown attribute in priority element."));
}
2017-05-06 20:24:17 +00:00
priority = Some(Priority::from_str(elem.text().as_ref())?);
} else {
2017-05-24 20:30:33 +00:00
presence.payloads.push(elem.clone());
2017-05-06 20:24:17 +00:00
}
}
2017-05-24 20:30:33 +00:00
if let Some(priority) = priority {
presence.priority = priority;
}
Ok(presence)
2017-04-23 16:30:23 +00:00
}
}
impl Into<Element> for Presence {
2017-05-06 20:24:17 +00:00
fn into(self) -> Element {
2017-05-24 20:30:33 +00:00
Element::builder("presence")
.ns(ns::JABBER_CLIENT)
.attr("from", self.from.and_then(|value| Some(String::from(value))))
.attr("to", self.to.and_then(|value| Some(String::from(value))))
.attr("id", self.id)
.attr("type", self.type_)
.append(match self.show {
Some(show) => Some({ let elem: Element = show.into(); elem }),
None => None
})
.append(self.statuses.iter().map(|(lang, status)| {
Element::builder("status")
.attr("xml:lang", match lang.as_ref() {
"" => None,
lang => Some(lang),
})
.append(status)
.build()
}).collect::<Vec<_>>())
.append(if self.priority == 0 { None } else { Some(format!("{}", self.priority)) })
.append(self.payloads)
.build()
2017-04-23 16:30:23 +00:00
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
2017-05-06 20:24:17 +00:00
use super::*;
2017-04-23 16:30:23 +00:00
#[test]
fn test_simple() {
let elem: Element = "<presence xmlns='jabber:client'/>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
2017-04-23 16:30:23 +00:00
assert_eq!(presence.from, None);
assert_eq!(presence.to, None);
assert_eq!(presence.id, None);
assert_eq!(presence.type_, PresenceType::None);
2017-04-23 16:30:23 +00:00
assert!(presence.payloads.is_empty());
}
#[test]
fn test_serialise() {
let elem: Element = "<presence xmlns='jabber:client' type='unavailable'/>".parse().unwrap();
2017-05-06 20:24:17 +00:00
let presence = Presence {
2017-04-23 16:30:23 +00:00
from: None,
to: None,
id: None,
2017-05-06 20:24:17 +00:00
type_: PresenceType::Unavailable,
show: None,
statuses: BTreeMap::new(),
priority: 0i8,
2017-04-23 16:30:23 +00:00
payloads: vec!(),
};
let elem2 = presence.into();
2017-04-23 16:30:23 +00:00
assert_eq!(elem, elem2);
}
2017-04-30 20:03:04 +00:00
#[test]
fn test_show() {
let elem: Element = "<presence xmlns='jabber:client'><show>chat</show></presence>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
assert_eq!(presence.payloads.len(), 0);
2017-05-06 20:24:17 +00:00
assert_eq!(presence.show, Some(Show::Chat));
2017-04-30 20:03:04 +00:00
}
#[test]
fn test_missing_show_value() {
// "online" used to be a pretty common mistake.
let elem: Element = "<presence xmlns='jabber:client'><show/></presence>".parse().unwrap();
let error = Presence::try_from(elem).unwrap_err();
2017-04-30 20:03:04 +00:00
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Invalid value for show.");
}
#[test]
fn test_invalid_show() {
// "online" used to be a pretty common mistake.
let elem: Element = "<presence xmlns='jabber:client'><show>online</show></presence>".parse().unwrap();
let error = Presence::try_from(elem).unwrap_err();
2017-04-30 20:03:04 +00:00
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Invalid value for show.");
}
#[test]
fn test_empty_status() {
let elem: Element = "<presence xmlns='jabber:client'><status/></presence>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
assert_eq!(presence.payloads.len(), 0);
assert_eq!(presence.statuses.len(), 1);
assert_eq!(presence.statuses[""], "");
}
#[test]
fn test_status() {
let elem: Element = "<presence xmlns='jabber:client'><status>Here!</status></presence>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
assert_eq!(presence.payloads.len(), 0);
assert_eq!(presence.statuses.len(), 1);
assert_eq!(presence.statuses[""], "Here!");
}
#[test]
fn test_multiple_statuses() {
let elem: Element = "<presence xmlns='jabber:client'><status>Here!</status><status xml:lang='fr'>Là!</status></presence>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
assert_eq!(presence.payloads.len(), 0);
assert_eq!(presence.statuses.len(), 2);
assert_eq!(presence.statuses[""], "Here!");
assert_eq!(presence.statuses["fr"], "Là!");
}
#[test]
fn test_invalid_multiple_statuses() {
let elem: Element = "<presence xmlns='jabber:client'><status xml:lang='fr'>Here!</status><status xml:lang='fr'>Là!</status></presence>".parse().unwrap();
let error = Presence::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Status element present twice for the same xml:lang.");
}
2017-04-30 20:29:55 +00:00
#[test]
fn test_priority() {
let elem: Element = "<presence xmlns='jabber:client'><priority>-1</priority></presence>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
assert_eq!(presence.payloads.len(), 0);
assert_eq!(presence.priority, -1i8);
2017-04-30 20:29:55 +00:00
}
#[test]
fn test_invalid_priority() {
let elem: Element = "<presence xmlns='jabber:client'><priority>128</priority></presence>".parse().unwrap();
let error = Presence::try_from(elem).unwrap_err();
2017-04-30 20:29:55 +00:00
match error {
Error::ParseIntError(_) => (),
_ => panic!(),
};
}
#[test]
fn test_unknown_child() {
let elem: Element = "<presence xmlns='jabber:client'><test xmlns='invalid'/></presence>".parse().unwrap();
let presence = Presence::try_from(elem).unwrap();
let payload = &presence.payloads[0];
assert!(payload.is("test", "invalid"));
}
#[test]
fn test_invalid_status_child() {
let elem: Element = "<presence xmlns='jabber:client'><status><coucou/></status></presence>".parse().unwrap();
let error = Presence::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown child in status element.");
}
#[test]
fn test_invalid_attribute() {
let elem: Element = "<presence xmlns='jabber:client'><status coucou=''/></presence>".parse().unwrap();
let error = Presence::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown attribute in status element.");
}
#[test]
fn test_serialise_status() {
2017-05-06 20:24:17 +00:00
let status = Status::from("Hello world!");
let mut statuses = BTreeMap::new();
statuses.insert(String::from(""), status);
2017-05-06 20:24:17 +00:00
let presence = Presence {
from: None,
to: None,
id: None,
2017-05-06 20:24:17 +00:00
type_: PresenceType::Unavailable,
show: None,
statuses: statuses,
priority: 0i8,
payloads: vec!(),
};
let elem: Element = presence.into();
assert!(elem.is("presence", ns::JABBER_CLIENT));
assert!(elem.children().collect::<Vec<_>>()[0].is("status", ns::JABBER_CLIENT));
}
2017-04-23 16:30:23 +00:00
}