1extern crate futures;
2extern crate tokio_core;
3extern crate tokio_xmpp;
4extern crate jid;
5extern crate xml;
6
7use tokio_core::reactor::Core;
8use futures::{Future, Stream, Sink, future};
9use tokio_xmpp::{Client, ClientEvent};
10
11fn main() {
12 let mut core = Core::new().unwrap();
13 let client = Client::new("astrobot@example.org", "", &core.handle()).unwrap();
14
15 let (sink, stream) = client.split();
16 let mut sink = Some(sink);
17 let done = stream.for_each(move |event| {
18 let result: Box<Future<Item=(), Error=String>> = match event {
19 ClientEvent::Online => {
20 println!("Online!");
21
22 let presence = make_presence();
23 sink = Some(
24 sink.take().
25 expect("sink")
26 .send(presence)
27 .wait()
28 .expect("sink.send")
29 );
30 Box::new(
31 future::ok(())
32 )
33 },
34 ClientEvent::Stanza(ref stanza)
35 if stanza.name == "message"
36 && stanza.get_attribute("type", None) != Some("error") =>
37 {
38 let from = stanza.get_attribute("from", None);
39 let body = stanza.get_child("body", Some("jabber:client"))
40 .map(|el| el.content_str());
41
42 match (from.as_ref(), body) {
43 (Some(from), Some(body)) => {
44 let reply = make_reply(from, body);
45 sink = Some(
46 sink.take().
47 expect("sink")
48 .send(reply)
49 .wait()
50 .expect("sink.send")
51 );
52 },
53 _ => (),
54 };
55 Box::new(future::ok(()))
56 },
57 _ => {
58 Box::new(future::ok(()))
59 },
60 };
61 result
62 });
63
64 match core.run(done) {
65 Ok(_) => (),
66 Err(e) => {
67 println!("Fatal: {}", e);
68 ()
69 }
70 }
71}
72
73fn make_presence() -> xml::Element {
74 let mut presence = xml::Element::new("presence".to_owned(), None, vec![]);
75 presence.tag(xml::Element::new("status".to_owned(), None, vec![]))
76 .text("chat".to_owned());
77 presence.tag(xml::Element::new("show".to_owned(), None, vec![]))
78 .text("Echoing messages".to_owned());
79 presence
80}
81
82fn make_reply(to: &str, body: String) -> xml::Element {
83 let mut message = xml::Element::new(
84 "message".to_owned(),
85 None,
86 vec![("type".to_owned(), None, "chat".to_owned()),
87 ("to".to_owned(), None, to.to_owned())]
88 );
89 message.tag(xml::Element::new("body".to_owned(), None, vec![]))
90 .text(body);
91 message
92}