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