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