use crate::iq::IqSetPayload;
use crate::jingle_grouping::Group;
use crate::jingle_ibb::Transport as IbbTransport;
use crate::jingle_ice_udp::Transport as IceUdpTransport;
use crate::jingle_rtp::Description as RtpDescription;
use crate::jingle_s5b::Transport as Socks5Transport;
use crate::ns;
use crate::util::error::Error;
use crate::Element;
use jid::Jid;
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
generate_attribute!(
Action, "action", {
ContentAccept => "content-accept",
ContentAdd => "content-add",
ContentModify => "content-modify",
ContentReject => "content-reject",
ContentRemove => "content-remove",
DescriptionInfo => "description-info",
SecurityInfo => "security-info",
SessionAccept => "session-accept",
SessionInfo => "session-info",
SessionInitiate => "session-initiate",
SessionTerminate => "session-terminate",
TransportAccept => "transport-accept",
TransportInfo => "transport-info",
TransportReject => "transport-reject",
TransportReplace => "transport-replace",
}
);
generate_attribute!(
Creator, "creator", {
Initiator => "initiator",
Responder => "responder",
}
);
generate_attribute!(
Senders, "senders", {
Both => "both",
Initiator => "initiator",
None => "none",
Responder => "responder",
}, Default = Both
);
generate_attribute!(
Disposition, "disposition", {
Inline => "inline",
Attachment => "attachment",
FormData => "form-data",
Signal => "signal",
Alert => "alert",
Icon => "icon",
Render => "render",
RecipientListHistory => "recipient-list-history",
Session => "session",
Aib => "aib",
EarlySession => "early-session",
RecipientList => "recipient-list",
Notification => "notification",
ByReference => "by-reference",
InfoPackage => "info-package",
RecordingSession => "recording-session",
}, Default = Session
);
generate_id!(
ContentId
);
#[derive(Debug, Clone, PartialEq)]
pub enum Description {
Rtp(RtpDescription),
Unknown(Element),
}
impl TryFrom<Element> for Description {
type Error = Error;
fn try_from(elem: Element) -> Result<Description, Error> {
Ok(if elem.is("description", ns::JINGLE_RTP) {
Description::Rtp(RtpDescription::try_from(elem)?)
} else {
Description::Unknown(elem)
})
}
}
impl From<RtpDescription> for Description {
fn from(desc: RtpDescription) -> Description {
Description::Rtp(desc)
}
}
impl From<Description> for Element {
fn from(desc: Description) -> Element {
match desc {
Description::Rtp(desc) => desc.into(),
Description::Unknown(elem) => elem,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Transport {
IceUdp(IceUdpTransport),
Ibb(IbbTransport),
Socks5(Socks5Transport),
Unknown(Element),
}
impl TryFrom<Element> for Transport {
type Error = Error;
fn try_from(elem: Element) -> Result<Transport, Error> {
Ok(if elem.is("transport", ns::JINGLE_ICE_UDP) {
Transport::IceUdp(IceUdpTransport::try_from(elem)?)
} else if elem.is("transport", ns::JINGLE_IBB) {
Transport::Ibb(IbbTransport::try_from(elem)?)
} else if elem.is("transport", ns::JINGLE_S5B) {
Transport::Socks5(Socks5Transport::try_from(elem)?)
} else {
Transport::Unknown(elem)
})
}
}
impl From<IceUdpTransport> for Transport {
fn from(transport: IceUdpTransport) -> Transport {
Transport::IceUdp(transport)
}
}
impl From<IbbTransport> for Transport {
fn from(transport: IbbTransport) -> Transport {
Transport::Ibb(transport)
}
}
impl From<Socks5Transport> for Transport {
fn from(transport: Socks5Transport) -> Transport {
Transport::Socks5(transport)
}
}
impl From<Transport> for Element {
fn from(transport: Transport) -> Element {
match transport {
Transport::IceUdp(transport) => transport.into(),
Transport::Ibb(transport) => transport.into(),
Transport::Socks5(transport) => transport.into(),
Transport::Unknown(elem) => elem,
}
}
}
generate_element!(
Content, "content", JINGLE,
attributes: [
creator: Required<Creator> = "creator",
disposition: Default<Disposition> = "disposition",
name: Required<ContentId> = "name",
senders: Default<Senders> = "senders",
],
children: [
description: Option<Description> = ("description", *) => Description,
transport: Option<Transport> = ("transport", *) => Transport,
security: Option<Element> = ("security", JINGLE) => Element
]
);
impl Content {
pub fn new(creator: Creator, name: ContentId) -> Content {
Content {
creator,
name,
disposition: Disposition::Session,
senders: Senders::Both,
description: None,
transport: None,
security: None,
}
}
pub fn with_disposition(mut self, disposition: Disposition) -> Content {
self.disposition = disposition;
self
}
pub fn with_senders(mut self, senders: Senders) -> Content {
self.senders = senders;
self
}
pub fn with_description<D: Into<Description>>(mut self, description: D) -> Content {
self.description = Some(description.into());
self
}
pub fn with_transport<T: Into<Transport>>(mut self, transport: T) -> Content {
self.transport = Some(transport.into());
self
}
pub fn with_security(mut self, security: Element) -> Content {
self.security = Some(security);
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Reason {
AlternativeSession, Busy,
Cancel,
ConnectivityError,
Decline,
Expired,
FailedApplication,
FailedTransport,
GeneralError,
Gone,
IncompatibleParameters,
MediaError,
SecurityError,
Success,
Timeout,
UnsupportedApplications,
UnsupportedTransports,
}
impl FromStr for Reason {
type Err = Error;
fn from_str(s: &str) -> Result<Reason, Error> {
Ok(match s {
"alternative-session" => Reason::AlternativeSession,
"busy" => Reason::Busy,
"cancel" => Reason::Cancel,
"connectivity-error" => Reason::ConnectivityError,
"decline" => Reason::Decline,
"expired" => Reason::Expired,
"failed-application" => Reason::FailedApplication,
"failed-transport" => Reason::FailedTransport,
"general-error" => Reason::GeneralError,
"gone" => Reason::Gone,
"incompatible-parameters" => Reason::IncompatibleParameters,
"media-error" => Reason::MediaError,
"security-error" => Reason::SecurityError,
"success" => Reason::Success,
"timeout" => Reason::Timeout,
"unsupported-applications" => Reason::UnsupportedApplications,
"unsupported-transports" => Reason::UnsupportedTransports,
_ => return Err(Error::ParseError("Unknown reason.")),
})
}
}
impl From<Reason> for Element {
fn from(reason: Reason) -> Element {
Element::builder(
match reason {
Reason::AlternativeSession => "alternative-session",
Reason::Busy => "busy",
Reason::Cancel => "cancel",
Reason::ConnectivityError => "connectivity-error",
Reason::Decline => "decline",
Reason::Expired => "expired",
Reason::FailedApplication => "failed-application",
Reason::FailedTransport => "failed-transport",
Reason::GeneralError => "general-error",
Reason::Gone => "gone",
Reason::IncompatibleParameters => "incompatible-parameters",
Reason::MediaError => "media-error",
Reason::SecurityError => "security-error",
Reason::Success => "success",
Reason::Timeout => "timeout",
Reason::UnsupportedApplications => "unsupported-applications",
Reason::UnsupportedTransports => "unsupported-transports",
},
ns::JINGLE,
)
.build()
}
}
type Lang = String;
#[derive(Debug, Clone, PartialEq)]
pub struct ReasonElement {
pub reason: Reason,
pub texts: BTreeMap<Lang, String>,
}
impl fmt::Display for ReasonElement {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", Element::from(self.reason.clone()).name())?;
if let Some(text) = self.texts.get("en") {
write!(fmt, ": {}", text)?;
} else if let Some(text) = self.texts.get("") {
write!(fmt, ": {}", text)?;
}
Ok(())
}
}
impl TryFrom<Element> for ReasonElement {
type Error = Error;
fn try_from(elem: Element) -> Result<ReasonElement, Error> {
check_self!(elem, "reason", JINGLE);
check_no_attributes!(elem, "reason");
let mut reason = None;
let mut texts = BTreeMap::new();
for child in elem.children() {
if child.is("text", ns::JINGLE) {
check_no_children!(child, "text");
check_no_unknown_attributes!(child, "text", ["xml:lang"]);
let lang = get_attr!(elem, "xml:lang", Default);
if texts.insert(lang, child.text()).is_some() {
return Err(Error::ParseError(
"Text element present twice for the same xml:lang.",
));
}
} else if child.has_ns(ns::JINGLE) {
if reason.is_some() {
return Err(Error::ParseError(
"Reason must not have more than one reason.",
));
}
check_no_children!(child, "reason");
check_no_attributes!(child, "reason");
reason = Some(child.name().parse()?);
} else {
return Err(Error::ParseError("Reason contains a foreign element."));
}
}
let reason = reason.ok_or(Error::ParseError("Reason doesn’t contain a valid reason."))?;
Ok(ReasonElement { reason, texts })
}
}
impl From<ReasonElement> for Element {
fn from(reason: ReasonElement) -> Element {
Element::builder("reason", ns::JINGLE)
.append(Element::from(reason.reason))
.append_all(reason.texts.into_iter().map(|(lang, text)| {
Element::builder("text", ns::JINGLE)
.attr("xml:lang", lang)
.append(text)
}))
.build()
}
}
generate_id!(
SessionId
);
#[derive(Debug, Clone, PartialEq)]
pub struct Jingle {
pub action: Action,
pub initiator: Option<Jid>,
pub responder: Option<Jid>,
pub sid: SessionId,
pub contents: Vec<Content>,
pub reason: Option<ReasonElement>,
pub group: Option<Group>,
pub other: Vec<Element>,
}
impl IqSetPayload for Jingle {}
impl Jingle {
pub fn new(action: Action, sid: SessionId) -> Jingle {
Jingle {
action,
sid,
initiator: None,
responder: None,
contents: Vec::new(),
reason: None,
group: None,
other: Vec::new(),
}
}
pub fn with_initiator(mut self, initiator: Jid) -> Jingle {
self.initiator = Some(initiator);
self
}
pub fn with_responder(mut self, responder: Jid) -> Jingle {
self.responder = Some(responder);
self
}
pub fn add_content(mut self, content: Content) -> Jingle {
self.contents.push(content);
self
}
pub fn set_reason(mut self, reason: ReasonElement) -> Jingle {
self.reason = Some(reason);
self
}
pub fn set_group(mut self, group: Group) -> Jingle {
self.group = Some(group);
self
}
}
impl TryFrom<Element> for Jingle {
type Error = Error;
fn try_from(root: Element) -> Result<Jingle, Error> {
check_self!(root, "jingle", JINGLE, "Jingle");
check_no_unknown_attributes!(root, "Jingle", ["action", "initiator", "responder", "sid"]);
let mut jingle = Jingle {
action: get_attr!(root, "action", Required),
initiator: get_attr!(root, "initiator", Option),
responder: get_attr!(root, "responder", Option),
sid: get_attr!(root, "sid", Required),
contents: vec![],
reason: None,
group: None,
other: vec![],
};
for child in root.children().cloned() {
if child.is("content", ns::JINGLE) {
let content = Content::try_from(child)?;
jingle.contents.push(content);
} else if child.is("reason", ns::JINGLE) {
if jingle.reason.is_some() {
return Err(Error::ParseError(
"Jingle must not have more than one reason.",
));
}
let reason = ReasonElement::try_from(child)?;
jingle.reason = Some(reason);
} else if child.is("group", ns::JINGLE_GROUPING) {
if jingle.group.is_some() {
return Err(Error::ParseError(
"Jingle must not have more than one grouping.",
));
}
let group = Group::try_from(child)?;
jingle.group = Some(group);
} else {
jingle.other.push(child);
}
}
Ok(jingle)
}
}
impl From<Jingle> for Element {
fn from(jingle: Jingle) -> Element {
Element::builder("jingle", ns::JINGLE)
.attr("action", jingle.action)
.attr("initiator", jingle.initiator)
.attr("responder", jingle.responder)
.attr("sid", jingle.sid)
.append_all(jingle.contents)
.append_all(jingle.reason.map(Element::from))
.append_all(jingle.group.map(Element::from))
.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_pointer_width = "32")]
#[test]
fn test_size() {
assert_size!(Action, 1);
assert_size!(Creator, 1);
assert_size!(Senders, 1);
assert_size!(Disposition, 1);
assert_size!(ContentId, 12);
assert_size!(Content, 216);
assert_size!(Reason, 1);
assert_size!(ReasonElement, 16);
assert_size!(SessionId, 12);
assert_size!(Jingle, 104);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_size() {
assert_size!(Action, 1);
assert_size!(Creator, 1);
assert_size!(Senders, 1);
assert_size!(Disposition, 1);
assert_size!(ContentId, 24);
assert_size!(Content, 432);
assert_size!(Reason, 1);
assert_size!(ReasonElement, 32);
assert_size!(SessionId, 24);
assert_size!(Jingle, 208);
}
#[test]
fn test_simple() {
let elem: Element =
"<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'/>"
.parse()
.unwrap();
let jingle = Jingle::try_from(elem).unwrap();
assert_eq!(jingle.action, Action::SessionInitiate);
assert_eq!(jingle.sid, SessionId(String::from("coucou")));
}
#[test]
fn test_invalid_jingle() {
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1'/>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Required attribute 'action' missing.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-info'/>"
.parse()
.unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Required attribute 'sid' missing.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='coucou' sid='coucou'/>"
.parse()
.unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown value for 'action' attribute.");
}
#[test]
fn test_content() {
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='initiator' name='coucou'><description/><transport xmlns='urn:xmpp:jingle:transports:stub:0'/></content></jingle>".parse().unwrap();
let jingle = Jingle::try_from(elem).unwrap();
assert_eq!(jingle.contents[0].creator, Creator::Initiator);
assert_eq!(jingle.contents[0].name, ContentId(String::from("coucou")));
assert_eq!(jingle.contents[0].senders, Senders::Both);
assert_eq!(jingle.contents[0].disposition, Disposition::Session);
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='initiator' name='coucou' senders='both'><description/><transport xmlns='urn:xmpp:jingle:transports:stub:0'/></content></jingle>".parse().unwrap();
let jingle = Jingle::try_from(elem).unwrap();
assert_eq!(jingle.contents[0].senders, Senders::Both);
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='initiator' name='coucou' disposition='early-session'><description/><transport xmlns='urn:xmpp:jingle:transports:stub:0'/></content></jingle>".parse().unwrap();
let jingle = Jingle::try_from(elem).unwrap();
assert_eq!(jingle.contents[0].disposition, Disposition::EarlySession);
}
#[test]
fn test_invalid_content() {
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Required attribute 'creator' missing.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='initiator'/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Required attribute 'name' missing.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='coucou' name='coucou'/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown value for 'creator' attribute.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='initiator' name='coucou' senders='coucou'/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown value for 'senders' attribute.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><content creator='initiator' name='coucou' senders=''/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown value for 'senders' attribute.");
}
#[test]
fn test_reason() {
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason><success/></reason></jingle>".parse().unwrap();
let jingle = Jingle::try_from(elem).unwrap();
let reason = jingle.reason.unwrap();
assert_eq!(reason.reason, Reason::Success);
assert_eq!(reason.texts, BTreeMap::new());
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason><success/><text>coucou</text></reason></jingle>".parse().unwrap();
let jingle = Jingle::try_from(elem).unwrap();
let reason = jingle.reason.unwrap();
assert_eq!(reason.reason, Reason::Success);
assert_eq!(reason.texts.get(""), Some(&String::from("coucou")));
}
#[test]
fn test_invalid_reason() {
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Reason doesn’t contain a valid reason.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason><a/></reason></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown reason.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason><a xmlns='http://www.w3.org/1999/xhtml'/></reason></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Reason contains a foreign element.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason><decline/></reason><reason/></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Jingle must not have more than one reason.");
let elem: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='coucou'><reason><decline/><text/><text/></reason></jingle>".parse().unwrap();
let error = Jingle::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Text element present twice for the same xml:lang.");
}
#[test]
fn test_serialize_jingle() {
let reference: Element = "<jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' sid='a73sjjvkla37jfea'><content xmlns='urn:xmpp:jingle:1' creator='initiator' name='this-is-a-stub'><description xmlns='urn:xmpp:jingle:apps:stub:0'/><transport xmlns='urn:xmpp:jingle:transports:stub:0'/></content></jingle>"
.parse()
.unwrap();
let jingle = Jingle {
action: Action::SessionInitiate,
initiator: None,
responder: None,
sid: SessionId(String::from("a73sjjvkla37jfea")),
contents: vec![Content {
creator: Creator::Initiator,
disposition: Disposition::default(),
name: ContentId(String::from("this-is-a-stub")),
senders: Senders::default(),
description: Some(Description::Unknown(
Element::builder("description", "urn:xmpp:jingle:apps:stub:0").build(),
)),
transport: Some(Transport::Unknown(
Element::builder("transport", "urn:xmpp:jingle:transports:stub:0").build(),
)),
security: None,
}],
reason: None,
group: None,
other: vec![],
};
let serialized: Element = jingle.into();
assert_eq!(serialized, reference);
}
}