stanza.rs

 1use std::fmt::Debug;
 2use std::any::Any;
 3
 4use plugin::PluginProxy;
 5use event::{Event, EventHandler, ReceiveElement, Propagation, Priority};
 6use minidom::Element;
 7use jid::Jid;
 8use ns;
 9
10pub trait Stanza: Any + Debug {}
11
12#[derive(Debug)]
13pub struct MessageEvent {
14    pub from: Option<Jid>,
15    pub to: Option<Jid>,
16    pub id: Option<String>,
17    pub type_: Option<String>,
18    pub payloads: Vec<Element>,
19}
20
21#[derive(Debug)]
22pub struct IqEvent {
23    pub from: Option<Jid>,
24    pub to: Option<Jid>,
25    pub id: Option<String>,
26    pub type_: Option<String>,
27    pub payloads: Vec<Element>,
28}
29
30#[derive(Debug)]
31pub struct PresenceEvent {
32    pub from: Option<Jid>,
33    pub to: Option<Jid>,
34    pub id: Option<String>,
35    pub type_: Option<String>,
36    pub payloads: Vec<Element>,
37}
38
39impl Event for MessageEvent {}
40impl Event for IqEvent {}
41impl Event for PresenceEvent {}
42
43pub struct StanzaPlugin {
44    proxy: PluginProxy,
45}
46
47impl StanzaPlugin {
48    pub fn new() -> StanzaPlugin {
49        StanzaPlugin {
50            proxy: PluginProxy::new(),
51        }
52    }
53}
54
55impl_plugin!(StanzaPlugin, proxy, [
56    ReceiveElement => Priority::Default,
57]);
58
59impl EventHandler<ReceiveElement> for StanzaPlugin {
60    fn handle(&self, evt: &ReceiveElement) -> Propagation {
61        let elem = &evt.0;
62
63        let from = match elem.attr("from") { Some(from) => Some(from.parse().unwrap()), None => None };
64        let to = match elem.attr("to") { Some(to) => Some(to.parse().unwrap()), None => None };
65        let id = match elem.attr("id") { Some(id) => Some(id.parse().unwrap()), None => None };
66        let type_ = match elem.attr("type") { Some(type_) => Some(type_.parse().unwrap()), None => None };
67        let payloads = elem.children().cloned().collect::<Vec<_>>();
68
69        if elem.is("message", ns::CLIENT) {
70            self.proxy.dispatch(MessageEvent {
71                from: from,
72                to: to,
73                id: id,
74                type_: type_,
75                payloads: payloads,
76            });
77        } else if elem.is("presence", ns::CLIENT) {
78            self.proxy.dispatch(PresenceEvent {
79                from: from,
80                to: to,
81                id: id,
82                type_: type_,
83                payloads: payloads,
84            });
85        } else if elem.is("iq", ns::CLIENT) {
86            self.proxy.dispatch(IqEvent {
87                from: from,
88                to: to,
89                id: id,
90                type_: type_,
91                payloads: payloads,
92            });
93        }
94
95        Propagation::Continue
96    }
97}