1use plugin::PluginProxy;
2use event::{Event, Priority, Propagation, ReceiveElement};
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 fn handle_receive_element(&self, evt: &ReceiveElement) -> Propagation {
48 let elem = &evt.0;
49 if elem.is("iq", ns::CLIENT) && elem.attr("type") == Some("get") {
50 if elem.has_child("ping", ns::PING) {
51 self.proxy.dispatch(PingEvent { // TODO: safety!!!
52 from: elem.attr("from").unwrap().parse().unwrap(),
53 to: elem.attr("to").unwrap().parse().unwrap(),
54 id: elem.attr("id").unwrap().parse().unwrap(),
55 });
56 }
57 }
58 Propagation::Continue
59 }
60}
61
62impl_plugin!(PingPlugin, proxy, [
63 (ReceiveElement, Priority::Default) => handle_receive_element,
64]);