summaryrefslogtreecommitdiffstats
path: root/src/stanza/bind.rs
blob: 939a716e189e8330eb70d3dc90fcee376464956e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use super::{Element, ElementParseError};
use crate::{JabberError, JID};

const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-bind";

pub struct Bind {
    pub resource: Option<String>,
    pub jid: Option<JID>,
}

impl From<Bind> for Element {
    fn from(bind: Bind) -> Self {
        let bind_element = Element::new("bind", None, XMLNS);
        bind_element.push_namespace_declaration((None, XMLNS));
        if let Some(resource) = bind.resource {
            let resource_element = Element::new("resource", None, XMLNS);
            resource_element.push_child(resource);
            bind_element.push_child(resource_element)
        }
        if let Some(jid) = bind.jid {
            let jid_element = Element::new("jid", None, XMLNS);
            jid_element.push_child(jid);
            bind_element.push_child(jid_element)
        }
        bind_element
    }
}

impl TryFrom<Element> for Bind {
    type Error = JabberError;

    fn try_from(element: Element) -> Result<Self, Self::Error> {
        if element.namespace() == XMLNS && element.localname() == "bind" {
            let (resource, jid);
            let child: &Element = element.child()?;
            if child.namespace() == XMLNS {
                match child.localname() {
                    "resource" => Bind::new(Some(
                        child
                            .text_content()?
                            .first()
                            .ok_or(ElementParseError::NoContent)?,
                    )),
                }
            }
        }
    }
}