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