1#![feature(try_from)]
2
3extern crate futures;
4extern crate tokio_core;
5extern crate tokio_xmpp;
6extern crate jid;
7extern crate minidom;
8extern crate xmpp_parsers;
9
10use std::env::args;
11use std::process::exit;
12use std::convert::TryFrom;
13use tokio_core::reactor::Core;
14use futures::{Future, Stream, Sink, future};
15use tokio_xmpp::Client;
16use minidom::Element;
17use xmpp_parsers::presence::{Presence, Type as PresenceType, Show as PresenceShow};
18use xmpp_parsers::message::{Message, MessageType};
19use jid::Jid;
20
21fn main() {
22 let args: Vec<String> = args().collect();
23 if args.len() != 3 {
24 println!("Usage: {} <jid> <password>", args[0]);
25 exit(1);
26 }
27 let jid = &args[1];
28 let password = &args[2];
29
30 // tokio_core context
31 let mut core = Core::new().unwrap();
32 // Client instance
33 let client = Client::new(jid, password, core.handle()).unwrap();
34
35 // Make the two interfaces for sending and receiving independent
36 // of each other so we can move one into a closure.
37 let (sink, stream) = client.split();
38 // Wrap sink in Option so that we can take() it for the send(self)
39 // to consume and return it back when ready.
40 let mut sink = Some(sink);
41 let mut send = move |stanza| {
42 sink = Some(
43 sink.take().
44 expect("sink")
45 .send(stanza)
46 .wait()
47 .expect("sink.send")
48 );
49 };
50 // Main loop, processes events
51 let done = stream.for_each(|event| {
52 if event.is_online() {
53 println!("Online!");
54
55 let presence = make_presence();
56 send(presence);
57 } else if let Some(message) = event.into_stanza()
58 .and_then(|stanza| Message::try_from(stanza).ok())
59 {
60 // This is a message we'll echo
61 match (message.from, message.bodies.get("")) {
62 (Some(from), Some(body)) =>
63 if message.type_ != MessageType::Error {
64 let reply = make_reply(from, body);
65 send(reply);
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 presence.into()
90}
91
92// Construct a chat <message/>
93fn make_reply(to: Jid, body: &str) -> Element {
94 let mut message = Message::new(Some(to));
95 message.bodies.insert(String::new(), body.to_owned());
96 message.into()
97}