ping.rs

 1use plugin::{Plugin, PluginReturn, PluginProxy};
 2use event::Event;
 3use minidom::Element;
 4use error::Error;
 5use jid::Jid;
 6use ns;
 7
 8#[derive(Debug)]
 9pub struct PingEvent {
10    pub from: Jid,
11    pub to: Jid,
12    pub id: String,
13}
14
15impl Event for PingEvent {}
16
17pub struct PingPlugin {
18    proxy: PluginProxy,
19}
20
21impl PingPlugin {
22    pub fn new() -> PingPlugin {
23        PingPlugin {
24            proxy: PluginProxy::new(),
25        }
26    }
27
28    pub fn send_ping(&self, to: &Jid) -> Result<(), Error> {
29        let mut elem = Element::builder("iq")
30                               .attr("type", "get")
31                               .attr("to", to.to_string())
32                               .build();
33        elem.append_child(Element::builder("ping").ns(ns::PING).build());
34        self.proxy.send(elem);
35        Ok(())
36    }
37
38    pub fn reply_ping(&self, event: &PingEvent) {
39        let reply = Element::builder("iq")
40                            .attr("type", "result")
41                            .attr("to", event.from.to_string())
42                            .attr("id", event.id.to_string())
43                            .build();
44        self.proxy.send(reply);
45    }
46}
47
48impl Plugin for PingPlugin {
49    fn get_proxy(&mut self) -> &mut PluginProxy {
50        &mut self.proxy
51    }
52
53    fn handle(&mut self, elem: &Element) -> PluginReturn {
54        if elem.is("iq", ns::CLIENT) && elem.attr("type") == Some("get") {
55            if elem.has_child("ping", ns::PING) {
56                self.proxy.dispatch(PingEvent { // TODO: safety!!!
57                    from: elem.attr("from").unwrap().parse().unwrap(),
58                    to: elem.attr("to").unwrap().parse().unwrap(),
59                    id: elem.attr("id").unwrap().parse().unwrap(),
60                });
61            }
62        }
63        PluginReturn::Continue
64    }
65}