1extern crate futures;
2extern crate tokio_core;
3extern crate tokio_xmpp;
4extern crate jid;
5extern crate minidom;
6extern crate xmpp_parsers;
7
8use std::env::args;
9use std::process::exit;
10use tokio_core::reactor::Core;
11use futures::{Future, Stream, Sink, future};
12use tokio_xmpp::Client;
13use minidom::Element;
14use xmpp_parsers::presence::{Presence, Type as PresenceType, Show as PresenceShow};
15use xmpp_parsers::message::Message;
16
17fn main() {
18 let args: Vec<String> = args().collect();
19 if args.len() != 3 {
20 println!("Usage: {} <jid> <password>", args[0]);
21 exit(1);
22 }
23 let jid = &args[1];
24 let password = &args[2];
25
26 // tokio_core context
27 let mut core = Core::new().unwrap();
28 // Client instance
29 let client = Client::new(jid, password, core.handle()).unwrap();
30
31 // Make the two interfaces for sending and receiving independent
32 // of each other so we can move one into a closure.
33 let (sink, stream) = client.split();
34 // Wrap sink in Option so that we can take() it for the send(self)
35 // to consume and return it back when ready.
36 let mut sink = Some(sink);
37 let mut send = move |stanza| {
38 sink = Some(
39 sink.take().
40 expect("sink")
41 .send(stanza)
42 .wait()
43 .expect("sink.send")
44 );
45 };
46 // Main loop, processes events
47 let done = stream.for_each(|event| {
48 if event.is_online() {
49 println!("Online!");
50
51 let presence = make_presence();
52 send(presence);
53 } else if let Some(stanza) = event.as_stanza() {
54 if stanza.name() == "message" &&
55 stanza.attr("type") != Some("error") {
56 // This is a message we'll echo
57 let from = stanza.attr("from");
58 let body = stanza.get_child("body", "jabber:client")
59 .map(|el| el.text());
60
61 match (from, body) {
62 (Some(from), Some(body)) => {
63 let reply = make_reply(from, body);
64 send(reply);
65 },
66 _ => (),
67 };
68 }
69 }
70
71 Box::new(future::ok(()))
72 });
73
74 // Start polling `done`
75 match core.run(done) {
76 Ok(_) => (),
77 Err(e) => {
78 println!("Fatal: {}", e);
79 ()
80 }
81 }
82}
83
84// Construct a <presence/>
85fn make_presence() -> Element {
86 let mut presence = Presence::new(PresenceType::None);
87 presence.show = PresenceShow::Chat;
88 presence.statuses.insert(String::from("en"), String::from("Echoing messages."));
89 Element::from(presence)
90}
91
92// Construct a chat <message/>
93fn make_reply(to: &str, body: String) -> Element {
94 let jid = to.parse().unwrap();
95 let mut message = Message::new(Some(jid));
96 message.bodies.insert(String::new(), body);
97 Element::from(message)
98}