messaging.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 MessageEvent {
10    pub from: Jid,
11    pub to: Jid,
12    pub body: String,
13}
14
15impl Event for MessageEvent {}
16
17pub struct MessagingPlugin {
18    proxy: PluginProxy,
19}
20
21impl MessagingPlugin {
22    pub fn new() -> MessagingPlugin {
23        MessagingPlugin {
24            proxy: PluginProxy::new(),
25        }
26    }
27
28    pub fn send_message(&self, to: &Jid, body: &str) -> Result<(), Error> {
29        let mut elem = Element::builder("message")
30                               .attr("type", "chat")
31                               .attr("to", to.to_string())
32                               .build();
33        elem.append_child(Element::builder("body").append(body).build());
34        self.proxy.send(elem);
35        Ok(())
36    }
37}
38
39impl Plugin for MessagingPlugin {
40    fn get_proxy(&mut self) -> &mut PluginProxy {
41        &mut self.proxy
42    }
43
44    fn handle(&mut self, elem: &Element) -> PluginReturn {
45        if elem.is("message", ns::CLIENT) && elem.attr("type") == Some("chat") {
46            if let Some(body) = elem.get_child("body", ns::CLIENT) {
47                self.proxy.dispatch(MessageEvent { // TODO: safety!!!
48                    from: elem.attr("from").unwrap().parse().unwrap(),
49                    to: elem.attr("to").unwrap().parse().unwrap(),
50                    body: body.text(),
51                });
52            }
53        }
54        PluginReturn::Continue
55    }
56}